Search in sources :

Example 96 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class UserVmManagerTest method testUpdateVmNicIpSuccess2.

@Test
public void testUpdateVmNicIpSuccess2() throws Exception {
    UpdateVmNicIpCmd cmd = new UpdateVmNicIpCmd();
    Class<?> _class = cmd.getClass();
    Field virtualmachineIdField = _class.getDeclaredField("nicId");
    virtualmachineIdField.setAccessible(true);
    virtualmachineIdField.set(cmd, 1L);
    Field accountNameField = _class.getDeclaredField("ipAddr");
    accountNameField.setAccessible(true);
    accountNameField.set(cmd, "10.10.10.10");
    NicVO nic = new NicVO("nic", 1L, 2L, VirtualMachine.Type.User);
    when(_nicDao.findById(anyLong())).thenReturn(nic);
    nic.setIPv4Address("10.10.10.9");
    when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
    when(_networkDao.findById(anyLong())).thenReturn(_networkMock);
    doReturn(9L).when(_networkMock).getNetworkOfferingId();
    when(_networkOfferingDao.findByIdIncludingRemoved(anyLong())).thenReturn(_networkOfferingMock);
    doReturn(10L).when(_networkOfferingMock).getId();
    List<Service> services = new ArrayList<Service>();
    when(_networkModel.listNetworkOfferingServices(anyLong())).thenReturn(services);
    lenient().when(_vmMock.getState()).thenReturn(State.Running);
    lenient().doNothing().when(_accountMgr).checkAccess(_account, null, true, _vmMock);
    when(_accountDao.findByIdIncludingRemoved(anyLong())).thenReturn(_accountMock);
    when(_networkMock.getState()).thenReturn(Network.State.Implemented);
    when(_networkMock.getDataCenterId()).thenReturn(3L);
    when(_networkMock.getGuestType()).thenReturn(GuestType.Shared);
    when(_dcDao.findById(anyLong())).thenReturn(_dcMock);
    when(_dcMock.getNetworkType()).thenReturn(NetworkType.Advanced);
    IPAddressVO newIp = mock(IPAddressVO.class);
    when(newIp.getVlanId()).thenReturn(1L);
    VlanVO vlan = mock(VlanVO.class);
    when(vlan.getVlanGateway()).thenReturn("10.10.10.1");
    when(vlan.getVlanNetmask()).thenReturn("255.255.255.0");
    when(_ipAddrMgr.allocatePublicIpForGuestNic(Mockito.eq(_networkMock), nullable(Long.class), Mockito.eq(_accountMock), anyString())).thenReturn("10.10.10.10");
    when(_ipAddressDao.findByIpAndSourceNetworkId(anyLong(), eq("10.10.10.10"))).thenReturn(newIp);
    when(_ipAddressDao.findByIpAndSourceNetworkId(anyLong(), eq("10.10.10.9"))).thenReturn(null);
    when(_nicDao.persist(any(NicVO.class))).thenReturn(nic);
    when(_vlanDao.findById(anyLong())).thenReturn(vlan);
    Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, caller);
    try {
        _userVmMgr.updateNicIpForVirtualMachine(cmd);
    } finally {
        CallContext.unregister();
    }
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) AccountService(com.cloud.user.AccountService) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) VolumeOrchestrationService(org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService) ResourceLimitService(com.cloud.user.ResourceLimitService) AccountVO(com.cloud.user.AccountVO) Field(java.lang.reflect.Field) UserVO(com.cloud.user.UserVO) Matchers.anyLong(org.mockito.Matchers.anyLong) IPAddressVO(com.cloud.network.dao.IPAddressVO) UpdateVmNicIpCmd(org.apache.cloudstack.api.command.user.vm.UpdateVmNicIpCmd) VlanVO(com.cloud.dc.VlanVO) Test(org.junit.Test)

Example 97 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class ConfigurationManagerImpl method updateVlanAndIpv4Range.

