Search in sources :

Example 1 with DispatchTask

use of com.cloud.api.dispatch.DispatchTask in project cloudstack by apache.

the class AutoScaleManagerImpl method createAutoScaleVmProfile.

@Override
@ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_CREATE, eventDescription = "creating autoscale vm profile", create = true)
public AutoScaleVmProfile createAutoScaleVmProfile(CreateAutoScaleVmProfileCmd cmd) {
    Account owner = _accountDao.findById(cmd.getAccountId());
    Account caller = CallContext.current().getCallingAccount();
    _accountMgr.checkAccess(caller, null, true, owner);
    long zoneId = cmd.getZoneId();
    long serviceOfferingId = cmd.getServiceOfferingId();
    long autoscaleUserId = cmd.getAutoscaleUserId();
    DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id");
    }
    ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException("Unable to find service offering by id");
    }
    // validations
    HashMap<String, String> deployParams = cmd.getDeployParamMap();
    if (deployParams.containsKey("networks") && deployParams.get("networks").length() > 0) {
        throw new InvalidParameterValueException("'networks' is not a valid parameter, network for an AutoScaled VM is chosen automatically. An autoscaled VM is deployed in the loadbalancer's network");
    }
    /*
         * Just for making sure the values are right in other deploy params.
         * For ex. if projectId is given as a string instead of an long value, this
         * will be throwing an error.
         */
    dispatchChainFactory.getStandardDispatchChain().dispatch(new DispatchTask(ComponentContext.inject(DeployVMCmd.class), deployParams));
    AutoScaleVmProfileVO profileVO = new AutoScaleVmProfileVO(cmd.getZoneId(), cmd.getDomainId(), cmd.getAccountId(), cmd.getServiceOfferingId(), cmd.getTemplateId(), cmd.getOtherDeployParams(), cmd.getCounterParamList(), cmd.getDestroyVmGraceperiod(), autoscaleUserId);
    if (cmd.getDisplay() != null) {
        profileVO.setDisplay(cmd.getDisplay());
    }
    profileVO = checkValidityAndPersist(profileVO);
    s_logger.info("Successfully create AutoScale Vm Profile with Id: " + profileVO.getId());
    return profileVO;
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ServiceOffering(com.cloud.offering.ServiceOffering) DispatchTask(com.cloud.api.dispatch.DispatchTask) ActionEvent(com.cloud.event.ActionEvent)

Example 2 with DispatchTask

use of com.cloud.api.dispatch.DispatchTask in project cloudstack by apache.

the class ApiDispatcher method dispatch.

public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws Exception {
    // Let the chain of responsibility dispatch gradually
    standardDispatchChain.dispatch(new DispatchTask(cmd, params));
    final CallContext ctx = CallContext.current();
    ctx.setEventDisplayEnabled(cmd.isDisplay());
    if (params.get(ApiConstants.PROJECT_ID) != null) {
        Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
        ctx.setProject(project);
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCmd) {
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
        final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
        ctx.setStartEventId(Long.parseLong(startEventId));
        // Synchronise job on the object if needed
        if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
            Long queueSizeLimit = null;
            if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
                queueSizeLimit = _createSnapshotQueueSizeLimit;
            } else {
                queueSizeLimit = 1L;
            }
            if (queueSizeLimit != null) {
                if (!execute) {
                    // if we are not within async-execution context, enqueue the command
                    _asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
                    return;
                }
            } else {
                s_logger.trace("The queue size is unlimited, skipping the synchronizing");
            }
        }
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCustomIdCmd) {
        ((BaseAsyncCustomIdCmd) cmd).checkUuid();
    } else if (cmd instanceof BaseCustomIdCmd) {
        ((BaseCustomIdCmd) cmd).checkUuid();
    }
    cmd.execute();
}
Also used : Project(com.cloud.projects.Project) BaseCustomIdCmd(org.apache.cloudstack.api.BaseCustomIdCmd) CallContext(org.apache.cloudstack.context.CallContext) DispatchTask(com.cloud.api.dispatch.DispatchTask) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) BaseAsyncCustomIdCmd(org.apache.cloudstack.api.BaseAsyncCustomIdCmd)

Example 3 with DispatchTask

use of com.cloud.api.dispatch.DispatchTask in project cloudstack by apache.

