org.apache.brooklyn.core.effector.Effectors Java Examples

The following examples show how to use org.apache.brooklyn.core.effector.Effectors. 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: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private Effector<Void> newStopEffector() {
    return Effectors.effector(Startable.STOP)
            .parameter(SoftwareProcess.StopSoftwareParameters.STOP_PROCESS_MODE)
            .parameter(SoftwareProcess.StopSoftwareParameters.STOP_MACHINE_MODE)
            .impl(new EffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    LOG.info("Stopping SeaCloudsInitializerPolicy " + "for " + entity.getId());
                    removeSlaAgreement();
                    removeMonitoringRules();
                    removeInfluxDbObservers();
                    removeGrafanaDashboard();

                    // Rewire the original behaviour
                    ((StartableApplication) entity).stop();

                    return null;
                }
            })
            .build();
}
 
Example #2
Source File: InitSlaveTaskBody.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
private Future<ReplicationSnapshot> createSlaveReplicationSnapshot(final MySqlNode slave, final String dumpName) {
    MySqlClusterUtils.executeSqlOnNodeAsync(slave, "STOP SLAVE SQL_THREAD;");
    try {
        log.info("MySql cluster " + cluster + ": generating new replication snapshot on slave node " + slave + " with name " + dumpName);
        String dumpOptions = SNAPSHOT_DUMP_OPTIONS + getDumpDatabases(slave);
        ImmutableMap<String, String> params = ImmutableMap.of(
                ExportDumpEffector.PATH.getName(), dumpName,
                ExportDumpEffector.ADDITIONAL_OPTIONS.getName(), dumpOptions);
        DynamicTasks.queue(Effectors.invocation(slave, MySqlNode.EXPORT_DUMP, params));
        return DynamicTasks.queue("get master log info from slave", new Callable<ReplicationSnapshot>() {
            @Override
            public ReplicationSnapshot call() throws Exception {
                String slaveStatusRow = slave.executeScript("SHOW SLAVE STATUS \\G");
                Map<String, String> slaveStatus = MySqlRowParser.parseSingle(slaveStatusRow);
                String masterLogFile = slaveStatus.get("Relay_Master_Log_File");
                int masterLogPosition = Integer.parseInt(slaveStatus.get("Exec_Master_Log_Pos"));
                ReplicationSnapshot replicationSnapshot = new ReplicationSnapshot(slave.getId(), dumpName, masterLogFile, masterLogPosition);
                cluster.sensors().set(MySqlCluster.REPLICATION_LAST_SLAVE_SNAPSHOT, replicationSnapshot);
                return replicationSnapshot;
            }
        });
    } finally {
        MySqlClusterUtils.executeSqlOnNodeAsync(slave, "START SLAVE SQL_THREAD;");
    }
}
 
