Search in sources :

Example 1 with ListVMsCmdByAdmin

use of com.cloud.api.command.admin.vm.ListVMsCmdByAdmin in project cosmic by MissionCriticalCloud.

the class ApiServer method queueCommand.

private String queueCommand(final BaseCmd cmdObj, final Map<String, String> params, final StringBuilder log) throws Exception {
    final CallContext ctx = CallContext.current();
    final Long callerUserId = ctx.getCallingUserId();
    final Account caller = ctx.getCallingAccount();
    // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned.
    if (cmdObj instanceof BaseAsyncCmd) {
        Long objectId = null;
        final String objectUuid;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            final BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
            _dispatcher.dispatchCreateCmd(createCmd, params);
            objectId = createCmd.getEntityId();
            objectUuid = createCmd.getEntityUuid();
            params.put("id", objectId.toString());
            final Class entityClass = EventTypes.getEntityClassForEvent(createCmd.getEventType());
            if (entityClass != null) {
                ctx.putContextParameter(entityClass, objectUuid);
            }
        } else {
            // Extract the uuid before params are processed and id reflects internal db id
            objectUuid = params.get(ApiConstants.ID);
            dispatchChainFactory.getStandardDispatchChain().dispatch(new DispatchTask(cmdObj, params));
        }
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj;
        if (callerUserId != null) {
            params.put("ctxUserId", callerUserId.toString());
        }
        if (caller != null) {
            params.put("ctxAccountId", String.valueOf(caller.getId()));
        }
        if (objectUuid != null) {
            params.put("uuid", objectUuid);
        }
        long startEventId = ctx.getStartEventId();
        asyncCmd.setStartEventId(startEventId);
        // save the scheduled event
        final Long eventId = ActionEventUtils.onScheduledActionEvent((callerUserId == null) ? (Long) User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), asyncCmd.isDisplay(), startEventId);
        if (startEventId == 0) {
            // There was no create event before, set current event id as start eventId
            startEventId = eventId;
        }
        params.put("ctxStartEventId", String.valueOf(startEventId));
        params.put("cmdEventType", asyncCmd.getEventType().toString());
        params.put("ctxDetails", ApiGsonHelper.getBuilder().create().toJson(ctx.getContextParameters()));
        final Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId;
        // users can provide the job id they want to use, so log as it is a uuid and is unique
        final String injectedJobId = asyncCmd.getInjectedJobId();
        _uuidMgr.checkUuidSimple(injectedJobId, AsyncJob.class);
        final AsyncJobVO job = new AsyncJobVO("", callerUserId, caller.getId(), cmdObj.getClass().getName(), ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType() != null ? asyncCmd.getInstanceType().toString() : null, injectedJobId);
        job.setDispatcher(_asyncDispatcher.getName());
        final long jobId = _asyncMgr.submitAsyncJob(job);
        if (jobId == 0L) {
            final String errorMsg = "Unable to schedule async job for command " + job.getCmd();
            s_logger.warn(errorMsg);
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
        }
        final String response;
        if (objectId != null) {
            final String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
            response = getBaseAsyncCreateResponse(jobId, (BaseAsyncCreateCmd) asyncCmd, objUuid);
        } else {
            SerializationContext.current().setUuidTranslation(true);
            response = getBaseAsyncResponse(jobId, asyncCmd);
        }
        // Always log response for async for now, I don't think any sensitive data will be in here.
        // It might be nice to send this through scrubbing similar to how
        // ApiResponseSerializer.toSerializedStringWithSecureLogs works. For now, this gets jobid's
        // in the api logs.
        log.append(response);
        return response;
    } else {
        _dispatcher.dispatch(cmdObj, params, false);
        // For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views.
        if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListVMsCmdByAdmin) && !(cmdObj instanceof ListRoutersCmd) && !(cmdObj instanceof ListTagsCmd) && !(cmdObj instanceof ListEventsCmd) && !(cmdObj instanceof ListVMGroupsCmd) && !(cmdObj instanceof ListProjectsCmd) && !(cmdObj instanceof ListProjectAccountsCmd) && !(cmdObj instanceof ListProjectInvitationsCmd) && !(cmdObj instanceof ListHostsCmd) && !(cmdObj instanceof ListVolumesCmd) && !(cmdObj instanceof ListVolumesCmdByAdmin) && !(cmdObj instanceof ListUsersCmd) && !(cmdObj instanceof ListAccountsCmd) && !(cmdObj instanceof ListAccountsCmdByAdmin) && !(cmdObj instanceof ListStoragePoolsCmd) && !(cmdObj instanceof ListDiskOfferingsCmd) && !(cmdObj instanceof ListServiceOfferingsCmd) && !(cmdObj instanceof ListZonesCmd) && !(cmdObj instanceof ListZonesCmdByAdmin)) {
            buildAsyncListResponse((BaseListCmd) cmdObj, caller);
        }
        SerializationContext.current().setUuidTranslation(true);
        return ApiResponseSerializer.toSerializedStringWithSecureLogs((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType(), log);
    }
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) ListHostsCmd(com.cloud.api.command.admin.host.ListHostsCmd) ListVolumesCmdByAdmin(com.cloud.api.command.admin.volume.ListVolumesCmdByAdmin) ListZonesCmdByAdmin(com.cloud.api.command.admin.zone.ListZonesCmdByAdmin) AsyncJobVO(com.cloud.framework.jobs.impl.AsyncJobVO) ListZonesCmd(com.cloud.api.command.user.zone.ListZonesCmd) ListProjectInvitationsCmd(com.cloud.api.command.user.project.ListProjectInvitationsCmd) ListProjectAccountsCmd(com.cloud.api.command.user.account.ListProjectAccountsCmd) ListAccountsCmd(com.cloud.api.command.user.account.ListAccountsCmd) DispatchTask(com.cloud.api.dispatch.DispatchTask) ListUsersCmd(com.cloud.api.command.admin.user.ListUsersCmd) ListEventsCmd(com.cloud.api.command.user.event.ListEventsCmd) ListVolumesCmd(com.cloud.api.command.user.volume.ListVolumesCmd) ListDiskOfferingsCmd(com.cloud.api.command.user.offering.ListDiskOfferingsCmd) ListRoutersCmd(com.cloud.api.command.admin.router.ListRoutersCmd) ListProjectsCmd(com.cloud.api.command.user.project.ListProjectsCmd) ListAccountsCmdByAdmin(com.cloud.api.command.admin.account.ListAccountsCmdByAdmin) CallContext(com.cloud.context.CallContext) ListVMGroupsCmd(com.cloud.api.command.user.vmgroup.ListVMGroupsCmd) ListVMsCmd(com.cloud.api.command.user.vm.ListVMsCmd) ListVMsCmdByAdmin(com.cloud.api.command.admin.vm.ListVMsCmdByAdmin) ListStoragePoolsCmd(com.cloud.api.command.admin.storage.ListStoragePoolsCmd) ListServiceOfferingsCmd(com.cloud.api.command.user.offering.ListServiceOfferingsCmd) ListTagsCmd(com.cloud.api.command.user.tag.ListTagsCmd)

