@Override public T call() throws Exception { ExecutionContext executionContext = ((EntityInternal) entity).getExecutionContext(); return executionContext.submit(Maps.newHashMap(), job).get(); } }
/** * Submits a {@link TaskFactory} to construct its task at the entity (in a precursor task) and then to submit it. * <p> * Important if task construction relies on an entity being in scope (in tags, via {@link BrooklynTaskTags}) */ public static <T extends TaskAdaptable<?>> T submit(final Entity entity, final TaskFactory<T> taskFactory) { // TODO it is messy to have to do this, but not sure there is a cleaner way :( final Semaphore s = new Semaphore(0); final AtomicReference<T> result = new AtomicReference<T>(); final ExecutionContext executionContext = ((EntityInternal)entity).getExecutionContext(); executionContext.execute(new Runnable() { // TODO could give this task a name, like "create task from factory" @Override public void run() { T t = taskFactory.newTask(); result.set(t); s.release(); } }); try { s.acquire(); } catch (InterruptedException e) { throw Exceptions.propagate(e); } executionContext.submit(result.get().asTask()); return result.get(); }
try { Set<Task<?>> tasksCancelled = MutableSet.of(); for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (entity.equals(BrooklynTaskTags.getContextEntity(Tasks.current())) && hasTaskAsAncestor(t, Tasks.current())) { Set<Task<?>> tasksIncomplete = MutableSet.of(); for (Task<?> t: managementContext.getExecutionContext(entity).getTasks()) { if (hasTaskAsAncestor(t, Tasks.current())) continue;
result = exec.getImmediately(v); exec.submit(task); Task<Object> vt = exec.submit(tb.build()); Maybe<Object> vm = Durations.get(vt, timer); vt.cancel(true);
@Override public void rebind() { super.rebind(); if (taskScan == null) { // The feed calls scanTasks, which modifies other entities.That is dangerous during // rebind, because the rebind-thread may concurrently (or subsequently) be initialising // those other entities. Similar code (e.g. DynamicMultiGroup) has caused rebind of // of those other entities to subsequently fail. // // Normal best-practice would be to use {@code feeds().addFeed(feed)} so that the entity // automatically persists its feed, but this is no ordinary feed! Therefore safer (for // now) to do it this way. getExecutionContext().execute(new Runnable() { @Override public void run() { LOG.debug("Deferring scanner for {} until management context initialisation complete", MesosFrameworkImpl.this); while (!isRebindComplete()) { Time.sleep(100); // avoid thrashing } LOG.debug("Connecting scanner for {}", MesosFrameworkImpl.this); connectSensors(); } private boolean isRebindComplete() { return !getManagementContext().getRebindManager().isAwaitingInitialRebind(); }}); } }
/** * Whether we have been stopped, ie are stopping are or fully stopped, * in which case will not persist or store anything * (except for a final internal persistence called while STOPPING.) */ private boolean isStopped() { return state == ListenerState.STOPPING || state == ListenerState.STOPPED || executionContext.isShutdown(); }
/** * For resolving a {@link StructuredConfigKey}, such as a {@link MapConfigKey}. Here we need to * execute the custom logic, as is done by {@link #get(ConfigKey)}, but non-blocking! */ protected <T> Maybe<T> getNonBlockingResolvingStructuredKey(final ConfigKey<T> key) { Callable<T> job = new Callable<T>() { @Override public T call() { try { return get(key); } catch (RuntimeInterruptedException e) { throw Exceptions.propagate(e); // expected; return gracefully } } }; Task<T> t = Tasks.<T>builder().body(job) .displayName("Resolving dependent value") .description("Resolving "+key.getName()) .tag(BrooklynTaskTags.TRANSIENT_TASK_TAG) .build(); try { return getContext().getImmediately(t); } catch (ImmediateUnsupportedException e) { return Maybe.absent(); } }
getExecutionContext().execute(new Runnable() { @Override public void run() { LOG.debug("Deferring scanner for {} until management context initialisation complete", DynamicMultiGroupImpl.this);
@Override public T call() throws Exception { final ExecutionContext executionContext = ((EntityInternal) entity).getExecutionContext(); return executionContext.submit(Maps.newHashMap(), job).get(); } }
synchronized (sonsConfig) { assertEquals(null, sonsConfig[0]); for (Task tt : ((EntityInternal)dad).getExecutionContext().getTasks()) { log.info("task at dad: {}, {}", tt, tt.getStatusDetail(false)); } for (Task tt : ((EntityInternal)son).getExecutionContext().getTasks()) { log.info("task at son: {}, {}", tt, tt.getStatusDetail(false)); } dad.sensors().set(HelloEntity.FAVOURITE_NAME, "Dan"); if (!s1.tryAcquire(2, TimeUnit.SECONDS)) fail("race mismatch, missing permits");
@Override public T call() throws Exception { final ExecutionContext executionContext = ((EntityInternal) entity).getExecutionContext(); return executionContext.submit(Maps.newHashMap(), job).get(); } }
/** * Submits a task to run at the entity. * * @return the task passed in, for fluency */ public static <T extends TaskAdaptable<?>> T submit(final Entity entity, final T task) { final ExecutionContext executionContext = ((EntityInternal)entity).getExecutionContext(); executionContext.submit(task.asTask()); return task; }
@SuppressWarnings("unchecked") protected void schedulePublish(long delay) { if (isRunning() && executorQueued.compareAndSet(false, true)) { long now = System.currentTimeMillis(); delay = Math.max(0, Math.max(delay, (executorTime + MIN_PERIOD_BETWEEN_EXECS_MILLIS) - now)); if (LOG.isTraceEnabled()) LOG.trace("{} scheduling publish in {}ms", this, delay); Runnable job = new PublishJob(); ScheduledTask task = new ScheduledTask(MutableMap.of("delay", Duration.of(delay, TimeUnit.MILLISECONDS)), new BasicTask<Void>(job)); ((EntityInternal)entity).getExecutionContext().submit(task); } }
/** * Convenience for creating and submitted a given shell command against the given mgmt context, * primarily intended for use in the groovy GUI console. */ @Beta public static ProcessTaskWrapper<Integer> shell(ManagementContext mgmt, String command) { ProcessTaskWrapper<Integer> t = SystemTasks.exec(command).newTask(); mgmt.getServerExecutionContext().submit(t).getUnchecked(); System.out.println(t.getStdout()); System.err.println(t.getStderr()); return t; }
private <T> Task<T> submit(Task<T> task) { return app.getExecutionContext().submit(task); }
@Override public SshPollValue call() throws Exception { ProcessTaskWrapper<?> taskWrapper = taskFactory.newTask(); executionContext.submit(taskWrapper); taskWrapper.block(); Optional<Integer> exitCode = Optional.fromNullable(taskWrapper.getExitCode()); return new SshPollValue(null, exitCode.or(-1), taskWrapper.getStdout(), taskWrapper.getStderr()); }}, new DelegatingPollHandler<SshPollValue>(handlers),
protected void runConcurrentWorker(Supplier<Runnable> taskSupplier) { Collection<Task<?>> results = new ArrayList<>(); for (int i = 0; i < MAX_PARALLEL_RESOLVERS; i++) { Task<?> result = app.getExecutionContext().submit(taskSupplier.get()); results.add(result); } for (Task<?> result : results) { result.getUnchecked(); } }
@Override public void onEvent(final SensorEvent<Object> event) { // Must execute in another thread - if we called entity.restart in the event-listener's thread // then we'd block all other events being delivered to this entity's other subscribers. // Relies on synchronization of `onDetectedFailure`. // See same pattern used in ServiceReplacer. // TODO Could use BasicExecutionManager.setTaskSchedulerForTag to prevent race of two // events being received in rapid succession, and onDetectedFailure being executed out-of-order // for them; or could write events to a blocking queue and have onDetectedFailure read from that. if (isRunning()) { LOG.info("ServiceRestarter notified; dispatching job for "+entity+" ("+event.getValue()+")"); ((EntityInternal)entity).getExecutionContext().submit(MutableMap.of(), new Runnable() { @Override public void run() { onDetectedFailure(event); }}); } else { LOG.warn("ServiceRestarter not running, so not acting on failure detected at "+entity+" ("+event.getValue()+")"); } } });
@Override public SshPollValue call() throws Exception { ProcessTaskWrapper<String> taskWrapper = knifeTaskFactory.newTask(); final ExecutionContext executionContext = ((EntityInternal) entity).getExecutionContext(); log.debug("START: Running knife to query attributes of Chef node {}", nodeName); executionContext.submit(taskWrapper); taskWrapper.block(); log.debug("DONE: Running knife to query attributes of Chef node {}", nodeName); return new SshPollValue(null, taskWrapper.getExitCode(), taskWrapper.getStdout(), taskWrapper.getStderr()); } };
@Override public SshPollValue call() throws Exception { ProcessTaskWrapper<String> taskWrapper = knifeTaskFactory.newTask(); final ExecutionContext executionContext = ((EntityInternal) entity).getExecutionContext(); log.debug("START: Running knife to query attributes of Chef node {}", nodeName); executionContext.submit(taskWrapper); taskWrapper.block(); log.debug("DONE: Running knife to query attributes of Chef node {}", nodeName); return new SshPollValue(null, taskWrapper.getExitCode(), taskWrapper.getStdout(), taskWrapper.getStderr()); } };