Search in sources :

Example 66 with IPAddressVO

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

the class ConfigurationManagerTest method runDedicatePublicIpRangeIPAdressAllocated.

void runDedicatePublicIpRangeIPAdressAllocated() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runDedicatePublicIpRangeIPAdressAllocated");
    when(configurationMgr._vlanDao.findById(anyLong())).thenReturn(vlan);
    when(configurationMgr._accountVlanMapDao.listAccountVlanMapsByAccount(anyLong())).thenReturn(null);
    DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", null, null, NetworkType.Advanced, null, null, true, true, null, null);
    when(configurationMgr._zoneDao.findById(anyLong())).thenReturn(dc);
    // one of the ip addresses of the range is allocated to different account
    List<IPAddressVO> ipAddressList = new ArrayList<IPAddressVO>();
    IPAddressVO ipAddress = new IPAddressVO(new Ip("75.75.75.75"), 1, 0xaabbccddeeffL, 10, false);
    ipAddress.setAllocatedToAccountId(1L);
    ipAddressList.add(ipAddress);
    when(configurationMgr._publicIpAddressDao.listByVlanId(anyLong())).thenReturn(ipAddressList);
    try {
        configurationMgr.dedicatePublicIpRange(dedicatePublicIpRangesCmd);
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("Public IP address in range is allocated to another account"));
    } finally {
        txn.close("runDedicatePublicIpRangeIPAdressAllocated");
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) IPAddressVO(com.cloud.network.dao.IPAddressVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 67 with IPAddressVO

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

the class ConfigurationManagerTest method runReleasePublicIpRangePostiveTest2.

void runReleasePublicIpRangePostiveTest2() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runReleasePublicIpRangePostiveTest2");
    when(configurationMgr._vlanDao.findById(anyLong())).thenReturn(vlan);
    List<AccountVlanMapVO> accountVlanMaps = new ArrayList<AccountVlanMapVO>();
    AccountVlanMapVO accountVlanMap = new AccountVlanMapVO(1, 1);
    accountVlanMaps.add(accountVlanMap);
    when(configurationMgr._accountVlanMapDao.listAccountVlanMapsByVlan(anyLong())).thenReturn(accountVlanMaps);
    when(configurationMgr._publicIpAddressDao.countIPs(anyLong(), anyLong(), anyBoolean())).thenReturn(1);
    List<IPAddressVO> ipAddressList = new ArrayList<IPAddressVO>();
    IPAddressVO ipAddress = new IPAddressVO(new Ip("75.75.75.75"), 1, 0xaabbccddeeffL, 10, false);
    ipAddressList.add(ipAddress);
    when(configurationMgr._publicIpAddressDao.listByVlanId(anyLong())).thenReturn(ipAddressList);
    when(configurationMgr._firewallDao.countRulesByIpId(anyLong())).thenReturn(0L);
    when(configurationMgr._ipAddrMgr.disassociatePublicIpAddress(anyLong(), anyLong(), any(Account.class))).thenReturn(true);
    when(configurationMgr._vlanDao.releaseFromLockTable(anyLong())).thenReturn(true);
    when(configurationMgr._accountVlanMapDao.remove(anyLong())).thenReturn(true);
    try {
        Boolean result = configurationMgr.releasePublicIpRange(releasePublicIpRangesCmd);
        Assert.assertTrue(result);
    } catch (Exception e) {
        s_logger.info("exception in testing runReleasePublicIpRangePostiveTest2 message: " + e.toString());
    } finally {
        txn.close("runReleasePublicIpRangePostiveTest2");
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Account(com.cloud.user.Account) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 68 with IPAddressVO

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

the class IpAddressManagerTest method testGetStaticNatSourceIps.

@Test
public void testGetStaticNatSourceIps() {
    String publicIpAddress = "192.168.1.3";
    IPAddressVO vo = mock(IPAddressVO.class);
    when(vo.getAddress()).thenReturn(new Ip(publicIpAddress));
    when(vo.getId()).thenReturn(1l);
    when(_ipAddrDao.findById(anyLong())).thenReturn(vo);
    StaticNat snat = new StaticNatImpl(1, 1, 1, 1, publicIpAddress, false);
    List<IPAddressVO> ips = _ipManager.getStaticNatSourceIps(Collections.singletonList(snat));
    Assert.assertNotNull(ips);
    Assert.assertEquals(1, ips.size());
    IPAddressVO returnedVO = ips.get(0);
    Assert.assertEquals(vo, returnedVO);
}
Also used : StaticNatImpl(com.cloud.network.rules.StaticNatImpl) Ip(com.cloud.utils.net.Ip) IPAddressVO(com.cloud.network.dao.IPAddressVO) StaticNat(com.cloud.network.rules.StaticNat) Test(org.junit.Test)

Example 69 with IPAddressVO

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

the class NuageVspGuestNetworkGuru method reserve.

@Override
public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
    boolean lockedNetwork = lockNetworkForUserVm(network, vm);
    if (lockedNetwork && s_logger.isDebugEnabled()) {
        s_logger.debug("Locked network " + network.getId() + " for creation of user VM " + vm.getInstanceName());
    }
    try {
        //We don't support a shared network with UserData and multiple IP ranges at the same time.
        checkMultipleSubnetsCombinedWithUseData(network);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Handling reserve() call back to with Create a new VM or add an interface to existing VM in network " + network.getName());
        }
        DataCenter dc = _dcDao.findById(network.getDataCenterId());
        AccountVO neworkAccountDetails = _accountDao.findById(network.getAccountId());
        if (neworkAccountDetails.getType() == Account.ACCOUNT_TYPE_PROJECT) {
            throw new InsufficientVirtualNetworkCapacityException("CS project support is not yet implemented in NuageVsp", DataCenter.class, dc.getId());
        }
        if (Strings.isNullOrEmpty(network.getBroadcastUri().getPath()) || !network.getBroadcastUri().getPath().startsWith("/")) {
            throw new IllegalStateException("The broadcast URI path " + network.getBroadcastUri() + " is empty or in an incorrect format.");
        }
        HostVO nuageVspHost = _nuageVspManager.getNuageVspHost(network.getPhysicalNetworkId());
        VspNetwork vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(vm.getVirtualMachine().getDomainId(), network);
        if (vspNetwork.isShared()) {
            vspNetwork = _nuageVspEntityBuilder.updateVspNetworkByPublicIp(vspNetwork, network, nic.getIPv4Address());
            if (VirtualMachine.Type.DomainRouter.equals(vm.getType()) && !nic.getIPv4Address().equals(vspNetwork.getVirtualRouterIp())) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("VR got spawned with a different IP, releasing the previously allocated public IP " + nic.getIPv4Address());
                }
                IPAddressVO oldIpAddress = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), nic.getIPv4Address());
                _ipAddressDao.unassignIpAddress(oldIpAddress.getId());
                _ipAddressDao.mark(network.getDataCenterId(), new Ip(vspNetwork.getVirtualRouterIp()));
            } else if (VirtualMachine.Type.User.equals(vm.getType()) && nic.getIPv4Address().equals(vspNetwork.getVirtualRouterIp())) {
                s_logger.error("Deploying a user VM with the same IP as the VR is not allowed.");
                throw new InsufficientVirtualNetworkCapacityException("Deploying a user VM with the same IP " + nic.getIPv4Address() + " as the VR is not allowed.", Network.class, network.getId());
            }
            // Make sure the shared network is present
            NetworkOffering offering = _ntwkOfferingDao.findById(network.getNetworkOfferingId());
            if (!implement(network.getPhysicalNetworkId(), vspNetwork, _nuageVspEntityBuilder.buildNetworkDhcpOption(network, offering))) {
                s_logger.error("Failed to implement shared network " + network.getUuid() + " under domain " + context.getDomain().getUuid());
                throw new InsufficientVirtualNetworkCapacityException("Failed to implement shared network " + network.getUuid() + " under domain " + context.getDomain().getUuid(), Network.class, network.getId());
            }
        }
        // Set flags for dhcp options
        boolean networkHasDns = networkHasDns(network);
        Map<Long, Boolean> networkHasDnsCache = Maps.newHashMap();
        networkHasDnsCache.put(network.getId(), networkHasDns);
        // Determine if dhcp options of the other nics in the network need to be updated
        if (vm.getType() == VirtualMachine.Type.DomainRouter && network.getState() != State.Implementing) {
            updateDhcpOptionsForExistingVms(network, nuageVspHost, vspNetwork, networkHasDns, networkHasDnsCache);
        }
        nic.setBroadcastUri(network.getBroadcastUri());
        nic.setIsolationUri(network.getBroadcastUri());
        //NicProfile does not contain the NIC UUID. We need this information to set it in the VMInterface and VPort
        //that we create in VSP
        NicVO nicFromDb = _nicDao.findById(nic.getId());
        IPAddressVO staticNatIp = _ipAddressDao.findByVmIdAndNetworkId(network.getId(), vm.getId());
        VspVm vspVm = _nuageVspEntityBuilder.buildVspVm(vm.getVirtualMachine(), network);
        VspNic vspNic = _nuageVspEntityBuilder.buildVspNic(nicFromDb.getUuid(), nic);
        VspStaticNat vspStaticNat = null;
        if (staticNatIp != null) {
            VlanVO staticNatVlan = _vlanDao.findById(staticNatIp.getVlanId());
            vspStaticNat = _nuageVspEntityBuilder.buildVspStaticNat(null, staticNatIp, staticNatVlan, null);
        }
        boolean defaultHasDns = getDefaultHasDns(networkHasDnsCache, nicFromDb);
        VspDhcpVMOption dhcpOption = _nuageVspEntityBuilder.buildVmDhcpOption(nicFromDb, defaultHasDns, networkHasDns);
        ReserveVmInterfaceVspCommand cmd = new ReserveVmInterfaceVspCommand(vspNetwork, vspVm, vspNic, vspStaticNat, dhcpOption);
        Answer answer = _agentMgr.easySend(nuageVspHost.getId(), cmd);
        if (answer == null || !answer.getResult()) {
            s_logger.error("ReserveVmInterfaceNuageVspCommand failed for NIC " + nic.getId() + " attached to VM " + vm.getId() + " in network " + network.getId());
            if ((null != answer) && (null != answer.getDetails())) {
                s_logger.error(answer.getDetails());
            }
            throw new InsufficientVirtualNetworkCapacityException("Failed to reserve VM in Nuage VSP.", Network.class, network.getId());
        }
        if (vspVm.getDomainRouter() == Boolean.TRUE) {
            nic.setIPv4Address(vspVm.getDomainRouterIp());
        }
    } finally {
        if (network != null && lockedNetwork) {
            _networkDao.releaseFromLockTable(network.getId());
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unlocked network " + network.getId() + " for creation of user VM " + vm.getInstanceName());
            }
        }
    }
}
Also used : NetworkOffering(com.cloud.offering.NetworkOffering) Ip(com.cloud.utils.net.Ip) VspStaticNat(net.nuage.vsp.acs.client.api.model.VspStaticNat) ReserveVmInterfaceVspCommand(com.cloud.agent.api.guru.ReserveVmInterfaceVspCommand) AccountVO(com.cloud.user.AccountVO) HostVO(com.cloud.host.HostVO) Answer(com.cloud.agent.api.Answer) DataCenter(com.cloud.dc.DataCenter) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) Network(com.cloud.network.Network) VspNetwork(net.nuage.vsp.acs.client.api.model.VspNetwork) PhysicalNetwork(com.cloud.network.PhysicalNetwork) IPAddressVO(com.cloud.network.dao.IPAddressVO) VspVm(net.nuage.vsp.acs.client.api.model.VspVm) VspNetwork(net.nuage.vsp.acs.client.api.model.VspNetwork) VspNic(net.nuage.vsp.acs.client.api.model.VspNic) VlanVO(com.cloud.dc.VlanVO) NicVO(com.cloud.vm.NicVO) VspDhcpVMOption(net.nuage.vsp.acs.client.api.model.VspDhcpVMOption)

