Search in sources :

Example 21 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class LdapImportUsersCmd method execute.

@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
    if (getAccountType() == null && getRoleId() == null) {
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Both account type and role ID are not provided");
    }
    List<LdapUser> users;
    try {
        if (StringUtils.isNotBlank(groupName)) {
            users = _ldapManager.getUsersInGroup(groupName);
        } else {
            users = _ldapManager.getUsers();
        }
    } catch (NoLdapUserMatchingQueryException ex) {
        users = new ArrayList<LdapUser>();
        s_logger.info("No Ldap user matching query. " + " ::: " + ex.getMessage());
    }
    List<LdapUser> addedUsers = new ArrayList<LdapUser>();
    for (LdapUser user : users) {
        Domain domain = getDomain(user);
        try {
            createCloudstackUserAccount(user, getAccountName(user), domain);
            addedUsers.add(user);
        } catch (InvalidParameterValueException ex) {
            s_logger.error("Failed to create user with username: " + user.getUsername() + " ::: " + ex.getMessage());
        }
    }
    ListResponse<LdapUserResponse> response = new ListResponse<LdapUserResponse>();
    response.setResponses(createLdapUserResponse(addedUsers));
    response.setResponseName(getCommandName());
    setResponseObject(response);
}
Also used : NoLdapUserMatchingQueryException(org.apache.cloudstack.ldap.NoLdapUserMatchingQueryException) LdapUser(org.apache.cloudstack.ldap.LdapUser) ServerApiException(org.apache.cloudstack.api.ServerApiException) ListResponse(org.apache.cloudstack.api.response.ListResponse) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList) Domain(com.cloud.domain.Domain) LdapUserResponse(org.apache.cloudstack.api.response.LdapUserResponse)

Example 22 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class DomainJoinDaoImpl method newDomainResponse.

@Override
public DomainResponse newDomainResponse(ResponseView view, DomainJoinVO domain) {
    DomainResponse domainResponse = new DomainResponse();
    domainResponse.setDomainName(domain.getName());
    domainResponse.setId(domain.getUuid());
    domainResponse.setLevel(domain.getLevel());
    domainResponse.setNetworkDomain(domain.getNetworkDomain());
    Domain parentDomain = ApiDBUtils.findDomainById(domain.getParent());
    if (parentDomain != null) {
        domainResponse.setParentDomainId(parentDomain.getUuid());
    }
    StringBuilder domainPath = new StringBuilder("ROOT");
    (domainPath.append(domain.getPath())).deleteCharAt(domainPath.length() - 1);
    domainResponse.setPath(domainPath.toString());
    if (domain.getParent() != null) {
        domainResponse.setParentDomainName(ApiDBUtils.findDomainById(domain.getParent()).getName());
    }
    if (domain.getChildCount() > 0) {
        domainResponse.setHasChild(true);
    }
    domainResponse.setState(domain.getState().toString());
    domainResponse.setNetworkDomain(domain.getNetworkDomain());
    boolean fullView = (view == ResponseView.Full && domain.getId() == Domain.ROOT_DOMAIN);
    setResourceLimits(domain, fullView, domainResponse);
    //get resource limits for projects
    long projectLimit = ApiDBUtils.findCorrectResourceLimitForDomain(domain.getProjectLimit(), fullView, ResourceType.project, domain.getId());
    String projectLimitDisplay = (fullView || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit);
    long projectTotal = (domain.getProjectTotal() == null) ? 0 : domain.getProjectTotal();
    String projectAvail = (fullView || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal);
    domainResponse.setProjectLimit(projectLimitDisplay);
    domainResponse.setProjectTotal(projectTotal);
    domainResponse.setProjectAvailable(projectAvail);
    domainResponse.setObjectName("domain");
    return domainResponse;
}
Also used : DomainResponse(org.apache.cloudstack.api.response.DomainResponse) Domain(com.cloud.domain.Domain)

Example 23 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class AccountManagerImpl method createUserAccount.

