org.apache.brooklyn.api.sensor.AttributeSensor Java Examples

The following examples show how to use org.apache.brooklyn.api.sensor.AttributeSensor. 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: ReducerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReducingBuilderWithConcatenator() {
    entity.enrichers().add(Enrichers.builder()
            .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
            .from(entity)
            .computing(new Concatenator())
            .publishing(STR3)
            .build()
    );

    EntityAsserts.assertAttributeEquals(entity, STR3, null);
    
    entity.sensors().set(STR1, "foo");
    EntityAsserts.assertAttributeEqualsContinually(entity, STR3, null);

    entity.sensors().set(STR2, "bar");
    EntityAsserts.assertAttributeEqualsEventually(entity, STR3, "foobar");
}
 
Example #2
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@DataProvider(name = "variants")
public Object[][] provideVariants() {
    AttributeSensor<HostAndPort> hostAndPortSensor = Sensors.newSensor(HostAndPort.class, "test.endpoint");
    List<Object[]> result = Lists.newArrayList();
    for (Timing setSensor : Timing.values()) {
        for (Timing addLocation : Timing.values()) {
            result.add(new Object[] {setSensor, addLocation, Attributes.MAIN_URI, 
                    URI.create("http://"+publicIp+":1234/my/path"), "main.uri.mapped.subnet", "http://"+privateIp+":1234/my/path"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    "http://"+publicIp+":1234/my/path", "test.name.mapped.subnet", "http://"+privateIp+":1234/my/path"});
            result.add(new Object[] {setSensor, addLocation, Attributes.HTTP_PORT, 
                    1234, "http.endpoint.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    "1234", "test.name.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, TestEntity.NAME, 
                    publicIp+":1234", "test.name.mapped.subnet", privateIp+":1234"});
            result.add(new Object[] {setSensor, addLocation, hostAndPortSensor, 
                    HostAndPort.fromString(publicIp+":1234"), "test.endpoint.mapped.subnet", privateIp+":1234"});
        }
    }
    return result.toArray(new Object[result.size()][]);
}
 
Example #3
Source File: ConditionalEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddsConditionalAndPropagatesSensors() throws Exception {
    optional = app.addChild(EntitySpec.create(ConditionalEntity.class)
            .configure(ConditionalEntity.CREATE_CONDITIONAL_ENTITY, true)
            .configure(ConditionalEntity.PROPAGATE_CONDITIONAL_ENTITY_SENSORS, true)
            .configure(ConditionalEntity.CONDITIONAL_ENTITY_SENSOR_LIST, ImmutableList.<AttributeSensor<?>>of(TestEntity.SEQUENCE))
            .configure(ConditionalEntity.CONDITIONAL_ENTITY_SPEC, EntitySpec.create(TestEntity.class)));
    app.start(ImmutableList.of(loc1));

    assertEquals(optional.getChildren().size(), 1);
    Entity child = Iterables.getOnlyElement(optional.getChildren());
    assertTrue(child instanceof TestEntity);
    assertEquals(child, optional.sensors().get(ConditionalEntity.CONDITIONAL_ENTITY));

    // Check that the configured sensors are propagated
    child.sensors().set(TestEntity.SEQUENCE, 123);
    EntityAsserts.assertAttributeEqualsEventually(child, TestEntity.SEQUENCE, 123);
    EntityAsserts.assertAttributeEqualsEventually(optional, TestEntity.SEQUENCE, 123);
    child.sensors().set(TestEntity.NAME, "frog");
    EntityAsserts.assertAttributeEqualsEventually(child, TestEntity.NAME, "frog");
    EntityAsserts.assertAttribute(optional, TestEntity.NAME, Predicates.isNull());
}
 
Example #4
Source File: TemplateProcessorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testConditionalComparingAttributes() {
    AttributeSensor<String> sensor1 = Sensors.newStringSensor("sensor1");
    AttributeSensor<String> sensor2 = Sensors.newStringSensor("sensor2");
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
    entity.sensors().set(sensor1, "myval1");
    entity.sensors().set(sensor2, "myval1");
    String templateContents = Joiner.on("\n").join(
            "[#ftl]",
            "[#if attribute['sensor1'] == attribute['sensor2']]",
            "true",
            "[#else]",
            "false",
            "[/#if]");
    String result = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of());
    assertEquals(result.trim(), "true");
    
    entity.sensors().set(sensor2, "myval2");
    String result2 = TemplateProcessor.processTemplateContents(templateContents, entity, ImmutableMap.<String,Object>of());
    assertEquals(result2.trim(), "false");
}
 