private void updateVlanAndIpv4Range(final long id, final VlanVO vlanRange, String startIp, String endIp, String gateway, String netmask, final Boolean isRangeForSystemVM, final Boolean forSystemVms) {
    final List<IPAddressVO> listAllocatedIPs = _publicIpAddressDao.listByVlanIdAndState(id, IpAddress.State.Allocated);
    if (gateway != null && !gateway.equals(vlanRange.getVlanGateway()) && CollectionUtils.isNotEmpty(listAllocatedIPs)) {
        throw new InvalidParameterValueException(String.format("Unable to change gateway to %s because some IPs are in use", gateway));
    }
    if (netmask != null && !netmask.equals(vlanRange.getVlanNetmask()) && CollectionUtils.isNotEmpty(listAllocatedIPs)) {
        throw new InvalidParameterValueException(String.format("Unable to change netmask to %s because some IPs are in use", netmask));
    }
    gateway = MoreObjects.firstNonNull(gateway, vlanRange.getVlanGateway());
    netmask = MoreObjects.firstNonNull(netmask, vlanRange.getVlanNetmask());
    final String[] existingVlanIPRangeArray = vlanRange.getIpRange().split("-");
    final String currentStartIP = existingVlanIPRangeArray[0];
    final String currentEndIP = existingVlanIPRangeArray[1];
    startIp = MoreObjects.firstNonNull(startIp, currentStartIP);
    endIp = MoreObjects.firstNonNull(endIp, currentEndIP);
    final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
    if (StringUtils.isEmpty(cidr)) {
        throw new InvalidParameterValueException(String.format("Invalid gateway (%s) or netmask (%s)", gateway, netmask));
    }
    final String cidrAddress = getCidrAddress(cidr);
    final long cidrSize = getCidrSize(cidr);
    checkIpRange(startIp, endIp, cidrAddress, cidrSize);
    checkGatewayOverlap(startIp, endIp, gateway);
    checkAllocatedIpsAreWithinVlanRange(listAllocatedIPs, startIp, endIp, forSystemVms);
    try {
        final String newStartIP = startIp;
        final String newEndIP = endIp;
        VlanVO range = _vlanDao.acquireInLockTable(id, 30);
        if (range == null) {
            throw new CloudRuntimeException("Unable to acquire vlan configuration: " + id);
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("lock vlan " + id + " is acquired");
        }
        commitUpdateVlanAndIpRange(id, newStartIP, newEndIP, currentStartIP, currentEndIP, gateway, netmask, true, isRangeForSystemVM, forSystemVms);
    } catch (final Exception e) {
        s_logger.error("Unable to edit VlanRange due to " + e.getMessage(), e);
        throw new CloudRuntimeException("Failed to edit VlanRange. Please contact Cloud Support.");
    } finally {
        _vlanDao.releaseFromLockTable(id);
    }
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) URISyntaxException(java.net.URISyntaxException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException)

