Java Code Examples for org.apache.brooklyn.core.entity.Entities#submit()

The following examples show how to use org.apache.brooklyn.core.entity.Entities#submit() . 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: JavaSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Checks for the version of Java installed on the entity's location over SSH.
 * @return An Optional containing the version portion of `java -version`, or absent if no Java found.
 */
protected Optional<String> getInstalledJavaVersion() {
    log.debug("Checking Java version at {}@{}", getEntity(), getLocation());
    // sed gets stdin like 'java version "1.7.0_45"'
    ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
            getLocation(), "java -version 2>&1 | grep \" version\" | sed 's/.*\"\\(.*\\).*\"/\\1/'"));
    versionCommand.get();
    String stdOut = versionCommand.getStdout().trim();
    if (!Strings.isBlank(stdOut)) {
        log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
        return Optional.of(stdOut);
    } else {
        log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
        return Optional.absent();
    }
}
 
Example 2
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 3
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 4
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicSoftwareProcessStopsProcess() throws Exception {
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
    entity.start(ImmutableList.of(loc));
    SimulatedDriver d = (SimulatedDriver) entity.getDriver();
    Location machine = Iterables.getOnlyElement(entity.getLocations());
    d.events.clear();

    TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
            ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.NEVER)));
    t1.asTask().get(10, TimeUnit.SECONDS);

    assertEquals(d.events, ImmutableList.of("stop"));
    assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
    assertFalse(loc.getAvailable().contains(machine));
}
 
Example 5
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicSoftwareProcessStopEverythingExplicitly() throws Exception {
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
    entity.start(ImmutableList.of(loc));
    SimulatedDriver d = (SimulatedDriver) entity.getDriver();
    Location machine = Iterables.getOnlyElement(entity.getLocations());
    d.events.clear();

    TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
            ConfigBag.newInstance().configure(StopSoftwareParameters.STOP_MACHINE_MODE, StopSoftwareParameters.StopMode.IF_NOT_STOPPED)));
    t1.asTask().get();

    assertEquals(d.events, ImmutableList.of("stop"));
    assertEquals(entity.getLocations().size(), 0);
    assertTrue(loc.getAvailable().contains(machine));
}
 
Example 6
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 7
Source File: JavaSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private int tryJavaInstall(String version, String command) {
    getLocation().acquireMutex("installing", "installing Java at " + getLocation());
    try {
        log.debug("Installing Java {} at {}@{}", new Object[]{version, getEntity(), getLocation()});
        ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(getLocation(), command)
                .summary("install java ("+version+")")
                .configure(ShellTool.PROP_EXEC_ASYNC, true);
        ProcessTaskWrapper<Integer> installCommand = Entities.submit(getEntity(), taskFactory);
        int result = installCommand.get();
        if (result != 0) {
            log.warn("Installation of Java {} failed at {}@{}: {}",
                    new Object[]{version, getEntity(), getLocation(), installCommand.getStderr()});
        }
        return result;
    } finally {
        getLocation().releaseMutex("installing");
    }
}
 