Example #5
Source File: ReducerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReducingBuilderWithJoinerFunction() {
    entity.enrichers().add(Enrichers.builder()
            .reducing(Reducer.class, ImmutableList.<AttributeSensor<?>>of(STR1, STR2))
            .from(entity)
            .computing("joiner", ImmutableMap.<String, Object>of("separator", "-"))
            .publishing(STR3)
            .build()
    );

    EntityAsserts.assertAttributeEquals(entity, STR3, null);
    
    entity.sensors().set(STR1, "foo");
    EntityAsserts.assertAttributeEqualsEventually(entity, STR3, "foo-null");

    entity.sensors().set(STR2, "bar");
    EntityAsserts.assertAttributeEqualsEventually(entity, STR3, "foo-bar");
}
 
Example #6
Source File: SensorResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> batchSensorRead(final String application, final String entityToken, final Boolean raw) {
    final Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to see entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    Map<String, Object> sensorMap = Maps.newHashMap();
    @SuppressWarnings("rawtypes")
    Iterable<AttributeSensor> sensors = filter(entity.getEntityType().getSensors(), AttributeSensor.class);

    for (AttributeSensor<?> sensor : sensors) {
        // Exclude sensors that user is not allowed to see
        if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_SENSOR, new EntityAndItem<String>(entity, sensor.getName()))) {
            log.trace("User {} not authorized to see sensor {} of entity {}; excluding from current-state results", 
                    new Object[] {Entitlements.getEntitlementContext().user(), sensor.getName(), entity});
            continue;
        }

        Object value = entity.getAttribute(findSensor(entity, sensor.getName()));
        sensorMap.put(sensor.getName(), 
            resolving(value).preferJson(true).asJerseyOutermostReturnValue(false).raw(raw).context(entity).timeout(Duration.ZERO).renderAs(sensor).resolve());
    }
    return sensorMap;
}
 
Example #7
Source File: DslAndRebindYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegexReplacementFunctionWithAttributeWhenReady() throws Exception {
    Entity testEntity = setupAndCheckTestEntityInBasicYamlWith(
            "  brooklyn.enrichers:",
            "  - type: org.apache.brooklyn.enricher.stock.Transformer",
            "    brooklyn.config:",
            "      enricher.sourceSensor: $brooklyn:sensor(\"test.name\")",
            "      enricher.targetSensor: $brooklyn:sensor(\"test.name.transformed\")",
            "      enricher.transformation: $brooklyn:function.regexReplacement($brooklyn:attributeWhenReady(\"test.pattern\"), $brooklyn:attributeWhenReady(\"test.replacement\"))"
    );
    testEntity.sensors().set(Sensors.newStringSensor("test.pattern"), "foo");
    testEntity.sensors().set(Sensors.newStringSensor("test.replacement"), "bar");
    testEntity.sensors().set(TestEntity.NAME, "somefooname");
    AttributeSensor<String> transformedSensor = Sensors.newStringSensor("test.name.transformed");
    EntityAsserts.assertAttributeEqualsEventually(testEntity, transformedSensor, "somebarname");
}
 
Example #8
Source File: DeltaEnrichersTests.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testMonospaceTimeWeightedDeltaEnricher() {
    AttributeSensor<Double> deltaSensor = new BasicAttributeSensor<Double>(Double.class, "per second delta delta sensor");
    @SuppressWarnings("unchecked")
    TimeWeightedDeltaEnricher<Integer> delta = producer.enrichers().add(EnricherSpec.create(TimeWeightedDeltaEnricher.class)
            .configure("producer", producer)
            .configure("source", intSensor)
            .configure("target", deltaSensor)
            .configure("unitMillis", 1000));
    
    // Don't start with timestamp=0: that may be treated special 
    delta.onEvent(intSensor.newEvent(producer, 0), 1000);
    assertEquals(producer.getAttribute(deltaSensor), null);
    delta.onEvent(intSensor.newEvent(producer, 0), 2000);
    assertEquals(producer.getAttribute(deltaSensor), 0d);
    delta.onEvent(intSensor.newEvent(producer, 1), 3000);
    assertEquals(producer.getAttribute(deltaSensor), 1d);
    delta.onEvent(intSensor.newEvent(producer, 3), 4000);
    assertEquals(producer.getAttribute(deltaSensor), 2d);
    delta.onEvent(intSensor.newEvent(producer, 8), 5000);
    assertEquals(producer.getAttribute(deltaSensor), 5d);
}
 