Example 2 with ListVMsCmdByAdmin

use of com.cloud.api.command.admin.vm.ListVMsCmdByAdmin in project cosmic by MissionCriticalCloud.

the class QueryManagerImpl method searchForUserVMs.

@Override
public ListResponse<UserVmResponse> searchForUserVMs(final ListVMsCmd cmd) {
    final Pair<List<UserVmJoinVO>, Integer> result = searchForUserVMsInternal(cmd);
    final ListResponse<UserVmResponse> response = new ListResponse<>();
    ResponseView respView = ResponseView.Restricted;
    if (cmd instanceof ListVMsCmdByAdmin) {
        respView = ResponseView.Full;
    }
    final List<UserVmResponse> vmResponses = ViewResponseHelper.createUserVmResponse(respView, "virtualmachine", cmd.getDetails(), result.first().toArray(new UserVmJoinVO[result.first().size()]));
    response.setResponses(vmResponses, result.second());
    return response;
}
Also used : ResponseView(com.cloud.api.ResponseObject.ResponseView) ListResponse(com.cloud.api.response.ListResponse) ListVMsCmdByAdmin(com.cloud.api.command.admin.vm.ListVMsCmdByAdmin) ArrayList(java.util.ArrayList) List(java.util.List) UserVmResponse(com.cloud.api.response.UserVmResponse) UserVmJoinVO(com.cloud.api.query.vo.UserVmJoinVO)

Example 3 with ListVMsCmdByAdmin

use of com.cloud.api.command.admin.vm.ListVMsCmdByAdmin in project cosmic by MissionCriticalCloud.

the class QueryManagerImpl method searchForUserVMsInternal.