Example 8
Source File: PostgreSqlSaltLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups="Live")
public void testPostgresStartsAndStops() throws Exception {
    psql = app.createAndManageChild(EntitySpec.create(PostgreSqlNode.class, PostgreSqlNodeSaltImpl.class)
            .configure(SaltConfig.MASTERLESS_MODE, true));

    app.start(ImmutableList.of(targetLocation));

    Entities.submit(psql, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").requiringExitCodeZero());
    SshMachineLocation targetMachine = EffectorTasks.getSshMachine(psql);

    psql.stop();

    try {
        // if host is still contactable ensure postgres is not running
        ProcessTaskWrapper<Integer> t = Entities.submit(app, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").machine(targetMachine).allowingNonZeroExitCode());
        t.getTask().blockUntilEnded(Duration.TEN_SECONDS);
        if (!t.isDone()) {
            Assert.fail("Task not finished yet: "+t.getTask());
        }
        Assert.assertNotEquals(t.get(), (Integer)0, "Task ended with code "+t.get()+"; output: "+t.getStdout() );
    } catch (Exception e) {
        // host has been killed, that is fine
        log.info("Machine "+targetMachine+" destroyed on stop (expected - "+e+")");
    }
}
 
Example 9
Source File: PostgreSqlChefTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups="Live")
public void testPostgresStartsAndStops() throws Exception {
    ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
    psql = app.createAndManageChild(PostgreSqlSpecs.specChef());

    app.start(ImmutableList.of(targetLocation));
    
    Entities.submit(psql, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").requiringExitCodeZero());
    SshMachineLocation targetMachine = EffectorTasks.getSshMachine(psql);
    
    psql.stop();
    
    try {
        // if host is still contactable ensure postgres is not running
        ProcessTaskWrapper<Integer> t = Entities.submit(app, SshEffectorTasks.ssh("ps aux | grep [p]ostgres").machine(targetMachine).allowingNonZeroExitCode());
        t.getTask().blockUntilEnded(Duration.TEN_SECONDS);
        if (!t.isDone())
            Assert.fail("Task not finished yet: "+t.getTask());
        Assert.assertNotEquals(t.get(), 0, "Task ended with code "+t.get()+"; output: "+t.getStdout() );
    } catch (Exception e) {
        // host has been killed, that is fine
        log.info("Machine "+targetMachine+" destroyed on stop (expected - "+e+")");
    }
}
 
Example 10
Source File: ChefServerTasksIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testKnifeWithConfig() {
    // requires that knife is installed on the path of login shells
    // (creates the config in a temp space)
    ChefLiveTestSupport.installBrooklynChefHostedConfig(app);
    ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
    log.info("isKnifeInstalled *with* config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
    Assert.assertTrue(t.get());
}
 
Example 11
Source File: StaticSensor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    class ResolveValue implements Callable<Maybe<T>> {
        @Override
        public Maybe<T> call() throws Exception {
            // TODO resolve deep?
            return Tasks.resolving(value).as(sensor.getTypeToken()).timeout(timeout).getMaybe();
        }
    }
    final Task<Maybe<T>> resolveValue = Tasks.<Maybe<T>>builder().displayName("resolving " + value).body(new ResolveValue()).build();

    class SetValue implements Callable<T> {
        @Override
        public T call() throws Exception {
            Maybe<T> v = resolveValue.get();
            if (!v.isPresent()) {
                log.debug(this+" not setting sensor "+sensor+" on "+entity+"; cannot resolve "+value+" after timeout " + timeout);
                return null;
            }
            log.debug(this+" setting sensor "+sensor+" to "+v.get()+" on "+entity);
            return entity.sensors().set(sensor, v.get());
        }
    }
    Task<T> setValue = Tasks.<T>builder().displayName("Setting " + sensor + " on " + entity).body(new SetValue()).build();

    Entities.submit(entity, Tasks.sequential("Resolving and setting " + sensor + " on " + entity, resolveValue, setValue));
}
 
Example 12
Source File: SoftwareProcessDriverLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected String startProcessesAtMachine(final Supplier<MachineLocation> machineS) {
    ChildStartableMode mode = getChildrenStartableModeEffective();
    TaskAdaptable<?> children = null;
    if (!mode.isDisabled) {
        children = StartableMethods.startingChildren(entity(), machineS.get());
        // submit rather than queue so it runs in parallel
        // (could also wrap as parallel task with driver.start() -
        // but only benefit is that child starts show as child task,
        // rather than bg task, so not worth the code complexity)
        if (!mode.isLate) Entities.submit(entity(), children);
    }
    
    entity().getDriver().start();
    String result = "Started with driver "+entity().getDriver();
    
    if (!mode.isDisabled) {
        if (mode.isLate) {
            DynamicTasks.waitForLast();
            if (mode.isBackground) {
                Entities.submit(entity(), children);
            } else {
                // when running foreground late, there is no harm here in queueing
                DynamicTasks.queue(children);
            }
        }
        if (!mode.isBackground) children.asTask().getUnchecked();
        result += "; children started "+mode;
    }
    return result;
}
 
Example 13
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicSoftwareProcessRestarts() throws Exception {
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
    entity.start(ImmutableList.of(loc));
    SimulatedDriver d = (SimulatedDriver) entity.getDriver();
    Assert.assertTrue(d.isRunning());
    
    // this will cause restart to fail if it attempts to replace the machine
    loc.removeMachine(Locations.findUniqueSshMachineLocation(entity.getLocations()).get());
    
    // with defaults, it won't reboot machine
    d.events.clear();
    entity.restart();
    assertEquals(d.events, ImmutableList.of("stop", "launch"));

    // but here, it will try to reboot, and fail because there is no machine available
    TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
            ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
    t1.asTask().blockUntilEnded(Duration.TEN_SECONDS);
    if (!t1.asTask().isError()) {
        Assert.fail("Should have thrown error during "+t1+" because no more machines available at "+loc);
    }

    // now it has a machine, so reboot should succeed
    SshMachineLocation machine2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
        .configure("address", "localhost"));
    loc.addMachine(machine2);
    TaskAdaptable<Void> t2 = Entities.submit(entity, Effectors.invocation(entity, Startable.RESTART, 
        ConfigBag.newInstance().configure(RestartSoftwareParameters.RESTART_MACHINE_TYPED, RestartMachineMode.TRUE)));
    t2.asTask().get();
    
    assertFalse(d.isRunning());
}
 
Example 14
Source File: ChefServerTasksIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testKnifeWithoutConfig() {
    // without config it shouldn't pass
    // (assumes that knife global config is *not* installed on your machine)
    ProcessTaskWrapper<Boolean> t = Entities.submit(app, ChefServerTasks.isKnifeInstalled());
    log.info("isKnifeInstalled without config returned: "+t.get()+" ("+t.getExitCode()+")\n"+t.getStdout()+"\nERR:\n"+t.getStderr());
    Assert.assertFalse(t.get());
}
 
Example 15
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testBasicSoftwareProcessStopModes(StopMode stopProcessMode, StopMode stopMachineMode, boolean isEntityStopped) throws Exception {
    FixedListMachineProvisioningLocation<SshMachineLocation> l = getLocation();
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class));
    entity.start(ImmutableList.of(l));
    SimulatedDriver d = (SimulatedDriver) entity.getDriver();
    Location machine = Iterables.getOnlyElement(entity.getLocations());
    d.events.clear();

    if (isEntityStopped) {
        ((EntityInternal)entity).sensors().set(ServiceStateLogic.SERVICE_STATE_ACTUAL, Lifecycle.STOPPED);
    }

    TaskAdaptable<Void> t1 = Entities.submit(entity, Effectors.invocation(entity, Startable.STOP,
            ConfigBag.newInstance()
                .configure(StopSoftwareParameters.STOP_PROCESS_MODE, stopProcessMode)
                .configure(StopSoftwareParameters.STOP_MACHINE_MODE, stopMachineMode)));
    t1.asTask().get(10, TimeUnit.SECONDS);

    if (MachineLifecycleEffectorTasksTest.canStop(app, stopProcessMode, isEntityStopped)) {
        assertEquals(d.events, ImmutableList.of("stop"));
    } else {
        assertTrue(d.events.isEmpty());
    }
    if (MachineLifecycleEffectorTasksTest.canStop(app, stopMachineMode, machine == null)) {
        assertTrue(entity.getLocations().isEmpty());
        assertTrue(l.getAvailable().contains(machine));
    } else {
        assertEquals(ImmutableList.copyOf(entity.getLocations()), ImmutableList.of(machine));
        assertFalse(l.getAvailable().contains(machine));
    }
}
 