Example #9
Source File: Reducer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    Sensor<?> destinationSensor = getConfig(TARGET_SENSOR);

    List<Object> values = Lists.newArrayList();

    for (AttributeSensor<?> sourceSensor : subscribedSensors) {
        Object resolvedSensorValue = entity.sensors().get(sourceSensor);
        values.add(resolvedSensorValue);
    }
    Object result = reducerFunction.apply(values);

    if (LOG.isTraceEnabled()) LOG.trace("enricher {} got {}, propagating via {} as {}",
            new Object[] {this, event, entity, reducerFunction, destinationSensor});

    emit(destinationSensor, result);
}
 
Example #10
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * The sensorVal must include port 1234, so that it will be converted to "+publicIp+":1234
 */
@Test(dataProvider = "variants")
public <T> void testSensorTransformed(Timing setUri, Timing addLocation, 
        AttributeSensor<T> sensor, T sensorVal, String targetSensorName, String expectedVal) throws Exception {
    entity.sensors().set(Attributes.SUBNET_ADDRESS, privateIp);
    if (setUri == Timing.BEFORE) {
        entity.sensors().set(sensor, sensorVal);
    }
    if (addLocation == Timing.BEFORE) {
        entity.addLocations(ImmutableList.of(machine));
    }
    
    entity.enrichers().add(EnricherSpec.create(OnSubnetNetworkEnricher.class)
            .configure(OnSubnetNetworkEnricher.SENSORS, ImmutableList.of(sensor)));

    if (setUri == Timing.AFTER) {
        entity.sensors().set(sensor, sensorVal);
    }
    if (addLocation == Timing.AFTER) {
        entity.addLocations(ImmutableList.of(machine));
    }
    
    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(targetSensorName), expectedVal);
    EntityAsserts.assertAttributeEquals(entity, sensor, sensorVal);
}
 
Example #11
Source File: ElectPrimaryPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void addSubscriptions(Entity entity) {
    String weightSensorName = config().get(PRIMARY_WEIGHT_NAME);
    TargetMode target = config().get(TARGET_MODE);
    if (target==TargetMode.AUTO) target =  entity instanceof Group ? TargetMode.MEMBERS : TargetMode.CHILDREN;

    highlightTriggers("Listening for "+weightSensorName+" and service up, state on all " + target.name().toLowerCase());
    
    Change<Entity> candidateSetChange = new Change<Entity>();
    Change<Boolean> candidateUpChange = new Change<Boolean>();
    Change<Lifecycle> candidateLifecycleChange = new Change<Lifecycle>();
    Change<Number> candidateWeightChange = new Change<Number>();
    AttributeSensor<Number> weightSensor = Sensors.newSensor(Number.class, weightSensorName);
    
    switch (target) {
    case CHILDREN:
        subscriptions().subscribe(entity, AbstractEntity.CHILD_ADDED, candidateSetChange);
        subscriptions().subscribe(entity, AbstractEntity.CHILD_REMOVED, candidateSetChange);
        subscriptions().subscribeToChildren(entity, Attributes.SERVICE_UP, candidateUpChange);
        subscriptions().subscribeToChildren(entity, Attributes.SERVICE_STATE_ACTUAL, candidateLifecycleChange);
        subscriptions().subscribeToChildren(entity, weightSensor, candidateWeightChange);
        break;
    case MEMBERS:
        subscriptions().subscribe(entity, DynamicGroup.MEMBER_ADDED, candidateSetChange);
        subscriptions().subscribe(entity, DynamicGroup.MEMBER_REMOVED, candidateSetChange);
        subscriptions().subscribeToMembers(((Group)entity), Attributes.SERVICE_UP, candidateUpChange);
        subscriptions().subscribeToMembers(((Group)entity), Attributes.SERVICE_STATE_ACTUAL, candidateLifecycleChange);
        subscriptions().subscribeToMembers(((Group)entity), weightSensor, candidateWeightChange);
        break;
    default:
        throw new IllegalArgumentException("Unexpected target mode "+target);
    }
}
 
