Search in sources :

Example 81 with NetworkRuleConflictException

use of com.cloud.exception.NetworkRuleConflictException in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method createPublicLoadBalancerRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer")
public LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm, long networkId, long lbOwnerId, boolean openFirewall, String lbProtocol, Boolean forDisplay) throws NetworkRuleConflictException, InsufficientAddressCapacityException {
    Account lbOwner = _accountMgr.getAccount(lbOwnerId);
    if (srcPortStart != srcPortEnd) {
        throw new InvalidParameterValueException("Port ranges are not supported by the load balancer");
    }
    IPAddressVO ipVO = null;
    if (ipAddrId != null) {
        ipVO = _ipAddressDao.findById(ipAddrId);
    }
    Network network = _networkModel.getNetwork(networkId);
    // FIXME: breaking the dependency on ELB manager. This breaks
    // functionality of ELB using virtual router
    // Bug CS-15411 opened to document this
    // LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb,
    // lbOwner, lb.getNetworkId());
    LoadBalancer result = null;
    IpAddress systemIp = null;
    NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
    if (srcPortStart == DNS_PORT && ipVO.isSourceNat()) {
        List<NetworkOfferingServiceMapVO> offeringServices = _networkOfferingServiceDao.listByNetworkOfferingId(network.getNetworkOfferingId());
        for (NetworkOfferingServiceMapVO serviceMapVo : offeringServices) {
            if (serviceMapVo.getService().equals(Service.Dns.getName())) {
                throw new InvalidParameterValueException("Error adding load balancer rule, cannot add port 53 with network service offering having DNS service and Source NAT.");
            }
        }
    }
    if (off.isElasticLb() && ipVO == null && network.getVpcId() == null) {
        systemIp = _ipAddrMgr.assignSystemIp(networkId, lbOwner, true, false);
        if (systemIp != null) {
            ipVO = _ipAddressDao.findById(systemIp.getId());
        }
    }
    // Validate ip address
    if (ipVO == null) {
        throw new InvalidParameterValueException("Unable to create load balance rule; can't find/allocate source IP");
    } else if (ipVO.isOneToOneNat()) {
        throw new NetworkRuleConflictException("Can't do load balance on ip address: " + ipVO.getAddress());
    }
    boolean performedIpAssoc = false;
    try {
        if (ipVO.getAssociatedWithNetworkId() == null) {
            boolean assignToVpcNtwk = network.getVpcId() != null && ipVO.getVpcId() != null && ipVO.getVpcId().longValue() == network.getVpcId();
            if (assignToVpcNtwk) {
                // set networkId just for verification purposes
                _networkModel.checkIpForService(ipVO, Service.Lb, networkId);
                s_logger.debug("The ip is not associated with the VPC network id=" + networkId + " so assigning");
                ipVO = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
                performedIpAssoc = true;
            }
        } else {
            _networkModel.checkIpForService(ipVO, Service.Lb, null);
        }
        if (ipVO.getAssociatedWithNetworkId() == null) {
            throw new InvalidParameterValueException("Ip address " + ipVO + " is not assigned to the network " + network);
        }
        result = createPublicLoadBalancer(xId, name, description, srcPortStart, defPortStart, ipVO.getId(), protocol, algorithm, openFirewall, CallContext.current(), lbProtocol, forDisplay);
    } catch (Exception ex) {
        s_logger.warn("Failed to create load balancer due to ", ex);
        if (ex instanceof NetworkRuleConflictException) {
            throw (NetworkRuleConflictException) ex;
        }
        if (ex instanceof InvalidParameterValueException) {
            throw (InvalidParameterValueException) ex;
        }
    } finally {
        if (result == null && systemIp != null) {
            s_logger.debug("Releasing system IP address " + systemIp + " as corresponding lb rule failed to create");
            _ipAddrMgr.handleSystemIpRelease(systemIp);
        }
        // release ip address if ipassoc was perfored
        if (performedIpAssoc) {
            ipVO = _ipAddressDao.findById(ipVO.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ipVO.getId(), networkId);
        }
    }
    if (result == null) {
        throw new CloudRuntimeException("Failed to create load balancer rule: " + name);
    }
    return result;
}
Also used : Account(com.cloud.user.Account) NetworkOfferingServiceMapVO(com.cloud.offerings.NetworkOfferingServiceMapVO) NetworkOffering(com.cloud.offering.NetworkOffering) LoadBalancer(com.cloud.network.rules.LoadBalancer) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress) ActionEvent(com.cloud.event.ActionEvent)

