Search in sources :

Example 81 with DomainVO

use of com.cloud.domain.DomainVO in project cosmic by MissionCriticalCloud.

the class ApiServer method handleAsyncJobPublishEvent.

@MessageHandler(topic = AsyncJob.Topics.JOB_EVENT_PUBLISH)
private void handleAsyncJobPublishEvent(final String subject, final String senderAddress, final Object args) {
    assert (args != null);
    final Pair<AsyncJob, String> eventInfo = (Pair<AsyncJob, String>) args;
    final AsyncJob job = eventInfo.first();
    final String jobEvent = eventInfo.second();
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Handle asyjob publish event " + jobEvent);
    }
    final EventBus eventBus;
    try {
        eventBus = ComponentContext.getComponent(EventBus.class);
    } catch (final NoSuchBeanDefinitionException nbe) {
        // no provider is configured to provide events bus, so just return
        return;
    }
    if (!job.getDispatcher().equalsIgnoreCase("ApiAsyncJobDispatcher")) {
        return;
    }
    final User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
    final Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
    // Get the event type from the cmdInfo json string
    final String info = job.getCmdInfo();
    String cmdEventType = "unknown";
    if (info != null) {
        final Type type = new TypeToken<Map<String, String>>() {
        }.getType();
        final Map<String, String> cmdInfo = ApiGsonHelper.getBuilder().create().fromJson(info, type);
        final String eventTypeObj = cmdInfo.get("cmdEventType");
        if (eventTypeObj != null) {
            cmdEventType = eventTypeObj;
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Retrieved cmdEventType from job info: " + cmdEventType);
            }
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to locate cmdEventType marker in job info. publish as unknown event");
            }
        }
    }
    // For some reason, the instanceType / instanceId are not abstract, which means we may get null values.
    final String instanceType = job.getInstanceType() != null ? job.getInstanceType() : "unknown";
    final String instanceUuid = job.getInstanceId() != null ? ApiDBUtils.findJobInstanceUuid(job) : "";
    final Event event = new Event("management-server", EventCategory.ASYNC_JOB_CHANGE_EVENT.getName(), jobEvent, instanceType, instanceUuid);
    final Map<String, String> eventDescription = new HashMap<>();
    eventDescription.put("command", job.getCmd());
    eventDescription.put("user", userJobOwner.getUuid());
    eventDescription.put("account", jobOwner.getUuid());
    eventDescription.put("processStatus", "" + job.getProcessStatus());
    eventDescription.put("resultCode", "" + job.getResultCode());
    eventDescription.put("instanceUuid", instanceUuid);
    eventDescription.put("instanceType", instanceType);
    eventDescription.put("commandEventType", cmdEventType);
    eventDescription.put("jobId", job.getUuid());
    eventDescription.put("jobResult", job.getResult());
    eventDescription.put("cmdInfo", job.getCmdInfo());
    eventDescription.put("status", "" + job.getStatus());
    // If the event.accountinfo boolean value is set, get the human readable value for the username / domainname
    final Map<String, String> configs = _configDao.getConfiguration("management-server", new HashMap<String, String>());
    if (Boolean.valueOf(configs.get("event.accountinfo"))) {
        final DomainVO domain = _domainDao.findById(jobOwner.getDomainId());
        eventDescription.put("username", userJobOwner.getUsername());
        eventDescription.put("accountname", jobOwner.getAccountName());
        eventDescription.put("domainname", domain.getName());
    }
    event.setDescription(eventDescription);
    try {
        eventBus.publish(event);
    } catch (final EventBusException evx) {
        final String errMsg = "Failed to publish async job event on the the event bus.";
        s_logger.warn(errMsg, evx);
    }
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) HashMap(java.util.HashMap) EventBus(com.cloud.framework.events.EventBus) AsyncJob(com.cloud.framework.jobs.AsyncJob) DomainVO(com.cloud.domain.DomainVO) Type(java.lang.reflect.Type) Event(com.cloud.framework.events.Event) EventBusException(com.cloud.framework.events.EventBusException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) Map(java.util.Map) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair) NameValuePair(org.apache.http.NameValuePair) MessageHandler(com.cloud.framework.messagebus.MessageHandler)