Example #3
Source File: DynamicWebAppClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@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).displayName(redeployPrefix+" across cluster (size "+Iterables.size(targetEntities)+")");
    for (Entity targetEntity: targetEntities) {
        TaskBuilder<Void> redeployAllToTarget = Tasks.<Void>builder().displayName(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();
}
 
Example #4
Source File: InitSlaveTaskBody.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
private Future<ReplicationSnapshot> createMasterReplicationSnapshot(final MySqlNode master, final String dumpName) {
    log.info("MySql cluster " + cluster + ": generating new replication snapshot on master node " + master + " with name " + dumpName);
    String dumpOptions = SNAPSHOT_DUMP_OPTIONS + " --master-data=2" + getDumpDatabases(master);
    ImmutableMap<String, String> params = ImmutableMap.of(
            ExportDumpEffector.PATH.getName(), dumpName,
            ExportDumpEffector.ADDITIONAL_OPTIONS.getName(), dumpOptions);
    DynamicTasks.queue(Effectors.invocation(master, MySqlNode.EXPORT_DUMP, params));
    return DynamicTasks.queue("get master log info from dump", new Callable<ReplicationSnapshot>() {
        @Override
        public ReplicationSnapshot call() throws Exception {
            Pattern masterInfoPattern = Pattern.compile("CHANGE MASTER TO.*MASTER_LOG_FILE\\s*=\\s*'([^']+)'.*MASTER_LOG_POS\\s*=\\s*(\\d+)");
            String masterInfo = DynamicTasks.queue(execSshTask(master, "grep -m1 'CHANGE MASTER TO' " + dumpName, "Extract master replication status from dump")
                    .requiringZeroAndReturningStdout()).asTask().getUnchecked();
            Matcher masterInfoMatcher = masterInfoPattern.matcher(masterInfo);
            if (!masterInfoMatcher.find() || masterInfoMatcher.groupCount() != 2) {
                throw new IllegalStateException("Master dump doesn't contain replication info: " + masterInfo);
            }
            String masterLogFile = masterInfoMatcher.group(1);
            int masterLogPosition = Integer.parseInt(masterInfoMatcher.group(2));
            ReplicationSnapshot replicationSnapshot = new ReplicationSnapshot(master.getId(), dumpName, masterLogFile, masterLogPosition);
            cluster.sensors().set(MySqlCluster.REPLICATION_LAST_SLAVE_SNAPSHOT, replicationSnapshot);
            return replicationSnapshot;
        }
    });
}
 
Example #5
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityWithConfigurableInitializerNonEmpty() throws Exception {
    String yaml =
            "services:\n"+
            "- type: "+TestEntity.class.getName()+"\n"+
            "  brooklyn.initializers: [ { "
              + "type: "+TestSensorAndEffectorInitializer.TestConfigurableInitializer.class.getName()+","
              + "brooklyn.config: { "+TestSensorAndEffectorInitializer.TestConfigurableInitializer.HELLO_WORD+": Hey }"
              + " } ]";
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    
    Task<String> saying = entity.invoke(Effectors.effector(String.class, TestSensorAndEffectorInitializer.EFFECTOR_SAY_HELLO).buildAbstract(), 
        MutableMap.of("name", "Bob"));
    Assert.assertEquals(saying.get(Duration.TEN_SECONDS), "Hey Bob");
}
 
Example #6
Source File: DynamicWebAppClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@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).displayName("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) );
    sensors().set(DEPLOYED_WARS, deployedWars);
}
 
Example #7
Source File: DynamicWebAppClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@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).displayName("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);
    sensors().set(DEPLOYED_WARS, deployedWars);
}
 
Example #8
Source File: TestSensorAndEffectorInitializer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(@SuppressWarnings("deprecation") org.apache.brooklyn.api.entity.EntityLocal entity) {
    Effector<String> eff = Effectors.effector(String.class, EFFECTOR_SAY_HELLO).parameter(String.class, "name").impl(
        new EffectorBody<String>() {
            @Override
            public String call(ConfigBag parameters) {
                Object name = parameters.getStringKey("name");
                entity().sensors().set(Sensors.newStringSensor(SENSOR_LAST_HELLO), Strings.toString(name));
                return helloWord()+" "+name;
            }
        }).build();
    ((EntityInternal)entity).getMutableEntityType().addEffector(eff);
    
    ((EntityInternal)entity).getMutableEntityType().addSensor(Sensors.newStringSensor(SENSOR_HELLO_DEFINED));
    
    AttributeSensor<String> emitted = Sensors.newStringSensor(SENSOR_HELLO_DEFINED_EMITTED);
    ((EntityInternal)entity).getMutableEntityType().addSensor(emitted);
    entity.sensors().set(emitted, "1");
}
 
Example #9
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 #10
Source File: SoftwareEffectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testBadExitCodeCaughtAndStdErrAvailable() {
    final ProcessTaskWrapper<?>[] sshTasks = new ProcessTaskWrapper[1];
    
    Task<Void> call = Entities.invokeEffector(app, app, Effectors.effector(Void.class, "badExitCode")
            .impl(new SshEffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    sshTasks[0] = queue( ssh(COMMAND_THAT_DOES_NOT_EXIST).requiringExitCodeZero() );
                    return null;
                }
            }).build() );
    call.blockUntilEnded();
    Assert.assertTrue(call.isError());
    log.info("stderr gives: "+new String(sshTasks[0].getStderr()));
    Assert.assertTrue(new String(sshTasks[0].getStderr()).indexOf(COMMAND_THAT_DOES_NOT_EXIST) >= 0);
}
 
