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

The following examples show how to use org.apache.brooklyn.api.mgmt.Task#getUnchecked() . 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: SoftwareEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testBadExitCodeCaught() {
    Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
            .impl(new SshEffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringZeroAndReturningStdout() );
                    return null;
                }
            }).build() );
    try {
        Object result = call.getUnchecked();
        Assert.fail("ERROR: should have failed earlier in this test, instead got successful task result "+result+" from "+call);
    } catch (Exception e) {
        Throwable root = Throwables.getRootCause(e);
        if (!(root instanceof IllegalStateException)) Assert.fail("Should have failed with IAE, but got: "+root);
        if (root.getMessage()==null || root.getMessage().indexOf("exit code")<=0) 
            Assert.fail("Should have failed with 'exit code' message, but got: "+root);
        // test passed
        return;
    }
}
 
Example 2
Source File: MachineDetailsIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void testGetMachineDetails() {
    Task<BasicMachineDetails> detailsTask = app.getExecutionContext().submit(
            BasicMachineDetails.taskForSshMachineLocation(host));
    MachineDetails machine = detailsTask.getUnchecked();
    LOG.info("Found the following on localhost: {}", machine);
    assertNotNull(machine);
    OsDetails details = machine.getOsDetails();
    assertNotNull(details);
    assertNotNull(details.getArch());
    assertNotNull(details.getName());
    assertNotNull(details.getVersion());
    assertFalse(details.getArch().startsWith("architecture:"), "architecture prefix not removed from details");
    assertFalse(details.getName().startsWith("name:"), "name prefix not removed from details");
    assertFalse(details.getVersion().startsWith("version:"), "version prefix not removed from details");
}
 
Example 3
Source File: MaxConcurrencySensor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(@SuppressWarnings("deprecation") final org.apache.brooklyn.api.entity.EntityLocal entity) {
    final AttributeSensor<ReleaseableLatch> sensor = Sensors.newSensor(ReleaseableLatch.class, sensorName);
    ((EntityInternal) entity).getMutableEntityType().addSensor(sensor);

    final Task<ReleaseableLatch> resolveValueTask = DependentConfiguration.maxConcurrency(maxConcurrency);

    class SetValue implements Runnable {
        @Override
        public void run() {
            ReleaseableLatch releaseableLatch = resolveValueTask.getUnchecked();
            log.debug(this+" setting sensor "+sensor+" to "+releaseableLatch+" on "+entity);
            entity.sensors().set(sensor, releaseableLatch);
        }
    }
    Task<ReleaseableLatch> setValueTask = Tasks.<ReleaseableLatch>builder().displayName("Setting " + sensor + " on " + entity).body(new SetValue()).build();

    Entities.submit(entity, Tasks.sequential("Resolving and setting " + sensor + " on " + entity, resolveValueTask, setValueTask));
}
 
Example 4
Source File: RelativeEntityTestCaseImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Entity resolveTarget() {
    Entity anchor = config().get(ANCHOR);
    if (anchor == null) {
        Maybe<Entity> resolvedTarget = tryResolveTarget();
        if (resolvedTarget.isPresent()) {
            anchor = resolvedTarget.get();
        } else {
            throw new IllegalArgumentException("No anchor entity found for " + this);
        }
    }
    sensors().set(ANCHOR, anchor);
    
    Maybe<Object> component = config().getRaw(COMPONENT);
    if (component.isAbsentOrNull()) {
        throw new IllegalArgumentException("No component found for " + this);
    } else if (!(component.get() instanceof DslComponent)) {
        throw new IllegalArgumentException("Expected DslComponent value for component, found " + component.get());
    }
    DslComponent finder = DslComponent.class.cast(component.get());
    Task<Entity> task = Entities.submit(anchor, finder);
    return task.getUnchecked();
}
 
