Search in sources :

Example 11 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cloudstack by apache.

the class AddIpToVmNicCmd method create.

@Override
public void create() throws ResourceAllocationException {
    NicSecondaryIp result;
    IpAddresses requestedIpPair = new IpAddresses(ipAddr, null);
    if (!NetUtils.isIpv4(ipAddr)) {
        requestedIpPair = new IpAddresses(null, ipAddr);
    }
    try {
        result = _networkService.allocateSecondaryGuestIP(getNicId(), requestedIpPair);
        if (result != null) {
            setEntityId(result.getId());
            setEntityUuid(result.getUuid());
        }
    } catch (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 : IpAddresses(com.cloud.network.Network.IpAddresses) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) NicSecondaryIp(com.cloud.vm.NicSecondaryIp)

Example 12 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cloudstack by apache.

the class AddIpToVmNicTest method testCreateSuccess.

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

Example 13 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cloudstack by apache.

the class ApiResponseHelperTest method setResponseIpAddressTestIpv6.

@Test
public void setResponseIpAddressTestIpv6() {
    NicSecondaryIp result = Mockito.mock(NicSecondaryIp.class);
    NicSecondaryIpResponse response = new NicSecondaryIpResponse();
    setResult(result, null, "ipv6");
    ApiResponseHelper.setResponseIpAddress(result, response);
    assertTrue(response.getIpAddr().equals("ipv6"));
}
Also used : NicSecondaryIpResponse(org.apache.cloudstack.api.response.NicSecondaryIpResponse) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 14 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp in project cloudstack by apache.

the class ApiResponseHelperTest method setResponseIpAddressTestIpv4.

@Test
public void setResponseIpAddressTestIpv4() {
    NicSecondaryIp result = Mockito.mock(NicSecondaryIp.class);
    NicSecondaryIpResponse response = new NicSecondaryIpResponse();
    setResult(result, "ipv4", "ipv6");
    ApiResponseHelper.setResponseIpAddress(result, response);
    assertTrue(response.getIpAddr().equals("ipv4"));
}
Also used : NicSecondaryIpResponse(org.apache.cloudstack.api.response.NicSecondaryIpResponse) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 15 with NicSecondaryIp

use of com.cloud.vm.NicSecondaryIp 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)

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