Example #11
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 #12
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 #13
Source File: ElectPrimaryEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Object call() throws Exception {
    String promoteEffectorName = params.get(PROMOTE_EFFECTOR_NAME);
    Effector<?> eff = entity().getEffector(promoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(entity(), eff, params) ).asTask().getUnchecked();
    }
    EntityInternal newPrimary = (EntityInternal)params.getStringKey("newPrimary");
    if (newPrimary==null) {
        return "Nothing to promote; no new primary";
    }
    eff = newPrimary.getEffector(promoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(newPrimary, eff, params) ).asTask().getUnchecked();
    }
    if (params.containsKey(PROMOTE_EFFECTOR_NAME)) {
        throw new IllegalStateException("Key "+PROMOTE_EFFECTOR_NAME.getName()+" set as "+promoteEffectorName+
            " but that effector isn't available on this entity or new primary "+newPrimary);
    }
    return "No promotion effector '"+promoteEffectorName+"'; nothing to do";
}
 
Example #14
Source File: ElectPrimaryEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Object call() throws Exception {
    String demoteEffectorName = params.get(DEMOTE_EFFECTOR_NAME);
    Effector<?> eff = entity().getEffector(demoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(entity(), eff, params) ).asTask().getUnchecked();
    }
    EntityInternal oldPrimary = (EntityInternal)params.getStringKey("oldPrimary");
    if (oldPrimary==null) return "Nothing to demote; no old primary";
    if (Entities.isNoLongerManaged(oldPrimary)) return "Entity to demote is gone";
    // could bail out if stopping or stopped; demotion may take a while
    // but demotion might simply be setting metadata.
    // ideally the "isRunning" check would take place within old.demote
    // (but that's currently not easy in yaml)
    eff = oldPrimary.getEffector(demoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(oldPrimary, eff, params) ).asTask().getUnchecked();
    }
    if (params.containsKey(DEMOTE_EFFECTOR_NAME)) {
        throw new IllegalStateException("Key "+DEMOTE_EFFECTOR_NAME.getName()+" set as "+demoteEffectorName+
            " but that effector isn't available on this entity or old primary "+oldPrimary);
    }
    return "No demotion effector '"+demoteEffectorName+"'; nothing to do";
}
 
Example #15
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void restart() {
    String mode = getConfig(RESTART_MODE);
    if (mode==null) {
        throw new UnsupportedOperationException("Restart not supported for this cluster: "+RESTART_MODE.getName()+" is not configured.");
    }
    if ("off".equalsIgnoreCase(mode)) {
        throw new UnsupportedOperationException("Restart not supported for this cluster.");
    }
    
    if ("sequential".equalsIgnoreCase(mode)) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
        DynamicTasks.queue(Effectors.invocationSequential(Startable.RESTART, null, 
            Iterables.filter(getChildren(), Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged()))));
    } else if ("parallel".equalsIgnoreCase(mode)) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
        for (Entity member : Iterables.filter(getChildren(), Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged()))) {
            DynamicTasks.queue(newThrottledEffectorTask(member, Startable.RESTART, Collections.emptyMap()));
        }
    } else {
        throw new IllegalArgumentException("Unknown "+RESTART_MODE.getName()+" '"+mode+"'");
    }
    
    DynamicTasks.waitForLast();
    ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
}
 
