Search in sources :

Example 1 with AsyncJob

use of com.cloud.framework.jobs.AsyncJob in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method createUpgradeRouterTemplateResponse.

@Override
public ListResponse<UpgradeRouterTemplateResponse> createUpgradeRouterTemplateResponse(final List<Long> jobIds) {
    final ListResponse<UpgradeRouterTemplateResponse> response = new ListResponse<>();
    final List<UpgradeRouterTemplateResponse> responses = new ArrayList<>();
    for (final Long jobId : jobIds) {
        final UpgradeRouterTemplateResponse routerResponse = new UpgradeRouterTemplateResponse();
        final AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId);
        routerResponse.setAsyncJobId(job.getUuid());
        routerResponse.setObjectName("asyncjobs");
        responses.add(routerResponse);
    }
    response.setResponses(responses);
    return response;
}
Also used : UpgradeRouterTemplateResponse(com.cloud.api.response.UpgradeRouterTemplateResponse) ListResponse(com.cloud.api.response.ListResponse) ArrayList(java.util.ArrayList) AsyncJob(com.cloud.framework.jobs.AsyncJob)

Example 2 with AsyncJob

use of com.cloud.framework.jobs.AsyncJob 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 3 with AsyncJob

use of com.cloud.framework.jobs.AsyncJob in project cosmic by MissionCriticalCloud.

the class ApiServer method getBaseAsyncResponse.

private String getBaseAsyncResponse(final long jobId, final BaseAsyncCmd cmd) {
    final AsyncJobResponse response = new AsyncJobResponse();
    final AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId);
    response.setJobId(job.getUuid());
    response.setResponseName(cmd.getCommandName());
    return ApiResponseSerializer.toSerializedString(response, cmd.getResponseType());
}
Also used : AsyncJobResponse(com.cloud.api.response.AsyncJobResponse) AsyncJob(com.cloud.framework.jobs.AsyncJob)

Example 4 with AsyncJob

use of com.cloud.framework.jobs.AsyncJob in project cosmic by MissionCriticalCloud.

the class AsyncJobManagerImpl method getExecutorRunnable.

private Runnable getExecutorRunnable(final AsyncJob job) {
    return new ManagedContextRunnable() {

        @Override
        public void run() {
            // register place-holder context to avoid installing system account call context
            if (CallContext.current() == null) {
                CallContext.registerPlaceHolderContext();
            }
            final String related = job.getRelated();
            String logContext = job.getShortUuid();
            if (related != null && !related.isEmpty()) {
                MDC.put("job", " (job: " + related + "/" + "job: " + job.getId() + ")");
                final AsyncJob relatedJob = _jobDao.findByIdIncludingRemoved(Long.parseLong(related));
                if (relatedJob != null) {
                    logContext = relatedJob.getShortUuid();
                }
            } else {
                MDC.put("job", " (job: " + job.getId() + ")");
            }
            MDC.put("logcontextid", " (logid: " + logContext + ")");
            try {
                super.run();
            } finally {
                MDC.remove("job");
            }
        }

        @Override
        protected void runInContext() {
            final long runNumber = getJobRunNumber();
            try {
                // 
                try {
                    JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job));
                } catch (final Exception e) {
                    // is expected to fail under situations
                    if (s_logger.isTraceEnabled()) {
                        s_logger.trace("Unable to register active job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e));
                    }
                }
                _jobMonitor.registerActiveTask(runNumber, job.getId());
                AsyncJobExecutionContext.setCurrentExecutionContext(new AsyncJobExecutionContext(job));
                final String related = job.getRelated();
                String logContext = job.getShortUuid();
                if (related != null && !related.isEmpty()) {
                    final AsyncJob relatedJob = _jobDao.findByIdIncludingRemoved(Long.parseLong(related));
                    if (relatedJob != null) {
                        logContext = relatedJob.getShortUuid();
                    }
                }
                MDC.put("logcontextid", " (logid: " + logContext + ")");
                // execute the job
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Executing " + StringUtils.cleanString(job.toString()));
                }
                if ((getAndResetPendingSignals(job) & AsyncJob.Constants.SIGNAL_MASK_WAKEUP) != 0) {
                    final AsyncJobDispatcher jobDispatcher = getWakeupDispatcher(job);
                    if (jobDispatcher != null) {
                        jobDispatcher.runJob(job);
                    } else {
                        // TODO, job wakeup is not in use yet
                        if (s_logger.isTraceEnabled()) {
                            s_logger.trace("Unable to find a wakeup dispatcher from the joined job: " + job);
                        }
                    }
                } else {
                    final AsyncJobDispatcher jobDispatcher = getDispatcher(job.getDispatcher());
                    if (jobDispatcher != null) {
                        jobDispatcher.runJob(job);
                    } else {
                        s_logger.error("Unable to find job dispatcher, job will be cancelled");
                        final ExceptionResponse response = new ExceptionResponse();
                        response.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode());
                        response.setErrorText("Unable to find job dispatcher, job will be cancelled");
                        completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), JobSerializerHelper.toSerializedString(response));
                    }
                }
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Done executing " + job.getCmd() + " for job-" + job.getId());
                }
            } catch (final Throwable e) {
                s_logger.error("Unexpected exception", e);
                final ExceptionResponse response = new ExceptionResponse();
                response.setErrorCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode());
                response.setErrorText(ExceptionUtils.getRootCauseMessage(e));
                completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), JobSerializerHelper.toSerializedString(response));
            } finally {
                // guard final clause as well
                try {
                    if (job.getSyncSource() != null) {
                        // here check queue item one more time to double make sure that queue item is removed in case of any uncaught exception
                        _queueMgr.purgeItem(job.getSyncSource().getId());
                    }
                    try {
                        JmxUtil.unregisterMBean("AsyncJobManager", "Active Job " + job.getId());
                    } catch (final Exception e) {
                        // is expected to fail under situations
                        if (s_logger.isTraceEnabled()) {
                            s_logger.trace("Unable to unregister job " + job.getId() + " to JMX monitoring due to exception " + ExceptionUtil.toString(e));
                        }
                    }
                    // 
                    // clean execution environment
                    // 
                    AsyncJobExecutionContext.unregister();
                    _jobMonitor.unregisterActiveTask(runNumber);
                } catch (final Throwable e) {
                    s_logger.error("Double exception", e);
                }
            }
        }
    };
}
Also used : ManagedContextRunnable(com.cloud.managed.context.ManagedContextRunnable) ExceptionResponse(com.cloud.api.response.ExceptionResponse) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) AsyncJob(com.cloud.framework.jobs.AsyncJob) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) AsyncJobDispatcher(com.cloud.framework.jobs.AsyncJobDispatcher)