Example 98 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class ConfigurationManagerImpl method createVlanAndPublicIpRange.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_CREATE, eventDescription = "creating vlan ip range", async = false)
public Vlan createVlanAndPublicIpRange(final CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException {
    Long zoneId = cmd.getZoneId();
    final Long podId = cmd.getPodId();
    final String startIP = cmd.getStartIp();
    String endIP = cmd.getEndIp();
    final String newVlanGateway = cmd.getGateway();
    final String newVlanNetmask = cmd.getNetmask();
    String vlanId = cmd.getVlan();
    // TODO decide if we should be forgiving or demand a valid and complete URI
    if (!(vlanId == null || "".equals(vlanId) || vlanId.startsWith(BroadcastDomainType.Vlan.scheme()))) {
        vlanId = BroadcastDomainType.Vlan.toUri(vlanId).toString();
    }
    final Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
    Long networkId = cmd.getNetworkID();
    Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final String accountName = cmd.getAccountName();
    final Long projectId = cmd.getProjectId();
    final Long domainId = cmd.getDomainId();
    final String startIPv6 = cmd.getStartIpv6();
    String endIPv6 = cmd.getEndIpv6();
    final String ip6Gateway = cmd.getIp6Gateway();
    final String ip6Cidr = cmd.getIp6Cidr();
    final Boolean forSystemVms = cmd.isForSystemVms();
    Account vlanOwner = null;
    if (forSystemVms && accountName != null) {
        throw new InvalidParameterValueException("Account name should not be provided when ForSystemVMs is enabled");
    }
    final boolean ipv4 = startIP != null;
    final boolean ipv6 = ip6Cidr != null;
    if (!ipv4 && !ipv6) {
        throw new InvalidParameterValueException("StartIP or IPv6 CIDR is missing in the parameters!");
    }
    if (ipv4) {
        // if end ip is not specified, default it to startIp
        if (endIP == null && startIP != null) {
            endIP = startIP;
        }
    }
    if (ipv6) {
        // if end ip is not specified, default it to startIp
        if (endIPv6 == null && startIPv6 != null) {
            endIPv6 = startIPv6;
        }
    }
    if (projectId != null) {
        if (accountName != null) {
            throw new InvalidParameterValueException("Account 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("Please specify a valid account.");
        } else if (vlanOwner.getId() == Account.ACCOUNT_ID_SYSTEM) {
            // by default vlan is dedicated to system account
            vlanOwner = null;
        }
    } else if (domainId != null) {
        domain = _domainDao.findById(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Please specify a valid domain id");
        }
    }
    // Verify that network exists
    Network network = null;
    if (networkId != null) {
        network = _networkDao.findById(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find network by id " + networkId);
        } else {
            zoneId = network.getDataCenterId();
            physicalNetworkId = network.getPhysicalNetworkId();
        }
    } else if (ipv6) {
        throw new InvalidParameterValueException("Only support IPv6 on extending existed network");
    }
    // Verify that zone exists
    final DataCenterVO zone = _zoneDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
    }
    if (ipv6) {
        if (network.getGuestType() != GuestType.Shared || zone.isSecurityGroupEnabled()) {
            throw new InvalidParameterValueException("Only support IPv6 on extending existed share network without SG");
        }
    }
    // verify that physical network exists
    PhysicalNetworkVO pNtwk = null;
    if (physicalNetworkId != null) {
        pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
        if (pNtwk == null) {
            throw new InvalidParameterValueException("Unable to find Physical Network with id=" + physicalNetworkId);
        }
        if (zoneId == null) {
            zoneId = pNtwk.getDataCenterId();
        }
    } else {
        if (zoneId == null) {
            throw new InvalidParameterValueException("");
        }
        // deduce physicalNetworkFrom Zone or Network.
        if (network != null && network.getPhysicalNetworkId() != null) {
            physicalNetworkId = network.getPhysicalNetworkId();
        } else {
            if (forVirtualNetwork) {
                // default physical network with public traffic in the zone
                physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
            } else {
                if (zone.getNetworkType() == DataCenter.NetworkType.Basic) {
                    // default physical network with guest traffic in the
                    // zone
                    physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId();
                } else if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) {
                    if (zone.isSecurityGroupEnabled()) {
                        physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Guest).getId();
                    } else {
                        throw new InvalidParameterValueException("Physical Network Id is null, please provide the Network id for Direct vlan creation ");
                    }
                }
            }
        }
    }
    // Check if zone is enabled
    final Account caller = CallContext.current().getCallingAccount();
    if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
    }
    if (zone.isSecurityGroupEnabled() && zone.getNetworkType() != DataCenter.NetworkType.Basic && forVirtualNetwork) {
        throw new InvalidParameterValueException("Can't add virtual ip range into a zone with security group enabled");
    }
    // Untagged, try to locate default networks
    if (forVirtualNetwork) {
        if (network == null) {
            // find default public network in the zone
            networkId = _networkModel.getSystemNetworkByZoneAndTrafficType(zoneId, TrafficType.Public).getId();
            network = _networkModel.getNetwork(networkId);
        } else if (network.getGuestType() != null || network.getTrafficType() != TrafficType.Public) {
            throw new InvalidParameterValueException("Can't find Public network by id=" + networkId);
        }
    } else {
        if (network == null) {
            if (zone.getNetworkType() == DataCenter.NetworkType.Basic) {
                networkId = _networkModel.getExclusiveGuestNetwork(zoneId).getId();
                network = _networkModel.getNetwork(networkId);
            } else {
                network = _networkModel.getNetworkWithSecurityGroupEnabled(zoneId);
                if (network == null) {
                    throw new InvalidParameterValueException("Nework id is required for Direct vlan creation ");
                }
                networkId = network.getId();
                zoneId = network.getDataCenterId();
            }
        } else if (network.getGuestType() == null || network.getGuestType() == Network.GuestType.Isolated && _ntwkOffServiceMapDao.areServicesSupportedByNetworkOffering(network.getNetworkOfferingId(), Service.SourceNat)) {
            throw new InvalidParameterValueException("Can't create direct vlan for network id=" + networkId + " with type: " + network.getGuestType());
        }
    }
    Pair<Boolean, Pair<String, String>> sameSubnet = null;
    // Can add vlan range only to the network which allows it
    if (!network.getSpecifyIpRanges()) {
        throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges");
    }
    if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) {
        if (network.getTrafficType() == TrafficType.Guest) {
            if (network.getGuestType() != GuestType.Shared) {
                throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network " + network.getId() + " is " + network.getGuestType());
            }
            final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
            if (vlans != null && vlans.size() > 0) {
                final VlanVO vlan = vlans.get(0);
                if (vlanId == null || vlanId.contains(Vlan.UNTAGGED)) {
                    vlanId = vlan.getVlanTag();
                } else if (!NetUtils.isSameIsolationId(vlan.getVlanTag(), vlanId)) {
                    throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" + +network.getId() + ", only one vlan is allowed on guest network");
                }
            }
            sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
        }
    } else if (network.getTrafficType() == TrafficType.Management) {
        throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
    } else if (zone.getNetworkType() == NetworkType.Basic) {
        final List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
        sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
    }
    if (zoneId == null || ipv6 && (ip6Gateway == null || ip6Cidr == null)) {
        throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
    }
    if (forVirtualNetwork) {
        if (vlanOwner != null) {
            final long accountIpRange = NetUtils.ip2Long(endIP) - NetUtils.ip2Long(startIP) + 1;
            // check resource limits
            _resourceLimitMgr.checkResourceLimit(vlanOwner, ResourceType.public_ip, accountIpRange);
        }
    }
    // Check if the IP range overlaps with the private ip
    if (ipv4) {
        checkOverlapPrivateIpRange(zoneId, startIP, endIP);
    }
    return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId, forVirtualNetwork, forSystemVms, networkId, physicalNetworkId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, domain, vlanOwner, network, sameSubnet);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Domain(com.cloud.domain.Domain) VlanVO(com.cloud.dc.VlanVO) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 99 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class ConfigurationManagerImpl method updateVlanAndPublicIpRange.

