Java Code Examples for org.apache.brooklyn.api.mgmt.Task#isSubmitted()

The following examples show how to use org.apache.brooklyn.api.mgmt.Task#isSubmitted() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicExecutionManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected boolean deleteTaskNonRecursive(Task<?> task) {
    Set<?> tags = TaskTags.getTagsFast(checkNotNull(task, "task"));
    for (Object tag : tags) {
        synchronized (tasksByTag) {
            Set<Task<?>> tasks = tasksWithTagLiveOrNull(tag);
            if (tasks != null) {
                tasks.remove(task);
                if (tasks.isEmpty()) {
                    tasksByTag.remove(tag);
                }
            }
        }
    }
    Task<?> removed = tasksById.remove(task.getId());
    incompleteTaskIds.remove(task.getId());
    if (removed!=null && removed.isSubmitted() && !removed.isDone(true)) {
        Entity context = BrooklynTaskTags.getContextEntity(removed);
        if (context!=null && !Entities.isManaged(context)) {
            log.debug("Forgetting about active task on unmanagement of "+context+": "+removed);
        } else {
            log.warn("Deleting submitted task before completion: "+removed+"; this task will continue to run in the background outwith "+this+", but perhaps it should have been cancelled?");
        }
    }
    return removed != null;
}
 
Example 2
Source File: BasicTask.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onTaskFinalization(Task<?> t) {
    if (!Tasks.isAncestorCancelled(t) && !t.isSubmitted()) {
        log.warn(t+" was never submitted; did the code create it and forget to run it? ('cancel' the task to suppress this message)");
        log.debug("Detail of unsubmitted task "+t+":\n"+t.getStatusDetail(true));
        return;
    }
    if (!t.isDone()) {
        if (!BrooklynTaskTags.getExecutionContext(t).isShutdown()) {
            // not sure how this could happen
            log.warn("Task "+t+" was submitted but forgotten before it was run (finalized before completion)");
        }
        return;
    }
}
 
Example 3
Source File: DynamicSequentialTask.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** submits the indicated task for execution in the current execution context, and returns immediately */
protected void submitBackgroundInheritingContext(Task<?> task) {
    BasicExecutionContext ec = BasicExecutionContext.getCurrentExecutionContext();
    if (log.isTraceEnabled()) {
        log.trace("task {} - submitting background task {} ({})", new Object[] { Tasks.current(), task, ec });
    }
    if (ec==null) {
        String message = Tasks.current()!=null ?
                // user forgot ExecContext:
                    "Task "+this+" submitting background task requires an ExecutionContext (an ExecutionManager is not enough): submitting "+task+" in "+Tasks.current()
                : // should not happen:
                    "Cannot submit tasks inside DST when not in a task : submitting "+task+" in "+this;
        log.warn(message+" (rethrowing)");
        throw new IllegalStateException(message);
    }
    synchronized (task) {
        if (task.isSubmitted()) {
            if (log.isTraceEnabled()) {
                log.trace("DST "+this+" skipping submission of child "+task+" because it is already submitted");
            }
        } else {
            try {
                ec.submit(task);
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                // Give some context when the submit fails (happens when the target is already unmanaged)
                throw new IllegalStateException("Failure submitting task "+task+" in "+this+": "+e.getMessage(), e);
            }
        }
    }
}
 
Example 4
Source File: EntityResource.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public int compare(Task<?> o1, Task<?> o2) {
    // absolute pref for submitted items
    if (!Objects.equal(o1.isSubmitted(), o2.isSubmitted())) {
        return o1.isSubmitted() ? -1 : 1;
    }

    // big pref for top-level tasks (manual operations), where submitter null
    int weight = 0;
    Task<?> o1s = o1.getSubmittedByTask();
    Task<?> o2s = o2.getSubmittedByTask();
    if ("start".equals(o1.getDisplayName()) ||"start".equals(o2.getDisplayName())) {
        weight = 0;
    }
    if (!Objects.equal(o1s==null, o2s==null))
        weight += 2*60*60 * (o1s==null ? -1 : 1);
    
    // pretty big pref for things invoked by other entities
    if (context!=null && o1s!=null && o2s!=null) {
        boolean o1se = context.equals(BrooklynTaskTags.getContextEntity(o1s));
        boolean o2se = context.equals(BrooklynTaskTags.getContextEntity(o2s));
        if (!Objects.equal(o1se, o2se))
            weight += 10*60 *  (o2se ? -1 : 1);
    }
    // slight pref for things in progress
    if (!Objects.equal(o1.isBegun() && !o1.isDone(), o2.isBegun() && !o2.isDone()))
        weight += 60 * (o1.isBegun() && !o1.isDone() ? -1 : 1);
    // and very slight pref for things not begun
    if (!Objects.equal(o1.isBegun(), o2.isBegun())) 
        weight += 10 * (!o1.isBegun() ? -1 : 1);
    
    // sort based on how recently the task changed state
    long now = System.currentTimeMillis();
    long t1 = o1.isDone() ? o1.getEndTimeUtc() : o1.isBegun() ? o1.getStartTimeUtc() : o1.getSubmitTimeUtc();
    long t2 = o2.isDone() ? o2.getEndTimeUtc() : o2.isBegun() ? o2.getStartTimeUtc() : o2.getSubmitTimeUtc();
    long u1 = now - t1;
    long u2 = now - t2;
    // so smaller = more recent
    // and if there is a weight, increase the other side so it is de-emphasised
    // IE if weight was -10 that means T1 is "10 times more interesting"
    // or more precisely, a task T1 from 10 mins ago equals a task T2 from 1 min ago
    if (weight<0) u2 *= -weight;
    else if (weight>0) u1 *= weight;
    if (u1!=u2) return u1 > u2 ? 1 : -1;
    // if equal under mapping, use weight
    if (weight!=0) return weight < 0 ? -1 : 1;
    // lastly use ID to ensure canonical order
    return o1.getId().compareTo(o2.getId());
}
 