Example #12
Source File: UpdatingMapTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateServiceNotUpIndicator() throws Exception {
    AttributeSensor<Object> extraIsUpSensor = Sensors.newSensor(Object.class, "extraIsUp");
    
    Entity entity = app.createAndManageChild(EntitySpec.create(BasicApplication.class)
            .enricher(EnricherSpec.create(UpdatingMap.class)
                    .configure(UpdatingMap.SOURCE_SENSOR.getName(), extraIsUpSensor.getName())
                    .configure(UpdatingMap.TARGET_SENSOR, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS)
                    .configure(UpdatingMap.COMPUTING, Functions.forMap(MutableMap.of(true, null, false, "valIsFalse"), "myDefault"))));

    assertMapSensorContainsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.of("extraIsUp", "myDefault"));
    
    entity.sensors().set(extraIsUpSensor, true);
    assertMapSensorNotContainsKeysEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableList.of("extraIsUp"));

    app.start(ImmutableList.<Location>of());
    
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsContinually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    
    entity.sensors().set(extraIsUpSensor, false);
    EntityAsserts.assertAttributeEqualsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.of("extraIsUp", "valIsFalse"));
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);

    entity.sensors().set(extraIsUpSensor, true);
    EntityAsserts.assertAttributeEqualsEventually(entity, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, ImmutableMap.of());
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true);
}
 
Example #13
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorAvoidsInfiniteLoopInPropagateAllWithImplicitProducer() throws Exception {
    AttributeSensor<String> mySensor = Sensors.newSensor(String.class, "mySensor");

    EnricherSpec<?> spec = EnricherSpec.create(Propagator.class)
            .configure(Propagator.PROPAGATING_ALL, true);

    assertAddEnricherThrowsIllegalStateException(spec, "when publishing to own entity");
    assertAttributeNotRepublished(app, mySensor);
}
 
Example #14
Source File: AttributeMapTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected <T> Runnable newUpdateMapRunnable(final AttributeMap map, final AttributeSensor<T> attribute, final T val) {
    return new Runnable() {
        @Override public void run() {
            map.update(attribute, val);
        }
    };
}
 
Example #15
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 #16
Source File: DurationSinceSensorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSensorAddedAndUpdated() {
    final AtomicLong ticker = new AtomicLong(0);
    Supplier<Long> timeSupplier = new Supplier<Long>() {
        @Override
        public Long get() {
            return ticker.get();
        }
    };
    Entity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
            .addInitializer(new DurationSinceSensor(ConfigBag.newInstance(ImmutableMap.of(
                    AddSensor.SENSOR_NAME, "sensor",
                    AddSensor.SENSOR_TYPE, Duration.class.getName(),
                    AddSensor.SENSOR_PERIOD, Duration.ONE_MILLISECOND,
                    DurationSinceSensor.EPOCH_SUPPLIER, Suppliers.ofInstance(0L),
                    DurationSinceSensor.TIME_SUPPLIER, timeSupplier)))));

    final Map<?, ?> continuallyTimeout = ImmutableMap.of("timeout", Duration.millis(10));
    final AttributeSensor<Duration> duration = Sensors.newSensor(Duration.class, "sensor");
    assertAttributeEqualsEventually(entity, duration, Duration.millis(0));
    assertAttributeEqualsContinually(continuallyTimeout, entity, duration, Duration.millis(0));
    ticker.incrementAndGet();
    assertAttributeEqualsEventually(entity, duration, Duration.millis(1));
    assertAttributeEqualsContinually(continuallyTimeout, entity, duration, Duration.millis(1));
    ticker.incrementAndGet();
    assertAttributeEqualsEventually(entity, duration, Duration.millis(2));
    assertAttributeEqualsContinually(continuallyTimeout, entity, duration, Duration.millis(2));
}
 