Example 5
Source File: MachineInitTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void openIptablesImpl(Iterable<Integer> inboundPorts, SshMachineLocation machine) {
    if (inboundPorts == null || Iterables.isEmpty(inboundPorts)) {
        log.info("No ports to open in iptables (no inbound ports) for {} at {}", machine, this);
    } else {
        log.info("Opening ports in iptables for {} at {}", entity(), machine);

        List<String> iptablesRules = Lists.newArrayList();
        String iptablesInstallCommands = null;

        Task<Integer> checkFirewall = checkLocationFirewall(machine);

        if (checkFirewall.getUnchecked() == 0) {
            for (Integer port : inboundPorts) {
                iptablesRules.add(IptablesCommands.addFirewalldRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT));
             }
        } else {
            iptablesRules = createIptablesRulesForNetworkInterface(inboundPorts);
            iptablesInstallCommands = IptablesCommands.saveIptablesRules();
        }

        insertIptablesRules(iptablesRules, iptablesInstallCommands, machine);
        listIptablesRules(machine);
    }
}
 
Example 6
Source File: AnsibleEntityIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testAnsible() {
    Task<BasicMachineDetails> detailsTask = app.getExecutionContext().submit(
            BasicMachineDetails.taskForSshMachineLocation(sshHost));
    MachineDetails machine = detailsTask.getUnchecked();


    OsDetails details = machine.getOsDetails();
    
    String osName = details.getName();
    String playbookServiceName = getPlaybookServiceName(osName);
    ansible = app.createAndManageChild(EntitySpec.create(AnsibleEntity.class)
            .configure("playbook.yaml", playbookYaml)
            .configure("playbook", playbookServiceName)
            .configure("service.name", playbookServiceName));

    app.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(ansible, Startable.SERVICE_UP, true);

    ansible.stop();
    EntityAsserts.assertAttributeEqualsEventually(ansible, Startable.SERVICE_UP, false);
}
 
Example 7
Source File: WebAppConcurrentDeployTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Live", dataProvider="basicEntities")
public void testConcurrentDeploys(EntitySpec<? extends JavaWebAppSoftwareProcess> webServerSpec) throws Exception {
    JavaWebAppSoftwareProcess server = app.createAndManageChild(webServerSpec);
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE);
    Collection<Task<Void>> deploys = MutableList.of();
    for (int i = 0; i < 5; i++) {
        deploys.add(server.invoke(TomcatServer.DEPLOY, MutableMap.of("url", getTestWar(), "targetName", "/")));
    }
    for(Task<Void> t : deploys) {
        t.getUnchecked();
    }

    final HttpClient client = HttpTool.httpClientBuilder().build();
    final URI warUrl = URI.create(server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL));
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            HttpToolResponse resp = HttpTool.httpGet(client, warUrl, ImmutableMap.<String,String>of());
            assertEquals(resp.getResponseCode(), 200);
        }
    });
}
 
Example 8
Source File: CoLocatedMongoDBRouterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart(Collection<? extends Location> locations) {
    MongoDBRouter router = sensors().get(ROUTER);

    // Do not attempt to read the configuration until after the router has been added to the cluster
    // as it is at this point that the authentication configuration is set
    Task<?> clusterTask = DependentConfiguration.attributeWhenReady(router, AbstractGroup.FIRST);
    Entities.submit(this, clusterTask);
    clusterTask.getUnchecked();

    MongoDBAuthenticationUtils.setAuthenticationConfig(router, this);
    router.sensors().set(MongoDBAuthenticationMixins.ROOT_PASSWORD, router.config().get(MongoDBAuthenticationMixins.ROOT_PASSWORD));
    router.sensors().set(MongoDBAuthenticationMixins.ROOT_USERNAME, router.config().get(MongoDBAuthenticationMixins.ROOT_USERNAME));
    router.sensors().set(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE, router.config().get(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE));
    enrichers().add(Enrichers.builder().propagating(MongoDBRouter.PORT).from(router).build());
    
    super.doStart(locations);
    sensors().set(Startable.SERVICE_UP, true);
}
 
Example 9
Source File: RedisClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private void doStart(Collection<? extends Location> locations) {
    // Start the master and slaves asynchronously (the slave has a LAUNCH_LATCH on master to ensure it is available before the slaves are launched)
    Task<Void> masterStartTask = getMaster().invoke(RedisStore.START, ImmutableMap.<String, Object>of("locations", ImmutableList.copyOf(locations)));
    Task<Void> slaveStartTask = getSlaves().invoke(DynamicCluster.START, ImmutableMap.<String, Object>of("locations", ImmutableList.copyOf(locations)));

    // Wait for both master and slave to start before returning
    masterStartTask.getUnchecked();
    slaveStartTask.getUnchecked();
}
 
