Search in sources :

Example 11 with UserVO

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

the class InternalLBVMServiceTest method setUp.

@Override
@Before
public void setUp() {
    //mock system offering creation as it's used by configure() method called by initComponentsLifeCycle
    Mockito.when(_accountMgr.getAccount(1L)).thenReturn(new AccountVO());
    ServiceOfferingVO off = new ServiceOfferingVO("alena", 1, 1, 1, 1, 1, false, "alena", Storage.ProvisioningType.THIN, false, false, null, false, VirtualMachine.Type.InternalLoadBalancerVm, false);
    off = setId(off, 1);
    List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
    list.add(off);
    list.add(off);
    Mockito.when(_svcOffDao.createSystemServiceOfferings(Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.any(ProvisioningType.class), Matchers.anyBoolean(), Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(VirtualMachine.Type.class), Matchers.anyBoolean())).thenReturn(list);
    ComponentContext.initComponentsLifeCycle();
    Mockito.when(_accountMgr.getSystemUser()).thenReturn(new UserVO(1));
    Mockito.when(_accountMgr.getSystemAccount()).thenReturn(new AccountVO(2));
    Mockito.when(_accountDao.findByIdIncludingRemoved(Matchers.anyLong())).thenReturn(new AccountVO(2));
    CallContext.register(_accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
    final DomainRouterVO validVm = new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false, VirtualMachine.Type.InternalLoadBalancerVm, null);
    validVm.setRole(Role.INTERNAL_LB_VM);
    final DomainRouterVO nonInternalLbVm = new DomainRouterVO(validVmId, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false, VirtualMachine.Type.DomainRouter, null);
    nonInternalLbVm.setRole(Role.VIRTUAL_ROUTER);
    Mockito.when(_domainRouterDao.findById(validVmId)).thenReturn(validVm);
    Mockito.when(_domainRouterDao.findById(nonExistingVmId)).thenReturn(null);
    Mockito.when(_domainRouterDao.findById(nonInternalLbVmId)).thenReturn(nonInternalLbVm);
}
Also used : ProvisioningType(com.cloud.storage.Storage.ProvisioningType) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ProvisioningType(com.cloud.storage.Storage.ProvisioningType) UserVO(com.cloud.user.UserVO) ArrayList(java.util.ArrayList) AccountVO(com.cloud.user.AccountVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) DomainRouterVO(com.cloud.vm.DomainRouterVO) Before(org.junit.Before)

Example 12 with UserVO

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

the class GloboDnsElementTest method setUp.

@Before
public void setUp() throws Exception {
    ComponentContext.initComponentsLifeCycle();
    acct = new AccountVO(200L);
    acct.setType(Account.ACCOUNT_TYPE_NORMAL);
    acct.setAccountName("user");
    acct.setDomainId(domainId);
    user = new UserVO();
    user.setUsername("user");
    user.setAccountId(acct.getAccountId());
    CallContext.register(user, acct);
    when(_acctMgr.getSystemAccount()).thenReturn(this.acct);
    when(_acctMgr.getSystemUser()).thenReturn(this.user);
}
Also used : UserVO(com.cloud.user.UserVO) AccountVO(com.cloud.user.AccountVO) Before(org.junit.Before)

Example 13 with UserVO

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

the class InternalLoadBalancerVMManagerImpl method deployInternalLbVm.

