Search in sources :

Example 6 with AccountGuestVlanMapVO

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

the class DedicateGuestVlanRangesTest method runDedicateGuestVlanRangePostiveTest.

void runDedicateGuestVlanRangePostiveTest() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runDedicateGuestVlanRangePostiveTest");
    Field dedicateVlanField = _dedicateGuestVlanRangeClass.getDeclaredField("vlan");
    dedicateVlanField.setAccessible(true);
    dedicateVlanField.set(dedicateGuestVlanRangesCmd, "2-5");
    PhysicalNetworkVO physicalNetwork = new PhysicalNetworkVO(1L, 1L, "2-5", "200", 1L, null, "testphysicalnetwork");
    physicalNetwork.addIsolationMethod("VLAN");
    AccountGuestVlanMapVO accountGuestVlanMapVO = new AccountGuestVlanMapVO(1L, 1L);
    when(networkService._physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetwork);
    when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null);
    when(networkService._accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(anyLong())).thenReturn(null);
    when(networkService._accountGuestVlanMapDao.persist(any(AccountGuestVlanMapVO.class))).thenReturn(accountGuestVlanMapVO);
    when(networkService._datacneterVnet.update(anyLong(), any(DataCenterVnetVO.class))).thenReturn(true);
    List<DataCenterVnetVO> dataCenterVnetList = new ArrayList<DataCenterVnetVO>();
    DataCenterVnetVO dataCenterVnetVO = new DataCenterVnetVO("2-5", 1L, 1L);
    dataCenterVnetList.add(dataCenterVnetVO);
    when(networkService._datacneterVnet.findVnet(anyLong(), anyString())).thenReturn(dataCenterVnetList);
    try {
        GuestVlan result = networkService.dedicateGuestVlanRange(dedicateGuestVlanRangesCmd);
        Assert.assertNotNull(result);
    } catch (Exception e) {
        s_logger.info("exception in testing runDedicateGuestVlanRangePostiveTest message: " + e.toString());
    } finally {
        txn.close("runDedicateGuestRangePostiveTest");
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Field(java.lang.reflect.Field) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList)

Example 7 with AccountGuestVlanMapVO

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

the class DedicateGuestVlanRangesTest method runDedicateGuestVlanRangePartiallyDedicated.

void runDedicateGuestVlanRangePartiallyDedicated() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runDedicateGuestVlanRangePartiallyDedicated");
    Field dedicateVlanField = _dedicateGuestVlanRangeClass.getDeclaredField("vlan");
    dedicateVlanField.setAccessible(true);
    dedicateVlanField.set(dedicateGuestVlanRangesCmd, "2-5");
    PhysicalNetworkVO physicalNetwork = new PhysicalNetworkVO(1L, 1L, "2-5", "200", 1L, null, "testphysicalnetwork");
    physicalNetwork.addIsolationMethod("VLAN");
    when(networkService._physicalNetworkDao.findById(anyLong())).thenReturn(physicalNetwork);
    when(networkService._datacneterVnet.listAllocatedVnetsInRange(anyLong(), anyLong(), anyInt(), anyInt())).thenReturn(null);
    List<AccountGuestVlanMapVO> guestVlanMaps = new ArrayList<AccountGuestVlanMapVO>();
    AccountGuestVlanMapVO accountGuestVlanMap = new AccountGuestVlanMapVO(2L, 1L);
    accountGuestVlanMap.setGuestVlanRange("4-8");
    guestVlanMaps.add(accountGuestVlanMap);
    when(networkService._accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(anyLong())).thenReturn(guestVlanMaps);
    try {
        networkService.dedicateGuestVlanRange(dedicateGuestVlanRangesCmd);
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("Vlan range is already dedicated"));
    } finally {
        txn.close("runDedicateGuestVlanRangePartiallyDedicated");
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Field(java.lang.reflect.Field) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList)

Example 8 with AccountGuestVlanMapVO

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

the class DedicateGuestVlanRangesTest method runReleaseDedicatedGuestVlanRangePostiveTest.

void runReleaseDedicatedGuestVlanRangePostiveTest() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runReleaseDedicatedGuestVlanRangePostiveTest");
    AccountGuestVlanMapVO accountGuestVlanMap = new AccountGuestVlanMapVO(1L, 1L);
    when(networkService._accountGuestVlanMapDao.findById(anyLong())).thenReturn(accountGuestVlanMap);
    doNothing().when(networkService._datacneterVnet).releaseDedicatedGuestVlans(anyLong());
    when(networkService._accountGuestVlanMapDao.remove(anyLong())).thenReturn(true);
    try {
        Boolean result = networkService.releaseDedicatedGuestVlanRange(releaseDedicatedGuestVlanRangesCmd.getId());
        Assert.assertTrue(result);
    } catch (Exception e) {
        s_logger.info("exception in testing runReleaseGuestVlanRangePostiveTest1 message: " + e.toString());
    } finally {
        txn.close("runReleaseDedicatedGuestVlanRangePostiveTest");
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO)

Example 9 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) {
            if (!volume.getState().equals(Volume.State.Destroy)) {
                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);
        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)

Example 10 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)

Aggregations

AccountGuestVlanMapVO (com.cloud.network.dao.AccountGuestVlanMapVO)11 ArrayList (java.util.ArrayList)8 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)6 DataCenterVnetVO (com.cloud.dc.DataCenterVnetVO)5 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)4 DB (com.cloud.utils.db.DB)3 Field (java.lang.reflect.Field)3 ActionEvent (com.cloud.event.ActionEvent)2 NetworkVO (com.cloud.network.dao.NetworkVO)2 Project (com.cloud.projects.Project)2 Account (com.cloud.user.Account)2 Pair (com.cloud.utils.Pair)2 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)2 List (java.util.List)2 ResourceCountVO (com.cloud.configuration.ResourceCountVO)1 DataCenterVO (com.cloud.dc.DataCenterVO)1 DedicatedResourceVO (com.cloud.dc.DedicatedResourceVO)1 DataCenterDeployment (com.cloud.deploy.DataCenterDeployment)1 DomainVO (com.cloud.domain.DomainVO)1