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);
}
}
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;
}
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);
}
Aggregations