@Override
  public void redeployAll() {
    Map<String, String> wars = MutableMap.copyOf(getConfig(WARS_BY_CONTEXT));
    String redeployPrefix = "Redeploy all WARs (count " + wars.size() + ")";

    log.debug("Redeplying all WARs across cluster " + this + ": " + getConfig(WARS_BY_CONTEXT));

    Iterable<CanDeployAndUndeploy> targetEntities =
        Iterables.filter(getChildren(), CanDeployAndUndeploy.class);
    TaskBuilder<Void> tb =
        Tasks.<Void>builder()
            .parallel(true)
            .name(redeployPrefix + " across cluster (size " + Iterables.size(targetEntities) + ")");
    for (Entity targetEntity : targetEntities) {
      TaskBuilder<Void> redeployAllToTarget =
          Tasks.<Void>builder()
              .name(redeployPrefix + " at " + targetEntity + " (after ready check)");
      for (String warContextPath : wars.keySet()) {
        redeployAllToTarget.add(
            Effectors.invocation(
                targetEntity,
                DEPLOY,
                MutableMap.of("url", wars.get(warContextPath), "targetName", warContextPath)));
      }
      tb.add(
          whenServiceUp(
              targetEntity,
              redeployAllToTarget.build(),
              redeployPrefix + " at " + targetEntity + " when ready"));
    }
    DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked();
  }
 @Test
 public void testInessentialChildrenFailureDoesNotAbortSecondaryOrFailPrimary() {
   Task<String> t1 = monitorableTask(null, "1", new FailCallable());
   TaskTags.markInessential(t1);
   Task<String> t =
       Tasks.<String>builder()
           .dynamic(true)
           .body(monitorableJob("main"))
           .add(t1)
           .add(monitorableTask("2"))
           .build();
   ec.submit(t);
   releaseAndWaitForMonitorableJob("1");
   Assert.assertFalse(t.blockUntilEnded(TINY_TIME));
   releaseAndWaitForMonitorableJob("2");
   Assert.assertFalse(t.blockUntilEnded(TINY_TIME));
   releaseMonitorableJob("main");
   Assert.assertTrue(t.blockUntilEnded(TIMEOUT));
   Assert.assertEquals(messages, MutableList.of("1", "2", "main"));
   Assert.assertTrue(
       stopwatch.elapsed(TimeUnit.MILLISECONDS) < TIMEOUT.toMilliseconds(),
       "took too long: " + stopwatch);
   Assert.assertFalse(t.isError());
   Assert.assertTrue(t1.isError());
 }
