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

The following examples show how to use org.apache.brooklyn.api.mgmt.Task#isDone() . 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: MachineLifecycleEffectorTasksTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testProvisionLatchObeyed() throws Exception {

    AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");

    BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));

    EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
            .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));

    final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
            "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
    
    Time.sleep(ValueResolver.PRETTY_QUICK_WAIT);
    if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.get());
    assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());

    Asserts.succeedsContinually(new Runnable() {
        @Override
        public void run() {
            if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.getUnchecked());
        }
    });
    try {
        triggerEntity.sensors().set(ready, true);
        task.get(Duration.THIRTY_SECONDS);
    } catch (Throwable t) {
        Exceptions.propagateIfFatal(t);
        if ((t.toString().contains(BailOutJcloudsLocation.ERROR_MESSAGE))) {
            // expected - BailOut location throws - just swallow
        } else {
            Exceptions.propagate(t);
        }
    }
}
 
Example 3
Source File: AbstractInvokeEffectorPolicyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCountReflectsNumberOfExecutingEffectors() {
    final CountDownLatch effectorLatch = new CountDownLatch(1);
    final AttributeSensor<Boolean> policyIsBusy = Sensors.newBooleanSensor(
            "policyIsBusy");
    final Effector<Void> blockingEffector = Effectors.effector(Void.class, "abstract-invoke-effector-policy-test")
            .impl(new BlockingEffector(effectorLatch))
            .build();
    final TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    final TestAbstractInvokeEffectorPolicy policy = entity.policies().add(
            PolicySpec.create(TestAbstractInvokeEffectorPolicy.class)
                    .configure(AbstractInvokeEffectorPolicy.IS_BUSY_SENSOR_NAME, policyIsBusy.getName()));
    final Task<?> effectorTask = policy.invoke(blockingEffector, ImmutableMap.<String, Object>of());

    // expect isbusy on entity, effector incomplete.
    Supplier<Boolean> effectorTaskDoneSupplier = new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return effectorTask.isDone();
        }
    };
    Asserts.continually(effectorTaskDoneSupplier, Predicates.equalTo(false));
    EntityAsserts.assertAttributeEqualsEventually(entity, policyIsBusy, true);

    effectorLatch.countDown();

    Asserts.eventually(effectorTaskDoneSupplier, Predicates.equalTo(true));
    EntityAsserts.assertAttributeEqualsEventually(entity, policyIsBusy, false);
}
 
Example 4
Source File: Poller.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public boolean isRunning() {
    boolean hasActiveTasks = false;
    for (Task<?> task: tasks) {
        if (task.isBegun() && !task.isDone()) {
            hasActiveTasks = true;
            break;
        }
    }
    if (!started && hasActiveTasks) {
        log.warn("Poller should not be running, but has active tasks, tasks: "+tasks);
    }
    return started && hasActiveTasks;
}
 
Example 5
Source File: MementosGenerators.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected static Object configValueToPersistable(Object value, BrooklynObject obj, String keyName) {
    // TODO Swapping an attributeWhenReady task for the actual value, if completed.
    // Long-term, want to just handle task-persistence properly.
    if (value instanceof Task) {
        Task<?> task = (Task<?>) value;
        String contextName = "";
        if (obj!=null) {
            contextName = obj.getCatalogItemId();
            if (Strings.isBlank(contextName)) contextName= obj.getDisplayName();
        }
        if (keyName!=null) {
            if (Strings.isNonBlank(contextName)) contextName += ":";
            contextName += keyName;
        }
        String message = "Persisting "+contextName+" - encountered task "+value;
        Object result = null;
        if (task.isDone() && !task.isError()) {
            result = task.getUnchecked();
            message += "; persisting result "+result;
        } else {
            // TODO how to record a completed but errored task?
            message += "; persisting as null";
            result = null;
        }
        if (WARNED_ON_PERSISTING_TASK_CONFIG.add(contextName)) {
            log.warn(message+" (subsequent values for this key will be at null)");
        } else {
            log.debug(message);
        }
        return result;
    }
    return value;
}
 
Example 6
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected int expireIfOverCapacityGlobally() {
    Collection<Task<?>> tasksLive = executionManager.allTasksLive();
    if (tasksLive.size() <= brooklynProperties.getConfig(MAX_TASKS_GLOBAL))
        return 0;
    LOG.debug("brooklyn-gc detected "+tasksLive.size()+" tasks in memory, over global limit, looking at deleting some");
    
    try {
        tasksLive = MutableList.copyOf(tasksLive);
    } catch (ConcurrentModificationException e) {
        tasksLive = executionManager.getTasksWithAllTags(MutableList.of());
    }

    MutableList<Task<?>> tasks = MutableList.of();
    for (Task<?> task: tasksLive) {
        if (task.isDone()) {
            tasks.add(task);
        }
    }
    
    int numToDelete = tasks.size() - brooklynProperties.getConfig(MAX_TASKS_GLOBAL);
    if (numToDelete <= 0) {
        LOG.debug("brooklyn-gc detected only "+tasks.size()+" completed tasks in memory, not over global limit, so not deleting any");
        return 0;
    }
        
    Collections.sort(tasks, TASKS_OLDEST_FIRST_COMPARATOR);
    
    int numDeleted = 0;
    while (numDeleted < numToDelete && tasks.size()>numDeleted) {
        executionManager.deleteTask( tasks.get(numDeleted++) );
    }
    if (LOG.isDebugEnabled())
        LOG.debug("brooklyn-gc deleted "+numDeleted+" tasks as was over global limit, now have "+executionManager.allTasksLive().size());
    return numDeleted;
}
 