Example #16
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes an {@link Effector} on multiple entities, with the named arguments from the parameters {@link Map}
 * using the context of the provided {@link Entity}.
 * <p>
 * Intended for use only from the callingEntity.
 * <p>
 * Returns a {@link ParallelTask} containing the results from each tasks invocation. Calling
 * {@link java.util.concurrent.Future#get() get()} on this will block until all tasks are complete,
 * and will throw an exception if any task resulted in an error.
 *
 * @return {@link ParallelTask} containing results from each invocation
 */
public static <T> Task<List<T>> invokeEffectorList(Entity callingEntity, Iterable<? extends Entity> entitiesToCall,
        final Effector<T> effector, final Map<String,?> parameters) {
    // formulation is complicated, but it is building up a list of tasks, without blocking on them initially,
    // but ensuring that when the parallel task is gotten it does block on all of them

    if (entitiesToCall == null){
        entitiesToCall = ImmutableList.of();
    }

    List<TaskAdaptable<T>> tasks = Lists.newArrayList();

    for (final Entity entity : entitiesToCall) {
        tasks.add( Effectors.invocation(entity, effector, parameters) );
    }
    ParallelTask<T> invoke = new ParallelTask<T>(
            MutableMap.of(
                    "displayName", effector.getName()+" (parallel)",
                    "description", "Invoking effector \""+effector.getName()+"\" on "+tasks.size()+(tasks.size() == 1 ? " entity" : " entities"),
                    "tag", BrooklynTaskTags.tagForCallerEntity(callingEntity)),
            tasks);
    TaskTags.markInessential(invoke);
    return DynamicTasks.queueIfPossible(invoke).orSubmitAsync(callingEntity).asTask();
}
 
Example #17
Source File: Entities.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static <T> Task<T> invokeEffector(Entity callingEntity, Entity entityToCall,
        final Effector<T> effector, final Map<String,?> parameters) {
    Task<T> t = Effectors.invocation(entityToCall, effector, parameters).asTask();
    TaskTags.markInessential(t);

    // we pass to callingEntity for consistency above, but in exec-context it should be re-dispatched to targetEntity
    // reassign t as the return value may be a wrapper, if it is switching execution contexts; see submitInternal's javadoc
    t = ((EntityInternal)callingEntity).getExecutionContext().submit(
            MutableMap.of("tag", BrooklynTaskTags.tagForCallerEntity(callingEntity)), t);

    if (DynamicTasks.getTaskQueuingContext()!=null) {
        // include it as a child (in the gui), marked inessential, because the caller is invoking programmatically
        DynamicTasks.queue(t);
    }

    return t;
}
 
Example #18
Source File: StartableMethods.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static void stopSequentially(Iterable<? extends Startable> entities) {
    List<Exception> exceptions = Lists.newArrayList();
    List<Startable> failedEntities = Lists.newArrayList();
    
    for (final Startable entity : entities) {
        if (!Entities.isManaged((Entity)entity)) {
            log.debug("Not stopping {} because it is not managed; continuing", entity);
            continue;
        }
        try {
            TaskAdaptable<Void> task = TaskTags.markInessential(Effectors.invocation((Entity)entity, Startable.STOP, Collections.emptyMap()));
            DynamicTasks.submit(task, (Entity)entity).getUnchecked();
        } catch (Exception e) {
            log.warn("Error stopping "+entity+"; continuing with shutdown", e);
            exceptions.add(e);
            failedEntities.add(entity);
        }
    }
    
    if (exceptions.size() > 0) {
        throw new CompoundRuntimeException("Error stopping "+(failedEntities.size() > 1 ? "entities" : "entity")+": "+failedEntities, exceptions);
    }
}
 
Example #19
Source File: InvokeEffectorOnCollectionSensorChangeTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    onAddedParameters = new LinkedBlockingQueue<>();
    onRemovedParameters = new LinkedBlockingQueue<>();
    onAddedEffector = Effectors.effector(Void.class, "on-added-effector")
            .impl(new RecordingEffector(onAddedParameters))
            .build();
    onRemovedEffector = Effectors.effector(Void.class, "on-removed-effector")
            .impl(new RecordingEffector(onRemovedParameters))
            .build();
    testEntity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
            .addInitializer(new AddEffector(onAddedEffector))
            .addInitializer(new AddEffector(onRemovedEffector)));
}
 
Example #20
Source File: InvokeEffectorOnCollectionSensorChangeRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEffectorMaintainsPreviousCollectionThroughRebind() throws Exception {
    final Set<Integer> input1 = ImmutableSet.of(1, 2);
    final Set<Integer> input2 = ImmutableSet.of(2, 3);
    final Set<Integer> input3 = ImmutableSet.of(3, 4);

    Entity testEntity = app().createAndManageChild(EntitySpec.create(TestEntity.class)
            .policy(PolicySpec.create(InvokeEffectorOnCollectionSensorChange.class)
                    .configure(InvokeEffectorOnCollectionSensorChange.TRIGGER_SENSOR, SENSOR)
                    .configure(InvokeEffectorOnCollectionSensorChange.ON_REMOVED_EFFECTOR_NAME, "on-removed-effector"))
            .addInitializer(new AddEffector(Effectors.effector(Void.class, "on-removed-effector")
                    .impl(new PublishingEffector())
                    .build())));
    testEntity.sensors().set(SENSOR, input1);
    testEntity.sensors().set(SENSOR, input2);
    EntityAsserts.assertAttributeEqualsEventually(testEntity, REMOVED_EFFECTOR_VALUES, ImmutableSet.<Object>of(1));

    newApp = rebind();

    testEntity = Iterables.getOnlyElement(newApp.getChildren());
    testEntity.sensors().set(SENSOR, input3);
    EntityAsserts.assertAttributeEqualsEventually(testEntity, REMOVED_EFFECTOR_VALUES, ImmutableSet.<Object>of(1, 2));
}
 