protected DomainRouterVO deployInternalLbVm(final Account owner, final DeployDestination dest, final DeploymentPlan plan, final Map<Param, Object> params, final long internalLbProviderId, final long svcOffId, final Long vpcId, final LinkedHashMap<Network, List<? extends NicProfile>> networks, final boolean startVm) throws ConcurrentOperationException, InsufficientAddressCapacityException, InsufficientServerCapacityException, InsufficientCapacityException, StorageUnavailableException, ResourceUnavailableException {
    final ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(svcOffId);
    // Internal lb is the network element, we don't know the hypervisor type yet.
    // Try to allocate the internal lb twice using diff hypervisors, and when failed both times, throw the exception up
    final List<HypervisorType> hypervisors = getHypervisors(dest, plan, null);
    int allocateRetry = 0;
    int startRetry = 0;
    DomainRouterVO internalLbVm = null;
    for (final Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext(); ) {
        final HypervisorType hType = iter.next();
        try {
            final long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating the internal lb vm " + id + " in datacenter " + dest.getDataCenter() + " with hypervisor type " + hType);
            }
            String templateName = null;
            switch(hType) {
                case XenServer:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateXen.valueIn(dest.getDataCenter().getId());
                    break;
                case KVM:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateKvm.valueIn(dest.getDataCenter().getId());
                    break;
                case VMware:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateVmware.valueIn(dest.getDataCenter().getId());
                    break;
                case Hyperv:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateHyperV.valueIn(dest.getDataCenter().getId());
                    break;
                case LXC:
                    templateName = VirtualNetworkApplianceManager.RouterTemplateLxc.valueIn(dest.getDataCenter().getId());
                    break;
                default:
                    break;
            }
            final VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
            if (template == null) {
                s_logger.debug(hType + " won't support system vm, skip it");
                continue;
            }
            long userId = CallContext.current().getCallingUserId();
            if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
                List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
                if (!userVOs.isEmpty()) {
                    userId = userVOs.get(0).getId();
                }
            }
            internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, VirtualMachineName.getSystemVmName(id, _instance, InternalLbVmNamePrefix), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
            internalLbVm.setRole(Role.INTERNAL_LB_VM);
            internalLbVm = _internalLbVmDao.persist(internalLbVm);
            _itMgr.allocate(internalLbVm.getInstanceName(), template, routerOffering, networks, plan, null);
            internalLbVm = _internalLbVmDao.findById(internalLbVm.getId());
        } catch (final InsufficientCapacityException ex) {
            if (allocateRetry < 2 && iter.hasNext()) {
                s_logger.debug("Failed to allocate the Internal lb vm with hypervisor type " + hType + ", retrying one more time");
                continue;
            } else {
                throw ex;
            }
        } finally {
            allocateRetry++;
        }
        if (startVm) {
            try {
                internalLbVm = startInternalLbVm(internalLbVm, _accountMgr.getSystemAccount(), User.UID_SYSTEM, params);
                break;
            } catch (final InsufficientCapacityException ex) {
                if (startRetry < 2 && iter.hasNext()) {
                    s_logger.debug("Failed to start the Internal lb vm  " + internalLbVm + " with hypervisor type " + hType + ", " + "destroying it and recreating one more time");
                    // destroy the internal lb vm
                    destroyInternalLbVm(internalLbVm.getId(), _accountMgr.getSystemAccount(), User.UID_SYSTEM);
                    continue;
                } else {
                    throw ex;
                }
            } finally {
                startRetry++;
            }
        } else {
            //return stopped internal lb vm
            return internalLbVm;
        }
    }
    return internalLbVm;
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) UserVO(com.cloud.user.UserVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 14 with UserVO

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

the class AccountDaoImpl method findUserAccountByApiKey.

@Override
public Pair<User, Account> findUserAccountByApiKey(String apiKey) {
    TransactionLegacy txn = TransactionLegacy.currentTxn();
    PreparedStatement pstmt = null;
    Pair<User, Account> userAcctPair = null;
    try {
        String sql = FIND_USER_ACCOUNT_BY_API_KEY;
        pstmt = txn.prepareAutoCloseStatement(sql);
        pstmt.setString(1, apiKey);
        ResultSet rs = pstmt.executeQuery();
        // TODO:  make sure we don't have more than 1 result?  ApiKey had better be unique
        if (rs.next()) {
            User u = new UserVO(rs.getLong(1));
            u.setUsername(rs.getString(2));
            u.setAccountId(rs.getLong(3));
            u.setSecretKey(DBEncryptionUtil.decrypt(rs.getString(4)));
            u.setState(State.valueOf(rs.getString(5)));
            AccountVO a = new AccountVO(rs.getLong(6));
            a.setAccountName(rs.getString(7));
            a.setType(rs.getShort(8));
            a.setRoleId(rs.getLong(9));
            a.setDomainId(rs.getLong(10));
            a.setState(State.valueOf(rs.getString(11)));
            userAcctPair = new Pair<User, Account>(u, a);
        }
    } catch (Exception e) {
        s_logger.warn("Exception finding user/acct by api key: " + apiKey, e);
    }
    return userAcctPair;
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Account(com.cloud.user.Account) User(com.cloud.user.User) UserVO(com.cloud.user.UserVO) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) AccountVO(com.cloud.user.AccountVO)

Example 15 with UserVO

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

the class QuotaAlertManagerImpl method sendQuotaAlert.

public void sendQuotaAlert(DeferredQuotaEmail emailToBeSent) {
    final AccountVO account = emailToBeSent.getAccount();
    final BigDecimal balance = emailToBeSent.getQuotaBalance();
    final BigDecimal usage = emailToBeSent.getQuotaUsage();
    final QuotaConfig.QuotaEmailTemplateTypes emailType = emailToBeSent.getEmailTemplateType();
    final List<QuotaEmailTemplatesVO> emailTemplates = _quotaEmailTemplateDao.listAllQuotaEmailTemplates(emailType.toString());
    if (emailTemplates != null && emailTemplates.get(0) != null) {
        final QuotaEmailTemplatesVO emailTemplate = emailTemplates.get(0);
        final DomainVO accountDomain = _domainDao.findByIdIncludingRemoved(account.getDomainId());
        final List<UserVO> usersInAccount = _userDao.listByAccount(account.getId());
        String userNames = "";
        final List<String> emailRecipients = new ArrayList<String>();
        for (UserVO user : usersInAccount) {
            userNames += String.format("%s <%s>,", user.getUsername(), user.getEmail());
            emailRecipients.add(user.getEmail());
        }
        if (userNames.endsWith(",")) {
            userNames = userNames.substring(0, userNames.length() - 1);
        }
        final Map<String, String> optionMap = new HashMap<String, String>();
        optionMap.put("accountName", account.getAccountName());
        optionMap.put("accountID", account.getUuid());
        optionMap.put("accountUsers", userNames);
        optionMap.put("domainName", accountDomain.getName());
        optionMap.put("domainID", accountDomain.getUuid());
        optionMap.put("quotaBalance", QuotaConfig.QuotaCurrencySymbol.value() + " " + balance.toString());
        if (emailType == QuotaEmailTemplateTypes.QUOTA_STATEMENT) {
            optionMap.put("quotaUsage", QuotaConfig.QuotaCurrencySymbol.value() + " " + usage.toString());
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("accountName" + account.getAccountName() + "accountID" + account.getUuid() + "accountUsers" + userNames + "domainName" + accountDomain.getName() + "domainID" + accountDomain.getUuid());
        }
        final StrSubstitutor templateEngine = new StrSubstitutor(optionMap);
        final String subject = templateEngine.replace(emailTemplate.getTemplateSubject());
        final String body = templateEngine.replace(emailTemplate.getTemplateBody());
        try {
            _emailQuotaAlert.sendQuotaAlert(emailRecipients, subject, body);
            emailToBeSent.sentSuccessfully(_quotaAcc);
        } catch (Exception e) {
            s_logger.error(String.format("Unable to send quota alert email (subject=%s; body=%s) to account %s (%s) recipients (%s) due to error (%s)", subject, body, account.getAccountName(), account.getUuid(), emailRecipients, e));
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Exception", e);
            }
        }
    } else {
        s_logger.error(String.format("No quota email template found for type %s, cannot send quota alert email to account %s(%s)", emailType, account.getAccountName(), account.getUuid()));
    }
}
Also used : QuotaEmailTemplatesVO(org.apache.cloudstack.quota.vo.QuotaEmailTemplatesVO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QuotaEmailTemplateTypes(org.apache.cloudstack.quota.constant.QuotaConfig.QuotaEmailTemplateTypes) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) BigDecimal(java.math.BigDecimal) MessagingException(javax.mail.MessagingException) ConfigurationException(javax.naming.ConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DomainVO(com.cloud.domain.DomainVO) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) UserVO(com.cloud.user.UserVO) QuotaConfig(org.apache.cloudstack.quota.constant.QuotaConfig)

Aggregations

UserVO (com.cloud.user.UserVO)72 AccountVO (com.cloud.user.AccountVO)44 Account (com.cloud.user.Account)42 Test (org.junit.Test)23 Before (org.junit.Before)21 ArrayList (java.util.ArrayList)19 Field (java.lang.reflect.Field)15 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)11 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)11 HashMap (java.util.HashMap)11 DomainVO (com.cloud.domain.DomainVO)10 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 DomainRouterVO (com.cloud.vm.DomainRouterVO)8 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7 Service (com.cloud.network.Network.Service)7 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)6 DataCenterVO (com.cloud.dc.DataCenterVO)5 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)5 LinkedHashMap (java.util.LinkedHashMap)5 NetworkOrchestrationService (org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService)5