Search in sources :

Example 1 with AsyncJob

use of org.apache.cloudstack.framework.jobs.AsyncJob in project cloudstack by apache.

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();
            String related = job.getRelated();
            String logContext = job.getShortUuid();
            if (related != null && !related.isEmpty()) {
                NDC.push("job-" + related + "/" + "job-" + job.getId());
                AsyncJob relatedJob = _jobDao.findByIdIncludingRemoved(Long.parseLong(related));
                if (relatedJob != null) {
                    logContext = relatedJob.getShortUuid();
                }
            } else {
                NDC.push("job-" + job.getId());
            }
            MDC.put("logcontextid", logContext);
            try {
                super.run();
            } finally {
                NDC.pop();
            }
        }

        @Override
        protected void runInContext() {
            long runNumber = getJobRunNumber();
            try {
                // 
                try {
                    JmxUtil.registerMBean("AsyncJobManager", "Active Job " + job.getId(), new AsyncJobMBeanImpl(job));
                } catch (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));
                String related = job.getRelated();
                String logContext = job.getShortUuid();
                if (related != null && !related.isEmpty()) {
                    AsyncJob relatedJob = _jobDao.findByIdIncludingRemoved(Long.parseLong(related));
                    if (relatedJob != null) {
                        logContext = relatedJob.getShortUuid();
                    }
                }
                MDC.put("logcontextid", 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) {
                    AsyncJobDispatcher jobDispatcher = findWakeupDispatcher(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 {
                    AsyncJobDispatcher jobDispatcher = getDispatcher(job.getDispatcher());
                    if (jobDispatcher != null) {
                        jobDispatcher.runJob(job);
                    } else {
                        s_logger.error("Unable to find job dispatcher, job will be cancelled");
                        completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), null);
                    }
                }
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Done executing " + job.getCmd() + " for job-" + job.getId());
                }
            } catch (Throwable e) {
                s_logger.error("Unexpected exception", e);
                completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), null);
            } 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 (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 (Throwable e) {
                    s_logger.error("Double exception", e);
                }
            }
        }
    };
}
Also used : ManagedContextRunnable(org.apache.cloudstack.managed.context.ManagedContextRunnable) AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) AsyncJobDispatcher(org.apache.cloudstack.framework.jobs.AsyncJobDispatcher)

Example 2 with AsyncJob

use of org.apache.cloudstack.framework.jobs.AsyncJob in project cloudstack by apache.

the class AgentManagerImpl method tagCommand.

private static void tagCommand(final Command cmd) {
    final AsyncJobExecutionContext context = AsyncJobExecutionContext.getCurrent();
    if (context != null && context.getJob() != null) {
        final AsyncJob job = context.getJob();
        if (job.getRelated() != null && !job.getRelated().isEmpty()) {
            cmd.setContextParam("job", "job-" + job.getRelated() + "/" + "job-" + job.getId());
        } else {
            cmd.setContextParam("job", "job-" + job.getId());
        }
    }
    String logcontextid = (String) MDC.get("logcontextid");
    if (StringUtils.isNotEmpty(logcontextid)) {
        cmd.setContextParam("logid", logcontextid);
    }
}
Also used : AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob)

Example 3 with AsyncJob

use of org.apache.cloudstack.framework.jobs.AsyncJob in project cloudstack by apache.

the class ApiResponseHelper method queryJobResult.

@Override
public AsyncJobResponse queryJobResult(final QueryAsyncJobResultCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    final AsyncJob job = _entityMgr.findByIdIncludingRemoved(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 users can see only jobs they own
        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 : ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) User(com.cloud.user.User) VpnUser(com.cloud.network.VpnUser) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob)

Example 4 with AsyncJob

use of org.apache.cloudstack.framework.jobs.AsyncJob in project cloudstack by apache.

the class ApiServer method buildAsyncListResponse.

@SuppressWarnings("unchecked")
private void buildAsyncListResponse(final BaseListCmd command, final Account account) {
    final List<ResponseObject> responses = ((ListResponse) command.getResponseObject()).getResponses();
    if (responses != null && responses.size() > 0) {
        List<? extends AsyncJob> jobs = null;
        // list all jobs for ROOT admin
        if (accountMgr.isRootAdmin(account.getId())) {
            jobs = asyncMgr.findInstancePendingAsyncJobs(command.getInstanceType().toString(), null);
        } else {
            jobs = asyncMgr.findInstancePendingAsyncJobs(command.getInstanceType().toString(), account.getId());
        }
        if (jobs.size() == 0) {
            return;
        }
        final Map<String, AsyncJob> objectJobMap = new HashMap<String, AsyncJob>();
        for (final AsyncJob job : jobs) {
            if (job.getInstanceId() == null) {
                continue;
            }
            final String instanceUuid = ApiDBUtils.findJobInstanceUuid(job);
            objectJobMap.put(instanceUuid, job);
        }
        for (final ResponseObject response : responses) {
            if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) {
                final AsyncJob job = objectJobMap.get(response.getObjectId());
                response.setJobId(job.getUuid());
                response.setJobStatus(job.getStatus().ordinal());
            }
        }
    }
}
Also used : ListResponse(org.apache.cloudstack.api.response.ListResponse) HashMap(java.util.HashMap) ResponseObject(org.apache.cloudstack.api.ResponseObject) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob)

Example 5 with AsyncJob

use of org.apache.cloudstack.framework.jobs.AsyncJob in project cloudstack by apache.

the class ApiResponseHelper method createUpgradeRouterTemplateResponse.

@Override
public ListResponse<UpgradeRouterTemplateResponse> createUpgradeRouterTemplateResponse(List<Long> jobIds) {
    ListResponse<UpgradeRouterTemplateResponse> response = new ListResponse<UpgradeRouterTemplateResponse>();
    List<UpgradeRouterTemplateResponse> responses = new ArrayList<UpgradeRouterTemplateResponse>();
    for (Long jobId : jobIds) {
        UpgradeRouterTemplateResponse routerResponse = new UpgradeRouterTemplateResponse();
        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(org.apache.cloudstack.api.response.UpgradeRouterTemplateResponse) ListResponse(org.apache.cloudstack.api.response.ListResponse) ArrayList(java.util.ArrayList) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob)

Aggregations

AsyncJob (org.apache.cloudstack.framework.jobs.AsyncJob)10 Account (com.cloud.user.Account)4 AsyncJobExecutionContext (org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext)4 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)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 ResponseObject (org.apache.cloudstack.api.ResponseObject)2 ListResponse (org.apache.cloudstack.api.response.ListResponse)2 DataObject (org.apache.cloudstack.engine.subsystem.api.storage.DataObject)2