Example #21
Source File: HttpCommandEffectorHttpBinTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpEffectorWithPayload() throws Exception {
    new HttpCommandEffector(ConfigBag.newInstance()
            .configure(HttpCommandEffector.EFFECTOR_NAME, "HttpbinPost")
            .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/post")
            .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "POST")
            .configure(HttpCommandEffector.EFFECTOR_HTTP_PAYLOAD, ImmutableMap.<String, Object>of(
                    "description", "Created via API", 
                    "public", "false",
                    "files", ImmutableMap.of("demo.txt", ImmutableMap.of("content","Demo"))))
            .configure(HttpCommandEffector.EFFECTOR_HTTP_HEADERS, ImmutableMap.of("Content-Type", "application/json"))
            .configure(HttpCommandEffector.JSON_PATHS_AND_SENSORS, ImmutableMap.of("$.url", "result"))

    ).apply(entity);

    String url = entity.invoke(Effectors.effector(String.class, "HttpbinPost").buildAbstract(), MutableMap.<String,String>of()).get();
    Assert.assertNotNull(url, "url");
}
 
Example #22
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private Effector<Void> newStartEffector() {
    return Effectors.effector(Startable.START)
            .impl(new EffectorBody<Void>() {
                @Override
                public Void call(ConfigBag parameters) {
                    LOG.info("Starting SeaCloudsInitializerPolicy " + "for " + entity.getId());
                    installSLA();
                    installMonitoringRules();
                    notifyRulesReady();
                    installInfluxDbObservers();
                    installGrafanaDashboards();

                    // Rewire the original behaviour
                    Collection<? extends Location> locations = null;
                    Object locationRaw = parameters.getStringKey(EffectorStartableImpl.StartParameters.LOCATIONS.getName());
                    locations = Locations.coerceToCollectionOfLocationsManaged(getManagementContext(), locationRaw);
                    ((StartableApplication) entity).start(locations);

                    return null;
                }
            })
            .build();
}
 
Example #23
Source File: LocalManagementContext.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> Task<T> runAtEntity(final Entity entity, final Effector<T> eff, @SuppressWarnings("rawtypes") final Map parameters) {
    manageIfNecessary(entity, eff);
    // prefer to submit this from the current execution context so it sets up correct cross-context chaining
    ExecutionContext ec = BasicExecutionContext.getCurrentExecutionContext();
    if (ec == null) {
        log.debug("Top-level effector invocation: {} on {}", eff, entity);
        ec = getExecutionContext(entity);
    }
    return runAtEntity(entity, Effectors.invocation(entity, eff, parameters));
}
 
Example #24
Source File: EffectorTaskTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
// also assert it works when an abstract effector name is passed in to the entity
public void testSimpleEffectorNameMatching() throws Exception {
    Entity doubler = app.createAndManageChild(EntitySpec.create(Entity.class, DoublingEntity.class));
    
    Assert.assertEquals(doubler.invoke(Effectors.effector(Integer.class, "double").buildAbstract(), MutableMap.of("numberToDouble", 3)).get(), (Integer)6);
}
 
Example #25
Source File: DynamicFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * If including initial children, first look at existing Startable children - start them with 
 * the locations passed in here (if they have no locations yet). This "consumes" a location
 * so we won't create an additional member in that location.
 * 
 * If not {@code includeInitialChildren}, then start those children in the first location but
 * don't "consume" a location - so we'll create additional members.
 * 
 * @param includeInitialChildren
 * @param allLocations
 * @param tasks side-effects this map, to add the tasks created for starting the child entities
 * 
 * @return unused locations
 */
