Search in sources :

Example 36 with IpAddressTO

use of com.cloud.agent.api.to.IpAddressTO in project cloudstack by apache.

the class NotAValidCommand method testIpAssocCommand.

@Test
public void testIpAssocCommand() {
    final VirtualRoutingResource routingResource = Mockito.mock(VirtualRoutingResource.class);
    final IpAddressTO[] ips = new IpAddressTO[0];
    final IpAssocCommand ipAssociation = new IpAssocCommand(ips);
    final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
    assertNotNull(wrapper);
    when(citrixResourceBase.getVirtualRoutingResource()).thenReturn(routingResource);
    final Answer answer = wrapper.execute(ipAssociation, citrixResourceBase);
    verify(routingResource, times(1)).executeRequest(ipAssociation);
    // Requires more testing, but the VirtualResourceRouting is quite big.
    assertNull(answer);
}
Also used : RebootAnswer(com.cloud.agent.api.RebootAnswer) CreateAnswer(com.cloud.agent.api.storage.CreateAnswer) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) Answer(com.cloud.agent.api.Answer) IpAddressTO(com.cloud.agent.api.to.IpAddressTO) IpAssocCommand(com.cloud.agent.api.routing.IpAssocCommand) VirtualRoutingResource(com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource) Test(org.junit.Test)

Example 37 with IpAddressTO

use of com.cloud.agent.api.to.IpAddressTO in project cloudstack by apache.

the class CitrixResourceBase method cleanupNetworkElementCommand.

protected ExecutionResult cleanupNetworkElementCommand(final IpAssocCommand cmd) {
    final Connection conn = getConnection();
    final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
    final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
    final String lastIp = cmd.getAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP);
    try {
        final IpAddressTO[] ips = cmd.getIpAddresses();
        final int ipsCount = ips.length;
        for (final IpAddressTO ip : ips) {
            final VM router = getVM(conn, routerName);
            final NicTO nic = new NicTO();
            nic.setMac(ip.getVifMacAddress());
            nic.setType(ip.getTrafficType());
            if (ip.getBroadcastUri() == null) {
                nic.setBroadcastType(BroadcastDomainType.Native);
            } else {
                final URI uri = BroadcastDomainType.fromString(ip.getBroadcastUri());
                nic.setBroadcastType(BroadcastDomainType.getSchemeValue(uri));
                nic.setBroadcastUri(uri);
            }
            nic.setDeviceId(0);
            nic.setNetworkRateMbps(ip.getNetworkRate());
            nic.setName(ip.getNetworkName());
            Network network = getNetwork(conn, nic);
            // If we are disassociating the last IP address in the VLAN, we
            // need
            // to remove a VIF
            boolean removeVif = false;
            // remove the nic
            if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(lastIp, "true") && !ip.isAdd()) {
                final VIF correctVif = getCorrectVif(conn, router, network);
                // in isolated network eth2 is the default public interface. We don't want to delete it.
                if (correctVif != null && !correctVif.getDevice(conn).equals("2")) {
                    removeVif = true;
                }
            }
            if (removeVif) {
                // Determine the correct VIF on DomR to
                // associate/disassociate the
                // IP address with
                final VIF correctVif = getCorrectVif(conn, router, network);
                if (correctVif != null) {
                    network = correctVif.getNetwork(conn);
                    // Mark this vif to be removed from network usage
                    networkUsage(conn, routerIp, "deleteVif", "eth" + correctVif.getDevice(conn));
                    // Remove the VIF from DomR
                    correctVif.unplug(conn);
                    correctVif.destroy(conn);
                    // Disable the VLAN network if necessary
                    disableVlanNetwork(conn, network);
                }
            }
        }
    } catch (final Exception e) {
        s_logger.debug("Ip Assoc failure on applying one ip due to exception:  ", e);
        return new ExecutionResult(false, e.getMessage());
    }
    return new ExecutionResult(true, null);
}
Also used : IpAddressTO(com.cloud.agent.api.to.IpAddressTO) Connection(com.xensource.xenapi.Connection) URLConnection(java.net.URLConnection) ExecutionResult(com.cloud.utils.ExecutionResult) URI(java.net.URI) XenAPIException(com.xensource.xenapi.Types.XenAPIException) XmlRpcException(org.apache.xmlrpc.XmlRpcException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) SAXException(org.xml.sax.SAXException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) MalformedURLException(java.net.MalformedURLException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) VIF(com.xensource.xenapi.VIF) VM(com.xensource.xenapi.VM) Network(com.xensource.xenapi.Network) NicTO(com.cloud.agent.api.to.NicTO)