Example 82 with DomainVO

use of com.cloud.domain.DomainVO in project cosmic by MissionCriticalCloud.

the class AffinityGroupServiceImpl method createAffinityGroup.

@DB
@Override
public AffinityGroup createAffinityGroup(final String accountName, final Long projectId, final Long domainId, final String affinityGroupName, final String affinityGroupType, final String description) {
    // validate the affinityGroupType
    final Map<String, AffinityGroupProcessor> typeProcessorMap = getAffinityTypeToProcessorMap();
    if (typeProcessorMap == null || typeProcessorMap.isEmpty()) {
        throw new InvalidParameterValueException("Unable to create affinity group, no Affinity Group Types configured");
    }
    final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
    if (processor == null) {
        throw new InvalidParameterValueException("Unable to create affinity group, invalid affinity group type" + affinityGroupType);
    }
    final Account caller = CallContext.current().getCallingAccount();
    if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot create the affinity group");
    }
    final ControlledEntity.ACLType aclType;
    final Account owner;
    boolean domainLevel = false;
    if (projectId == null && domainId != null && accountName == null) {
        verifyAccessToDomainWideProcessor(caller, processor);
        final DomainVO domain = getDomain(domainId);
        _accountMgr.checkAccess(caller, domain);
        // domain level group, owner is SYSTEM.
        owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM);
        aclType = ControlledEntity.ACLType.Domain;
        domainLevel = true;
    } else {
        owner = _accountMgr.finalizeOwner(caller, accountName, domainId, projectId);
        aclType = ControlledEntity.ACLType.Account;
    }
    verifyAffinityGroupNameInUse(owner.getAccountId(), owner.getDomainId(), affinityGroupName);
    verifyDomainLevelAffinityGroupName(domainLevel, owner.getDomainId(), affinityGroupName);
    final AffinityGroupVO group = createAffinityGroup(processor, owner, aclType, affinityGroupName, affinityGroupType, description, domainLevel, domainId);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Created affinity group =" + affinityGroupName);
    }
    return group;
}
Also used : Account(com.cloud.user.Account) DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ControlledEntity(com.cloud.acl.ControlledEntity) ACLType(com.cloud.acl.ControlledEntity.ACLType) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) DB(com.cloud.utils.db.DB)

Example 83 with DomainVO

use of com.cloud.domain.DomainVO in project cosmic by MissionCriticalCloud.

the class QueryManagerImpl method listDataCentersInternal.

