Java Code Examples for org.apache.brooklyn.core.sensor.Sensors#newBooleanSensor()

The following examples show how to use org.apache.brooklyn.core.sensor.Sensors#newBooleanSensor() . 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: MachineLifecycleEffectorTasksTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testProvisionLatchObeyed() throws Exception {

    AttributeSensor<Boolean> ready = Sensors.newBooleanSensor("readiness");

    BasicEntity triggerEntity = app.createAndManageChild(EntitySpec.create(BasicEntity.class));

    EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
            .configure(BrooklynConfigKeys.PROVISION_LATCH, DependentConfiguration.attributeWhenReady(triggerEntity, ready)));

    final Task<Void> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of(
            "locations", ImmutableList.of(BailOutJcloudsLocation.newBailOutJcloudsLocation(app.getManagementContext()))));
    
    Time.sleep(ValueResolver.PRETTY_QUICK_WAIT);
    if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.get());
    assertEffectorBlockingDetailsEventually(entity, "Waiting for config " + BrooklynConfigKeys.PROVISION_LATCH.getName());

    Asserts.succeedsContinually(new Runnable() {
        @Override
        public void run() {
            if (task.isDone()) throw new IllegalStateException("Task finished early with: "+task.getUnchecked());
        }
    });
    try {
        triggerEntity.sensors().set(ready, true);
        task.get(Duration.THIRTY_SECONDS);
    } catch (Throwable t) {
        Exceptions.propagateIfFatal(t);
        if ((t.toString().contains(BailOutJcloudsLocation.ERROR_MESSAGE))) {
            // expected - BailOut location throws - just swallow
        } else {
            Exceptions.propagate(t);
        }
    }
}
 
Example 2
Source File: InvokeEffectorOnSensorChangeIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = "Integration")
public void testIsBusySensorAlwaysFalseAtEnd() throws InterruptedException {
    /*
     * Stress-test isBusy. Reliably failed with insufficient synchronisation
     * in AbstractInvokeEffectorPolicy.
     */
    final AttributeSensor<String> sensor = Sensors.newStringSensor("my-sensor");
    final AttributeSensor<Boolean> isBusy = Sensors.newBooleanSensor("is-busy");
    Effector<Void> effector = Effectors.effector(Void.class, "effector")
            .impl(new DoNothingEffector())
            .build();
    final BasicEntity entity = app.createAndManageChild(EntitySpec.create(BasicEntity.class)
            .addInitializer(new AddEffector(effector))
            .policy(PolicySpec.create(InvokeEffectorOnSensorChange.class)
                    .configure(InvokeEffectorOnSensorChange.SENSOR, sensor)
                    .configure(InvokeEffectorOnSensorChange.EFFECTOR, "effector")
                    .configure(InvokeEffectorOnSensorChange.IS_BUSY_SENSOR_NAME, isBusy.getName())));
    final AtomicInteger threadId = new AtomicInteger();
    Thread[] threads = new Thread[10];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new Runnable() {
            private int count = 0;
            @Override
            public void run() {
                int id = threadId.incrementAndGet();
                while (count++ < 1000) {
                    entity.sensors().set(sensor, "thread-" + id + "-" + count);
                }
            }
        });
        threads[i].start();
    }
    for (Thread thread : threads) {
        thread.join();
    }

    EntityAsserts.assertAttributeEqualsEventually(entity, isBusy, false);
}
 
Example 3
Source File: AbstractInvokeEffectorPolicyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCountReflectsNumberOfExecutingEffectors() {
    final CountDownLatch effectorLatch = new CountDownLatch(1);
    final AttributeSensor<Boolean> policyIsBusy = Sensors.newBooleanSensor(
            "policyIsBusy");
    final Effector<Void> blockingEffector = Effectors.effector(Void.class, "abstract-invoke-effector-policy-test")
            .impl(new BlockingEffector(effectorLatch))
            .build();
    final TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    final TestAbstractInvokeEffectorPolicy policy = entity.policies().add(
            PolicySpec.create(TestAbstractInvokeEffectorPolicy.class)
                    .configure(AbstractInvokeEffectorPolicy.IS_BUSY_SENSOR_NAME, policyIsBusy.getName()));
    final Task<?> effectorTask = policy.invoke(blockingEffector, ImmutableMap.<String, Object>of());

    // expect isbusy on entity, effector incomplete.
    Supplier<Boolean> effectorTaskDoneSupplier = new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return effectorTask.isDone();
        }
    };
    Asserts.continually(effectorTaskDoneSupplier, Predicates.equalTo(false));
    EntityAsserts.assertAttributeEqualsEventually(entity, policyIsBusy, true);

    effectorLatch.countDown();

    Asserts.eventually(effectorTaskDoneSupplier, Predicates.equalTo(true));
    EntityAsserts.assertAttributeEqualsEventually(entity, policyIsBusy, false);
}
 