Example 10
Source File: AbstractControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void update() {
    try {
        Task<?> task = updateAsync();
        if (task != null) task.getUnchecked();
        ServiceStateLogic.ServiceProblemsLogic.clearProblemsIndicator(this, "update");
    } catch (Exception e) {
        ServiceStateLogic.ServiceProblemsLogic.updateProblemsIndicator(this, "update", "update failed with: "+Exceptions.collapseText(e));
        throw Exceptions.propagate(e);
    }
}
 
Example 11
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    Entity child = Iterables.getOnlyElement(entity().getChildren());
    AtomicBoolean lock = new AtomicBoolean();
    Task<Void> dummyTask = null;

    try {
        // Queue a (DST secondary) task which waits until notified, so that tasks queued later will get blocked
        queue(Effectors.invocation(entity(), STALL, ImmutableMap.of("lock", lock)));
    
        // Start a new task - submitted directly to child's ExecutionContext, as well as added as a
        // DST secondary of the current effector.
        dummyTask = child.invoke(DUMMY, ImmutableMap.<String, Object>of());
        dummyTask.getUnchecked();

        // Execution completed in the child's ExecutionContext, but still queued as a secondary.
        // Destroy the child entity so that no subsequent tasks can be executed in its context.
        Entities.destroy(child);
    } finally {
        // Let STALL complete
        synchronized(lock) {
            lock.set(true);
            lock.notifyAll();
        }
        // At this point DUMMY will be unblocked and the DST will try to execute it as a secondary.
        // Submission will be ignored because DUMMY already executed.
        // If it's not ignored then submission will fail because entity is already unmanaged.
    }
    return null;
}
 
Example 12
Source File: DynamicRegionsFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String addRegion(String location) {
    Preconditions.checkNotNull(location, "location");
    Location l = getManagementContext().getLocationRegistry().getLocationManaged(location);
    addLocations(Arrays.asList(l));
    
    Entity e = addCluster(l);
    ((EntityInternal)e).addLocations(Arrays.asList(l));
    if (e instanceof Startable) {
        Task<?> task = e.invoke(Startable.START, ImmutableMap.of("locations", ImmutableList.of(l)));
        task.getUnchecked();
    }
    return e.getId();
}
 
Example 13
Source File: DynamicSequentialTask.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void drain(Duration optionalTimeout, boolean includePrimary, boolean throwFirstError) {
    try {
        dstJob.join(includePrimary, optionalTimeout);
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    }
    if (throwFirstError) {
        if (isError()) 
            getUnchecked();
        for (Task<?> t: getQueue())
            if (t.isError() && !TaskTags.isInessential(t))
                t.getUnchecked();
    }
}
 
Example 14
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 15
Source File: AbstractNonProvisionedControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void update() {
    try {
        Task<?> task = updateAsync();
        if (task != null) task.getUnchecked();
        ServiceStateLogic.ServiceProblemsLogic.clearProblemsIndicator(this, "update");
    } catch (Exception e) {
        ServiceStateLogic.ServiceProblemsLogic.updateProblemsIndicator(this, "update", "update failed with: "+Exceptions.collapseText(e));
        throw Exceptions.propagate(e);
    }
}
 
Example 16
Source File: EntityExecutionManagerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected static Task<?> runEmptyTaskWithNameAndTags(Entity target, String name, Object ...tags) {
    TaskBuilder<Object> tb = newEmptyTask(name);
    for (Object tag: tags) tb.tag(tag);
    Task<?> task = ((EntityInternal)target).getExecutionContext().submit(tb.build());
    task.getUnchecked();
    return task;
}
 