Example #17
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> getSensorMap(String sensor, Iterable<Entity> descs) {
    if (Iterables.isEmpty(descs))
        return Collections.emptyMap();
    Map<String, Object> result = MutableMap.of();
    Iterator<Entity> di = descs.iterator();
    Sensor<?> s = null;
    while (di.hasNext()) {
        Entity potentialSource = di.next();
        s = potentialSource.getEntityType().getSensor(sensor);
        if (s!=null) break;
    }
    if (s==null)
        s = Sensors.newSensor(Object.class, sensor);
    if (!(s instanceof AttributeSensor<?>)) {
        log.warn("Cannot retrieve non-attribute sensor "+s+" for entities; returning empty map");
        return result;
    }
    for (Entity e: descs) {
        Object v = null;
        try {
            v = e.getAttribute((AttributeSensor<?>)s);
        } catch (Exception exc) {
            Exceptions.propagateIfFatal(exc);
            log.warn("Error retrieving sensor "+s+" for "+e+" (ignoring): "+exc);
        }
        if (v!=null)
            result.put(e.getId(), v);
    }
    return result;
}
 
Example #18
Source File: TestSensorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoesNotAbortIfConditionUnsatisfied() throws Exception {
    final AttributeSensor<Lifecycle> serviceStateSensor = Sensors.newSensor(Lifecycle.class,
            "test.service.state", "Actual lifecycle state of the service (for testing)");

    final TestEntity entity = app.addChild(EntitySpec.create(TestEntity.class));
    
    TestSensor testCase = app.createAndManageChild(EntitySpec.create(TestSensor.class)
            .configure(TestSensor.TIMEOUT, Asserts.DEFAULT_LONG_TIMEOUT)
            .configure(TestSensor.TARGET_ENTITY, entity)
            .configure(TestSensor.SENSOR_NAME, serviceStateSensor.getName())
            .configure(TestSensor.ASSERTIONS, newMapAssertion("equals", Lifecycle.RUNNING))
            .configure(TestSensor.ABORT_CONDITIONS, newMapAssertion("equals", Lifecycle.ON_FIRE)));

    // Set the state to running while we are starting (so that the abort-condition will have
    // been checked).
    entity.sensors().set(serviceStateSensor, Lifecycle.STARTING);
    executor.submit(new Runnable() {
        @Override
        public void run() {
            Time.sleep(Duration.millis(50));
            entity.sensors().set(serviceStateSensor, Lifecycle.RUNNING);
        }});
    
    app.start(locs);
    
    assertTestSensorSucceeds(testCase);
}
 
Example #19
Source File: AutoScalerPolicyNoMoreMachinesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testMetricResizingBeyondMaxMachines() throws Exception {
    AttributeSensor<Integer> metric = Sensors.newIntegerSensor("test.aggregatedLoad");
    
    cluster.resize(1);
    policy = cluster.policies().add(PolicySpec.create(AutoScalerPolicy.class)
            .configure(AutoScalerPolicy.METRIC, metric)
            .configure(AutoScalerPolicy.METRIC_LOWER_BOUND, 10)
            .configure(AutoScalerPolicy.METRIC_UPPER_BOUND, 20)
            .configure(AutoScalerPolicy.MIN_PERIOD_BETWEEN_EXECS, Duration.millis(10)));

    // Single node trying to handle a load of 21; too high, so will add one more node.
    // That takes the load back to within acceptable limits
    cluster.sensors().set(metric, 21);
    assertSizeEventually(2);
    cluster.sensors().set(metric, 19);

    // With two nodes, load is now too high, so will try (and fail) to add one more node.
    // Trigger another attempt to resize.
    // Any nodes that fail with NoMachinesAvailableException will be immediately deleted.
    cluster.sensors().set(metric, 22);
    assertSizeEventually(2, 0, 1);
    assertSizeContinually(2, 0, 1);
    
    // Metric is re-published; should not keep retrying
    cluster.sensors().set(metric, 21);
    assertSizeContinually(2, 0, 1);
}
 
Example #20
Source File: RollingMeanEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated since 0.12.0; use {@link EnricherSpec}
 */