private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsInternal(final ListVMsCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final boolean listAll = cmd.listAll();
    final Long id = cmd.getId();
    final Long userId = cmd.getUserId();
    final Map<String, String> tags = cmd.getTags();
    final Boolean display = cmd.getDisplay();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(UserVmJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final List<Long> ids;
    if (cmd.getId() != null) {
        if (cmd.getIds() != null && !cmd.getIds().isEmpty()) {
            throw new InvalidParameterValueException("Specify either id or ids but not both parameters");
        }
        ids = new ArrayList<>();
        ids.add(cmd.getId());
    } else {
        ids = cmd.getIds();
    }
    // first search distinct vm id by using query criteria and pagination
    final SearchBuilder<UserVmJoinVO> sb = _userVmJoinDao.createSearchBuilder();
    // select distinct ids
    sb.select(null, Func.DISTINCT, sb.entity().getId());
    _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    final String hypervisor = cmd.getHypervisor();
    final Object name = cmd.getName();
    final String state = cmd.getState();
    final Object zoneId = cmd.getZoneId();
    final Object keyword = cmd.getKeyword();
    boolean isAdmin = false;
    boolean isRootAdmin = false;
    if (_accountMgr.isAdmin(caller.getId())) {
        isAdmin = true;
    }
    if (_accountMgr.isRootAdmin(caller.getId())) {
        isRootAdmin = true;
    }
    final Object groupId = cmd.getGroupId();
    final Object networkId = cmd.getNetworkId();
    if (HypervisorType.getType(hypervisor) == HypervisorType.None && hypervisor != null) {
        // invalid hypervisor type input
        throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor);
    }
    final Object templateId = cmd.getTemplateId();
    final Object isoId = cmd.getIsoId();
    final Object vpcId = cmd.getVpcId();
    final Object affinityGroupId = cmd.getAffinityGroupId();
    final Object keyPairName = cmd.getKeyPairName();
    final Object serviceOffId = cmd.getServiceOfferingId();
    Object pod = null;
    Object hostId = null;
    Object storageId = null;
    if (cmd instanceof ListVMsCmdByAdmin) {
        final ListVMsCmdByAdmin adCmd = (ListVMsCmdByAdmin) cmd;
        pod = adCmd.getPodId();
        hostId = adCmd.getHostId();
        storageId = adCmd.getStorageId();
    }
    sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);
    sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ);
    sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
    sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
    sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
    sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ);
    sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
    sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ);
    sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
    if (serviceOffId != null) {
        sb.and("serviceOfferingId", sb.entity().getServiceOfferingId(), SearchCriteria.Op.EQ);
    }
    if (display != null) {
        sb.and("display", sb.entity().isDisplayVm(), SearchCriteria.Op.EQ);
    }
    if (groupId != null && (Long) groupId != -1) {
        sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
    }
    if (userId != null) {
        sb.and("userId", sb.entity().getUserId(), SearchCriteria.Op.EQ);
    }
    if (networkId != null) {
        sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
    }
    if (vpcId != null && networkId == null) {
        sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
    }
    if (storageId != null) {
        sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ);
    }
    if (affinityGroupId != null) {
        sb.and("affinityGroupId", sb.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
    }
    if (keyPairName != null) {
        sb.and("keyPairName", sb.entity().getKeypairName(), SearchCriteria.Op.EQ);
    }
    if (!isRootAdmin) {
        sb.and("displayVm", sb.entity().isDisplayVm(), SearchCriteria.Op.EQ);
    }
    // populate the search criteria with the values passed in
    final SearchCriteria<UserVmJoinVO> sc = sb.create();
    // building ACL condition
    _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (tags != null && !tags.isEmpty()) {
        final SearchCriteria<UserVmJoinVO> tagSc = _userVmJoinDao.createSearchCriteria();
        for (final Map.Entry<String, String> entry : tags.entrySet()) {
            final SearchCriteria<UserVmJoinVO> tsc = _userVmJoinDao.createSearchCriteria();
            tsc.addAnd("tagKey", SearchCriteria.Op.EQ, entry.getKey());
            tsc.addAnd("tagValue", SearchCriteria.Op.EQ, entry.getValue());
            tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
        }
        sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
    }
    if (groupId != null && (Long) groupId != -1) {
        sc.setParameters("instanceGroupId", groupId);
    }
    if (keyword != null) {
        final SearchCriteria<UserVmJoinVO> ssc = _userVmJoinDao.createSearchCriteria();
        ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("state", SearchCriteria.Op.EQ, keyword);
        sc.addAnd("displayName", SearchCriteria.Op.SC, ssc);
    }
    if (serviceOffId != null) {
        sc.setParameters("serviceOfferingId", serviceOffId);
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (ids != null && !ids.isEmpty()) {
        sc.setParameters("idIN", ids.toArray());
    }
    if (templateId != null) {
        sc.setParameters("templateId", templateId);
    }
    if (isoId != null) {
        sc.setParameters("isoId", isoId);
    }
    if (userId != null) {
        sc.setParameters("userId", userId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    if (vpcId != null && networkId == null) {
        sc.setParameters("vpcId", vpcId);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (state != null) {
        if (state.equalsIgnoreCase("present")) {
            sc.setParameters("stateNIN", "Destroyed", "Expunging");
        } else {
            sc.setParameters("stateEQ", state);
        }
    }
    if (hypervisor != null) {
        sc.setParameters("hypervisorType", hypervisor);
    }
    // Don't show Destroyed and Expunging vms to the end user if the AllowUserViewDestroyedVM flag is not set.
    if (!isAdmin && !AllowUserViewDestroyedVM.valueIn(caller.getAccountId())) {
        sc.setParameters("stateNIN", "Destroyed", "Expunging");
    }
    if (zoneId != null) {
        sc.setParameters("dataCenterId", zoneId);
    }
    if (affinityGroupId != null) {
        sc.setParameters("affinityGroupId", affinityGroupId);
    }
    if (keyPairName != null) {
        sc.setParameters("keyPairName", keyPairName);
    }
    if (cmd instanceof ListVMsCmdByAdmin) {
        final ListVMsCmdByAdmin aCmd = (ListVMsCmdByAdmin) cmd;
        if (aCmd.getPodId() != null) {
            sc.setParameters("podId", pod);
            if (state == null) {
                sc.setParameters("stateNEQ", "Destroyed");
            }
        }
        if (hostId != null) {
            sc.setParameters("hostIdEQ", hostId);
        }
        if (storageId != null) {
            sc.setParameters("poolId", storageId);
        }
    }
    if (!isRootAdmin) {
        sc.setParameters("displayVm", 1);
    }
    // search vm details by ids
    final Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndDistinctCount(sc, searchFilter);
    final Integer count = uniqueVmPair.second();
    if (count.intValue() == 0) {
        // handle empty result cases
        return uniqueVmPair;
    }
    final List<UserVmJoinVO> uniqueVms = uniqueVmPair.first();
    final Long[] vmIds = new Long[uniqueVms.size()];
    int i = 0;
    for (final UserVmJoinVO v : uniqueVms) {
        vmIds[i++] = v.getId();
    }
    final List<UserVmJoinVO> vms = _userVmJoinDao.searchByIds(vmIds);
    return new Pair<>(vms, count);
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) Ternary(com.cloud.utils.Ternary) UserVmJoinVO(com.cloud.api.query.vo.UserVmJoinVO) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) ListVMsCmdByAdmin(com.cloud.api.command.admin.vm.ListVMsCmdByAdmin) Map(java.util.Map)

Aggregations

ListVMsCmdByAdmin (com.cloud.api.command.admin.vm.ListVMsCmdByAdmin)3 UserVmJoinVO (com.cloud.api.query.vo.UserVmJoinVO)2 Account (com.cloud.user.Account)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ResponseView (com.cloud.api.ResponseObject.ResponseView)1 ListAccountsCmdByAdmin (com.cloud.api.command.admin.account.ListAccountsCmdByAdmin)1 ListHostsCmd (com.cloud.api.command.admin.host.ListHostsCmd)1 ListRoutersCmd (com.cloud.api.command.admin.router.ListRoutersCmd)1 ListStoragePoolsCmd (com.cloud.api.command.admin.storage.ListStoragePoolsCmd)1 ListUsersCmd (com.cloud.api.command.admin.user.ListUsersCmd)1 ListVolumesCmdByAdmin (com.cloud.api.command.admin.volume.ListVolumesCmdByAdmin)1 ListZonesCmdByAdmin (com.cloud.api.command.admin.zone.ListZonesCmdByAdmin)1 ListAccountsCmd (com.cloud.api.command.user.account.ListAccountsCmd)1 ListProjectAccountsCmd (com.cloud.api.command.user.account.ListProjectAccountsCmd)1 ListEventsCmd (com.cloud.api.command.user.event.ListEventsCmd)1 ListDiskOfferingsCmd (com.cloud.api.command.user.offering.ListDiskOfferingsCmd)1 ListServiceOfferingsCmd (com.cloud.api.command.user.offering.ListServiceOfferingsCmd)1 ListProjectInvitationsCmd (com.cloud.api.command.user.project.ListProjectInvitationsCmd)1 ListProjectsCmd (com.cloud.api.command.user.project.ListProjectsCmd)1