Search in sources :

Example 21 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class SolidFireSharedPrimaryDataStoreLifeCycle method initialize.

// invoked to add primary storage that is based on the SolidFire plug-in
@Override
public DataStore initialize(Map<String, Object> dsInfos) {
    final String CAPACITY_IOPS = "capacityIops";
    String url = (String) dsInfos.get("url");
    Long zoneId = (Long) dsInfos.get("zoneId");
    Long podId = (Long) dsInfos.get("podId");
    Long clusterId = (Long) dsInfos.get("clusterId");
    String storagePoolName = (String) dsInfos.get("name");
    String providerName = (String) dsInfos.get("providerName");
    Long capacityBytes = (Long) dsInfos.get("capacityBytes");
    Long capacityIops = (Long) dsInfos.get(CAPACITY_IOPS);
    String tags = (String) dsInfos.get("tags");
    @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) dsInfos.get("details");
    if (podId == null) {
        throw new CloudRuntimeException("The Pod ID must be specified.");
    }
    if (clusterId == null) {
        throw new CloudRuntimeException("The Cluster ID must be specified.");
    }
    String storageVip = SolidFireUtil.getStorageVip(url);
    int storagePort = SolidFireUtil.getStoragePort(url);
    if (capacityBytes == null || capacityBytes <= 0) {
        throw new IllegalArgumentException("'capacityBytes' must be present and greater than 0.");
    }
    if (capacityIops == null || capacityIops <= 0) {
        throw new IllegalArgumentException("'capacityIops' must be present and greater than 0.");
    }
    HypervisorType hypervisorType = getHypervisorTypeForCluster(clusterId);
    if (!isSupportedHypervisorType(hypervisorType)) {
        throw new CloudRuntimeException(hypervisorType + " is not a supported hypervisor type.");
    }
    String datacenter = SolidFireUtil.getValue(SolidFireUtil.DATACENTER, url, false);
    if (HypervisorType.VMware.equals(hypervisorType) && datacenter == null) {
        throw new CloudRuntimeException("'Datacenter' must be set for hypervisor type of " + HypervisorType.VMware);
    }
    PrimaryDataStoreParameters parameters = new PrimaryDataStoreParameters();
    parameters.setType(getStorageType(hypervisorType));
    parameters.setZoneId(zoneId);
    parameters.setPodId(podId);
    parameters.setClusterId(clusterId);
    parameters.setName(storagePoolName);
    parameters.setProviderName(providerName);
    parameters.setManaged(false);
    parameters.setCapacityBytes(capacityBytes);
    parameters.setUsedBytes(0);
    parameters.setCapacityIops(capacityIops);
    parameters.setHypervisorType(hypervisorType);
    parameters.setTags(tags);
    parameters.setDetails(details);
    String managementVip = SolidFireUtil.getManagementVip(url);
    int managementPort = SolidFireUtil.getManagementPort(url);
    details.put(SolidFireUtil.MANAGEMENT_VIP, managementVip);
    details.put(SolidFireUtil.MANAGEMENT_PORT, String.valueOf(managementPort));
    String clusterAdminUsername = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_USERNAME, url);
    String clusterAdminPassword = SolidFireUtil.getValue(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, url);
    details.put(SolidFireUtil.CLUSTER_ADMIN_USERNAME, clusterAdminUsername);
    details.put(SolidFireUtil.CLUSTER_ADMIN_PASSWORD, clusterAdminPassword);
    long lMinIops = 100;
    long lMaxIops = 15000;
    long lBurstIops = 15000;
    try {
        String minIops = SolidFireUtil.getValue(SolidFireUtil.MIN_IOPS, url);
        if (minIops != null && minIops.trim().length() > 0) {
            lMinIops = Long.parseLong(minIops);
        }
    } catch (Exception ex) {
        s_logger.info("[ignored] error getting Min IOPS: " + ex.getLocalizedMessage());
    }
    try {
        String maxIops = SolidFireUtil.getValue(SolidFireUtil.MAX_IOPS, url);
        if (maxIops != null && maxIops.trim().length() > 0) {
            lMaxIops = Long.parseLong(maxIops);
        }
    } catch (Exception ex) {
        s_logger.info("[ignored] error getting Max IOPS: " + ex.getLocalizedMessage());
    }
    try {
        String burstIops = SolidFireUtil.getValue(SolidFireUtil.BURST_IOPS, url);
        if (burstIops != null && burstIops.trim().length() > 0) {
            lBurstIops = Long.parseLong(burstIops);
        }
    } catch (Exception ex) {
        s_logger.info("[ignored] error getting Burst IOPS: " + ex.getLocalizedMessage());
    }
    if (lMinIops > lMaxIops) {
        throw new CloudRuntimeException("The parameter '" + SolidFireUtil.MIN_IOPS + "' must be less than or equal to the parameter '" + SolidFireUtil.MAX_IOPS + "'.");
    }
    if (lMaxIops > lBurstIops) {
        throw new CloudRuntimeException("The parameter '" + SolidFireUtil.MAX_IOPS + "' must be less than or equal to the parameter '" + SolidFireUtil.BURST_IOPS + "'.");
    }
    if (lMinIops != capacityIops) {
        throw new CloudRuntimeException("The parameter '" + CAPACITY_IOPS + "' must be equal to the parameter '" + SolidFireUtil.MIN_IOPS + "'.");
    }
    if (lMinIops > SolidFireUtil.MAX_IOPS_PER_VOLUME || lMaxIops > SolidFireUtil.MAX_IOPS_PER_VOLUME || lBurstIops > SolidFireUtil.MAX_IOPS_PER_VOLUME) {
        throw new CloudRuntimeException("This volume cannot exceed " + NumberFormat.getInstance().format(SolidFireUtil.MAX_IOPS_PER_VOLUME) + " IOPS.");
    }
    details.put(SolidFireUtil.MIN_IOPS, String.valueOf(lMinIops));
    details.put(SolidFireUtil.MAX_IOPS, String.valueOf(lMaxIops));
    details.put(SolidFireUtil.BURST_IOPS, String.valueOf(lBurstIops));
    SolidFireUtil.SolidFireConnection sfConnection = new SolidFireUtil.SolidFireConnection(managementVip, managementPort, clusterAdminUsername, clusterAdminPassword);
    SolidFireCreateVolume sfCreateVolume = createSolidFireVolume(sfConnection, storagePoolName, capacityBytes, lMinIops, lMaxIops, lBurstIops);
    SolidFireUtil.SolidFireVolume sfVolume = sfCreateVolume.getVolume();
    String iqn = sfVolume.getIqn();
    details.put(SolidFireUtil.VOLUME_ID, String.valueOf(sfVolume.getId()));
    parameters.setUuid(iqn);
    if (HypervisorType.VMware.equals(hypervisorType)) {
        String datastore = iqn.replace("/", "_");
        String path = "/" + datacenter + "/" + datastore;
        parameters.setHost("VMFS datastore: " + path);
        parameters.setPort(0);
        parameters.setPath(path);
        details.put(SolidFireUtil.DATASTORE_NAME, datastore);
        details.put(SolidFireUtil.IQN, iqn);
        details.put(SolidFireUtil.STORAGE_VIP, storageVip);
        details.put(SolidFireUtil.STORAGE_PORT, String.valueOf(storagePort));
    } else {
        parameters.setHost(storageVip);
        parameters.setPort(storagePort);
        parameters.setPath(iqn);
    }
    ClusterVO cluster = _clusterDao.findById(clusterId);
    GlobalLock lock = GlobalLock.getInternLock(cluster.getUuid());
    if (!lock.lock(SolidFireUtil.s_lockTimeInSeconds)) {
        String errMsg = "Couldn't lock the DB on the following string: " + cluster.getUuid();
        s_logger.debug(errMsg);
        throw new CloudRuntimeException(errMsg);
    }
    DataStore dataStore = null;
    try {
        // this adds a row in the cloud.storage_pool table for this SolidFire volume
        dataStore = _primaryDataStoreHelper.createPrimaryDataStore(parameters);
        // now that we have a DataStore (we need the id from the DataStore instance), we can create a Volume Access Group, if need be, and
        // place the newly created volume in the Volume Access Group
        List<HostVO> hosts = _hostDao.findByClusterId(clusterId);
        SolidFireUtil.placeVolumeInVolumeAccessGroup(sfConnection, sfVolume.getId(), dataStore.getId(), cluster.getUuid(), hosts, _clusterDetailsDao);
        SolidFireUtil.SolidFireAccount sfAccount = sfCreateVolume.getAccount();
        Account csAccount = CallContext.current().getCallingAccount();
        SolidFireUtil.updateCsDbWithSolidFireAccountInfo(csAccount.getId(), sfAccount, dataStore.getId(), _accountDetailsDao);
    } catch (Exception ex) {
        _primaryDataStoreDao.expunge(dataStore.getId());
        throw new CloudRuntimeException(ex.getMessage());
    } finally {
        lock.unlock();
        lock.releaseRef();
    }
    return dataStore;
}
Also used : Account(com.cloud.user.Account) ClusterVO(com.cloud.dc.ClusterVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HostVO(com.cloud.host.HostVO) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) GlobalLock(com.cloud.utils.db.GlobalLock) PrimaryDataStoreParameters(org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreParameters) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) SolidFireUtil(org.apache.cloudstack.storage.datastore.util.SolidFireUtil) Map(java.util.Map) HashMap(java.util.HashMap)