@Deprecated
public RollingMeanEnricher(Entity producer, AttributeSensor<T> source, AttributeSensor<Double> target,
        int windowSize) {
    super(producer, source, target);
    this.windowSize = windowSize;
    if (source!=null && target!=null)
        this.uniqueTag = JavaClassNames.simpleClassName(getClass())+":"+source.getName()+"->"+target.getName();
}
 
Example #21
Source File: SoftwareProcessDriverCopyResourcesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testPhase(MapConfigKey<String> filePhase, MapConfigKey<String> templatePhase,
                       AttributeSensor<String> directory) throws IOException {

    File file1 = new File(sourceFileDir, "file1");
    Files.write(TEST_CONTENT_FILE, file1, Charset.defaultCharset());
    File template1 = new File(sourceTemplateDir, "template1");
    Files.write(TEST_CONTENT_TEMPLATE, template1, Charset.defaultCharset());
    final EmptySoftwareProcess testEntity =
        app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true")
            .configure(filePhase.getName(),
                ImmutableMap.of(file1.getAbsolutePath(), "file1"))
            .configure(templatePhase.getName(),
                ImmutableMap.of(template1.getAbsolutePath(), "template1")));

    app.start(ImmutableList.of(location));
    final String installDirName = testEntity.sensors().get(directory);
    assertNotNull(installDirName);
    final File installDir = new File(installDirName);

    final File file1Installed = new File(installDir, "file1");
    final String firstLine = Files.readFirstLine(file1Installed, Charset.defaultCharset());
    assertEquals(TEST_CONTENT_FILE, firstLine);

    final File template1Installed = new File(installDir, "template1");
    Properties props = new Properties();
    final FileInputStream templateStream = new FileInputStream(template1Installed);
    props.load(templateStream);
    assertEquals(props.getProperty("id"), testEntity.getId());
}
 
Example #22
Source File: EntityTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** as {@link #testingAttributeEventually(Entity, AttributeSensor, Predicate, Duration) for multiple entities */
public static <T> Task<Boolean> testingAttributeEventually(Iterable<Entity> entities, AttributeSensor<T> sensor, Predicate<T> condition, Duration timeout) {
    return DependentConfiguration.builder().attributeWhenReadyFromMultiple(entities, sensor, condition)
        .postProcess(Functions.constant(true))
        .timeout(timeout)
        .onTimeoutReturn(false)
        .onUnmanagedReturn(false)
        .postProcessFromMultiple(CollectionFunctionals.all(Predicates.equalTo(true)))
        .build();
}
 
Example #23
Source File: FeedConfig.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    result.append(toStringBaseName());
    result.append("[");
    boolean contents = false;
    Object source = toStringPollSource();
    AttributeSensor<T> s = getSensor();
    if (Strings.isNonBlank(Strings.toString(source))) {
        result.append(Strings.toUniqueString(source, 40));
        if (s!=null) {
            result.append("->");
            result.append(s.getName());
        }
        contents = true;
    } else if (s!=null) {
        result.append(s.getName());
        contents = true;
    }
    MutableList<Object> fields = toStringOtherFields();
    if (fields!=null) {
        for (Object field: fields) {
            if (Strings.isNonBlank(Strings.toString(field))) {
                if (contents) result.append(";");
                contents = true;
                result.append(field);
            }
        }
    }
    result.append("]");
    return result.toString();
}
 
Example #24
Source File: TransformerEnricherWithDslTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testTransformerResolvesResolvableValues(int portStart, int portCount) {
    // Note: The test gets progressively slower with iterations, probably due to the GC triggering much more frequently.
    //       There's no memory leak, but doesn't seem right to be putting so much pressure on the GC with such a simple test.
    AttributeSensor<Integer> sourceSensor = Sensors.newIntegerSensor("port");
    AttributeSensor<String> targetSensor = Sensors.newStringSensor("port.transformed");
    app.enrichers().add(EnricherSpec.create(Transformer.class)
            .configure(Transformer.SOURCE_SENSOR, sourceSensor)
            .configure(Transformer.TARGET_SENSOR, targetSensor)
            .configure(Transformer.TARGET_VALUE,
                    // Can only use the inner-most sensor, but including the
                    // wrapping formatStrings amplifies the resolving effort, making
                    // a bug more probable to manifest.
                    BrooklynDslCommon.formatString("%s",
                            BrooklynDslCommon.formatString("%d",
                                    BrooklynDslCommon.attributeWhenReady("port")))));

    int failures = 0;
    for (int port = portStart; port < portStart + portCount; port++) {
        app.sensors().set(sourceSensor, port);
        try {
            EntityAsserts.assertAttributeEqualsEventually(app, targetSensor, Integer.toString(port));
        } catch (Exception e) {
            failures++;
            LOG.warn("Assertion failed, port=" + port + ", transformed sensor is " + app.sensors().get(targetSensor), e);
        }
    }

    assertEquals(failures, 0, failures + " assertion failures while transforming sensor; see logs for detailed errors");
}
 