@DB
@ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_UPDATE, eventDescription = "update vlan ip Range", async = false)
public Vlan updateVlanAndPublicIpRange(final long id, String startIp, String endIp, String gateway, String netmask, String startIpv6, String endIpv6, String ip6Gateway, String ip6Cidr, Boolean forSystemVms) throws ConcurrentOperationException {
    VlanVO vlanRange = _vlanDao.findById(id);
    if (vlanRange == null) {
        throw new InvalidParameterValueException("Please specify a valid IP range id.");
    }
    final boolean ipv4 = vlanRange.getVlanGateway() != null;
    final boolean ipv6 = vlanRange.getIp6Gateway() != null;
    if (!ipv4) {
        if (startIp != null || endIp != null || gateway != null || netmask != null) {
            throw new InvalidParameterValueException("IPv4 is not support in this IP range.");
        }
    }
    if (!ipv6) {
        if (startIpv6 != null || endIpv6 != null || ip6Gateway != null || ip6Cidr != null) {
            throw new InvalidParameterValueException("IPv6 is not support in this IP range.");
        }
    }
    final Boolean isRangeForSystemVM = checkIfVlanRangeIsForSystemVM(id);
    if (forSystemVms != null && isRangeForSystemVM != forSystemVms) {
        if (VlanType.DirectAttached.equals(vlanRange.getVlanType())) {
            throw new InvalidParameterValueException("forSystemVms is not available for this IP range with vlan type: " + VlanType.DirectAttached);
        }
        // Check if range has already been dedicated
        final List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByVlan(id);
        if (maps != null && !maps.isEmpty()) {
            throw new InvalidParameterValueException("Specified Public IP range has already been dedicated to an account");
        }
        List<DomainVlanMapVO> domainmaps = _domainVlanMapDao.listDomainVlanMapsByVlan(id);
        if (domainmaps != null && !domainmaps.isEmpty()) {
            throw new InvalidParameterValueException("Specified Public IP range has already been dedicated to a domain");
        }
    }
    if (ipv4) {
        updateVlanAndIpv4Range(id, vlanRange, startIp, endIp, gateway, netmask, isRangeForSystemVM, forSystemVms);
    }
    if (ipv6) {
        updateVlanAndIpv6Range(id, vlanRange, startIpv6, endIpv6, ip6Gateway, ip6Cidr, isRangeForSystemVM, forSystemVms);
    }
    return _vlanDao.findById(id);
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) VlanVO(com.cloud.dc.VlanVO) DomainVlanMapVO(com.cloud.dc.DomainVlanMapVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 100 with VlanVO

use of com.cloud.dc.VlanVO 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
    boolean forSystemVms = false;
    final List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlanDbId);
    for (final IPAddressVO ip : ips) {
        forSystemVms = ip.isForSystemVms();
        final Long allocatedToAccountId = ip.getAllocatedToAccountId();
        if (allocatedToAccountId != null) {
            if (vlanOwner != null && allocatedToAccountId != vlanOwner.getId()) {
                throw new InvalidParameterValueException(ip.getAddress() + " Public IP address in range is allocated to another account ");
            }
            final Account accountAllocatedTo = _accountMgr.getActiveAccountById(allocatedToAccountId);
            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) {
            final boolean usageHidden = _ipAddrMgr.isUsageHidden(ip);
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip.getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan.getVlanType().toString(), ip.getSystem(), usageHidden, ip.getClass().getName(), ip.getUuid());
        }
    } else if (domain != null && !forSystemVms) {
        // 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

VlanVO (com.cloud.dc.VlanVO)103 ArrayList (java.util.ArrayList)39 IPAddressVO (com.cloud.network.dao.IPAddressVO)25 DB (com.cloud.utils.db.DB)25 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 TransactionStatus (com.cloud.utils.db.TransactionStatus)18 Network (com.cloud.network.Network)17 Account (com.cloud.user.Account)17 AccountVlanMapVO (com.cloud.dc.AccountVlanMapVO)15 List (java.util.List)15 DomainVlanMapVO (com.cloud.dc.DomainVlanMapVO)12 ActionEvent (com.cloud.event.ActionEvent)12 HostVO (com.cloud.host.HostVO)12 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)12 Vlan (com.cloud.dc.Vlan)11 NetworkVO (com.cloud.network.dao.NetworkVO)11 DataCenter (com.cloud.dc.DataCenter)10 DataCenterVO (com.cloud.dc.DataCenterVO)10 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)10