Example 7
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private boolean isSubmitterExpired(Task<?> task) {
    if (Strings.isBlank(task.getSubmittedByTaskId())) {
        return false;
    }
    Task<?> submitter = task.getSubmittedByTask();
    if (submitter!=null && (!submitter.isDone() || executionManager.getTask(submitter.getId())!=null)) {
        return false;
    }
    // submitter task is GC'd
    return true;
}
 
Example 8
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void expireTransientTasks() {
    Set<Task<?>> transientTasks = executionManager.getTasksWithTag(BrooklynTaskTags.TRANSIENT_TASK_TAG);
    for (Task<?> t: transientTasks) {
        if (!t.isDone(true)) continue;
        executionManager.deleteTask(t);
    }
}
 
Example 9
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** whether this task should be deleted on completion,
 * because it is transient, or because it is submitted background without much context information */
protected boolean shouldDeleteTaskImmediately(Task<?> task) {
    if (!task.isDone(true)) {
        return false;
    }
    
    Set<Object> tags = BrooklynTaskTags.getTagsFast(task);
    if (tags.contains(ManagementContextInternal.TRANSIENT_TASK_TAG))
        return true;
    if (tags.contains(ManagementContextInternal.EFFECTOR_TAG) || tags.contains(ManagementContextInternal.NON_TRANSIENT_TASK_TAG))
        return false;
    
    if (!isSubmitterExpired(task)) {
        return false;
    }
    if (isChild(task)) {
        // parent should manage this task's death; but above already kicks in if parent is not expired, so probably shouldn't come here?
        LOG.warn("Unexpected expiry candidacy for "+task);
        return false;
    }
    if (isAssociatedToActiveEntity(task)) {
        return false;
    }
    
    // e.g. scheduled tasks, sensor events, etc
    // (in future may keep some of these with another limit, based on a new TagCategory)
    // there may also be a server association for server-side tasks which should be kept
    // (but be careful not to keep too many subscriptions!)
    
    return true;
}
 
Example 10
Source File: CompoundTask.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doCancel(org.apache.brooklyn.util.core.task.TaskInternal.TaskCancellationMode mode) {
    boolean result = false;
    if (mode.isAllowedToInterruptDependentSubmittedTasks()) {
        for (Task<?> t: getChildren()) {
            if (!t.isDone()) {
                result = ((TaskInternal<?>)t).cancel(mode) || result;
            }
        }
    }
    result = super.doCancel(mode) || result;
    return result;
    // returns true if anything is successfully cancelled
}
 
Example 11
Source File: Tasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns the error thrown by the task if {@link Task#isError()}, or null if no error or not done */
public static Throwable getError(Task<?> t) {
    if (t==null) return null;
    if (!t.isDone()) return null;
    if (t.isCancelled()) return new CancellationException();
    try {
        t.get();
        return null;
    } catch (Throwable error) {
        // do not propagate as we are pretty much guaranteed above that it wasn't this
        // thread which originally threw the error
        return error;
    }
}
 
Example 12
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 13
Source File: EntityLaunchListener.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Lifecycle> event) {
    if (event.getValue() == Lifecycle.RUNNING) {
        Task<?>launchTask = getLatestLaunchTask(enricher.getEntity());
        if (launchTask != null) {
            launchTaskRef.set(launchTask);
            if (!launchTask.isDone()) {
                launchTask.addListener(this, enricher.getEntityExecutionContext());
            }
            if (launchTask.isDone()) {
                run();
            }
        }
    }
}
 
Example 14
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);
    }
}
 
Example 15
Source File: TaskPredicates.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Task<?> input) {
    return (input != null) && input.isDone();
}
 
Example 16
Source File: ActivityRestTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private Task<?> waitForCompletedDescendantWithChildAndSibling(Task<?> tRoot, Task<?> t, CountdownTimer timer, int depthSoFar) {
    while (timer.isLive()) {
        Iterable<Task<?>> children = ((HasTaskChildren)t).getChildren();
        Iterator<Task<?>> ci = children.iterator();
        Task<?> bestFinishedDescendant = null;
        while (ci.hasNext()) {
            Task<?> tc = ci.next();
            Task<?> finishedDescendant = waitForCompletedDescendantWithChildAndSibling(tRoot, tc, timer, depthSoFar+1);
            if (depthOf(finishedDescendant) > depthOf(bestFinishedDescendant)) {
                bestFinishedDescendant = finishedDescendant;
            }
            int finishedDescendantDepth = depthOf(bestFinishedDescendant);
            // log.info("finished "+tc+", depth "+finishedDescendantDepth);
            if (finishedDescendantDepth < 2) {
                if (ci.hasNext()) continue;
                throw new IllegalStateException("not deep enough: "+finishedDescendantDepth);
            }
            if (finishedDescendantDepth == depthSoFar+1) {
                // child completed; now check we complete soon, and assert we have siblings
                if (ci.hasNext()) continue;
                if (!t.blockUntilEnded(timer.getDurationRemaining())) {
                    Dumper.dumpInfo(tRoot);
                    // log.info("Incomplete after "+t+": "+t.getStatusDetail(false));
                    throw Exceptions.propagate( new TimeoutException("parent didn't complete after child depth "+finishedDescendantDepth) );
                }
            }
            if (finishedDescendantDepth == depthSoFar+2) {
                if (Iterables.size(children)<2) {
                    Dumper.dumpInfo(tRoot);
                    throw new IllegalStateException("finished child's parent has no sibling");
                }
            }
            
            return bestFinishedDescendant;
        }
        Thread.yield();
        
        // leaf nodeƄ
        if (t.isDone()) return t;
    }
    throw Exceptions.propagate( new TimeoutException("expired waiting for children") );
}
 
Example 17
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());
}