Example 38 with IpAddressTO

use of com.cloud.agent.api.to.IpAddressTO in project cloudstack by apache.

the class JuniperSrxResource method execute.

private Answer execute(IpAssocCommand cmd, int numRetries) {
    String[] results = new String[cmd.getIpAddresses().length];
    int i = 0;
    try {
        IpAddressTO ip;
        if (cmd.getIpAddresses().length != 1) {
            throw new ExecutionException("Received an invalid number of guest IPs to associate.");
        } else {
            ip = cmd.getIpAddresses()[0];
        }
        String sourceNatIpAddress = null;
        GuestNetworkType type = GuestNetworkType.INTERFACE_NAT;
        if (ip.isSourceNat()) {
            type = GuestNetworkType.SOURCE_NAT;
            if (ip.getPublicIp() == null) {
                throw new ExecutionException("Source NAT IP address must not be null.");
            } else {
                sourceNatIpAddress = ip.getPublicIp();
            }
        }
        long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG));
        String guestVlanGateway = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY);
        String cidr = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR);
        long cidrSize = NetUtils.cidrToLong(cidr)[1];
        String guestVlanSubnet = NetUtils.getCidrSubNet(guestVlanGateway, cidrSize);
        Long publicVlanTag = null;
        if (ip.getBroadcastUri() != null && !ip.getBroadcastUri().equals("untagged")) {
            try {
                publicVlanTag = Long.parseLong(BroadcastDomainType.getValue(ip.getBroadcastUri()));
            } catch (Exception e) {
                throw new ExecutionException("Could not parse public VLAN tag: " + ip.getBroadcastUri());
            }
        }
        openConfiguration();
        // Remove the guest network:
        // Remove source, static, and destination NAT rules
        // Remove VPN
        shutdownGuestNetwork(type, ip.getAccountId(), publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize);
        if (ip.isAdd()) {
            // Implement the guest network for this VLAN
            implementGuestNetwork(type, publicVlanTag, sourceNatIpAddress, guestVlanTag, guestVlanGateway, guestVlanSubnet, cidrSize);
        }
        commitConfiguration();
        results[i++] = ip.getPublicIp() + " - success";
    } catch (ExecutionException e) {
        s_logger.error(e);
        closeConfiguration();
        if (numRetries > 0 && refreshSrxConnection()) {
            int numRetriesRemaining = numRetries - 1;
            s_logger.debug("Retrying IPAssocCommand. Number of retries remaining: " + numRetriesRemaining);
            return execute(cmd, numRetriesRemaining);
        } else {
            results[i++] = IpAssocAnswer.errorResult;
        }
    }
    return new IpAssocAnswer(cmd, results);
}
Also used : IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) IpAddressTO(com.cloud.agent.api.to.IpAddressTO) ExecutionException(com.cloud.utils.exception.ExecutionException) ExecutionException(com.cloud.utils.exception.ExecutionException) ConfigurationException(javax.naming.ConfigurationException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Example 39 with IpAddressTO

use of com.cloud.agent.api.to.IpAddressTO in project cloudstack by apache.

the class ExternalFirewallDeviceManagerImpl method manageGuestNetworkWithExternalFirewall.

@Override
public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network) throws ResourceUnavailableException, InsufficientCapacityException {
    if (network.getTrafficType() != TrafficType.Guest) {
        s_logger.trace("External firewall can only be used for add/remove guest networks.");
        return false;
    }
    long zoneId = network.getDataCenterId();
    DataCenterVO zone = _dcDao.findById(zoneId);
    HostVO externalFirewall = null;
    if (add) {
        GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap");
        try {
            if (deviceMapLock.lock(120)) {
                try {
                    ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network);
                    long externalFirewallId = device.getId();
                    NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId);
                    _networkExternalFirewallDao.persist(networkFW);
                    externalFirewall = _hostDao.findById(device.getHostId());
                } finally {
                    deviceMapLock.unlock();
                }
            }
        } finally {
            deviceMapLock.releaseRef();
        }
    } else {
        ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
        if (fwDeviceVO == null) {
            s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed.");
            return true;
        }
        externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
    }
    Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId());
    NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    boolean sharedSourceNat = offering.getSharedSourceNat();
    IPAddressVO sourceNatIp = null;
    if (!sharedSourceNat) {
        // Get the source NAT IP address for this network
        List<? extends IpAddress> sourceNatIps = _networkModel.listPublicIpsAssignedToAccount(network.getAccountId(), zoneId, true);
        for (IpAddress ipAddress : sourceNatIps) {
            if (ipAddress.getAssociatedWithNetworkId().longValue() == network.getId()) {
                sourceNatIp = _ipAddressDao.findById(ipAddress.getId());
                break;
            }
        }
        if (sourceNatIp == null) {
            String errorMsg = "External firewall was unable to find the source NAT IP address for network " + network.getName();
            s_logger.error(errorMsg);
            return true;
        }
    }
    // Send a command to the external firewall to implement or shutdown the guest network
    long guestVlanTag = Long.parseLong(BroadcastDomainType.getValue(network.getBroadcastUri()));
    String guestVlanGateway = network.getGateway();
    String guestVlanCidr = network.getCidr();
    String sourceNatIpAddress = null;
    String publicVlanTag = null;
    if (sourceNatIp != null) {
        sourceNatIpAddress = sourceNatIp.getAddress().addr();
        VlanVO publicVlan = _vlanDao.findById(sourceNatIp.getVlanId());
        publicVlanTag = publicVlan.getVlanTag();
    }
    // Get network rate
    Integer networkRate = _networkModel.getNetworkRate(network.getId(), null);
    IpAddressTO ip = new IpAddressTO(account.getAccountId(), sourceNatIpAddress, add, false, !sharedSourceNat, publicVlanTag, null, null, null, networkRate, false);
    IpAddressTO[] ips = new IpAddressTO[1];
    ips[0] = ip;
    IpAssocCommand cmd = new IpAssocCommand(ips);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, guestVlanGateway);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, guestVlanCidr);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
    Answer answer = _agentMgr.easySend(externalFirewall.getId(), cmd);
    List<String> reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId());
    if (answer == null || !answer.getResult()) {
        String action = add ? "implement" : "shutdown";
        String answerDetails = (answer != null) ? answer.getDetails() : "answer was null";
        String msg = "External firewall was unable to " + action + " the guest network on the external firewall in zone " + zone.getName() + " due to " + answerDetails;
        s_logger.error(msg);
        if (!add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
            // If we failed the implementation as well, then just return, no complain
            s_logger.error("Skip the shutdown of guest network on SRX because it seems we didn't implement it as well");
            return true;
        }
        throw new ResourceUnavailableException(msg, DataCenter.class, zoneId);
    }
    if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
        // Insert a new NIC for this guest network to reserve the gateway address
        _networkMgr.savePlaceholderNic(network, network.getGateway(), null, null);
    }
    // Delete any mappings used for inline external load balancers in this network
    List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(network.getId());
    for (NicVO nic : nicsInNetwork) {
        InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId());
        if (mapping != null) {
            _nicDao.expunge(mapping.getNicId());
            _inlineLoadBalancerNicMapDao.expunge(mapping.getId());
        }
    }
    // on network shutdown, delete placeHolder nics used for the firewall device
    if (!add) {
        List<NicVO> nics = _nicDao.listByNetworkId(network.getId());
        for (NicVO nic : nics) {
            if (nic.getVmType() == null && nic.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && nic.getIPv4Address().equals(network.getGateway())) {
                s_logger.debug("Removing placeholder nic " + nic + " for the network " + network);
                _nicDao.remove(nic.getId());
            }
        }
        freeFirewallForNetwork(network);
    }
    String action = add ? "implemented" : "shut down";
    s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag);
    return true;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) ExternalFirewallDeviceVO(com.cloud.network.dao.ExternalFirewallDeviceVO) IpAddressTO(com.cloud.agent.api.to.IpAddressTO) NetworkOffering(com.cloud.offering.NetworkOffering) InlineLoadBalancerNicMapVO(com.cloud.network.dao.InlineLoadBalancerNicMapVO) HostVO(com.cloud.host.HostVO) GlobalLock(com.cloud.utils.db.GlobalLock) Answer(com.cloud.agent.api.Answer) NetworkExternalFirewallVO(com.cloud.network.dao.NetworkExternalFirewallVO) IpAssocCommand(com.cloud.agent.api.routing.IpAssocCommand) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) NicVO(com.cloud.vm.NicVO)

