Search in sources :

Example 81 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaServiceImpl method getQuotaUsage.

@Override
public List<QuotaUsageVO> getQuotaUsage(Long accountId, String accountName, Long domainId, Integer usageType, Date startDate, Date endDate) {
    // if accountId is not specified, use accountName and domainId
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        Account userAccount = null;
        Account caller = CallContext.current().getCallingAccount();
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (!accounts.isEmpty()) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    if (startDate.after(endDate)) {
        throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
    }
    if (endDate.after(_respBldr.startOfNextDay())) {
        throw new InvalidParameterValueException("Incorrect Date Range. End date:" + endDate + " should not be in future. ");
    }
    Date adjustedEndDate = computeAdjustedTime(endDate);
    Date adjustedStartDate = computeAdjustedTime(startDate);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Getting quota records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate);
    }
    return _quotaUsageDao.findQuotaUsage(accountId, domainId, usageType, adjustedStartDate, adjustedEndDate);
}
Also used : Account(com.cloud.user.Account) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date)

Example 82 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaResponseBuilderImpl method createQuotaSummaryResponse.

@Override
public List<QuotaSummaryResponse> createQuotaSummaryResponse(Boolean listAll) {
    List<QuotaSummaryResponse> result = new ArrayList<QuotaSummaryResponse>();
    if (listAll) {
        for (final AccountVO account : _accountDao.listAll()) {
            QuotaSummaryResponse qr = getQuotaSummaryResponse(account);
            result.add(qr);
        }
    } else {
        for (final QuotaAccountVO quotaAccount : _quotaAccountDao.listAllQuotaAccount()) {
            AccountVO account = _accountDao.findById(quotaAccount.getId());
            if (account == null)
                continue;
            QuotaSummaryResponse qr = getQuotaSummaryResponse(account);
            result.add(qr);
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO)

Example 83 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class QuotaCreditsCmdTest method testQuotaCreditsCmd.

@Test
public void testQuotaCreditsCmd() throws NoSuchFieldException, IllegalAccessException {
    QuotaCreditsCmd cmd = new QuotaCreditsCmd();
    cmd.setAccountName("admin");
    cmd.setMinBalance(200.0);
    Field rbField = QuotaCreditsCmd.class.getDeclaredField("_responseBuilder");
    rbField.setAccessible(true);
    rbField.set(cmd, responseBuilder);
    Field qsbField = QuotaCreditsCmd.class.getDeclaredField("_quotaService");
    qsbField.setAccessible(true);
    qsbField.set(cmd, quotaService);
    Field asField = BaseCmd.class.getDeclaredField("_accountService");
    asField.setAccessible(true);
    asField.set(cmd, accountService);
    AccountVO acc = new AccountVO();
    acc.setId(2L);
    Mockito.when(accountService.getActiveAccountByName(Mockito.anyString(), Mockito.anyLong())).thenReturn(acc);
    Mockito.when(responseBuilder.addQuotaCredits(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyDouble(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(new QuotaCreditsResponse());
    // No value provided test
    try {
        cmd.execute();
    } catch (ServerApiException e) {
        assertTrue(e.getErrorCode().equals(ApiErrorCode.PARAM_ERROR));
    }
    // With value provided test
    cmd.setValue(11.80);
    cmd.execute();
    Mockito.verify(quotaService, Mockito.times(0)).setLockAccount(Mockito.anyLong(), Mockito.anyBoolean());
    Mockito.verify(quotaService, Mockito.times(1)).setMinBalance(Mockito.anyLong(), Mockito.anyDouble());
    Mockito.verify(responseBuilder, Mockito.times(1)).addQuotaCredits(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyDouble(), Mockito.anyLong(), Mockito.anyBoolean());
}
Also used : Field(java.lang.reflect.Field) ServerApiException(org.apache.cloudstack.api.ServerApiException) AccountVO(com.cloud.user.AccountVO) QuotaCreditsResponse(org.apache.cloudstack.api.response.QuotaCreditsResponse) Test(org.junit.Test)

Example 84 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class NuageVspGuestNetworkGuru method reserve.

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

Example 85 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class NuageVspGuestNetworkGuru method implement.

@Override
public Network implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException {
    long networkId = network.getId();
    network = _networkDao.acquireInLockTable(network.getId(), 1200);
    if (network == null) {
        throw new ConcurrentOperationException("Unable to acquire lock on network " + networkId);
    }
    NetworkVO implemented = null;
    try {
        if (offering.getGuestType() == GuestType.Isolated && network.getState() != State.Implementing) {
            throw new IllegalStateException("Network " + networkId + " is not in expected state Implementing, but is in state " + network.getState());
        }
        //Get the Account details and find the type
        AccountVO networksAccount = _accountDao.findById(network.getAccountId());
        if (networksAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
            String errorMessage = "Networks created by account " + networksAccount.getAccountName() + " of type Project (" + Account.ACCOUNT_TYPE_PROJECT + ") " + "are not yet supported by NuageVsp provider";
            s_logger.error(errorMessage);
            throw new InsufficientVirtualNetworkCapacityException(errorMessage, Account.class, network.getAccountId());
        }
        //We don't support a shared network with UserData and multiple IP ranges at the same time.
        checkMultipleSubnetsCombinedWithUseData(network);
        long dcId = dest.getDataCenter().getId();
        //Get physical network id
        Long physicalNetworkId = network.getPhysicalNetworkId();
        //Physical network id can be null in Guest Network in Basic zone, so locate the physical network
        if (physicalNetworkId == null) {
            physicalNetworkId = _networkModel.findPhysicalNetworkId(dcId, offering.getTags(), offering.getTrafficType());
        }
        implemented = new NetworkVO(network.getId(), network, network.getNetworkOfferingId(), network.getGuruName(), network.getDomainId(), network.getAccountId(), network.getRelated(), network.getName(), network.getDisplayText(), network.getNetworkDomain(), network.getGuestType(), network.getDataCenterId(), physicalNetworkId, network.getAclType(), network.getSpecifyIpRanges(), network.getVpcId(), offering.getRedundantRouter());
        implemented.setUuid(network.getUuid());
        implemented.setState(State.Allocated);
        if (network.getGateway() != null) {
            implemented.setGateway(network.getGateway());
        }
        if (network.getCidr() != null) {
            implemented.setCidr(network.getCidr());
        }
        VspNetwork vspNetwork = _nuageVspEntityBuilder.buildVspNetwork(implemented);
        String tenantId = context.getDomain().getName() + "-" + context.getAccount().getAccountId();
        String broadcastUriStr = implemented.getUuid() + "/" + vspNetwork.getVirtualRouterIp();
        implemented.setBroadcastUri(Networks.BroadcastDomainType.Vsp.toUri(broadcastUriStr));
        implemented.setBroadcastDomainType(Networks.BroadcastDomainType.Vsp);
        if (!implement(physicalNetworkId, vspNetwork, _nuageVspEntityBuilder.buildNetworkDhcpOption(network, offering))) {
            return null;
        }
        if (StringUtils.isNotBlank(vspNetwork.getDomainTemplateName())) {
            if (network.getVpcId() != null) {
                VpcDetailVO vpcDetail = new VpcDetailVO(network.getVpcId(), NuageVspManager.nuageDomainTemplateDetailName, vspNetwork.getDomainTemplateName(), false);
                _vpcDetailsDao.persist(vpcDetail);
            } else {
                NetworkDetailVO networkDetail = new NetworkDetailVO(implemented.getId(), NuageVspManager.nuageDomainTemplateDetailName, vspNetwork.getDomainTemplateName(), false);
                _networkDetailsDao.persist(networkDetail);
            }
        }
        s_logger.info("Implemented OK, network " + implemented.getUuid() + " in tenant " + tenantId + " linked to " + implemented.getBroadcastUri());
    } finally {
        _networkDao.releaseFromLockTable(network.getId());
    }
    return implemented;
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) VspNetwork(net.nuage.vsp.acs.client.api.model.VspNetwork) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) AccountVO(com.cloud.user.AccountVO) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO) VpcDetailVO(org.apache.cloudstack.resourcedetail.VpcDetailVO)

Aggregations

AccountVO (com.cloud.user.AccountVO)139 Account (com.cloud.user.Account)65 Test (org.junit.Test)52 UserVO (com.cloud.user.UserVO)44 Field (java.lang.reflect.Field)41 ArrayList (java.util.ArrayList)40 DomainVO (com.cloud.domain.DomainVO)32 AccountManager (com.cloud.user.AccountManager)27 Before (org.junit.Before)22 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)21 Date (java.util.Date)16 QuotaAccountVO (org.apache.cloudstack.quota.vo.QuotaAccountVO)16 DomainDao (com.cloud.domain.dao.DomainDao)14 SslCertDao (com.cloud.network.dao.SslCertDao)14 AgentManager (com.cloud.agent.AgentManager)13 IPAddressDao (com.cloud.network.dao.IPAddressDao)13 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)13 NetworkDao (com.cloud.network.dao.NetworkDao)13 NetworkVO (com.cloud.network.dao.NetworkVO)13