Search in sources :

Example 16 with AccountGuestVlanMapVO

use of com.cloud.network.dao.AccountGuestVlanMapVO in project cosmic by MissionCriticalCloud.

the class NetworkOrchestrator method createGuestNetwork.

@Override
@DB
public Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, final String dns1, final String dns2, final String ipExclusionList) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    // this method supports only guest network creation
    if (ntwkOff.getTrafficType() != TrafficType.Guest) {
        s_logger.warn("Only guest networks can be created using this method");
        return null;
    }
    final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
    // check resource limits
    if (updateResourceCount) {
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
    }
    // Validate network offering
    if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
        // see NetworkOfferingVO
        final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its stat is not " + NetworkOffering.State.Enabled);
        ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        throw ex;
    }
    // Validate physical network
    if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
        // see PhysicalNetworkVO.java
        final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
        ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
        throw ex;
    }
    boolean ipv6 = false;
    if (ip6Gateway != null && ip6Cidr != null) {
        ipv6 = true;
    }
    // Validate zone
    final Zone zone = _zoneRepository.findOne(zoneId);
    if (zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Basic) {
        if (ipv6) {
            throw new InvalidParameterValueException("IPv6 is not supported in Basic zone");
        }
        // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
        if (aclType == null || aclType != ACLType.Domain) {
            throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
        }
        // Only one guest network is supported in Basic zone
        final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
        if (!guestNetworks.isEmpty()) {
            throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
        }
        // if zone is basic, only Shared network offerings w/o source nat service are allowed
        if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
            throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed");
        }
        if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
            throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
        }
        if (subdomainAccess == null) {
            subdomainAccess = true;
        } else if (!subdomainAccess) {
            throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
        }
        if (vlanId == null) {
            vlanId = Vlan.UNTAGGED;
        } else {
            if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
                throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
            }
        }
    } else if (zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Advanced) {
        // don't allow eip/elb networks in Advance zone
        if (ntwkOff.getElasticIp() || ntwkOff.getElasticLb()) {
            throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
        }
    }
    // TODO(VXLAN): Support VNI specified
    // VlanId can be specified only when network offering supports it
    final boolean vlanSpecified = vlanId != null;
    if (vlanSpecified != ntwkOff.getSpecifyVlan()) {
        if (vlanSpecified) {
            throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
        } else {
            throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
        }
    }
    if (vlanSpecified) {
        // don't allow to specify vlan tag used by physical network for dynamic vlan allocation
        if (_dcVnetDao.findVnet(zoneId, pNtwk.getId(), vlanId).size() > 0) {
            throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName());
        }
        final String uri = BroadcastDomainType.fromString(vlanId).toString();
        // For Isolated networks, don't allow to create network with vlan that already exists in the zone
        if (ntwkOff.getGuestType() == GuestType.Isolated) {
            if (_networksDao.countByZoneAndUri(zoneId, uri) > 0) {
                throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists in zone " + zoneId);
            } else {
                final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, vlanId);
                // the vnet is not coming from the data center vnet table, so the list can be empty
                if (!dcVnets.isEmpty()) {
                    final DataCenterVnetVO dcVnet = dcVnets.get(0);
                    // Fail network creation if specified vlan is dedicated to a different account
                    if (dcVnet.getAccountGuestVlanMapId() != null) {
                        final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
                        final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
                        if (map.getAccountId() != owner.getAccountId()) {
                            throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
                        }
                    // Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
                    } else {
                        final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
                        if (maps != null && !maps.isEmpty()) {
                            final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
                            final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
                            if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
                                throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner " + owner.getAccountName());
                            }
                        }
                    }
                }
            }
        } else {
            // shared network with same Vlan ID in the zone
            if (_networksDao.countByZoneUriAndGuestType(zoneId, uri, GuestType.Isolated) > 0) {
                throw new InvalidParameterValueException("There is a isolated/shared network with vlan id: " + vlanId + " already exists " + "in zone " + zoneId);
            }
        }
    }
    // If networkDomain is not specified, take it from the global configuration
    if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
        final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), Service.Dns);
        final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
        if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
            if (networkDomain != null) {
                // TBD: NetworkOfferingId and zoneId. Send uuids instead.
                throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
            }
        } else {
            if (networkDomain == null) {
                // 1) Get networkDomain from the corresponding account/domain/zone
                if (aclType == ACLType.Domain) {
                    networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
                } else if (aclType == ACLType.Account) {
                    networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
                }
                // 2) If null, generate networkDomain using domain suffix from the global config variables
                if (networkDomain == null) {
                    networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
                }
            } else {
                // validate network domain
                if (!NetUtils.verifyDomainName(networkDomain)) {
                    throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
                }
            }
        }
    }
    // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
    // limitation, remove after we introduce support for multiple ip ranges
    // with different Cidrs for the same Shared network
    final boolean cidrRequired = zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Advanced && ntwkOff.getTrafficType() == TrafficType.Guest && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
    if (cidr == null && ip6Cidr == null && cidrRequired) {
        throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + GuestType.Shared + " and network of type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
    }
    // No cidr can be specified in Basic zone
    if (zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Basic && cidr != null) {
        throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
    }
    // Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
    if (cidr != null && ntwkOff.getGuestType() != GuestType.Shared && ntwkOff.getTrafficType() == TrafficType.Guest) {
        if (!NetUtils.validateGuestCidr(cidr)) {
            throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC1918 compliant");
        }
    }
    final String networkDomainFinal = networkDomain;
    final String vlanIdFinal = vlanId;
    final Boolean subdomainAccessFinal = subdomainAccess;
    final Network network = Transaction.execute(new TransactionCallback<Network>() {

        @Override
        public Network doInTransaction(final TransactionStatus status) {
            Long physicalNetworkId = null;
            if (pNtwk != null) {
                physicalNetworkId = pNtwk.getId();
            }
            final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
            final NetworkVO userNetwork = new NetworkVO();
            userNetwork.setNetworkDomain(networkDomainFinal);
            userNetwork.setCidr(cidr);
            userNetwork.setGateway(gateway);
            if (dns1 != null) {
                userNetwork.setDns1(dns1);
            }
            if (dns2 != null) {
                userNetwork.setDns2(dns2);
            }
            if (ipExclusionList != null) {
                userNetwork.setIpExclusionList(ipExclusionList);
            }
            if (ip6Cidr != null && ip6Gateway != null) {
                userNetwork.setIp6Cidr(ip6Cidr);
                userNetwork.setIp6Gateway(ip6Gateway);
            }
            if (vlanIdFinal != null) {
                if (isolatedPvlan == null) {
                    final URI uri = BroadcastDomainType.fromString(vlanIdFinal);
                    userNetwork.setBroadcastUri(uri);
                    if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
                        userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
                    } else {
                        userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
                    }
                } else {
                    if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
                        throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
                    }
                    userNetwork.setBroadcastUri(NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan));
                    userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
                }
            }
            final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, null, isDisplayNetworkEnabled, dns1, dns2, ipExclusionList);
            Network network = null;
            if (networks == null || networks.isEmpty()) {
                throw new CloudRuntimeException("Fail to create a network");
            } else {
                if (networks.size() > 0 && networks.get(0).getGuestType() == GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
                    Network defaultGuestNetwork = networks.get(0);
                    for (final Network nw : networks) {
                        if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
                            defaultGuestNetwork = nw;
                        }
                    }
                    network = defaultGuestNetwork;
                } else {
                    // For shared network
                    network = networks.get(0);
                }
            }
            if (updateResourceCount) {
                _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
            }
            return network;
        }
    });
    CallContext.current().setEventDetails("Network Id: " + network.getId());
    CallContext.current().putContextParameter(Network.class, network.getUuid());
    return network;
}
Also used : AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) URI(java.net.URI) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ArrayList(java.util.ArrayList) List(java.util.List) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) Capability(com.cloud.network.Network.Capability) NetworkOffering(com.cloud.offering.NetworkOffering) Zone(com.cloud.db.model.Zone) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) DB(com.cloud.utils.db.DB)