Example 82 with NetworkRuleConflictException

use of com.cloud.exception.NetworkRuleConflictException in project cloudstack by apache.

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(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 (FirewallRuleVO newRule : rules) {
            _firewallMgr.detectRulesConflict(newRule);
        }
        success = true;
        return rules;
    } finally {
        if (!success) {
            Transaction.execute(new TransactionCallbackNoReturn() {

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

Example 83 with NetworkRuleConflictException

use of com.cloud.exception.NetworkRuleConflictException in project cloudstack by apache.

the class RulesManagerImpl method createPortForwardingRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true)
public PortForwardingRule createPortForwardingRule(final PortForwardingRule rule, final Long vmId, Ip vmIp, final boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
    CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final Long ipAddrId = rule.getSourceIpAddressId();
    IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
    // Validate ip address
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
    } else if (ipAddress.isOneToOneNat()) {
        throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
    }
    final Long networkId = rule.getNetworkId();
    Network network = _networkModel.getNetwork(networkId);
    // associate ip address to network (if needed)
    boolean performedIpAssoc = false;
    Nic guestNic;
    if (ipAddress.getAssociatedWithNetworkId() == null) {
        boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
        if (assignToVpcNtwk) {
            _networkModel.checkIpForService(ipAddress, Service.PortForwarding, networkId);
            s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
            try {
                ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
                performedIpAssoc = true;
            } catch (Exception ex) {
                throw new CloudRuntimeException("Failed to associate ip to VPC network as " + "a part of port forwarding rule creation");
            }
        }
    } else {
        _networkModel.checkIpForService(ipAddress, Service.PortForwarding, null);
    }
    if (ipAddress.getAssociatedWithNetworkId() == null) {
        throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
    }
    try {
        _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User, networkId, rule.getTrafficType());
        final Long accountId = ipAddress.getAllocatedToAccountId();
        final Long domainId = ipAddress.getAllocatedInDomainId();
        // start port can't be bigger than end port
        if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
            throw new InvalidParameterValueException("Start port can't be bigger than end port");
        }
        // check that the port ranges are of equal size
        if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
            throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
        }
        // validate user VM exists
        UserVm vm = _vmDao.findById(vmId);
        if (vm == null) {
            throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ").");
        } else if (vm.getState() == VirtualMachine.State.Destroyed || vm.getState() == VirtualMachine.State.Expunging) {
            throw new InvalidParameterValueException("Invalid user vm: " + vm.getId());
        }
        // Verify that vm has nic in the network
        Ip dstIp = rule.getDestinationIpAddress();
        guestNic = _networkModel.getNicInNetwork(vmId, networkId);
        if (guestNic == null || guestNic.getIPv4Address() == null) {
            throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
        } else {
            dstIp = new Ip(guestNic.getIPv4Address());
        }
        if (vmIp != null) {
            // vm ip is passed so it can be primary or secondary ip addreess.
            if (!dstIp.equals(vmIp)) {
                // the vm ip is secondary ip to the nic.
                // is vmIp is secondary ip or not
                NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmIp.toString(), guestNic.getId());
                if (secondaryIp == null) {
                    throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
                }
                dstIp = vmIp;
            }
        }
        // if start port and end port are passed in, and they are not equal to each other, perform the validation
        boolean validatePortRange = false;
        if (rule.getSourcePortStart().intValue() != rule.getSourcePortEnd().intValue() || rule.getDestinationPortStart() != rule.getDestinationPortEnd()) {
            validatePortRange = true;
        }
        if (validatePortRange) {
            // source start port and source dest port should be the same. The same applies to dest ports
            if (rule.getSourcePortStart().intValue() != rule.getDestinationPortStart()) {
                throw new InvalidParameterValueException("Private port start should be equal to public port start");
            }
            if (rule.getSourcePortEnd().intValue() != rule.getDestinationPortEnd()) {
                throw new InvalidParameterValueException("Private port end should be equal to public port end");
            }
        }
        final Ip dstIpFinal = dstIp;
        final IPAddressVO ipAddressFinal = ipAddress;
        return Transaction.execute(new TransactionCallbackWithException<PortForwardingRuleVO, NetworkRuleConflictException>() {

            @Override
            public PortForwardingRuleVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
                PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIpFinal, rule.getDestinationPortStart(), rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
                if (forDisplay != null) {
                    newRule.setDisplay(forDisplay);
                }
                newRule = _portForwardingDao.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());
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), ipAddressFinal.getDataCenterId(), newRule.getId(), null, PortForwardingRule.class.getName(), newRule.getUuid());
                    return newRule;
                } catch (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);
                        removePFRule(newRule);
                    }
                    if (e instanceof NetworkRuleConflictException) {
                        throw (NetworkRuleConflictException) e;
                    }
                    throw new CloudRuntimeException("Unable to add rule for the ip id=" + ipAddrId, e);
                }
            }
        });
    } finally {
        // release ip address if ipassoc was perfored
        if (performedIpAssoc) {
            // if the rule is the last one for the ip address assigned to VPC, unassign it from the network
            IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
        }
    }
}
Also used : Account(com.cloud.user.Account) Ip(com.cloud.utils.net.Ip) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) Nic(com.cloud.vm.Nic) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(org.apache.cloudstack.context.CallContext) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 84 with NetworkRuleConflictException