Example 5 with AsyncJob

use of com.cloud.framework.jobs.AsyncJob in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method queryJobResult.

@Override
public AsyncJobResponse queryJobResult(final QueryAsyncJobResultCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    final AsyncJob job = _entityMgr.findById(AsyncJob.class, cmd.getId());
    if (job == null) {
        throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId());
    }
    final User userJobOwner = _accountMgr.getUserIncludingRemoved(job.getUserId());
    final Account jobOwner = _accountMgr.getAccount(userJobOwner.getAccountId());
    // check permissions
    if (_accountMgr.isNormalUser(caller.getId())) {
        // regular user can see only jobs he owns
        if (caller.getId() != jobOwner.getId()) {
            throw new PermissionDeniedException("Account " + caller + " is not authorized to see job id=" + job.getId());
        }
    } else if (_accountMgr.isDomainAdmin(caller.getId())) {
        _accountMgr.checkAccess(caller, null, true, jobOwner);
    }
    return createAsyncJobResponse(_jobMgr.queryJob(cmd.getId(), true));
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) VpnUser(com.cloud.network.VpnUser) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) AsyncJob(com.cloud.framework.jobs.AsyncJob)

Aggregations

AsyncJob (com.cloud.framework.jobs.AsyncJob)9 Account (com.cloud.user.Account)4 AsyncJobExecutionContext (com.cloud.framework.jobs.AsyncJobExecutionContext)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)3 ListResponse (com.cloud.api.response.ListResponse)2 DataObject (com.cloud.engine.subsystem.api.storage.DataObject)2 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)2 VmWorkJobVO (com.cloud.framework.jobs.impl.VmWorkJobVO)2 User (com.cloud.user.User)2 UserAccount (com.cloud.user.UserAccount)2 UserVmVO (com.cloud.vm.UserVmVO)2 VmWorkAttachVolume (com.cloud.vm.VmWorkAttachVolume)2 VmWorkDetachVolume (com.cloud.vm.VmWorkDetachVolume)2 VmWorkExtractVolume (com.cloud.vm.VmWorkExtractVolume)2 VmWorkMigrateVolume (com.cloud.vm.VmWorkMigrateVolume)2 VmWorkResizeVolume (com.cloud.vm.VmWorkResizeVolume)2 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)2 HashMap (java.util.HashMap)2 ExecutionException (java.util.concurrent.ExecutionException)2