private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(final ListZonesCmd cmd) {
    final Account account = CallContext.current().getCallingAccount();
    final Long domainId = cmd.getDomainId();
    final Long id = cmd.getId();
    final String keyword = cmd.getKeyword();
    final String name = cmd.getName();
    final String networkType = cmd.getNetworkType();
    final Map<String, String> resourceTags = cmd.getTags();
    final SearchBuilder<DataCenterJoinVO> sb = _dcJoinDao.createSearchBuilder();
    if (resourceTags != null && !resourceTags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < resourceTags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    final Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchCriteria<DataCenterJoinVO> sc = sb.create();
    if (networkType != null) {
        sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    } else if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.EQ, name);
    } else {
        if (keyword != null) {
            final SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
            ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            sc.addAnd("name", SearchCriteria.Op.SC, ssc);
        }
        /*
             * List all resources due to Explicit Dedication except the
             * dedicated resources of other account
             */
        if (domainId != null) {
            // 
            // for domainId != null // right now, we made the decision to
            // only list zones associated // with this domain, private zone
            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
            if (_accountMgr.isNormalUser(account.getId())) {
                // accountId == null (zones dedicated to a domain) or
                // accountId = caller
                final SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
                sdc.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
                sdc.addOr("accountId", SearchCriteria.Op.NULL);
                sc.addAnd("accountId", SearchCriteria.Op.SC, sdc);
            }
        } else if (_accountMgr.isNormalUser(account.getId())) {
            // it was decided to return all zones for the user's domain, and
            // everything above till root
            // list all zones belonging to this domain, and all of its
            // parents
            // check the parent, if not null, add zones for that parent to
            // list
            // find all domain Id up to root domain for this account
            final List<Long> domainIds = new ArrayList<>();
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            if (domainRecord == null) {
                s_logger.error("Could not find the domainId for account:" + account.getAccountName());
                throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
            }
            domainIds.add(domainRecord.getId());
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            final SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, AllocationState.Disabled);
            // accountId == null (zones dedicated to a domain) or
            // accountId = caller
            final SearchCriteria<DataCenterJoinVO> sdc2 = _dcJoinDao.createSearchCriteria();
            sdc2.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
            sdc2.addOr("accountId", SearchCriteria.Op.NULL);
            sc.addAnd("accountId", SearchCriteria.Op.SC, sdc2);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            final List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        } else if (_accountMgr.isDomainAdmin(account.getId()) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
            // it was decided to return all zones for the domain admin, and
            // everything above till root, as well as zones till the domain
            // leaf
            final List<Long> domainIds = new ArrayList<>();
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            if (domainRecord == null) {
                s_logger.error("Could not find the domainId for account:" + account.getAccountName());
                throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
            }
            domainIds.add(domainRecord.getId());
            // find all domain Ids till leaf
            final List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId());
            for (final DomainVO domain : allChildDomains) {
                domainIds.add(domain.getId());
            }
            // then find all domain Id up to root domain for this account
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            final SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, AllocationState.Disabled);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            final List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        }
        // handle available=FALSE option, only return zones with at least
        // one VM running there
        final Boolean available = cmd.isAvailable();
        if (account != null) {
            if (available != null && Boolean.FALSE.equals(available)) {
                // data centers with
                final Set<Long> dcIds = new HashSet<>();
                // at least one VM
                // running
                final List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
                for (final DomainRouterVO router : routers) {
                    dcIds.add(router.getDataCenterId());
                }
                if (dcIds.size() == 0) {
                    return new Pair<>(new ArrayList<>(), 0);
                } else {
                    sc.addAnd("id", SearchCriteria.Op.IN, dcIds.toArray());
                }
            }
        }
    }
    if (resourceTags != null && !resourceTags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Zone.toString());
        for (final Map.Entry<String, String> entry : resourceTags.entrySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
            count++;
        }
    }
    return _dcJoinDao.searchAndCount(sc, searchFilter);
}
Also used : DataCenterJoinVO(com.cloud.api.query.vo.DataCenterJoinVO) Account(com.cloud.user.Account) HashSet(java.util.HashSet) Set(java.util.Set) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) ArrayList(java.util.ArrayList) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Map(java.util.Map) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 84 with DomainVO

use of com.cloud.domain.DomainVO in project cosmic by MissionCriticalCloud.