Example 16
Source File: AbstractControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public void updateNeeded() {
    synchronized (serverPoolAddresses) {
        if (updateNeeded) return;
        updateNeeded = true;
        LOG.debug("queueing an update-needed task for "+this+"; update will occur shortly");
        Entities.submit(this, Tasks.builder().displayName("update-needed").body(new Runnable() {
            @Override
            public void run() {
                if (updateNeeded)
                    AbstractControllerImpl.this.update();
            } 
        }).build());
    }
}
 
Example 17
Source File: AbstractNonProvisionedControllerImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public void updateNeeded() {
    synchronized (mutex) {
        if (updateNeeded) return;
        updateNeeded = true;
        LOG.debug("queueing an update-needed task for "+this+"; update will occur shortly");
        Entities.submit(this, Tasks.builder().displayName("update-needed").body(new Runnable() {
            @Override
            public void run() {
                if (updateNeeded)
                    AbstractNonProvisionedControllerImpl.this.update();
            } 
        }).build());
    }
}
 
Example 18
Source File: SaltEntitySshDriver.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
private void invokeEffector(Effector<Void> effector, ConfigBag config) {
    final TaskAdaptable<Void> stop = Entities.submit(getEntity(), Effectors.invocation(getEntity(), effector, config));
    stop.asTask().blockUntilEnded();
}
 