Example 17
Source File: MySqlSshDriver.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
public void customize() {
    copyDatabaseConfigScript();

    newScript(CUSTOMIZING)
        .updateTaskAndFailOnNonZeroResultCode()
        .body.append(
            "chmod 600 "+getConfigFile(),
            getBaseDir()+"/scripts/mysql_install_db "+
                "--basedir="+getBaseDir()+" --datadir="+getDataDir()+" "+
                "--defaults-file="+getConfigFile())
        .execute();

    // launch, then we will configure it
    launch();

    // Wrap in inessential task to allow the stop step to execute even if any of the nested
    // tasks fail - poor man's try-catch for tasks.
    Task<Void> configTask = DynamicTasks.<Void>queue("execute scripts", new Runnable() {
        @Override
        public void run() {
            Tasks.markInessential();
            CountdownTimer timer = Duration.seconds(20).countdownTimer();
            boolean hasCreationScript = copyDatabaseCreationScript();
            timer.waitForExpiryUnchecked();

            /*
             * TODO: this should not assume that the password is blank.
             * There may be an existing setup specified by datadir which has an existing password. The changePassword function
             * has been altered to try the specified `mysql.password` or blank to allow for a fresh install or a specified datadir.
             * This fix addresses the problem short term, but it should be properly fixed in any re-implementation.
             */
            changePassword("", getPassword());

            if (hasCreationScript)
                executeScriptFromInstalledFileAsync("creation-script.sql").asTask().getUnchecked();
        }
    });

    // not sure necessary to stop then subsequently launch, but seems safest
    // (if skipping, use a flag in launch to indicate we've just launched it)
    stop();

    // Fail if any of the tasks above failed, they are marked inessential so the
    // errors don't propagate automatically.
    if (configTask.isError()) {
        configTask.getUnchecked();
    }
}
 
Example 18
Source File: EffectorBasicTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void assertTaskSucceeds(Task<Void> task) {
    task.getUnchecked();
    Assert.assertFalse(task.isError());
}
 
Example 19
Source File: MachineInitTasks.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected void stopIptablesImpl(final SshMachineLocation machine) {

        log.info("Stopping iptables for {} at {}", entity(), machine);

        List<String> cmds = ImmutableList.<String>of();

        Task<Integer> checkFirewall = checkLocationFirewall(machine);

        if (checkFirewall.getUnchecked() == 0) {
            cmds = ImmutableList.of(IptablesCommands.firewalldServiceStop(), IptablesCommands.firewalldServiceStatus());
        } else {
            cmds = ImmutableList.of(IptablesCommands.iptablesServiceStop(), IptablesCommands.iptablesServiceStatus());
        }


        subTaskHelperAllowingNonZeroExitCode("execute stop iptables", machine, cmds.toArray(new String[cmds.size()]));
    }
 
Example 20
Source File: SshCommandMembershipTrackingPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void execute(Entity target, String command, String type, String memberId, boolean highlight) {
    if (Entities.isNoLongerManaged(target)) return;
    Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (state==Lifecycle.STOPPING || state==Lifecycle.STOPPED) return;
    
    Collection<? extends Location> locations = Locations.getLocationsCheckingAncestors(target.getLocations(), target);
    Maybe<SshMachineLocation> machine = Machines.findUniqueMachineLocation(locations, SshMachineLocation.class);
    if (machine.isAbsentOrNull()) {
        LOG.debug("No machine available to execute command");
        return;
    }

    LOG.info("Executing command on {}: {}", machine.get(), command);
    String executionDir = config().get(EXECUTION_DIR);
    String sshCommand = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, target);

    // Set things from the entities defined shell environment, overriding with our config
    Map<String, Object> env = MutableMap.of();
    env.putAll(MutableMap.copyOf(entity.config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));
    env.putAll(MutableMap.copyOf(config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));

    // Add variables describing this invocation
    env.put(EVENT_TYPE, type);
    env.put(MEMBER_ID, memberId);

    // Try to resolve the configuration in the env Map
    try {
        env = (Map<String, Object>) Tasks.resolveDeepValue(env, Object.class, getExecutionContext());
    } catch (InterruptedException | ExecutionException e) {
        throw Exceptions.propagate(e);
    }

    // Execute the command with the serialized environment strings
    ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(getManagementContext());
    SshEffectorTasks.SshEffectorTaskFactory<String> task = SshEffectorTasks.ssh(sshCommand)
            .machine(machine.get())
            .requiringZeroAndReturningStdout()
            .summary("group-" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, type))
            .environmentVariables(serializer.serialize(env));

    Task<String> taskI = DynamicTasks.submit(task.newTask(), target);
    if (highlight) {
        highlightAction("Run at "+machine.get().getAddress().getHostAddress(), taskI);
    }
    String output = taskI.getUnchecked();
    LOG.trace("Command returned: {}", output);
}