Example 4
Source File: VanillaSoftwareProcessYamlTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testAlternativeServiceUpPolling() throws Exception {
    AttributeSensor<Boolean> alternativeUpIndicator = Sensors.newBooleanSensor("myAlternativeUpIndicator");
    MyCallable.latch.set(new CountDownLatch(1));
    
    Entity app = createApplicationUnstarted(
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName(),
        "services:",
        "- type: "+VanillaSoftwareProcess.class.getName(),
        "  brooklyn.config:",
        "    softwareProcess.serviceProcessIsRunningPollPeriod: 10ms",
        "    sshMonitoring.enabled: false",
        "    checkRunning.command: myCheckRunning",
        "    launch.command: myLaunch",
        "  brooklyn.initializers:",
        "  - type: "+FunctionSensor.class.getName(),
        "    brooklyn.config:",
        "      "+FunctionSensor.SENSOR_PERIOD.getName()+": 10ms",
        "      "+FunctionSensor.SENSOR_NAME.getName()+": " + alternativeUpIndicator.getName(),
        "      "+FunctionSensor.SENSOR_TYPE.getName()+": boolean",
        "      "+FunctionSensor.FUNCTION.getName()+":",
        "        $brooklyn:object:",
        "          type: "+MyCallable.class.getName(),
        "  brooklyn.enrichers:",
        "  - type: " + UpdatingMap.class.getName(),
        "    brooklyn.config:",
        "      enricher.sourceSensor: $brooklyn:sensor(\"" + alternativeUpIndicator.getName() + "\")",
        "      enricher.targetSensor: $brooklyn:sensor(\"service.notUp.indicators\")",
        "      enricher.updatingMap.computing:",
        "        $brooklyn:object:",
        "          type: \"" + Functions.class.getName() + "\"",
        "          factoryMethod.name: \"forMap\"",
        "          factoryMethod.args:",
        "          - false: \"false\"",
        "            true: null",
        "          - \"no value\"");
    
    VanillaSoftwareProcess entity = (VanillaSoftwareProcess) Iterables.getOnlyElement(app.getChildren());
    
    RecordingSensorEventListener<Object> serviceUpListener = subscribe(entity, Attributes.SERVICE_UP);
    RecordingSensorEventListener<Object> serviceStateListener = subscribe(entity, Attributes.SERVICE_STATE_ACTUAL);

    // ensure these get the initial values because test relies on that later
    assertEventsEqualEventually(serviceStateListener, ImmutableList.of(Lifecycle.CREATED), true);
    assertEventsEqualEventually(serviceUpListener, ImmutableList.of(false), true);

    Task<Void> task = app.invoke(Startable.START, ImmutableMap.of());
    
    // Should eventually poll for 'checkRunning', but just once immediately after doing launch etc
    Asserts.succeedsEventually(new Runnable() {
        public void run() {
            ExecCmdAsserts.assertExecHasOnlyOnce(RecordingSshTool.getExecCmds(), "myCheckRunning");
        }});
    RecordingSshTool.clear();

    assertFalse(task.isDone());
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_NOT_UP_INDICATORS, ImmutableMap.of(alternativeUpIndicator.getName(), "no value"));
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STARTING);

    // Let the function return 'false'
    MyCallable.val.set(false);
    MyCallable.latch.get().countDown();
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_NOT_UP_INDICATORS, ImmutableMap.of(alternativeUpIndicator.getName(), "false"));
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
    assertFalse(task.isDone());

    // Let startup complete, by the function returning 'true'
    MyCallable.val.set(true);
    waitForApplicationTasks(app, Asserts.DEFAULT_LONG_TIMEOUT);
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);

    // Should not have transitioned through wrong states (e.g. never "on-fire"!)
    assertEventsEqualEventually(serviceUpListener, ImmutableList.of(false, true), true);
    assertEventsEqualEventually(serviceStateListener, ImmutableList.of(Lifecycle.CREATED, Lifecycle.STARTING, Lifecycle.RUNNING), true);
    
    ExecCmdAsserts.assertExecHasNever(RecordingSshTool.getExecCmds(), "myCheckRunning");
}
 
Example 5
Source File: AbstractInvokeEffectorPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void publishIsBusy() {
    final boolean busy = isBusy();
    LOG.trace("{} taskCount={}, isBusy={}", new Object[]{this, getTaskCounter().get(), busy});
    AttributeSensor<Boolean> sensor = Sensors.newBooleanSensor(getIsBusySensorName());
    entity.sensors().set(sensor, busy);
}