Example #25
Source File: SoftwareProcessEntityLatchTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider="latchAndTaskNamesProvider"/*, timeOut=Asserts.THIRTY_SECONDS_TIMEOUT_MS*/)
public void testFailedReleaseableUnblocks(final ConfigKey<Boolean> latch, List<String> _ignored) throws Exception {
    LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation(ImmutableMap.of("address", "127.0.0.1"));

    final int maxConcurrency = 1;
    final ReleaseableLatch latchSemaphore = ReleaseableLatch.Factory.newMaxConcurrencyLatch(maxConcurrency);
    final AttributeSensor<Object> latchSensor = Sensors.newSensor(Object.class, "latch");
    final CountingLatch countingLatch = new CountingLatch(latchSemaphore, maxConcurrency);
    // FIRST_MEMBER_SPEC latches are not guaranteed to be acquired before MEMBER_SPEC latches
    // so the start effector could complete, but the counting latch will catch if there are
    // any unreleased semaphores.
    @SuppressWarnings({"unused"})
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.INITIAL_SIZE, 2)
            .configure(DynamicCluster.FIRST_MEMBER_SPEC, EntitySpec.create(FailingMyService.class)
                    .configure(ConfigKeys.newConfigKey(Object.class, latch.getName()), (Object)DependentConfiguration.attributeWhenReady(app, latchSensor)))
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(MyService.class)
                    .configure(ConfigKeys.newConfigKey(Object.class, latch.getName()), (Object)DependentConfiguration.attributeWhenReady(app, latchSensor))));
    app.sensors().set(latchSensor, countingLatch);
    final Task<Void> startTask = Entities.invokeEffector(app, app, MyService.START, ImmutableMap.of("locations", ImmutableList.of(loc)));
    //expected to fail but should complete quickly
    assertTrue(startTask.blockUntilEnded(Asserts.DEFAULT_LONG_TIMEOUT), "timeout waiting for start effector to complete");
    assertTrue(latch == SoftwareProcess.STOP_LATCH || startTask.isError());
    final Task<Void> stopTask = Entities.invokeEffector(app, app, MyService.STOP, ImmutableMap.<String, Object>of());
    //expected to fail but should complete quickly
    assertTrue(stopTask.blockUntilEnded(Asserts.DEFAULT_LONG_TIMEOUT), "timeout waiting for stop effector to complete");
    // stop task won't fail because the process stop failed; the error is ignored
    assertTrue(stopTask.isDone());
    assertEquals(countingLatch.getCounter(), 0);
    // Check we have actually used the latch
    assertNotEquals(countingLatch.getMaxCounter(), 0, "Latch not acquired at all");
    // In theory this is 0 < maxCnt <= maxConcurrency contract, but in practice
    // we should always reach the maximum due to the sleeps in CountingLatch.
    // Change if found to fail in the wild.
    assertEquals(countingLatch.getMaxCounter(), maxConcurrency);
}
 