Example 17 with AccountGuestVlanMapVO

use of com.cloud.network.dao.AccountGuestVlanMapVO in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method cleanupAccount.

protected boolean cleanupAccount(final AccountVO account, final long callerUserId, final Account caller) {
    final long accountId = account.getId();
    boolean accountCleanupNeeded = false;
    try {
        // cleanup the users from the account
        final List<UserVO> users = _userDao.listByAccount(accountId);
        for (final UserVO user : users) {
            if (!_userDao.remove(user.getId())) {
                s_logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
                accountCleanupNeeded = true;
            }
        }
        // delete the account from project accounts
        _projectAccountDao.removeAccountFromProjects(accountId);
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            // delete the account from group
            _messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
        }
        // delete all vm groups belonging to accont
        final List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
        for (final InstanceGroupVO group : groups) {
            if (!_vmMgr.deleteVmGroup(group.getId())) {
                s_logger.error("Unable to delete group: " + group.getId());
                accountCleanupNeeded = true;
            }
        }
        // Delete the snapshots dir for the account. Have to do this before destroying the VMs.
        final boolean success = _snapMgr.deleteSnapshotDirsForAccount(accountId);
        if (success) {
            s_logger.debug("Successfully deleted snapshots directories for all volumes under account " + accountId + " across all zones");
        }
        // clean up templates
        final List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
        boolean allTemplatesDeleted = true;
        for (final VMTemplateVO template : userTemplates) {
            if (template.getRemoved() == null) {
                try {
                    allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
                } catch (final Exception e) {
                    s_logger.warn("Failed to delete template while removing account: " + template.getName() + " due to: ", e);
                    allTemplatesDeleted = false;
                }
            }
        }
        if (!allTemplatesDeleted) {
            s_logger.warn("Failed to delete templates while removing account id=" + accountId);
            accountCleanupNeeded = true;
        }
        // Destroy VM Snapshots
        final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
        for (final VMSnapshot vmSnapshot : vmSnapshots) {
            try {
                _vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
            } catch (final Exception e) {
                s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
            }
        }
        // Destroy the account's VMs
        final List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
        }
        // no need to catch exception at this place as expunging vm should pass in order to perform further cleanup
        for (final UserVmVO vm : vms) {
            if (!_vmMgr.expunge(vm, callerUserId, caller)) {
                s_logger.error("Unable to expunge vm: " + vm.getId());
                accountCleanupNeeded = true;
            }
        }
        // Mark the account's volumes as destroyed
        final List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
        for (final VolumeVO volume : volumes) {
            if (!volume.getState().equals(Volume.State.Destroy)) {
                try {
                    volumeService.deleteVolume(volume.getId(), caller);
                } catch (final Exception ex) {
                    s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
                    accountCleanupNeeded = true;
                }
            }
        }
        // delete remote access vpns and associated users
        final List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
        final List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
        for (final VpnUserVO vpnUser : vpnUsers) {
            _remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
        }
        try {
            for (final RemoteAccessVpnVO vpn : remoteAccessVpns) {
                _remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller);
            }
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
            accountCleanupNeeded = true;
        }
        // Cleanup affinity groups
        final int numAGRemoved = _affinityGroupDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Deleted " + numAGRemoved + " affinity groups for account " + accountId);
        // Delete all the networks
        boolean networksDeleted = true;
        s_logger.debug("Deleting networks for account " + account.getId());
        final List<NetworkVO> networks = _networkDao.listByOwner(accountId);
        if (networks != null) {
            for (final NetworkVO network : networks) {
                final ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller);
                if (!_networkMgr.destroyNetwork(network.getId(), context, false)) {
                    s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
                    accountCleanupNeeded = true;
                    networksDeleted = false;
                } else {
                    s_logger.debug("Network " + network.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
                }
            }
        }
        // Delete all VPCs
        boolean vpcsDeleted = true;
        s_logger.debug("Deleting vpcs for account " + account.getId());
        final List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
        for (final Vpc vpc : vpcs) {
            if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) {
                s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup.");
                accountCleanupNeeded = true;
                vpcsDeleted = false;
            } else {
                s_logger.debug("VPC " + vpc.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
            }
        }
        if (networksDeleted && vpcsDeleted) {
            // release ip addresses belonging to the account
            final List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
            for (final IpAddress ip : ipsToRelease) {
                s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
                if (!_ipAddrMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
                    s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
                    accountCleanupNeeded = true;
                }
            }
        }
        // Delete Site 2 Site VPN customer gateway
        s_logger.debug("Deleting site-to-site VPN customer gateways for account " + accountId);
        if (!_vpnMgr.deleteCustomerGatewayByAccount(accountId)) {
            s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId);
        }
        // up successfully
        if (networksDeleted) {
            if (!_configMgr.releaseAccountSpecificVirtualRanges(accountId)) {
                accountCleanupNeeded = true;
            } else {
                s_logger.debug("Account specific Virtual IP ranges " + " are successfully released as a part of account id=" + accountId + " cleanup.");
            }
        }
        // release account specific guest vlans
        final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
        for (final AccountGuestVlanMapVO map : maps) {
            _dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
        }
        final int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
        // release dedication if any
        final List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for account " + accountId);
            for (final DedicatedResourceVO dr : dedicatedResources) {
                if (!_dedicatedDao.remove(dr.getId())) {
                    s_logger.warn("Fail to release dedicated resources for account " + accountId);
                }
            }
        }
        // Updating and deleting the resourceLimit and resourceCount should be the last step in cleanupAccount
        // process.
        // Update resource count for this account and for parent domains.
        final List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
        for (final ResourceCountVO resourceCount : resourceCounts) {
            _resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
        }
        // Delete resource count and resource limits entries set for this account (if there are any).
        _resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
        _resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
        return true;
    } catch (final Exception ex) {
        s_logger.warn("Failed to cleanup account " + account + " due to ", ex);
        accountCleanupNeeded = true;
        return true;
    } finally {
        s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed."));
        if (accountCleanupNeeded) {
            _accountDao.markForCleanup(accountId);
        } else {
            account.setNeedsCleanup(false);
            _accountDao.update(accountId, account);
        }
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) VpnUserVO(com.cloud.network.VpnUserVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) Vpc(com.cloud.network.vpc.Vpc) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) VolumeVO(com.cloud.storage.VolumeVO) NetworkVO(com.cloud.network.dao.NetworkVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InstanceGroupVO(com.cloud.vm.InstanceGroupVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VpnUserVO(com.cloud.network.VpnUserVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceCountVO(com.cloud.configuration.ResourceCountVO) IpAddress(com.cloud.network.IpAddress) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Example 18 with AccountGuestVlanMapVO

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

the class NetworkOrchestrator method createGuestNetwork.

@DB
private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId, boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException {
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    final DataCenterVO zone = _dcDao.findById(zoneId);
    // this method supports only guest network creation
    if (ntwkOff.getTrafficType() != TrafficType.Guest) {
        s_logger.warn("Only guest networks can be created using this method");
        return null;
    }
    final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType);
    // check resource limits
    if (updateResourceCount) {
        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled);
    }
    // Validate network offering
    if (ntwkOff.getState() != NetworkOffering.State.Enabled) {
        // see NetworkOfferingVO
        final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled);
        ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        throw ex;
    }
    // Validate physical network
    if (pNtwk.getState() != PhysicalNetwork.State.Enabled) {
        // see PhysicalNetworkVO.java
        final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState());
        ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId");
        throw ex;
    }
    boolean ipv6 = false;
    if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
        ipv6 = true;
    }
    // Validate zone
    if (zone.getNetworkType() == NetworkType.Basic) {
        // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true
        if (aclType == null || aclType != ACLType.Domain) {
            throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone");
        }
        // Only one guest network is supported in Basic zone
        final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest);
        if (!guestNetworks.isEmpty()) {
            throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic);
        }
        // if zone is basic, only Shared network offerings w/o source nat service are allowed
        if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
            throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed");
        }
        if (domainId == null || domainId != Domain.ROOT_DOMAIN) {
            throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain");
        }
        if (subdomainAccess == null) {
            subdomainAccess = true;
        } else if (!subdomainAccess) {
            throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone");
        }
        if (vlanId == null) {
            vlanId = Vlan.UNTAGGED;
        } else {
            if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) {
                throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic);
            }
        }
    } else if (zone.getNetworkType() == NetworkType.Advanced) {
        if (zone.isSecurityGroupEnabled()) {
            if (isolatedPvlan != null) {
                throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!");
            }
            // enabled zone
            if (ntwkOff.getGuestType() != GuestType.Shared) {
                throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone");
            }
            if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) {
                throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone");
            }
        }
        // don't allow eip/elb networks in Advance zone
        if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) {
            throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic);
        }
    }
    if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) {
        throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size");
    }
    // TODO(VXLAN): Support VNI specified
    // VlanId can be specified only when network offering supports it
    final boolean vlanSpecified = vlanId != null;
    if (vlanSpecified != ntwkOff.isSpecifyVlan()) {
        if (vlanSpecified) {
            throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false");
        } else {
            throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true");
        }
    }
    if (vlanSpecified) {
        URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk);
        // Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks
        URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null;
        // don't allow to specify vlan tag used by physical network for dynamic vlan allocation
        if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) {
            throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName());
        }
        if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) {
            throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName());
        }
        if (!UuidUtils.validateUUID(vlanId)) {
            // For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone
            if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) {
                if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) {
                    throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId);
                } else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) {
                    throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId);
                } else {
                    final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri));
                    // the vnet is not coming from the data center vnet table, so the list can be empty
                    if (!dcVnets.isEmpty()) {
                        final DataCenterVnetVO dcVnet = dcVnets.get(0);
                        // Fail network creation if specified vlan is dedicated to a different account
                        if (dcVnet.getAccountGuestVlanMapId() != null) {
                            final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId();
                            final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId);
                            if (map.getAccountId() != owner.getAccountId()) {
                                throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account");
                            }
                        // Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool
                        } else {
                            final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId());
                            if (maps != null && !maps.isEmpty()) {
                                final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId());
                                final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId());
                                if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) {
                                    throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner " + owner.getAccountName());
                                }
                            }
                        }
                    }
                }
            } else {
                // shared network with same Vlan ID in the zone
                if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0) {
                    throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId);
                }
            }
        }
    }
    // If networkDomain is not specified, take it from the global configuration
    if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) {
        final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), Service.Dns);
        final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification);
        if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) {
            if (networkDomain != null) {
                // TBD: NetworkOfferingId and zoneId. Send uuids instead.
                throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId);
            }
        } else {
            if (networkDomain == null) {
                // 1) Get networkDomain from the corresponding account/domain/zone
                if (aclType == ACLType.Domain) {
                    networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId);
                } else if (aclType == ACLType.Account) {
                    networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId);
                }
                // 2) If null, generate networkDomain using domain suffix from the global config variables
                if (networkDomain == null) {
                    networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId);
                }
            } else {
                // validate network domain
                if (!NetUtils.verifyDomainName(networkDomain)) {
                    throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
                }
            }
        }
    }
    // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x
    // limitation, remove after we introduce support for multiple ip ranges
    // with different Cidrs for the same Shared network
    final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && ntwkOff.getTrafficType() == TrafficType.Guest && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)));
    if (cidr == null && ip6Cidr == null && cidrRequired) {
        if (ntwkOff.getGuestType() == GuestType.Shared) {
            throw new InvalidParameterValueException(String.format("Gateway/netmask are required when creating %s networks.", Network.GuestType.Shared));
        } else {
            throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled");
        }
    }
    checkL2OfferingServices(ntwkOff);
    // No cidr can be specified in Basic zone
    if (zone.getNetworkType() == NetworkType.Basic && cidr != null) {
        throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic);
    }
    // Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4
    if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) {
        if (!NetUtils.validateGuestCidr(cidr)) {
            throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant");
        }
    }
    final String networkDomainFinal = networkDomain;
    final String vlanIdFinal = vlanId;
    final Boolean subdomainAccessFinal = subdomainAccess;
    final Network network = Transaction.execute(new TransactionCallback<Network>() {

        @Override
        public Network doInTransaction(final TransactionStatus status) {
            Long physicalNetworkId = null;
            if (pNtwk != null) {
                physicalNetworkId = pNtwk.getId();
            }
            final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId);
            final NetworkVO userNetwork = new NetworkVO();
            userNetwork.setNetworkDomain(networkDomainFinal);
            if (cidr != null && gateway != null) {
                userNetwork.setCidr(cidr);
                userNetwork.setGateway(gateway);
            }
            if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) {
                userNetwork.setIp6Cidr(ip6Cidr);
                userNetwork.setIp6Gateway(ip6Gateway);
            }
            if (externalId != null) {
                userNetwork.setExternalId(externalId);
            }
            if (StringUtils.isNotBlank(routerIp)) {
                userNetwork.setRouterIp(routerIp);
            }
            if (StringUtils.isNotBlank(routerIpv6)) {
                userNetwork.setRouterIpv6(routerIpv6);
            }
            if (vlanIdFinal != null) {
                if (isolatedPvlan == null) {
                    URI uri = null;
                    if (UuidUtils.validateUUID(vlanIdFinal)) {
                        // Logical router's UUID provided as VLAN_ID
                        // Set transient field
                        userNetwork.setVlanIdAsUUID(vlanIdFinal);
                    } else {
                        uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk);
                    }
                    if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) {
                        throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal + " already exists or overlaps with other network pvlans in zone " + zoneId);
                    }
                    userNetwork.setBroadcastUri(uri);
                    if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
                        userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan);
                    } else {
                        userNetwork.setBroadcastDomainType(BroadcastDomainType.Native);
                    }
                } else {
                    if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) {
                        throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!");
                    }
                    URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString());
                    if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) {
                        throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal + " and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType + " already exists or overlaps with other network pvlans in zone " + zoneId);
                    }
                    userNetwork.setBroadcastUri(uri);
                    userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan);
                    userNetwork.setPvlanType(isolatedPvlanType);
                }
            }
            final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, isDisplayNetworkEnabled);
            Network network = null;
            if (networks == null || networks.isEmpty()) {
                throw new CloudRuntimeException("Fail to create a network");
            } else {
                if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) {
                    Network defaultGuestNetwork = networks.get(0);
                    for (final Network nw : networks) {
                        if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) {
                            defaultGuestNetwork = nw;
                        }
                    }
                    network = defaultGuestNetwork;
                } else {
                    // For shared network
                    network = networks.get(0);
                }
            }
            if (updateResourceCount) {
                _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled);
            }
            return network;
        }
    });
    CallContext.current().setEventDetails("Network Id: " + network.getId());
    CallContext.current().putContextParameter(Network.class, network.getUuid());
    return network;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) Capability(com.cloud.network.Network.Capability) NetworkOffering(com.cloud.offering.NetworkOffering) TransactionStatus(com.cloud.utils.db.TransactionStatus) URI(java.net.URI) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) List(java.util.List) DB(com.cloud.utils.db.DB)

