Search in sources :

Example 71 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class RulesManagerImpl method disableStaticNat.

@Override
public boolean disableStaticNat(long ipId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException {
    boolean success = true;
    IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
    checkIpAndUserVm(ipAddress, null, caller, false);
    long networkId = ipAddress.getAssociatedWithNetworkId();
    if (!ipAddress.isOneToOneNat()) {
        InvalidParameterValueException ex = new InvalidParameterValueException("One to one nat is not enabled for the specified ip id");
        ex.addProxyObject(ipAddress.getUuid(), "ipId");
        throw ex;
    }
    ipAddress.setRuleState(IpAddress.State.Releasing);
    _ipAddressDao.update(ipAddress.getId(), ipAddress);
    ipAddress = _ipAddressDao.findById(ipId);
    // Revoke all firewall rules for the ip
    try {
        s_logger.debug("Revoking all " + Purpose.Firewall + "rules as a part of disabling static nat for public IP id=" + ipId);
        if (!_firewallMgr.revokeFirewallRulesForIp(ipId, callerUserId, caller)) {
            s_logger.warn("Unable to revoke all the firewall rules for ip id=" + ipId + " as a part of disable statis nat");
            success = false;
        }
    } catch (ResourceUnavailableException e) {
        s_logger.warn("Unable to revoke all firewall rules for ip id=" + ipId + " as a part of ip release", e);
        success = false;
    }
    if (!revokeAllPFAndStaticNatRulesForIp(ipId, callerUserId, caller)) {
        s_logger.warn("Unable to revoke all static nat rules for ip " + ipAddress);
        success = false;
    }
    if (success) {
        boolean isIpSystem = ipAddress.getSystem();
        ipAddress.setOneToOneNat(false);
        ipAddress.setAssociatedWithVmId(null);
        ipAddress.setRuleState(null);
        ipAddress.setVmIp(null);
        if (isIpSystem && !releaseIpIfElastic) {
            ipAddress.setSystem(false);
        }
        _ipAddressDao.update(ipAddress.getId(), ipAddress);
        _vpcMgr.unassignIPFromVpcNetwork(ipAddress.getId(), networkId);
        if (isIpSystem && releaseIpIfElastic && !_ipAddrMgr.handleSystemIpRelease(ipAddress)) {
            s_logger.warn("Failed to release system ip address " + ipAddress);
            success = false;
        }
        return true;
    } else {
        s_logger.warn("Failed to disable one to one nat for the ip address id" + ipId);
        ipAddress = _ipAddressDao.findById(ipId);
        ipAddress.setRuleState(null);
        _ipAddressDao.update(ipAddress.getId(), ipAddress);
        return false;
    }
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 72 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class RulesManagerImpl method listPortForwardingRules.

@Override
public Pair<List<? extends PortForwardingRule>, Integer> listPortForwardingRules(ListPortForwardingRulesCmd cmd) {
    Long ipId = cmd.getIpAddressId();
    Long id = cmd.getId();
    Map<String, String> tags = cmd.getTags();
    Long networkId = cmd.getNetworkId();
    Boolean display = cmd.getDisplay();
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    if (ipId != null) {
        IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
        if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
            throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet");
        }
        _accountMgr.checkAccess(caller, null, true, ipAddressVO);
    }
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<PortForwardingRuleVO> sb = _portForwardingDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), Op.EQ);
    sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
    sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
    sb.and("display", sb.entity().isDisplay(), Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<PortForwardingRuleVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.PortForwardingRule.toString());
        for (String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (ipId != null) {
        sc.setParameters("ip", ipId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    sc.setParameters("purpose", Purpose.PortForwarding);
    Pair<List<PortForwardingRuleVO>, Integer> result = _portForwardingDao.searchAndCount(sc, filter);
    return new Pair<List<? extends PortForwardingRule>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair)

Example 73 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO 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) 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 74 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class RulesManagerImpl method searchStaticNatRules.

@Override
public Pair<List<? extends FirewallRule>, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) {
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    if (ipId != null) {
        IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
        if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
            throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet");
        }
        _accountMgr.checkAccess(caller, null, true, ipAddressVO);
    }
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
    _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
    domainId = domainIdRecursiveListProject.first();
    isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size);
    SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
    sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
    sb.and("id", sb.entity().getId(), Op.EQ);
    if (vmId != null) {
        SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
        ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ);
        sb.join("ipSearch", ipSearch, sb.entity().getSourceIpAddressId(), ipSearch.entity().getId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<FirewallRuleVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sc.setParameters("purpose", Purpose.StaticNat);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (ipId != null) {
        sc.setParameters("ip", ipId);
    }
    if (vmId != null) {
        sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId);
    }
    Pair<List<FirewallRuleVO>, Integer> result = _firewallDao.searchAndCount(sc, filter);
    return new Pair<List<? extends FirewallRule>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair)

Example 75 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class RulesManagerImpl method applyStaticNatsForNetwork.

@Override
public boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller) {
    List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(networkId);
    if (ips.isEmpty()) {
        s_logger.debug("There are no static nat to apply for network id=" + networkId);
        return true;
    }
    if (caller != null) {
        _accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()]));
    }
    List<StaticNat> staticNats = new ArrayList<StaticNat>();
    for (IPAddressVO ip : ips) {
        // Get nic IP4 address
        //String dstIp = _networkModel.getIpInNetwork(ip.getAssociatedWithVmId(), networkId);
        StaticNatImpl staticNat = new StaticNatImpl(ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), networkId, ip.getId(), ip.getVmIp(), false);
        staticNats.add(staticNat);
    }
    try {
        if (!_ipAddrMgr.applyStaticNats(staticNats, continueOnError, false)) {
            return false;
        }
    } catch (ResourceUnavailableException ex) {
        s_logger.warn("Failed to create static nat for network due to ", ex);
        return false;
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Aggregations

IPAddressVO (com.cloud.network.dao.IPAddressVO)109 ArrayList (java.util.ArrayList)43 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)42 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)39 Account (com.cloud.user.Account)37 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 DB (com.cloud.utils.db.DB)28 TransactionStatus (com.cloud.utils.db.TransactionStatus)26 Network (com.cloud.network.Network)25 PublicIp (com.cloud.network.addr.PublicIp)22 DataCenter (com.cloud.dc.DataCenter)17 VlanVO (com.cloud.dc.VlanVO)16 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)16 List (java.util.List)15 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)14 Ip (com.cloud.utils.net.Ip)14 NetworkOffering (com.cloud.offering.NetworkOffering)13 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)13 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)12 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)11