Example 22 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class QueryManagerImpl method searchForTemplatesInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags, boolean showRemovedTmpl, List<Long> ids) {
    // 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<List<TemplateJoinVO>, Integer>(new ArrayList<TemplateJoinVO>(), 0);
        }
    }
    VMTemplateVO template = null;
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? Boolean.TRUE : isAscending);
    Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
    searchFilter.addOrderBy(TemplateJoinVO.class, "tempZonePair", isAscending);
    SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
    // select distinct (templateId, zoneId) pair
    sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair());
    if (ids != null && !ids.isEmpty()) {
        sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    }
    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");
            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);
            InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
            Account template_acc = _accountMgr.getAccount(template.getAccountId());
            DomainVO domain = _domainDao.findById(template_acc.getDomainId());
            _accountMgr.checkAccess(caller, domain);
        } else // 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 {
        DomainVO domain = null;
        if (!permittedAccounts.isEmpty()) {
            domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
        } else {
            domain = _domainDao.findById(Domain.ROOT_DOMAIN);
        }
        // List<HypervisorType> hypers = null;
        // if (!isIso) {
        // hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
        // }
        setIdsListToSearchCriteria(sc, ids);
        // 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() + "%");
        }
        List<Long> relatedDomainIds = new ArrayList<Long>();
        List<Long> permittedAccountIds = new ArrayList<Long>();
        if (!permittedAccounts.isEmpty()) {
            for (Account account : permittedAccounts) {
                permittedAccountIds.add(account.getId());
                boolean publicTemplates = (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community);
                // get all parent domain ID's all the way till root domain
                DomainVO domainTreeNode = null;
                //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) {
                    List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId());
                    for (DomainVO childDomain : allChildDomains) {
                        relatedDomainIds.add(childDomain.getId());
                    }
                }
            }
        }
        if (!isIso) {
            // add hypervisor criteria for template case
            if (hypers != null && !hypers.isEmpty()) {
                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()) {
                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) {
            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) {
            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()) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            for (Map.Entry<String, String> entry : tags.entrySet()) {
                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) {
            SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
            readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
            readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
            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) {
        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 and vmware-tools.iso do not
        // have data_center information in template_view
        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
    Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = null;
    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);
    }
    Integer count = uniqueTmplPair.second();
    if (count.intValue() == 0) {
        // empty result
        return uniqueTmplPair;
    }
    List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
    String[] tzIds = new String[uniqueTmpls.size()];
    int i = 0;
    for (TemplateJoinVO v : uniqueTmpls) {
        tzIds[i++] = v.getTempZonePair();
    }
    List<TemplateJoinVO> vrs = _templateJoinDao.searchByTemplateZonePair(showRemovedTmpl, tzIds);
    return new Pair<List<TemplateJoinVO>, Integer>(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.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 23 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class QueryManagerImpl method searchForIsosInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(ListIsosCmd cmd) {
    TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
    Long id = cmd.getId();
    Map<String, String> tags = cmd.getTags();
    boolean showRemovedISO = cmd.getShowRemoved();
    Account caller = CallContext.current().getCallingAccount();
    boolean listAll = false;
    if (isoFilter != null && isoFilter == TemplateFilter.all) {
        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
            throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only");
        }
        listAll = true;
    }
    List<Long> permittedAccountIds = new ArrayList<Long>();
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false);
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    List<Account> permittedAccounts = new ArrayList<Account>();
    for (Long accountId : permittedAccountIds) {
        permittedAccounts.add(_accountMgr.getAccount(accountId));
    }
    HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
    return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedISO, null);
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException)