Example 19 with AccountGuestVlanMapVO

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

the class NetworkServiceImpl method getVnetsToremove.

private List<String> getVnetsToremove(PhysicalNetworkVO network, List<Pair<Integer, Integer>> vnetRanges) {
    int i;
    List<String> removeVnets = new ArrayList<String>();
    HashSet<String> vnetsInDb = new HashSet<String>();
    vnetsInDb.addAll(_datacneterVnet.listVnetsByPhysicalNetworkAndDataCenter(network.getDataCenterId(), network.getId()));
    // remove all the vnets not in the list of vnets passed by the user.
    if (vnetRanges.size() == 0) {
        // this implies remove all vlans.
        removeVnets.addAll(vnetsInDb);
        int allocated_vnets = _datacneterVnet.countAllocatedVnets(network.getId());
        if (allocated_vnets > 0) {
            throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has " + allocated_vnets + " vnets in use");
        }
        return removeVnets;
    }
    for (Pair<Integer, Integer> vlan : vnetRanges) {
        for (i = vlan.first(); i <= vlan.second(); i++) {
            vnetsInDb.remove(Integer.toString(i));
        }
    }
    String vnetRange = null;
    if (vnetsInDb.size() != 0) {
        removeVnets.addAll(vnetsInDb);
        vnetRange = generateVnetString(removeVnets);
    } else {
        return removeVnets;
    }
    for (String vnet : vnetRange.split(",")) {
        String[] range = vnet.split("-");
        Integer start = Integer.parseInt(range[0]);
        Integer end = Integer.parseInt(range[1]);
        _datacneterVnet.lockRange(network.getDataCenterId(), network.getId(), start, end);
        List<DataCenterVnetVO> result = _datacneterVnet.listAllocatedVnetsInRange(network.getDataCenterId(), network.getId(), start, end);
        if (!result.isEmpty()) {
            throw new InvalidParameterValueException("physicalnetwork " + network.getId() + " has allocated vnets in the range " + start + "-" + end);
        }
        // If the range is partially dedicated to an account fail the request
        List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(network.getId());
        for (AccountGuestVlanMapVO map : maps) {
            String[] vlans = map.getGuestVlanRange().split("-");
            Integer dedicatedStartVlan = Integer.parseInt(vlans[0]);
            Integer dedicatedEndVlan = Integer.parseInt(vlans[1]);
            if ((start >= dedicatedStartVlan && start <= dedicatedEndVlan) || (end >= dedicatedStartVlan && end <= dedicatedEndVlan)) {
                throw new InvalidParameterValueException("Vnet range " + map.getGuestVlanRange() + " is dedicated" + " to an account. The specified range " + start + "-" + end + " overlaps with the dedicated range " + " Please release the overlapping dedicated range before deleting the range");
            }
        }
    }
    return removeVnets;
}
Also used : AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) ArrayList(java.util.ArrayList) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) HashSet(java.util.HashSet)