protected List<Location> startChildren(boolean includeInitialChildren, Collection<? extends Location> allLocations, Map<Entity, Task<?>> tasks) {
    List<Location> locations = MutableList.copyOf(allLocations);
    int locIndex = 0;
    
    for (Entity child: getChildren()) {
        if (child instanceof Startable) {
            if (includeInitialChildren) {
                addMember(child);
            }
            
            Location it = null;
            if (child.getLocations().isEmpty()) {
                // give him any of these locations if he has none, allowing round robin here
                if (!locations.isEmpty()) {
                    if (includeInitialChildren) {
                        it = locations.get(locIndex++ % locations.size());
                    } else {
                        it = locations.get(0);
                    }
                    ((EntityInternal)child).addLocations(Arrays.asList(it));
                }
            }
            
            tasks.put(child, Entities.submit(this,
                Effectors.invocation(child, START, ImmutableMap.of("locations", 
                    it==null ? ImmutableList.of() : ImmutableList.of(it))).asTask()));
        }
    }
        
    // remove all the locations we applied to existing nodes
    while (locIndex-->0 && !locations.isEmpty()) {
        locations.remove(0);
    }
    
    return locations;
}
 
Example #26
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Creates tasks that obtain permits from {@link #childTaskSemaphore} before invoking <code>effector</code>
 * on <code>target</code>. Permits are released in a {@link ListenableFuture#addListener listener}. No
 * permits are obtained if {@link #childTaskSemaphore} is <code>null</code>.
 * @param target Entity to invoke effector on
 * @param effector Effector to invoke on target
 * @param arguments Effector arguments
 * @param isPrivileged If true the method obtains a permit from {@link #childTaskSemaphore}
 *                     immediately and returns the effector invocation task, otherwise it
 *                     returns a task that sequentially obtains a permit then runs the effector.
 * @return An unsubmitted task.
 */
protected <T> Task<?> newThrottledEffectorTask(Entity target, Effector<T> effector, Map<?, ?> arguments, boolean isPrivileged) {
    final Task<?> toSubmit;
    final Task<T> effectorTask = Effectors.invocation(target, effector, arguments).asTask();
    if (getChildTaskSemaphore() != null) {
        // permitObtained communicates to the release task whether the permit should really be released
        // or not. ObtainPermit sets it to true when a permit is acquired.
        final AtomicBoolean permitObtained = new AtomicBoolean();
        final String description = "Waiting for permit to run " + effector.getName() + " on " + target;
        final Runnable obtain = new ObtainPermit(getChildTaskSemaphore(), description, permitObtained);
        // Acquire the permit now for the privileged task and just queue the effector invocation.
        // If it's unprivileged then queue a task to obtain a permit first.
        if (isPrivileged) {
            obtain.run();
            toSubmit = effectorTask;
        } else {
            Task<?> obtainMutex = Tasks.builder()
                    .description(description)
                    .body(new ObtainPermit(getChildTaskSemaphore(), description, permitObtained))
                    .build();
            toSubmit = Tasks.sequential(
                    "Waiting for permit then running " + effector.getName() + " on " + target,
                    obtainMutex, effectorTask);
        }
        toSubmit.addListener(new ReleasePermit(getChildTaskSemaphore(), permitObtained), MoreExecutors.sameThreadExecutor());
    } else {
        toSubmit = effectorTask;
    }
    return toSubmit;
}
 
Example #27
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Entity makeAppAndAddChild(boolean includeDeclaredParameters, MutableMap<String,?> effectorInvocationParameters, String ...lines) throws Exception {
    Entity app = createAndStartApplication(
        "services:",
        "- type: " + BasicApplication.class.getName(),
        "  brooklyn.config:",
        "    p.parent: parent",
        "    p.child: parent",
        "    p.param1: parent",
        "  brooklyn.initializers:",
        "  - type: "+AddChildrenEffector.class.getName(),
        "    brooklyn.config:",
        "      name: add",
        (includeDeclaredParameters ? Strings.lines(indent("      ",
            "parameters:",
            "  p.param1:",
            "    defaultValue: default",
            "  p.param2:",
            "    defaultValue: default")) : ""),
        Strings.lines(indent("      ", lines))
        );
    waitForApplicationTasks(app);
    
    Asserts.assertThat(app.getChildren(), CollectionFunctionals.empty());
    
    Object result = app.invoke(Effectors.effector(Object.class, "add").buildAbstract(), effectorInvocationParameters).get();
    Asserts.assertThat((Iterable<?>)result, CollectionFunctionals.sizeEquals(1));
    Asserts.assertThat(app.getChildren(), CollectionFunctionals.sizeEquals(1));
    Entity child = Iterables.getOnlyElement(app.getChildren());
    Assert.assertEquals(child.getId(), Iterables.getOnlyElement((Iterable<?>)result));
    
    return child;
}
 
Example #28
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 #29
Source File: CampYamlLiteTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** based on {@link PdpYamlTest} for parsing,
 * then creating a {@link TestAppAssembly} */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testAddChildrenEffector() throws Exception {
    String childYaml = Streams.readFullyStringAndClose(getClass().getResourceAsStream("test-app-service-blueprint.yaml"));
    AddChildrenEffector newEff = new AddChildrenEffector(ConfigBag.newInstance()
        .configure(AddChildrenEffector.EFFECTOR_NAME, "add_tomcat")
        .configure(AddChildrenEffector.BLUEPRINT_YAML, childYaml)
        .configure(AddChildrenEffector.EFFECTOR_PARAMETER_DEFS, MutableMap.of("war", (Object)MutableMap.of(
            "defaultValue", "foo.war"))) ) ;
    TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class).addInitializer(newEff));

    // test adding, with a parameter
    Task<List> task = app.invoke(Effectors.effector(List.class, "add_tomcat").buildAbstract(), MutableMap.of("war", "foo.bar"));
    List result = task.get();
    
    Entity newChild = Iterables.getOnlyElement(app.getChildren());
    Assert.assertEquals(newChild.getConfig(ConfigKeys.newStringConfigKey("war")), "foo.bar");
    
    Assert.assertEquals(Iterables.getOnlyElement(result), newChild.getId());
    Entities.unmanage(newChild);
    
    // and test default value
    task = app.invoke(Effectors.effector(List.class, "add_tomcat").buildAbstract(), MutableMap.<String,Object>of());
    result = task.get();
    
    newChild = Iterables.getOnlyElement(app.getChildren());
    Assert.assertEquals(newChild.getConfig(ConfigKeys.newStringConfigKey("war")), "foo.war");
    
    Assert.assertEquals(Iterables.getOnlyElement(result), newChild.getId());
    Entities.unmanage(newChild);
}
 
Example #30
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntityWithInitializer() throws Exception {
    String yaml =
            "services:\n"+
            "- type: "+TestEntity.class.getName()+"\n"+
            "  brooklyn.initializers: [ { type: "+TestSensorAndEffectorInitializer.class.getName()+" } ]";
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    
    Effector<?> hi = entity.getEffector(TestSensorAndEffectorInitializer.EFFECTOR_SAY_HELLO);
    Assert.assertNotNull(hi);
    
    Assert.assertNotNull( entity.getEntityType().getSensor(TestSensorAndEffectorInitializer.SENSOR_HELLO_DEFINED) );
    Assert.assertNotNull( entity.getEntityType().getSensor(TestSensorAndEffectorInitializer.SENSOR_HELLO_DEFINED_EMITTED) );
    Assert.assertNull( entity.getEntityType().getSensor(TestSensorAndEffectorInitializer.SENSOR_LAST_HELLO) );
    
    Assert.assertNull( entity.getAttribute(Sensors.newStringSensor(TestSensorAndEffectorInitializer.SENSOR_LAST_HELLO)) );
    Assert.assertNull( entity.getAttribute(Sensors.newStringSensor(TestSensorAndEffectorInitializer.SENSOR_HELLO_DEFINED)) );
    Assert.assertEquals( entity.getAttribute(Sensors.newStringSensor(TestSensorAndEffectorInitializer.SENSOR_HELLO_DEFINED_EMITTED)),
        "1");
    
    Task<String> saying = entity.invoke(Effectors.effector(String.class, TestSensorAndEffectorInitializer.EFFECTOR_SAY_HELLO).buildAbstract(), 
        MutableMap.of("name", "Bob"));
    Assert.assertEquals(saying.get(Duration.TEN_SECONDS), "Hello Bob");
    Assert.assertEquals( entity.getAttribute(Sensors.newStringSensor(TestSensorAndEffectorInitializer.SENSOR_LAST_HELLO)),
        "Bob");
}