Search in sources :

Example 6 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cosmic by MissionCriticalCloud.

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, final Ip vmIp, final boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
    final 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();
    final Network network = _networkModel.getNetwork(networkId);
    // associate ip address to network (if needed)
    boolean performedIpAssoc = false;
    final Nic guestNic;
    if (ipAddress.getAssociatedWithNetworkId() == null) {
        final 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 (final 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
        final 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
                final 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(final 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());
                    return newRule;
                } 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);
                        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
            final 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(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.utils.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 7 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method updatePortForwardingRule.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_MODIFY, eventDescription = "updating forwarding rule", async = true)
public PortForwardingRule updatePortForwardingRule(final long id, final Integer privatePort, final Long virtualMachineId, final Ip vmGuestIp, final String customId, final Boolean forDisplay) {
    final Account caller = CallContext.current().getCallingAccount();
    PortForwardingRuleVO rule = _portForwardingDao.findById(id);
    if (rule == null) {
        throw new InvalidParameterValueException("Unable to find " + id);
    }
    _accountMgr.checkAccess(caller, null, true, rule);
    if (customId != null) {
        rule.setUuid(customId);
    }
    if (forDisplay != null) {
        rule.setDisplay(forDisplay);
    }
    if (!rule.getSourcePortStart().equals(rule.getSourcePortEnd()) && privatePort != null) {
        throw new InvalidParameterValueException("Unable to update the private port of port forwarding rule as  the rule has port range : " + rule.getSourcePortStart() + " " + "to " + rule.getSourcePortEnd());
    }
    if (virtualMachineId == null && vmGuestIp != null) {
        throw new InvalidParameterValueException("vmguestip should be set along with virtualmachineid");
    }
    Ip dstIp = rule.getDestinationIpAddress();
    if (virtualMachineId != null) {
        // Verify that vm has nic in the network
        final Nic guestNic = _networkModel.getNicInNetwork(virtualMachineId, rule.getNetworkId());
        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 (vmGuestIp != null) {
            // vm ip is passed so it can be primary or secondary ip addreess.
            if (!dstIp.equals(vmGuestIp)) {
                // the vm ip is secondary ip to the nic.
                // is vmIp is secondary ip or not
                final NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp.toString(), guestNic.getId());
                if (secondaryIp == null) {
                    throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
                }
                dstIp = vmGuestIp;
            }
        }
    }
    // revoke old rules at first
    final List<PortForwardingRuleVO> rules = new ArrayList<>();
    rule.setState(State.Revoke);
    _portForwardingDao.update(id, rule);
    rules.add(rule);
    try {
        if (!_firewallMgr.applyRules(rules, true, false)) {
            throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id);
        }
    } catch (final ResourceUnavailableException ex) {
        throw new CloudRuntimeException("Failed to revoke the existing port forwarding rule:" + id + " due to ", ex);
    }
    rule = _portForwardingDao.findById(id);
    rule.setState(State.Add);
    if (privatePort != null) {
        rule.setDestinationPortStart(privatePort.intValue());
        rule.setDestinationPortEnd(privatePort.intValue());
    }
    if (virtualMachineId != null) {
        rule.setVirtualMachineId(virtualMachineId);
        rule.setDestinationIpAddress(dstIp);
    }
    _portForwardingDao.update(id, rule);
    // apply new rules
    if (!applyPortForwardingRules(rule.getSourceIpAddressId(), false, caller)) {
        throw new CloudRuntimeException("Failed to apply the new port forwarding rule:" + id);
    }
    return _portForwardingDao.findById(id);
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Ip(com.cloud.utils.net.Ip) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Nic(com.cloud.vm.Nic) ActionEvent(com.cloud.event.ActionEvent)

Example 8 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicCmd method create.

@Override
public void create() {
    final String ip;
    final NicSecondaryIp result;
    if ((ip = getIpaddress()) != null) {
        if (!NetUtils.isValidIp4(ip)) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Invalid ip address " + ip);
        }
    }
    try {
        result = _networkService.allocateSecondaryGuestIP(getNicId(), getIpaddress());
        if (result != null) {
            setEntityId(result.getId());
            setEntityUuid(result.getUuid());
        }
    } catch (final InsufficientAddressCapacityException e) {
        throw new InvalidParameterValueException("Allocating guest ip for nic failed : " + e.getMessage());
    }
    if (result == null) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign secondary ip to nic");
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) NicSecondaryIp(com.cloud.vm.NicSecondaryIp)

Example 9 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    CallContext.current().setEventDetails("Nic Id: " + getNicId());
    final NicSecondaryIp result = _entityMgr.findById(NicSecondaryIp.class, getEntityId());
    if (result != null) {
        CallContext.current().setEventDetails("secondary Ip Id: " + getEntityId());
        boolean success;
        success = _networkService.configureNicSecondaryIp(result);
        if (!success) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to set security group rules for the secondary ip");
        }
        final NicSecondaryIpResponse response = _responseGenerator.createSecondaryIPToNicResponse(result);
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to assign secondary ip to nic");
    }
}
Also used : NicSecondaryIpResponse(com.cloud.api.response.NicSecondaryIpResponse) ServerApiException(com.cloud.api.ServerApiException) NicSecondaryIp(com.cloud.vm.NicSecondaryIp)

Example 10 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicTest method testCreateSuccess.

@Test
public void testCreateSuccess() throws ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException {
    final NetworkService networkService = Mockito.mock(NetworkService.class);
    final AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);
    final NicSecondaryIp secIp = Mockito.mock(NicSecondaryIp.class);
    Mockito.when(networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.anyString())).thenReturn(secIp);
    ipTonicCmd._networkService = networkService;
    responseGenerator = Mockito.mock(ResponseGenerator.class);
    final NicSecondaryIpResponse ipres = Mockito.mock(NicSecondaryIpResponse.class);
    Mockito.when(responseGenerator.createSecondaryIPToNicResponse(secIp)).thenReturn(ipres);
    ipTonicCmd._responseGenerator = responseGenerator;
    ipTonicCmd.execute();
}
Also used : NicSecondaryIpResponse(com.cloud.api.response.NicSecondaryIpResponse) AddIpToVmNicCmd(com.cloud.api.command.user.vm.AddIpToVmNicCmd) ResponseGenerator(com.cloud.api.ResponseGenerator) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) NetworkService(com.cloud.network.NetworkService) Test(org.junit.Test)

Aggregations

NicSecondaryIp (com.cloud.vm.NicSecondaryIp)15 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)5 Nic (com.cloud.vm.Nic)5 NicSecondaryIpResponse (org.apache.cloudstack.api.response.NicSecondaryIpResponse)5 ActionEvent (com.cloud.event.ActionEvent)4 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)4 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)4 Account (com.cloud.user.Account)4 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)4 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)4 Ip (com.cloud.utils.net.Ip)4 ServerApiException (org.apache.cloudstack.api.ServerApiException)4 Test (org.junit.Test)4 ServerApiException (com.cloud.api.ServerApiException)3 ArrayList (java.util.ArrayList)3 NicSecondaryIpResponse (com.cloud.api.response.NicSecondaryIpResponse)2 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)2 IpAddress (com.cloud.network.IpAddress)2 Network (com.cloud.network.Network)2 NetworkService (com.cloud.network.NetworkService)2