Example 20 with AccountGuestVlanMapVO

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

the class AccountManagerImpl method cleanupAccount.

protected boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
    long accountId = account.getId();
    boolean accountCleanupNeeded = false;
    try {
        // cleanup the users from the account
        List<UserVO> users = _userDao.listByAccount(accountId);
        for (UserVO user : users) {
            if (!_userDao.remove(user.getId())) {
                s_logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
                accountCleanupNeeded = true;
            }
        }
        // delete global load balancer rules for the account.
        List<org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(accountId);
        if (gslbRules != null && !gslbRules.isEmpty()) {
            _gslbService.revokeAllGslbRulesForAccount(caller, accountId);
        }
        // delete the account from project accounts
        _projectAccountDao.removeAccountFromProjects(accountId);
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            // delete the account from group
            _messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
        }
        // delete all vm groups belonging to accont
        List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
        for (InstanceGroupVO group : groups) {
            if (!_vmMgr.deleteVmGroup(group.getId())) {
                s_logger.error("Unable to delete group: " + group.getId());
                accountCleanupNeeded = true;
            }
        }
        // Delete the snapshots dir for the account. Have to do this before destroying the VMs.
        boolean success = _snapMgr.deleteSnapshotDirsForAccount(accountId);
        if (success) {
            s_logger.debug("Successfully deleted snapshots directories for all volumes under account " + accountId + " across all zones");
        }
        // clean up templates
        List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
        boolean allTemplatesDeleted = true;
        for (VMTemplateVO template : userTemplates) {
            if (template.getRemoved() == null) {
                try {
                    allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
                } catch (Exception e) {
                    s_logger.warn("Failed to delete template while removing account: " + template.getName() + " due to: ", e);
                    allTemplatesDeleted = false;
                }
            }
        }
        if (!allTemplatesDeleted) {
            s_logger.warn("Failed to delete templates while removing account id=" + accountId);
            accountCleanupNeeded = true;
        }
        // Destroy VM Snapshots
        List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
        for (VMSnapshot vmSnapshot : vmSnapshots) {
            try {
                _vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
            } catch (Exception e) {
                s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
            }
        }
        // Destroy the account's VMs
        List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
        }
        for (UserVmVO vm : vms) {
            if (vm.getState() != VirtualMachine.State.Destroyed && vm.getState() != VirtualMachine.State.Expunging) {
                try {
                    _vmMgr.destroyVm(vm.getId(), false);
                } catch (Exception e) {
                    e.printStackTrace();
                    s_logger.warn("Failed destroying instance " + vm.getUuid() + " as part of account deletion.");
                }
            }
            // should pass in order to perform further cleanup
            if (!_vmMgr.expunge(vm, callerUserId, caller)) {
                s_logger.error("Unable to expunge vm: " + vm.getId());
                accountCleanupNeeded = true;
            }
        }
        // Mark the account's volumes as destroyed
        List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
        for (VolumeVO volume : volumes) {
            try {
                volumeService.deleteVolume(volume.getId(), caller);
            } catch (Exception ex) {
                s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
                accountCleanupNeeded = true;
            }
        }
        // delete remote access vpns and associated users
        List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
        List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
        for (VpnUserVO vpnUser : vpnUsers) {
            _remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
        }
        try {
            for (RemoteAccessVpnVO vpn : remoteAccessVpns) {
                _remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, false);
            }
        } catch (ResourceUnavailableException ex) {
            s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
            accountCleanupNeeded = true;
        }
        // Cleanup security groups
        int numRemoved = _securityGroupDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
        // Cleanup affinity groups
        int numAGRemoved = _affinityGroupDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Deleted " + numAGRemoved + " affinity groups for account " + accountId);
        // Delete all the networks
        boolean networksDeleted = true;
        s_logger.debug("Deleting networks for account " + account.getId());
        List<NetworkVO> networks = _networkDao.listByOwner(accountId);
        if (networks != null) {
            for (NetworkVO network : networks) {
                ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller);
                if (!_networkMgr.destroyNetwork(network.getId(), context, false)) {
                    s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
                    accountCleanupNeeded = true;
                    networksDeleted = false;
                } else {
                    s_logger.debug("Network " + network.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
                }
            }
        }
        // Delete all VPCs
        boolean vpcsDeleted = true;
        s_logger.debug("Deleting vpcs for account " + account.getId());
        List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
        for (Vpc vpc : vpcs) {
            if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) {
                s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup.");
                accountCleanupNeeded = true;
                vpcsDeleted = false;
            } else {
                s_logger.debug("VPC " + vpc.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
            }
        }
        if (networksDeleted && vpcsDeleted) {
            // release ip addresses belonging to the account
            List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
            for (IpAddress ip : ipsToRelease) {
                s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
                if (!_ipAddrMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
                    s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
                    accountCleanupNeeded = true;
                }
            }
        }
        // Delete Site 2 Site VPN customer gateway
        s_logger.debug("Deleting site-to-site VPN customer gateways for account " + accountId);
        if (!_vpnMgr.deleteCustomerGatewayByAccount(accountId)) {
            s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId);
        }
        // Delete autoscale resources if any
        try {
            _autoscaleMgr.cleanUpAutoScaleResources(accountId);
        } catch (CloudRuntimeException ex) {
            s_logger.warn("Failed to cleanup AutoScale resources as a part of account id=" + accountId + " cleanup due to exception:", ex);
            accountCleanupNeeded = true;
        }
        // up successfully
        if (networksDeleted) {
            if (!_configMgr.releaseAccountSpecificVirtualRanges(accountId)) {
                accountCleanupNeeded = true;
            } else {
                s_logger.debug("Account specific Virtual IP ranges " + " are successfully released as a part of account id=" + accountId + " cleanup.");
            }
        }
        // release account specific guest vlans
        List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
        for (AccountGuestVlanMapVO map : maps) {
            _dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
        }
        int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
        // release account specific acquired portable IP's. Since all the portable IP's must have been already
        // disassociated with VPC/guest network (due to deletion), so just mark portable IP as free.
        List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
        for (IpAddress ip : ipsToRelease) {
            if (ip.isPortable()) {
                s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
                _ipAddrMgr.releasePortableIpAddress(ip.getId());
            }
        }
        // release dedication if any
        List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for account " + accountId);
            for (DedicatedResourceVO dr : dedicatedResources) {
                if (!_dedicatedDao.remove(dr.getId())) {
                    s_logger.warn("Fail to release dedicated resources for account " + accountId);
                }
            }
        }
        // Updating and deleting the resourceLimit and resourceCount should be the last step in cleanupAccount
        // process.
        // Update resource count for this account and for parent domains.
        List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
        for (ResourceCountVO resourceCount : resourceCounts) {
            _resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
        }
        // Delete resource count and resource limits entries set for this account (if there are any).
        _resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
        _resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
        // Delete ssh keypairs
        List<SSHKeyPairVO> sshkeypairs = _sshKeyPairDao.listKeyPairs(accountId, account.getDomainId());
        for (SSHKeyPairVO keypair : sshkeypairs) {
            _sshKeyPairDao.remove(keypair.getId());
        }
        return true;
    } catch (Exception ex) {
        s_logger.warn("Failed to cleanup account " + account + " due to ", ex);
        accountCleanupNeeded = true;
        return true;
    } finally {
        s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed."));
        if (accountCleanupNeeded) {
            _accountDao.markForCleanup(accountId);
        } else {
            account.setNeedsCleanup(false);
            _accountDao.update(accountId, account);
        }
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) VpnUserVO(com.cloud.network.VpnUserVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) Vpc(com.cloud.network.vpc.Vpc) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) VolumeVO(com.cloud.storage.VolumeVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkVO(com.cloud.network.dao.NetworkVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InstanceGroupVO(com.cloud.vm.InstanceGroupVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VpnUserVO(com.cloud.network.VpnUserVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ResourceCountVO(com.cloud.configuration.ResourceCountVO) IpAddress(com.cloud.network.IpAddress) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Aggregations

AccountGuestVlanMapVO (com.cloud.network.dao.AccountGuestVlanMapVO)23 ArrayList (java.util.ArrayList)17 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)13 DataCenterVnetVO (com.cloud.dc.DataCenterVnetVO)11 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)8 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)7 DB (com.cloud.utils.db.DB)7 List (java.util.List)7 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)6 Field (java.lang.reflect.Field)6 NetworkVO (com.cloud.network.dao.NetworkVO)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 ActionEvent (com.cloud.event.ActionEvent)4 Project (com.cloud.projects.Project)4 Account (com.cloud.user.Account)4 Pair (com.cloud.utils.Pair)4 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)3 Network (com.cloud.network.Network)3 Capability (com.cloud.network.Network.Capability)3 PhysicalNetwork (com.cloud.network.PhysicalNetwork)3