Example 5
Source File: BasicExecutionContext.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** performs execution without spawning a new task thread, though it does temporarily set a fake task for the purpose of getting context;
 * currently supports {@link Supplier}, {@link Callable}, {@link Runnable}, or {@link Task} instances; 
 * with tasks if it is submitted or in progress,
 * it fails if not completed; with unsubmitted, unqueued tasks, it gets the {@link Callable} job and 
 * uses that; with such a job, or any other callable/supplier/runnable, it runs that
 * in an {@link InterruptingImmediateSupplier}, with as much metadata as possible (eg task name if
 * given a task) set <i>temporarily</i> in the current thread context */
@SuppressWarnings("unchecked")
@Override
public <T> Maybe<T> getImmediately(Object callableOrSupplier) {
    BasicTask<T> fakeTaskForContext;
    if (callableOrSupplier instanceof BasicTask) {
        fakeTaskForContext = (BasicTask<T>)callableOrSupplier;
        if (fakeTaskForContext.isQueuedOrSubmitted()) {
            if (fakeTaskForContext.isDone()) {
                return Maybe.of(fakeTaskForContext.getUnchecked());
            } else {
                throw new ImmediateUnsupportedException("Task is in progress and incomplete: "+fakeTaskForContext);
            }
        }
        callableOrSupplier = fakeTaskForContext.getJob();
    } else if (callableOrSupplier instanceof TaskAdaptable) {
        Task<T> task = ((TaskAdaptable<T>)callableOrSupplier).asTask();
        if (task == callableOrSupplier) {
            // Our TaskAdaptable was a task, but not a BasicTask.
            // Avoid infinite recursion (don't just call ourselves again!).
            if (task.isDone()) {
                return Maybe.of(task.getUnchecked());
            } else if (task.isSubmitted() || task.isBegun()) {
                throw new ImmediateUnsupportedException("Task is in progress and incomplete: "+task);
            } else {
                throw new ImmediateUnsupportedException("Task not a 'BasicTask', so cannot extract job to get immediately: "+task);
            }
        } else {
            // recurse - try again with the task we've just generated
            return getImmediately(task);
        }
    } else {
        fakeTaskForContext = new BasicTask<T>(MutableMap.of("displayName", "Immediate evaluation"));
    }
    final ImmediateSupplier<T> job = callableOrSupplier instanceof ImmediateSupplier ? (ImmediateSupplier<T>) callableOrSupplier 
        : InterruptingImmediateSupplier.<T>of(callableOrSupplier);
    fakeTaskForContext.tags.add(BrooklynTaskTags.IMMEDIATE_TASK_TAG);
    fakeTaskForContext.tags.add(BrooklynTaskTags.TRANSIENT_TASK_TAG);

    ContextSwitchingInfo<T> switchContextWrapper = getContextSwitchingTask(fakeTaskForContext, Collections.emptyList(), true);
    if (switchContextWrapper!=null) {
        return switchContextWrapper.context.getImmediately(switchContextWrapper.wrapperTask);
    }

    try {
        return runInSameThread(fakeTaskForContext, new Callable<Maybe<T>>() {
            public Maybe<T> call() {
                boolean wasAlreadyInterrupted = Thread.interrupted();
                try {
                    return job.getImmediately();
                } finally {
                    if (wasAlreadyInterrupted) {
                        Thread.currentThread().interrupt();
                    }
                    // we've acknowledged that getImmediate may wreck (cancel) the task,
                    // their first priority is to prevent them from leaking;
                    // however previously we did the cancel before running, 
                    // doing it after means more tasks successfully execute 
                    // (the interrupt is sufficient to prevent them blocking); 
                    // see test EffectorSayHiTest.testInvocationGetImmediately
                    fakeTaskForContext.cancel();
                }
            } });
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}