Exemple #3
0
  @SuppressWarnings({"unchecked"})
  public void start() {
    // TODO Previous incarnation of this logged this logged polledSensors.keySet(), but we don't
    // know that anymore
    // Is that ok, are can we do better?

    if (log.isDebugEnabled())
      log.debug("Starting poll for {} (using {})", new Object[] {entity, this});
    if (running) {
      throw new IllegalStateException(
          String.format(
              "Attempt to start poller %s of entity %s when already running", this, entity));
    }

    running = true;

    for (final Callable<?> oneOffJob : oneOffJobs) {
      Task<?> task =
          Tasks.builder()
              .dynamic(false)
              .body((Callable<Object>) oneOffJob)
              .name("Poll")
              .description("One-time poll job " + oneOffJob)
              .build();
      oneOffTasks.add(((EntityInternal) entity).getExecutionContext().submit(task));
    }

    for (final PollJob<V> pollJob : pollJobs) {
      final String scheduleName = pollJob.handler.getDescription();
      if (pollJob.pollPeriod.compareTo(Duration.ZERO) > 0) {
        Callable<Task<?>> pollingTaskFactory =
            new Callable<Task<?>>() {
              public Task<?> call() {
                DynamicSequentialTask<Void> task =
                    new DynamicSequentialTask<Void>(
                        MutableMap.of("displayName", scheduleName, "entity", entity),
                        new Callable<Void>() {
                          public Void call() {
                            pollJob.wrappedJob.run();
                            return null;
                          }
                        });
                BrooklynTaskTags.setTransient(task);
                return task;
              }
            };
        ScheduledTask task =
            new ScheduledTask(MutableMap.of("period", pollJob.pollPeriod), pollingTaskFactory);
        tasks.add((ScheduledTask) Entities.submit(entity, task));
      } else {
        if (log.isDebugEnabled())
          log.debug(
              "Activating poll (but leaving off, as period {}) for {} (using {})",
              new Object[] {pollJob.pollPeriod, entity, this});
      }
    }
  }
  @Override
  public void undeploy(String targetName) {
    checkNotNull(targetName, "targetName");
    targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName);

    // set it up so future nodes get the right wars
    if (!removeFromWarsByContext(this, targetName)) {
      DynamicTasks.submit(
          Tasks.warning(
              "Context "
                  + targetName
                  + " not known at "
                  + this
                  + "; attempting to undeploy regardless",
              null),
          this);
    }

    log.debug(
        "Undeploying "
            + targetName
            + " across cluster "
            + this
            + "; WARs now "
            + getConfig(WARS_BY_CONTEXT));

    Iterable<CanDeployAndUndeploy> targets =
        Iterables.filter(getChildren(), CanDeployAndUndeploy.class);
    TaskBuilder<Void> tb =
        Tasks.<Void>builder()
            .parallel(true)
            .name(
                "Undeploy "
                    + targetName
                    + " across cluster (size "
                    + Iterables.size(targets)
                    + ")");
    for (Entity target : targets) {
      tb.add(
          whenServiceUp(
              target,
              Effectors.invocation(target, UNDEPLOY, MutableMap.of("targetName", targetName)),
              "Undeploy " + targetName + " at " + target + " when ready"));
    }
    DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked();

    // Update attribute
    Set<String> deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS));
    deployedWars.remove(
        FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName));
    setAttribute(DEPLOYED_WARS, deployedWars);
  }
  @Test
  public void testTaskBuilderUsingAddAllChildren() {
    Task<String> t =
        Tasks.<String>builder()
            .dynamic(true)
            .body(monitorableJob("main"))
            .addAll(ImmutableList.of(monitorableTask("1"), monitorableTask("2")))
            .build();
    ec.submit(t);
    releaseAndWaitForMonitorableJob("1");
    releaseAndWaitForMonitorableJob("2");
    releaseAndWaitForMonitorableJob("main");

    Assert.assertEquals(messages, MutableList.of("1", "2", "main"));
  }
  @Override
  public void deploy(String url, String targetName) {
    checkNotNull(url, "url");
    checkNotNull(targetName, "targetName");
    targetName = FILENAME_TO_WEB_CONTEXT_MAPPER.convertDeploymentTargetNameToContext(targetName);

    // set it up so future nodes get the right wars
    addToWarsByContext(this, url, targetName);

    log.debug(
        "Deploying "
            + targetName
            + "->"
            + url
            + " across cluster "
            + this
            + "; WARs now "
            + getConfig(WARS_BY_CONTEXT));

    Iterable<CanDeployAndUndeploy> targets =
        Iterables.filter(getChildren(), CanDeployAndUndeploy.class);
    TaskBuilder<Void> tb =
        Tasks.<Void>builder()
            .parallel(true)
            .name("Deploy " + targetName + " to cluster (size " + Iterables.size(targets) + ")");
    for (Entity target : targets) {
      tb.add(
          whenServiceUp(
              target,
              Effectors.invocation(
                  target, DEPLOY, MutableMap.of("url", url, "targetName", targetName)),
              "Deploy " + targetName + " to " + target + " when ready"));
    }
    DynamicTasks.queueIfPossible(tb.build()).orSubmitAsync(this).asTask().getUnchecked();

    // Update attribute
    // TODO support for atomic sensor update (should be part of standard tooling; NB there is some
    // work towards this, according to @aledsage)
    Set<String> deployedWars = MutableSet.copyOf(getAttribute(DEPLOYED_WARS));
    deployedWars.add(targetName);
    setAttribute(DEPLOYED_WARS, deployedWars);
  }
 /**
  * Waits for the given target to report service up, then runs the given task (often an invocation
  * on that entity), with the given name. If the target goes away, this task marks itself
  * inessential before failing so as not to cause a parent task to fail.
  */
 static <T> Task<T> whenServiceUp(final Entity target, final TaskAdaptable<T> task, String name) {
   return Tasks.<T>builder()
       .name(name)
       .dynamic(true)
       .body(
           new Callable<T>() {
             @Override
             public T call() {
               try {
                 while (true) {
                   if (!Entities.isManaged(target)) {
                     Tasks.markInessential();
                     throw new IllegalStateException("Target " + target + " is no longer managed");
                   }
                   if (Boolean.TRUE.equals(target.getAttribute(Attributes.SERVICE_UP))) {
                     Tasks.resetBlockingDetails();
                     TaskTags.markInessential(task);
                     DynamicTasks.queue(task);
                     try {
                       return task.asTask().getUnchecked();
                     } catch (Exception e) {
                       if (Entities.isManaged(target)) {
                         throw Exceptions.propagate(e);
                       } else {
                         Tasks.markInessential();
                         throw new IllegalStateException(
                             "Target " + target + " is no longer managed", e);
                       }
                     }
                   } else {
                     Tasks.setBlockingDetails("Waiting on " + target + " to be ready");
                   }
                   // TODO replace with subscription?
                   Time.sleep(Duration.ONE_SECOND);
                 }
               } finally {
                 Tasks.resetBlockingDetails();
               }
             }
           })
       .build();
 }
  @Test
  public void testChildrenRunConcurrentlyWithPrimary() {
    Task<String> t =
        Tasks.<String>builder()
            .dynamic(true)
            .body(monitorableJob("main"))
            .add(monitorableTask("1"))
            .add(monitorableTask("2"))
            .build();
    ec.submit(t);
    releaseAndWaitForMonitorableJob("1");
    releaseAndWaitForMonitorableJob("main");
    Assert.assertFalse(t.blockUntilEnded(TINY_TIME));
    releaseMonitorableJob("2");

    Assert.assertTrue(t.blockUntilEnded(TIMEOUT));
    Assert.assertEquals(messages, MutableList.of("1", "main", "2"));
    Assert.assertTrue(
        stopwatch.elapsed(TimeUnit.MILLISECONDS) < TIMEOUT.toMilliseconds(),
        "took too long: " + stopwatch);
    Assert.assertFalse(t.isError());
  }
 protected Task<String> monitorableTask(
     final Runnable pre, final String id, final Callable<String> post) {
   Task<String> t = Tasks.<String>builder().body(monitorableJob(pre, id, post)).build();
   monitorableTasksMap.put(id, t);
   return t;
 }
 public Task<String> sayTask(String message, Duration duration, String message2) {
   return Tasks.<String>builder().body(sayCallable(message, duration, message2)).build();
 }