Example 19
Source File: SshEffectorTasksTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public <T extends TaskAdaptable<?>> T submit(final TaskFactory<T> taskFactory) {
    return Entities.submit(app, taskFactory);
}
 
Example 20
Source File: AutoScalerPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void resizeNow(String reason) {
    final int currentPoolSize = getCurrentSizeOperator().apply(poolEntity);
    CalculatedDesiredPoolSize calculatedDesiredPoolSize = calculateDesiredPoolSize(currentPoolSize);
    long desiredPoolSize = calculatedDesiredPoolSize.size;
    boolean stable = calculatedDesiredPoolSize.stable;
    
    final int targetPoolSize = applyMinMaxConstraints(desiredPoolSize);
    
    if (!stable) {
        // the desired size fluctuations are not stable; ensure we check again later (due to time-window)
        // even if no additional events have been received
        // (note we continue now with as "good" a resize as we can given the instability)
        if (LOG.isTraceEnabled()) LOG.trace("{} re-scheduling resize check for {}, as desired size not stable (current {}, desired {}); continuing with resize...", 
                new Object[] {this, poolEntity, currentPoolSize, targetPoolSize});
        scheduleResize(reason);
    }
    if (currentPoolSize == targetPoolSize) {
        if (LOG.isTraceEnabled()) LOG.trace("{} not resizing pool {} from {} to {}", 
                new Object[] {this, poolEntity, currentPoolSize, targetPoolSize});
        return;
    }
    
    if (LOG.isDebugEnabled()) LOG.debug("{} requesting resize to {}; current {}, min {}, max {}", 
            new Object[] {this, targetPoolSize, currentPoolSize, getMinPoolSize(), getMaxPoolSize()});
    
    Task<Void> t = Entities.submit(entity, Tasks.<Void>builder().displayName("Auto-scaler")
        .description("Auto-scaler recommending resize from "+currentPoolSize+" to "+targetPoolSize)
        .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
        .body(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                // TODO Should we use int throughout, rather than casting here?
                try {
                    getResizeOperator().resize(poolEntity, targetPoolSize);
                } catch (Resizable.InsufficientCapacityException e) {
                    // cannot resize beyond this; set the high-water mark
                    int insufficientCapacityHighWaterMark = getCurrentSizeOperator().apply(poolEntity);
                    LOG.warn("{} failed to resize {} due to insufficient capacity; setting high-water mark to {}, "
                            + "and will not attempt to resize above that level again", 
                            new Object[] {AutoScalerPolicy.this, poolEntity, insufficientCapacityHighWaterMark});
                    config().set(INSUFFICIENT_CAPACITY_HIGH_WATER_MARK, insufficientCapacityHighWaterMark);
                }
                return null;
            }
        }).build());
    highlightAction("Resize from "+currentPoolSize+" to "+targetPoolSize+
        (reason!=null ? " because "+reason : ""), t);
    t.blockUntilEnded();
}