// ///////////////////////////////////////////////////
// ////////////// API commands /////////////////////
// ///////////////////////////////////////////////////
@Override
@DB
@ActionEvents({ @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"), @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") })
public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, final short accountType, final Long roleId, Long domainId, final String networkDomain, final Map<String, String> details, String accountUUID, final String userUUID, final User.Source source) {
    if (accountName == null) {
        accountName = userName;
    }
    if (domainId == null) {
        domainId = Domain.ROOT_DOMAIN;
    }
    if (StringUtils.isEmpty(userName)) {
        throw new InvalidParameterValueException("Username is empty");
    }
    if (StringUtils.isEmpty(firstName)) {
        throw new InvalidParameterValueException("Firstname is empty");
    }
    if (StringUtils.isEmpty(lastName)) {
        throw new InvalidParameterValueException("Lastname is empty");
    }
    // Validate domain
    Domain domain = _domainMgr.getDomain(domainId);
    if (domain == null) {
        throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account");
    }
    // Check permissions
    checkAccess(CallContext.current().getCallingAccount(), domain);
    if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) {
        throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId);
    }
    if (networkDomain != null && networkDomain.length() > 0) {
        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 \"-\"");
        }
    }
    final String accountNameFinal = accountName;
    final Long domainIdFinal = domainId;
    final String accountUUIDFinal = accountUUID;
    Pair<Long, Account> pair = Transaction.execute(new TransactionCallback<Pair<Long, Account>>() {

        @Override
        public Pair<Long, Account> doInTransaction(TransactionStatus status) {
            // create account
            String accountUUID = accountUUIDFinal;
            if (accountUUID == null) {
                accountUUID = UUID.randomUUID().toString();
            }
            AccountVO account = createAccount(accountNameFinal, accountType, roleId, domainIdFinal, networkDomain, details, accountUUID);
            long accountId = account.getId();
            // create the first user for the account
            UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID, source);
            if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
                // set registration token
                byte[] bytes = (domainIdFinal + accountNameFinal + userName + System.currentTimeMillis()).getBytes();
                String registrationToken = UUID.nameUUIDFromBytes(bytes).toString();
                user.setRegistrationToken(registrationToken);
            }
            return new Pair<Long, Account>(user.getId(), account);
        }
    });
    long userId = pair.first();
    Account account = pair.second();
    // create correct account and group association based on accountType
    if (accountType != Account.ACCOUNT_TYPE_PROJECT) {
        Map<Long, Long> accountGroupMap = new HashMap<Long, Long>();
        accountGroupMap.put(account.getId(), new Long(accountType + 1));
        _messageBus.publish(_name, MESSAGE_ADD_ACCOUNT_EVENT, PublishScope.LOCAL, accountGroupMap);
    }
    CallContext.current().putContextParameter(Account.class, account.getUuid());
    // check success
    return _userAccountDao.findById(userId);
}
Also used : HashMap(java.util.HashMap) TransactionStatus(com.cloud.utils.db.TransactionStatus) VpnUserVO(com.cloud.network.VpnUserVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Domain(com.cloud.domain.Domain) Pair(com.cloud.utils.Pair) DB(com.cloud.utils.db.DB) ActionEvents(com.cloud.event.ActionEvents)

Example 24 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class AccountManagerImpl method finalyzeAccountId.

@Override
public Long finalyzeAccountId(final String accountName, final Long domainId, final Long projectId, final boolean enabledOnly) {
    if (accountName != null) {
        if (domainId == null) {
            throw new InvalidParameterValueException("Account must be specified with domainId parameter");
        }
        final Domain domain = _domainMgr.getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Unable to find domain by id");
        }
        final Account account = getActiveAccountByName(accountName, domainId);
        if (account != null && account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            if (!enabledOnly || account.getState() == Account.State.enabled) {
                return account.getId();
            } else {
                throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active");
            }
        } else {
            // idList.add(new IdentityProxy("domain", domainId, "domainId"));
            throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id");
        }
    }
    if (projectId != null) {
        final Project project = _projectMgr.getProject(projectId);
        if (project != null) {
            if (!enabledOnly || project.getState() == Project.State.Active) {
                return project.getProjectAccountId();
            } else {
                final PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active");
                ex.addProxyObject(project.getUuid(), "projectId");
                throw ex;
            }
        } else {
            throw new InvalidParameterValueException("Unable to find project by id");
        }
    }
    return null;
}
Also used : Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Domain(com.cloud.domain.Domain)

Example 25 with Domain

use of com.cloud.domain.Domain in project cloudstack by apache.

the class AccountManagerImplTest method deleteUserAccount.

@Test
public void deleteUserAccount() {
    AccountVO account = new AccountVO();
    account.setId(42l);
    DomainVO domain = new DomainVO();
    Mockito.when(_accountDao.findById(42l)).thenReturn(account);
    Mockito.when(securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(ControlledEntity.class), Mockito.any(AccessType.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(_accountDao.remove(42l)).thenReturn(true);
    Mockito.when(_configMgr.releaseAccountSpecificVirtualRanges(42l)).thenReturn(true);
    Mockito.when(_domainMgr.getDomain(Mockito.anyLong())).thenReturn(domain);
    Mockito.when(securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(Domain.class))).thenReturn(true);
    Mockito.when(_vmSnapshotDao.listByAccountId(Mockito.anyLong())).thenReturn(new ArrayList<VMSnapshotVO>());
    Assert.assertTrue(accountManager.deleteUserAccount(42));
    // assert that this was a clean delete
    Mockito.verify(_accountDao, Mockito.never()).markForCleanup(Mockito.eq(42l));
}
Also used : DomainVO(com.cloud.domain.DomainVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) ControlledEntity(org.apache.cloudstack.acl.ControlledEntity) Domain(com.cloud.domain.Domain) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) Test(org.junit.Test)

Aggregations

Domain (com.cloud.domain.Domain)81 Account (com.cloud.user.Account)42 ArrayList (java.util.ArrayList)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)20 Test (org.junit.Test)20 DeployDestination (com.cloud.deploy.DeployDestination)17 Network (com.cloud.network.Network)17 ReservationContext (com.cloud.vm.ReservationContext)17 DataCenter (com.cloud.dc.DataCenter)16 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)16 NetworkOffering (com.cloud.offering.NetworkOffering)16 HostVO (com.cloud.host.HostVO)15 NetworkVO (com.cloud.network.dao.NetworkVO)15 UserAccount (com.cloud.user.UserAccount)15 URI (java.net.URI)12 DomainVO (com.cloud.domain.DomainVO)11 ProjectAccount (com.cloud.projects.ProjectAccount)11 Project (com.cloud.projects.Project)10 NiciraNvpDeviceVO (com.cloud.network.NiciraNvpDeviceVO)8 DB (com.cloud.utils.db.DB)8