Example #26
Source File: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void registerPortMappings(KubernetesSshMachineLocation machine, Entity entity, Service service) {
    PortForwardManager portForwardManager = (PortForwardManager) getManagementContext().getLocationRegistry()
            .getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
    List<ServicePort> ports = service.getSpec().getPorts();
    String publicHostText = machine.getSshHostAndPort().getHostText();
    LOG.debug("Recording port-mappings for container {} of {}: {}", machine, this, ports);

    for (ServicePort port : ports) {
        String protocol = port.getProtocol();
        Integer targetPort = port.getTargetPort().getIntVal();

        if (!"TCP".equalsIgnoreCase(protocol)) {
            LOG.debug("Ignoring port mapping {} for {} because only TCP is currently supported", port, machine);
        } else if (targetPort == null) {
            LOG.debug("Ignoring port mapping {} for {} because targetPort.intValue is null", port, machine);
        } else if (port.getNodePort() == null) {
            LOG.debug("Ignoring port mapping {} to {} because port.getNodePort() is null", targetPort, machine);
        } else {
            portForwardManager.associate(publicHostText, HostAndPort.fromParts(publicHostText, port.getNodePort()), machine, targetPort);
            AttributeSensor<Integer> sensor = Sensors.newIntegerSensor("kubernetes." + Strings.maybeNonBlank(port.getName()).or(targetPort.toString()) + ".port");
            entity.sensors().set(sensor, targetPort);
        }
    }

    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(AbstractOnNetworkEnricher.MAP_MATCHING, "kubernetes.[a-zA-Z0-9][a-zA-Z0-9-_]*.port"));
}
 
Example #27
Source File: PercentageEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testLong() {
    AttributeSensor<Long> currentSensor = new BasicAttributeSensor<Long>(Long.class, "current");
    AttributeSensor<Long> totalSensor = new BasicAttributeSensor<Long>(Long.class, "total");

    app.enrichers().add(EnricherSpec.create(PercentageEnricher.class)
            .configure(PercentageEnricher.SOURCE_CURRENT_SENSOR, currentSensor)
            .configure(PercentageEnricher.SOURCE_TOTAL_SENSOR, totalSensor)
            .configure(PercentageEnricher.TARGET_SENSOR, targetSensor)
    );

    app.sensors().set(currentSensor, 25l);
    app.sensors().set(totalSensor, 50l);
    EntityAsserts.assertAttributeEqualsEventually(app, targetSensor, 0.5d);
}
 
Example #28
Source File: DependentConfiguration.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public Task<V2> build() {
    List<Task<V>> tasks = MutableList.of();
    for (AttributeAndSensorCondition<?> source: multiSource) {
        builder.source(source.source);
        builder.sensor((AttributeSensor)source.sensor);
        builder.readiness((Predicate)source.predicate);
        tasks.add(builder.build());
    }
    final Task<List<V>> parallelTask = Tasks.<List<V>>builder().parallel(true).addAll(tasks)
        .displayName(name)
        .description(descriptionBase+
            (builder.timeout!=null ? ", timeout "+builder.timeout : ""))
        .build();
    
    if (postProcessFromMultiple == null) {
        // V2 should be the right type in normal operations
        return (Task<V2>) parallelTask;
    } else {
        return Tasks.<V2>builder().displayName(name).description(descriptionBase)
            .tag("attributeWhenReady")
            .body(new Callable<V2>() {
                @Override public V2 call() throws Exception {
                    List<V> prePostProgress = DynamicTasks.queue(parallelTask).get();
                    return DynamicTasks.queue(
                        Tasks.<V2>builder().displayName("post-processing").description("Applying "+postProcessFromMultiple)
                            .body(Functionals.callable(postProcessFromMultiple, prePostProgress))
                            .build()).get();
                }
            })
            .build();
    }
}
 
Example #29
Source File: ChefAttributeFeed.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onException(Exception exception) {
    log.error("Detected exception while retrieving Chef attributes from entity " + entity.getDisplayName(), exception);
    for (AttributeSensor<?> attribute : chefAttributeSensors.values()) {
        if (!attribute.getName().startsWith(CHEF_ATTRIBUTE_PREFIX))
            continue;
        entity.sensors().set(attribute, null);
    }
}
 
Example #30
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatorDefaultsToProducerAsSelf() throws Exception {
    AttributeSensor<String> sourceSensor = Sensors.newSensor(String.class, "mySensor");
    AttributeSensor<String> targetSensor = Sensors.newSensor(String.class, "myTarget");

    app.enrichers().add(EnricherSpec.create(Propagator.class)
            .configure(Propagator.PRODUCER, app)
            .configure(Propagator.SENSOR_MAPPING, ImmutableMap.of(sourceSensor, targetSensor)));

    app.sensors().set(sourceSensor, "myval");
    EntityAsserts.assertAttributeEqualsEventually(app, targetSensor, "myval");
}