Example 70 with IPAddressVO

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

the class ConfigurationManagerImpl method dedicatePublicIpRange.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DEDICATE, eventDescription = "dedicating vlan ip range", async = false)
public Vlan dedicatePublicIpRange(final DedicatePublicIpRangeCmd cmd) throws ResourceAllocationException {
    final Long vlanDbId = cmd.getId();
    final String accountName = cmd.getAccountName();
    final Long domainId = cmd.getDomainId();
    final Long projectId = cmd.getProjectId();
    // Check if account is valid
    Account vlanOwner = null;
    if (projectId != null) {
        if (accountName != null) {
            throw new InvalidParameterValueException("accountName and projectId are mutually exclusive");
        }
        final Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id " + projectId);
        }
        vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
        if (vlanOwner == null) {
            throw new InvalidParameterValueException("Please specify a valid projectId");
        }
    }
    Domain domain = null;
    if (accountName != null && domainId != null) {
        vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
        if (vlanOwner == null) {
            throw new InvalidParameterValueException("Unable to find account by name " + accountName);
        } else if (vlanOwner.getId() == Account.ACCOUNT_ID_SYSTEM) {
            throw new InvalidParameterValueException("Please specify a valid account. Cannot dedicate IP range to system account");
        }
    } else if (domainId != null) {
        domain = _domainDao.findById(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Please specify a valid domain id");
        }
    }
    // Check if range is valid
    final VlanVO vlan = _vlanDao.findById(vlanDbId);
    if (vlan == null) {
        throw new InvalidParameterValueException("Unable to find vlan by id " + vlanDbId);
    }
    // Check if range has already been dedicated
    final List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanDbId);
    if (maps != null && !maps.isEmpty()) {
        throw new InvalidParameterValueException("Specified Public IP range has already been dedicated");
    }
    List<DomainVlanMapVO> domainmaps = _domainVlanMapDao.listDomainVlanMapsByVlan(vlanDbId);
    if (domainmaps != null && !domainmaps.isEmpty()) {
        throw new InvalidParameterValueException("Specified Public IP range has already been dedicated to a domain");
    }
    // Verify that zone exists and is advanced
    final Long zoneId = vlan.getDataCenterId();
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
    }
    if (zone.getNetworkType() == NetworkType.Basic) {
        throw new InvalidParameterValueException("Public IP range can be dedicated to an account only in the zone of type " + NetworkType.Advanced);
    }
    // Check Public IP resource limits
    if (vlanOwner != null) {
        final int accountPublicIpRange = _publicIpAddressDao.countIPs(zoneId, vlanDbId, false);
        _resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountPublicIpRange);
    }
    // Check if any of the Public IP addresses is allocated to another
    // account
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    for (final IPAddressVO ip : ips) {
        final Long allocatedToAccountId = ip.getAllocatedToAccountId();
        if (allocatedToAccountId != null) {
            final Account accountAllocatedTo = _accountMgr.getActiveAccountById(allocatedToAccountId);
            if (!accountAllocatedTo.getAccountName().equalsIgnoreCase(accountName)) {
                throw new InvalidParameterValueException(ip.getAddress() + " Public IP address in range is allocated to another account ");
            }
            if (vlanOwner == null && domain != null && domain.getId() != accountAllocatedTo.getDomainId()) {
                throw new InvalidParameterValueException(ip.getAddress() + " Public IP address in range is allocated to another domain/account ");
            }
        }
    }
    if (vlanOwner != null) {
        // Create an AccountVlanMapVO entry
        final AccountVlanMapVO accountVlanMapVO = new AccountVlanMapVO(vlanOwner.getId(), vlan.getId());
        _accountVlanMapDao.persist(accountVlanMapVO);
        // generate usage event for dedication of every ip address in the range
        for (final IPAddressVO ip : ips) {
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid());
        }
    } else if (domain != null) {
        // Create an DomainVlanMapVO entry
        DomainVlanMapVO domainVlanMapVO = new DomainVlanMapVO(domain.getId(), vlan.getId());
        _domainVlanMapDao.persist(domainVlanMapVO);
    }
    // increment resource count for dedicated public ip's
    if (vlanOwner != null) {
        _resourceLimitMgr.incrementResourceCount(vlanOwner.getId(), ResourceType.public_ip, new Long(ips.size()));
    }
    return vlan;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) IPAddressVO(com.cloud.network.dao.IPAddressVO) Domain(com.cloud.domain.Domain) VlanVO(com.cloud.dc.VlanVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

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