Example 24 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class QueryManagerImpl method searchForTemplatesInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) {
    TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
    Long id = cmd.getId();
    Map<String, String> tags = cmd.getTags();
    boolean showRemovedTmpl = cmd.getShowRemoved();
    Account caller = CallContext.current().getCallingAccount();
    boolean listAll = false;
    if (templateFilter != null && templateFilter == TemplateFilter.all) {
        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
            throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only");
        }
        listAll = true;
    }
    List<Long> permittedAccountIds = new ArrayList<Long>();
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false);
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    List<Account> permittedAccounts = new ArrayList<Account>();
    for (Long accountId : permittedAccountIds) {
        permittedAccounts.add(_accountMgr.getAccount(accountId));
    }
    boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
    HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
    return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags, showRemovedTmpl, cmd.getIds());
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException)

Example 25 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class UserVmManagerTest method testValidateRootDiskResize.

@Test
public void testValidateRootDiskResize() {
    HypervisorType hypervisorType = HypervisorType.Any;
    Long rootDiskSize = Long.valueOf(10);
    UserVmVO vm = Mockito.mock(UserVmVO.class);
    VMTemplateVO templateVO = Mockito.mock(VMTemplateVO.class);
    Map<String, String> customParameters = new HashMap<String, String>();
    Map<String, String> vmDetals = new HashMap<String, String>();
    vmDetals.put("rootDiskController", "ide");
    when(vm.getDetails()).thenReturn(vmDetals);
    when(templateVO.getSize()).thenReturn((rootDiskSize << 30) + 1);
    //Case 1: >
    try {
        _userVmMgr.validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);
        Assert.fail("Function should throw InvalidParameterValueException");
    } catch (Exception e) {
        assertThat(e, instanceOf(InvalidParameterValueException.class));
    }
    //Case 2: =
    when(templateVO.getSize()).thenReturn((rootDiskSize << 30));
    customParameters.put("rootdisksize", "10");
    _userVmMgr.validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);
    assert (!customParameters.containsKey("rootdisksize"));
    when(templateVO.getSize()).thenReturn((rootDiskSize << 30) - 1);
    //Case 3:  <
    //Case 3.1: HypervisorType!=VMware
    _userVmMgr.validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);
    hypervisorType = HypervisorType.VMware;
    //Case 3.2:   0->(rootDiskController!=scsi)
    try {
        _userVmMgr.validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);
        Assert.fail("Function should throw InvalidParameterValueException");
    } catch (Exception e) {
        assertThat(e, instanceOf(InvalidParameterValueException.class));
    }
    //Case 3.3:   1->(rootDiskController==scsi)
    vmDetals.put("rootDiskController", "scsi");
    _userVmMgr.validateRootDiskResize(hypervisorType, rootDiskSize, templateVO, vm, customParameters);
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) HashMap(java.util.HashMap) Matchers.anyLong(org.mockito.Matchers.anyLong) VMTemplateVO(com.cloud.storage.VMTemplateVO) Matchers.anyString(org.mockito.Matchers.anyString) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Test(org.junit.Test)

Aggregations

HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)57 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)25 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)20 ArrayList (java.util.ArrayList)19 Account (com.cloud.user.Account)15 VMTemplateVO (com.cloud.storage.VMTemplateVO)12 ClusterVO (com.cloud.dc.ClusterVO)10 HostVO (com.cloud.host.HostVO)8 UserVmVO (com.cloud.vm.UserVmVO)8 HashMap (java.util.HashMap)8 StoragePoolVO (org.apache.cloudstack.storage.datastore.db.StoragePoolVO)8 DataCenterVO (com.cloud.dc.DataCenterVO)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)7 Answer (com.cloud.agent.api.Answer)6 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)6 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)6 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)6 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)6 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)5