use of com.cloud.exception.NetworkRuleConflictException in project cloudstack by apache.

the class AddBaremetalDhcpCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
    try {
        BaremetalDhcpVO vo = mgr.addDchpServer(this);
        BaremetalDhcpResponse response = mgr.generateApiResponse(vo);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    } catch (Exception e) {
        s_logger.warn("Unable to add external dhcp server with url: " + getUrl(), e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : BaremetalDhcpVO(com.cloud.baremetal.database.BaremetalDhcpVO) BaremetalDhcpResponse(com.cloud.baremetal.networkservice.BaremetalDhcpResponse) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException)

Example 85 with NetworkRuleConflictException

use of com.cloud.exception.NetworkRuleConflictException in project cloudstack by apache.

the class BaremetalProvisionDoneNotificationCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
    try {
        bmMgr.notifyProvisionDone(this);
        this.setResponseObject(new SuccessResponse(getCommandName()));
    } catch (Exception e) {
        s_logger.warn(String.format("unable to notify baremetal provision done[mac:%s]", mac), e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
    }
}
Also used : SuccessResponse(org.apache.cloudstack.api.response.SuccessResponse) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException)

Aggregations

NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)85 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)41 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)28 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)26 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)26 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)25 ServerApiException (org.apache.cloudstack.api.ServerApiException)25 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)19 ServerApiException (com.cloud.api.ServerApiException)18 Network (com.cloud.network.Network)18 IPAddressVO (com.cloud.network.dao.IPAddressVO)17 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)16 TransactionStatus (com.cloud.utils.db.TransactionStatus)16 DB (com.cloud.utils.db.DB)15 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)14 SuccessResponse (org.apache.cloudstack.api.response.SuccessResponse)13 Account (com.cloud.user.Account)12 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)11 IpAddress (com.cloud.network.IpAddress)10 ActionEvent (com.cloud.event.ActionEvent)8