the class ApiServer method queueCommand.

private String queueCommand(final BaseCmd cmdObj, final Map<String, String> params, 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;
        String objectUuid = null;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            final BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
            dispatcher.dispatchCreateCmd(createCmd, params);
            objectId = createCmd.getEntityId();
            objectUuid = createCmd.getEntityUuid();
            params.put("id", objectId.toString());
            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()));
        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
        String injectedJobId = asyncCmd.getInjectedJobId();
        uuidMgr.checkUuidSimple(injectedJobId, AsyncJob.class);
        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 ListSecurityGroupsCmd) && !(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(org.apache.cloudstack.api.command.admin.host.ListHostsCmd) ListVolumesCmdByAdmin(org.apache.cloudstack.api.command.admin.volume.ListVolumesCmdByAdmin) ListZonesCmdByAdmin(org.apache.cloudstack.api.command.admin.zone.ListZonesCmdByAdmin) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO) ListZonesCmd(org.apache.cloudstack.api.command.user.zone.ListZonesCmd) ServerApiException(org.apache.cloudstack.api.ServerApiException) ListProjectInvitationsCmd(org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd) ListProjectAccountsCmd(org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd) ListAccountsCmd(org.apache.cloudstack.api.command.user.account.ListAccountsCmd) DispatchTask(com.cloud.api.dispatch.DispatchTask) ListUsersCmd(org.apache.cloudstack.api.command.admin.user.ListUsersCmd) BaseListCmd(org.apache.cloudstack.api.BaseListCmd) ListSecurityGroupsCmd(org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd) ListEventsCmd(org.apache.cloudstack.api.command.user.event.ListEventsCmd) ListVolumesCmd(org.apache.cloudstack.api.command.user.volume.ListVolumesCmd) ListDiskOfferingsCmd(org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd) BaseAsyncCreateCmd(org.apache.cloudstack.api.BaseAsyncCreateCmd) ListRoutersCmd(org.apache.cloudstack.api.command.admin.router.ListRoutersCmd) ListProjectsCmd(org.apache.cloudstack.api.command.user.project.ListProjectsCmd) ListAccountsCmdByAdmin(org.apache.cloudstack.api.command.admin.account.ListAccountsCmdByAdmin) CallContext(org.apache.cloudstack.context.CallContext) ListVMGroupsCmd(org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) ListVMsCmd(org.apache.cloudstack.api.command.user.vm.ListVMsCmd) ListVMsCmdByAdmin(org.apache.cloudstack.api.command.admin.vm.ListVMsCmdByAdmin) ListStoragePoolsCmd(org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd) ListServiceOfferingsCmd(org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd) ListTagsCmd(org.apache.cloudstack.api.command.user.tag.ListTagsCmd)

Aggregations

DispatchTask (com.cloud.api.dispatch.DispatchTask)3 Account (com.cloud.user.Account)2 BaseAsyncCmd (org.apache.cloudstack.api.BaseAsyncCmd)2 CallContext (org.apache.cloudstack.context.CallContext)2 DataCenter (com.cloud.dc.DataCenter)1 ActionEvent (com.cloud.event.ActionEvent)1 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)1 ServiceOffering (com.cloud.offering.ServiceOffering)1 Project (com.cloud.projects.Project)1 UserAccount (com.cloud.user.UserAccount)1 BaseAsyncCreateCmd (org.apache.cloudstack.api.BaseAsyncCreateCmd)1 BaseAsyncCustomIdCmd (org.apache.cloudstack.api.BaseAsyncCustomIdCmd)1 BaseCustomIdCmd (org.apache.cloudstack.api.BaseCustomIdCmd)1 BaseListCmd (org.apache.cloudstack.api.BaseListCmd)1 ServerApiException (org.apache.cloudstack.api.ServerApiException)1 ListAccountsCmdByAdmin (org.apache.cloudstack.api.command.admin.account.ListAccountsCmdByAdmin)1 ListHostsCmd (org.apache.cloudstack.api.command.admin.host.ListHostsCmd)1 ListRoutersCmd (org.apache.cloudstack.api.command.admin.router.ListRoutersCmd)1 ListStoragePoolsCmd (org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd)1 ListUsersCmd (org.apache.cloudstack.api.command.admin.user.ListUsersCmd)1