the class QueryManagerImpl method searchForTemplatesInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(final Long templateId, final String name, final String keyword, final TemplateFilter templateFilter, final boolean isIso, final Boolean bootable, final Long pageSize, final Long startIndex, final Long zoneId, final HypervisorType hyperType, final boolean showDomr, final boolean onlyReady, final List<Account> permittedAccounts, final Account caller, final ListProjectResourcesCriteria listProjectResourcesCriteria, final Map<String, String> tags, final boolean showRemovedTmpl) {
    // check if zone is configured, if not, just return empty list
    List<HypervisorType> hypers = null;
    if (!isIso) {
        hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
        if (hypers == null || hypers.isEmpty()) {
            return new Pair<>(new ArrayList<>(), 0);
        }
    }
    final VMTemplateVO template;
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = isAscending == null ? Boolean.TRUE : isAscending;
    final Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
    searchFilter.addOrderBy(TemplateJoinVO.class, "tempZonePair", isAscending);
    final SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
    // select distinct (templateId, zoneId) pair
    sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair());
    final SearchCriteria<TemplateJoinVO> sc = sb.create();
    // verify templateId parameter and specially handle it
    if (templateId != null) {
        // Done for backward compatibility - Bug-5221
        template = _templateDao.findByIdIncludingRemoved(templateId);
        if (template == null) {
            throw new InvalidParameterValueException("Please specify a valid template ID.");
        }
        // If ISO requested then it should be ISO.
        if (isIso && template.getFormat() != ImageFormat.ISO) {
            s_logger.error("Template Id " + templateId + " is not an ISO");
            final InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        // If ISO not requested then it shouldn't be an ISO.
        if (!isIso && template.getFormat() == ImageFormat.ISO) {
            s_logger.error("Incorrect format of the template id " + templateId);
            final InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        // if template is not public, perform permission check here
        if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            _accountMgr.checkAccess(caller, null, false, template);
        }
        // if templateId is specified, then we will just use the id to
        // search and ignore other query parameters
        sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
    } else {
        final DomainVO domain;
        if (!permittedAccounts.isEmpty()) {
            domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
        } else {
            domain = _domainDao.findById(Domain.ROOT_DOMAIN);
        }
        // add criteria for project or not
        if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
            sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
        } else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
            sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
        }
        // add criteria for domain path in case of domain admin
        if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
            sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
        }
        final List<Long> relatedDomainIds = new ArrayList<>();
        final List<Long> permittedAccountIds = new ArrayList<>();
        if (!permittedAccounts.isEmpty()) {
            for (final Account account : permittedAccounts) {
                permittedAccountIds.add(account.getId());
                final boolean publicTemplates = templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community;
                // get all parent domain ID's all the way till root domain
                DomainVO domainTreeNode;
                // if template filter is featured, or community, all child domains should be included in search
                if (publicTemplates) {
                    domainTreeNode = _domainDao.findById(Domain.ROOT_DOMAIN);
                } else {
                    domainTreeNode = _domainDao.findById(account.getDomainId());
                }
                relatedDomainIds.add(domainTreeNode.getId());
                while (domainTreeNode.getParent() != null) {
                    domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
                    relatedDomainIds.add(domainTreeNode.getId());
                }
                // get all child domain ID's
                if (_accountMgr.isAdmin(account.getId()) || publicTemplates) {
                    final List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId());
                    for (final DomainVO childDomain : allChildDomains) {
                        relatedDomainIds.add(childDomain.getId());
                    }
                }
            }
        }
        if (!isIso) {
            // add hypervisor criteria for template case
            if (hypers != null && !hypers.isEmpty()) {
                final String[] relatedHypers = new String[hypers.size()];
                for (int i = 0; i < hypers.size(); i++) {
                    relatedHypers[i] = hypers.get(i).toString();
                }
                sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
            }
        }
        // control different template filters
        if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
            sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
            if (templateFilter == TemplateFilter.featured) {
                sc.addAnd("featured", SearchCriteria.Op.EQ, true);
            } else {
                sc.addAnd("featured", SearchCriteria.Op.EQ, false);
            }
            if (!permittedAccounts.isEmpty()) {
                final SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
                scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
                scc.addOr("domainId", SearchCriteria.Op.NULL);
                sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
            }
        } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
            if (!permittedAccounts.isEmpty()) {
                sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
        } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
            // only show templates shared by others
            sc.addAnd("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
        } else if (templateFilter == TemplateFilter.executable) {
            final SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (!permittedAccounts.isEmpty()) {
                scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        } else if (templateFilter == TemplateFilter.all && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            final SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
                scc.addOr("domainPath", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
            } else {
                if (!permittedAccounts.isEmpty()) {
                    scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                    scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                }
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        }
        // add tags criteria
        if (tags != null && !tags.isEmpty()) {
            final SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            for (final Map.Entry<String, String> entry : tags.entrySet()) {
                final SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
                scTag.addAnd("tagKey", SearchCriteria.Op.EQ, entry.getKey());
                scTag.addAnd("tagValue", SearchCriteria.Op.EQ, entry.getValue());
                if (isIso) {
                    scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.ISO);
                } else {
                    scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.Template);
                }
                scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
            }
            sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
        }
        if (keyword != null) {
            sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        } else if (name != null) {
            sc.addAnd("name", SearchCriteria.Op.EQ, name);
        }
        if (isIso) {
            sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
        } else {
            sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
        }
        if (!hyperType.equals(HypervisorType.None)) {
            sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
        }
        if (bootable != null) {
            sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
        }
        if (onlyReady) {
            final SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
            readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
            final SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
            isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
            isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
            readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
            sc.addAnd("state", SearchCriteria.Op.SC, readySc);
        }
        if (!showDomr) {
            // excluding system template
            sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
        }
    }
    if (zoneId != null) {
        final SearchCriteria<TemplateJoinVO> zoneSc = _templateJoinDao.createSearchCriteria();
        zoneSc.addOr("dataCenterId", SearchCriteria.Op.EQ, zoneId);
        zoneSc.addOr("dataStoreScope", SearchCriteria.Op.EQ, ScopeType.REGION);
        // handle the case where xs-tools.iso do not have data_center information in template_view
        final SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
        isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
        isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
        zoneSc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
        sc.addAnd("dataCenterId", SearchCriteria.Op.SC, zoneSc);
    }
    // don't return removed template, this should not be needed since we
    // changed annotation for removed field in TemplateJoinVO.
    // sc.addAnd("removed", SearchCriteria.Op.NULL);
    // search unique templates and find details by Ids
    final Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair;
    if (showRemovedTmpl) {
        uniqueTmplPair = _templateJoinDao.searchIncludingRemovedAndCount(sc, searchFilter);
    } else {
        sc.addAnd("templateState", SearchCriteria.Op.IN, new State[] { State.Active, State.NotUploaded, State.UploadInProgress });
        uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
    }
    final Integer count = uniqueTmplPair.second();
    if (count.intValue() == 0) {
        // empty result
        return uniqueTmplPair;
    }
    final List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
    final String[] tzIds = new String[uniqueTmpls.size()];
    int i = 0;
    for (final TemplateJoinVO v : uniqueTmpls) {
        tzIds[i++] = v.getTempZonePair();
    }
    final List<TemplateJoinVO> vrs = _templateJoinDao.searchByTemplateZonePair(showRemovedTmpl, tzIds);
    return new Pair<>(vrs, count);