Example 40 with IpAddressTO

use of com.cloud.agent.api.to.IpAddressTO in project cloudstack by apache.

the class ConfigHelperTest method generateIpAssocVpcCommand.

protected IpAssocVpcCommand generateIpAssocVpcCommand() {
    final List<IpAddressTO> ips = new ArrayList<IpAddressTO>();
    IpAddressTO ip1 = new IpAddressTO(1, "64.1.1.10", true, true, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false);
    IpAddressTO ip2 = new IpAddressTO(2, "64.1.1.11", false, false, true, "vlan://64", "64.1.1.1", "255.255.255.0", "01:23:45:67:89:AB", 1000, false);
    IpAddressTO ip3 = new IpAddressTO(3, "65.1.1.11", true, false, false, "vlan://65", "65.1.1.1", "255.255.255.0", "11:23:45:67:89:AB", 1000, false);
    ip1.setTrafficType(TrafficType.Public);
    ip2.setTrafficType(TrafficType.Public);
    ip3.setTrafficType(TrafficType.Public);
    ips.add(ip1);
    ips.add(ip2);
    ips.add(ip3);
    final IpAddressTO[] ipArray = ips.toArray(new IpAddressTO[ips.size()]);
    final IpAssocVpcCommand cmd = new IpAssocVpcCommand(ipArray);
    cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, ROUTERNAME);
    // AnswersCount is clearly wrong as it doesn't know enough to tell
    assertEquals(6, cmd.getAnswersCount());
    return cmd;
}
Also used : IpAddressTO(com.cloud.agent.api.to.IpAddressTO) ArrayList(java.util.ArrayList) IpAssocVpcCommand(com.cloud.agent.api.routing.IpAssocVpcCommand)

Aggregations

IpAddressTO (com.cloud.agent.api.to.IpAddressTO)41 ExecutionResult (com.cloud.utils.ExecutionResult)16 InternalErrorException (com.cloud.exception.InternalErrorException)14 IOException (java.io.IOException)12 ConfigurationException (javax.naming.ConfigurationException)12 IpAssocAnswer (com.cloud.agent.api.routing.IpAssocAnswer)9 IpAssocCommand (com.cloud.agent.api.routing.IpAssocCommand)8 ArrayList (java.util.ArrayList)8 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)7 URISyntaxException (java.net.URISyntaxException)7 HashMap (java.util.HashMap)7 Answer (com.cloud.agent.api.Answer)6 ConnectException (java.net.ConnectException)6 RemoteException (java.rmi.RemoteException)6 IpAssocVpcCommand (com.cloud.agent.api.routing.IpAssocVpcCommand)5 URI (java.net.URI)5 Connect (org.libvirt.Connect)5 LibvirtException (org.libvirt.LibvirtException)5 DataCenterVO (com.cloud.dc.DataCenterVO)4 ExecutionException (com.cloud.utils.exception.ExecutionException)4