// TODO: revisit the special logic for iso search in
// VMTemplateDaoImpl.searchForTemplates and understand why we need to
// specially handle ISO. The original logic is very twisted and no idea
// about what the code was doing.
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) TemplateJoinVO(com.cloud.api.query.vo.TemplateJoinVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) SearchCriteria(com.cloud.utils.db.SearchCriteria) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Map(java.util.Map)

Example 85 with DomainVO

use of com.cloud.domain.DomainVO in project cosmic by MissionCriticalCloud.

the class HostJoinDaoImpl method newHostResponse.

@Override
public HostResponse newHostResponse(final HostJoinVO host, final EnumSet<HostDetails> details) {
    final HostResponse hostResponse = new HostResponse();
    hostResponse.setId(host.getUuid());
    hostResponse.setCapabilities(host.getCapabilities());
    hostResponse.setClusterId(host.getClusterUuid());
    hostResponse.setCpuSockets(host.getCpuSockets());
    hostResponse.setCpuNumber(host.getCpus());
    hostResponse.setZoneId(host.getZoneUuid());
    hostResponse.setDisconnectedOn(host.getDisconnectedOn());
    hostResponse.setHypervisor(host.getHypervisorType());
    hostResponse.setHostType(host.getType());
    hostResponse.setLastPinged(new Date(host.getLastPinged()));
    hostResponse.setManagementServerId(host.getManagementServerId());
    hostResponse.setName(host.getName());
    hostResponse.setPodId(host.getPodUuid());
    hostResponse.setRemoved(host.getRemoved());
    hostResponse.setState(host.getStatus());
    hostResponse.setIpAddress(host.getPrivateIpAddress());
    hostResponse.setVersion(host.getVersion());
    hostResponse.setCreated(host.getCreated());
    final DedicatedResourceVO dedicatedResourceVO = dedicatedResourceDao.findByHostId(host.getId());
    if (dedicatedResourceVO != null) {
        hostResponse.setDedicated(true);
        final DomainVO domainVO = domainDao.findById(dedicatedResourceVO.getDomainId());
        if (domainVO != null) {
            hostResponse.setDomainId(domainVO.getUuid());
            hostResponse.setDomainName(domainVO.getName());
        }
        final AccountVO accountVO = accountDao.findById(dedicatedResourceVO.getAccountId());
        if (accountVO != null) {
            hostResponse.setAccountId(accountVO.getUuid());
            hostResponse.setAccountName(accountVO.getAccountName());
        }
        final AffinityGroupVO affinityGroupVO = affinityGroupDao.findById(dedicatedResourceVO.getAffinityGroupId());
        if (affinityGroupVO != null) {
            hostResponse.setAffinityGroupId(affinityGroupVO.getUuid());
            hostResponse.setAffinityGroupName(affinityGroupVO.getName());
        }
    }
    final List<HostGpuGroupsVO> gpuGroups = ApiDBUtils.getGpuGroups(host.getId());
    if (gpuGroups != null && !gpuGroups.isEmpty()) {
        final List<GpuResponse> gpus = new ArrayList<>();
        for (final HostGpuGroupsVO entry : gpuGroups) {
            final GpuResponse gpuResponse = new GpuResponse();
            gpuResponse.setGpuGroupName(entry.getGroupName());
            final List<VGPUTypesVO> vgpuTypes = ApiDBUtils.getVgpus(entry.getId());
            if (vgpuTypes != null && !vgpuTypes.isEmpty()) {
                final List<VgpuResponse> vgpus = new ArrayList<>();
                for (final VGPUTypesVO vgpuType : vgpuTypes) {
                    final VgpuResponse vgpuResponse = new VgpuResponse();
                    vgpuResponse.setName(vgpuType.getVgpuType());
                    vgpuResponse.setVideoRam(vgpuType.getVideoRam());
                    vgpuResponse.setMaxHeads(vgpuType.getMaxHeads());
                    vgpuResponse.setMaxResolutionX(vgpuType.getMaxResolutionX());
                    vgpuResponse.setMaxResolutionY(vgpuType.getMaxResolutionY());
                    vgpuResponse.setMaxVgpuPerPgpu(vgpuType.getMaxVgpuPerPgpu());
                    vgpuResponse.setRemainingCapacity(vgpuType.getRemainingCapacity());
                    vgpuResponse.setmaxCapacity(vgpuType.getMaxCapacity());
                    vgpus.add(vgpuResponse);
                }
                gpuResponse.setVgpu(vgpus);
            }
            gpus.add(gpuResponse);
        }
        hostResponse.setGpuGroups(gpus);
    }
    if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
        hostResponse.setOsCategoryId(host.getOsCategoryUuid());
        hostResponse.setOsCategoryName(host.getOsCategoryName());
        hostResponse.setZoneName(host.getZoneName());
        hostResponse.setPodName(host.getPodName());
        if (host.getClusterId() > 0) {
            hostResponse.setClusterName(host.getClusterName());
            hostResponse.setClusterType(host.getClusterType().toString());
        }
    }
    final DecimalFormat decimalFormat = new DecimalFormat("#.##");
    if (host.getType() == Host.Type.Routing) {
        if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) {
            // set allocated capacities
            final Long mem = host.getMemReservedCapacity() + host.getMemUsedCapacity();
            final Long cpu = host.getCpuReservedCapacity() + host.getCpuUsedCapacity();
            hostResponse.setMemoryAllocated(mem);
            hostResponse.setMemoryTotal(host.getTotalMemory());
            final String hostTags = host.getTag();
            hostResponse.setHostTags(host.getTag());
            final String haTag = ApiDBUtils.getHaTag();
            if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) {
                if (haTag.equalsIgnoreCase(hostTags)) {
                    hostResponse.setHaHost(true);
                } else {
                    hostResponse.setHaHost(false);
                }
            } else {
                hostResponse.setHaHost(false);
            }
            hostResponse.setHypervisorVersion(host.getHypervisorVersion());
            final String cpuAlloc = Float.toString(((float) cpu / (host.getCpus() * CapacityManager.CpuOverprovisioningFactor.valueIn(host.getClusterId()))) * 100f) + "%";
            hostResponse.setCpuAllocated(cpuAlloc);
            final String cpuWithOverprovisioning = Float.toString(host.getCpus() * CapacityManager.CpuOverprovisioningFactor.valueIn(host.getClusterId()));
            hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning);
        }
        if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) {
            // set CPU/RAM/Network stats
            final String cpuUsed;
            final HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId());
            if (hostStats != null) {
                final float cpuUtil = (float) hostStats.getCpuUtilization();
                cpuUsed = decimalFormat.format(cpuUtil) + "%";
                hostResponse.setCpuUsed(cpuUsed);
                hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue());
                hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue());
                hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue());
            }
        }
        if (details.contains(HostDetails.all) && host.getHypervisorType() == Hypervisor.HypervisorType.KVM) {
            // only kvm has the requirement to return host details
            try {
                final HostVO h = hostDao.findById(host.getId());
                hostDao.loadDetails(h);
                final Map<String, String> hostVoDetails;
                hostVoDetails = h.getDetails();
                hostResponse.setDetails(hostVoDetails);
                hostResponse.setHypervisorVersion(h.getDetail("Host.OS") + " " + h.getDetail("Host.OS.Version") + " with kernel " + h.getDetail("Host.OS.Kernel.Version"));
            } catch (final Exception e) {
                s_logger.debug("failed to get host details", e);
            }
        }
    } else if (host.getType() == Host.Type.SecondaryStorage) {
        final StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId());
        if (secStorageStats != null) {
            hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes());
            hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed());
        }
    }
    hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host.getId()));
    if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) {
        final Set<com.cloud.host.Status.Event> possibleEvents = host.getStatus().getPossibleEvents();
        if ((possibleEvents != null) && !possibleEvents.isEmpty()) {
            String events = "";
            final Iterator<com.cloud.host.Status.Event> iter = possibleEvents.iterator();
            while (iter.hasNext()) {
                final com.cloud.host.Status.Event event = iter.next();
                events += event.toString();
                if (iter.hasNext()) {
                    events += "; ";
                }
            }
            hostResponse.setEvents(events);
        }
    }
    hostResponse.setResourceState(host.getResourceState().toString());
    // set async job
    if (host.getJobId() != null) {
        hostResponse.setJobId(host.getJobUuid());
        hostResponse.setJobStatus(host.getJobStatus());
    }
    hostResponse.setObjectName("host");
    return hostResponse;
}
Also used : DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) GpuResponse(com.cloud.api.response.GpuResponse) AccountVO(com.cloud.user.AccountVO) HostResponse(com.cloud.api.response.HostResponse) VgpuResponse(com.cloud.api.response.VgpuResponse) AffinityGroupVO(com.cloud.affinity.AffinityGroupVO) VGPUTypesVO(com.cloud.gpu.VGPUTypesVO) StorageStats(com.cloud.storage.StorageStats) HostGpuGroupsVO(com.cloud.gpu.HostGpuGroupsVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) DomainVO(com.cloud.domain.DomainVO) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) HostStats(com.cloud.host.HostStats)

Aggregations

DomainVO (com.cloud.domain.DomainVO)196 Account (com.cloud.user.Account)85 AccountVO (com.cloud.user.AccountVO)64 Test (org.junit.Test)56 ArrayList (java.util.ArrayList)53 DomainDao (com.cloud.domain.dao.DomainDao)30 Field (java.lang.reflect.Field)30 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)29 SslCertDao (com.cloud.network.dao.SslCertDao)29 AccountManager (com.cloud.user.AccountManager)29 SslCertVO (com.cloud.network.dao.SslCertVO)27 List (java.util.List)26 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)24 Pair (com.cloud.utils.Pair)24 Domain (com.cloud.domain.Domain)23 Filter (com.cloud.utils.db.Filter)23 File (java.io.File)23 IOException (java.io.IOException)23 FileUtils.readFileToString (org.apache.commons.io.FileUtils.readFileToString)23 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)22