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

The following examples show how to use org.apache.brooklyn.api.sensor.EnricherSpec. 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: RebindEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeFractionDeltaEnricher() throws Exception {
    origApp.enrichers().add(EnricherSpec.create(TimeFractionDeltaEnricher.class)
            .configure("producer", origApp)
            .configure("source", INT_METRIC)
            .configure("target", DOUBLE_METRIC)
            .configure("durationPerOrigUnit", Duration.millis(1)));
    
    final TestApplication newApp = rebind();

    // TODO When doing two setAttributes in rapid succession, the test sometimes fails;
    // my hypothesis is that the two events had exactly the same timestamp.
    Asserts.succeedsEventually(new Runnable() {
        private int counter;
        @Override
        public void run() {
            newApp.sensors().set(INT_METRIC, counter++);
            assertNotNull(newApp.getAttribute(DOUBLE_METRIC));
        }});
}
 
Example #2
Source File: CampInternalUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static EnricherSpec<?> createEnricherSpec(BrooklynClassLoadingContext loader, Object enricher, Set<String> encounteredCatalogTypes) {
    Map<String, Object> itemMap;
    if (enricher instanceof String) {
        itemMap = ImmutableMap.<String, Object>of("type", enricher);
    } else if (enricher instanceof Map) {
        itemMap = (Map<String, Object>) enricher;
    } else {
        throw new IllegalStateException("Enricher expected to be string or map. Unsupported object type " + enricher.getClass().getName() + " (" + enricher.toString() + ")");
    }

    String versionedId = (String) checkNotNull(Yamls.getMultinameAttribute(itemMap, "enricher_type", "enricherType", "type"), "enricher type");
    EnricherSpec<? extends Enricher> spec = resolveEnricherSpec(versionedId, loader, encounteredCatalogTypes);
    initConfigAndParameters(spec, itemMap, loader);
    return spec;
}
 
Example #3
Source File: ServiceFailureDetectorStabilizationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration") // Because slow
public void testFailuresThenUpDownResetsStabilisationCount() throws Exception {
    LOG.debug("Running testFailuresThenUpDownResetsStabilisationCount");
    final long stabilisationDelay = 1000;
    
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
            .configure(ServiceFailureDetector.ENTITY_FAILED_STABILIZATION_DELAY, Duration.of(stabilisationDelay)));
    
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD));

    e1.sensors().set(TestEntity.SERVICE_UP, true);
    Thread.sleep(OVERHEAD);
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD));
    
    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
}
 
Example #4
Source File: CampInternalUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static EnricherSpec<? extends Enricher> resolveEnricherSpec(
        String versionedId,
        BrooklynClassLoadingContext loader,
        Set<String> encounteredCatalogTypes) {

    EnricherSpec<? extends Enricher> spec;
    RegisteredType item = loader.getManagementContext().getTypeRegistry().get(
        CatalogUpgrades.getTypeUpgradedIfNecessary(loader.getManagementContext(), versionedId));
    if (item != null && !encounteredCatalogTypes.contains(item.getSymbolicName())) {
        RegisteredTypeLoadingContext context = RegisteredTypeLoadingContexts.alreadyEncountered(encounteredCatalogTypes);
        return loader.getManagementContext().getTypeRegistry().createSpec(item, context, EnricherSpec.class);
    } else {
        // TODO-type-registry pass the loader in to the above, and allow it to load with the loader
        spec = EnricherSpec.create(loader.loadClass(versionedId, Enricher.class));
    }
    return spec;
}
 
Example #5
Source File: EntityConcurrencyTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrentAddEnricher() throws Exception {
    final int NUM_TASKS = 100;
    
    int numPreEnrichers = entity.enrichers().size();
    
    List<ListenableFuture<?>> futures = Lists.newArrayList();
    
    for (int i = 0; i < NUM_TASKS; i++) {
        ListenableFuture<?> future = executor.submit(new Runnable() {
            @Override public void run() {
                entity.enrichers().add(EnricherSpec.create(BasicEnricherTest.MyEnricher.class));
            }});
        futures.add(future);
    }

    Futures.allAsList(futures).get();
    
    assertEquals(entity.enrichers().size(), NUM_TASKS+numPreEnrichers);
}
 
Example #6
Source File: CatalogTransformer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** @deprecated since 0.12.0 use {@link RegisteredType} methods instead */  @Deprecated
public static CatalogEnricherSummary catalogEnricherSummary(BrooklynRestResourceUtils b, CatalogItem<? extends Enricher,EnricherSpec<?>> item, UriBuilder ub) {
    final Set<EnricherConfigSummary> config = Sets.newLinkedHashSet();
    try{
        final EnricherSpec<?> spec = (EnricherSpec<?>) b.getCatalog().peekSpec(item);
        AtomicInteger priority = new AtomicInteger();
        for (SpecParameter<?> input: spec.getParameters()) {
            config.add(ConfigTransformer.of(input).uiIncrementAndSetPriorityIfPinned(priority).transformLegacyEnricherConfig());
        }
    }catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.trace("Unable to create policy spec for "+item+": "+e, e);
    }
    return new CatalogEnricherSummary(item.getSymbolicName(), item.getVersion(), item.getContainingBundle(), item.getDisplayName(),
            item.getJavaType(), item.getCatalogItemType().toString(), item.getPlanYaml(),
            item.getDescription(), tidyIconLink(b, item, item.getIconUrl(), ub), config,
            item.tags().getTags(), item.isDeprecated(), makeLinks(item, ub));
}
 
Example #7
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultMapMatching() throws Exception {
    OnPublicNetworkEnricher enricher = entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class));
    String regex = enricher.getConfig(OnPublicNetworkEnricher.MAP_MATCHING);
    
    Map<String, Boolean> testCases = ImmutableMap.<String, Boolean>builder()
            .put("my.uri", true)
            .put("my.UrI", true)
            .put("my.url", true)
            .put("my.endpoint", true)
            .put("my.port", true)
            .put("port", true)
            .put("uri", true)
            .put("PREFIX_NO_DOTuri", false)
            .put("PREFIX_NO_DOTendpoint", false)
            .put("PREFIX_NO_DOTport", false)
            .put("portSUFFIX", false)
            .build();
    
    for (Map.Entry<String, Boolean> entry : testCases.entrySet()) {
        assertEquals(Boolean.valueOf(entry.getKey().matches(regex)), entry.getValue(), "input="+entry.getKey());
    }
}
 
Example #8
Source File: Enrichers.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public EnricherSpec<?> build() {
    return super.build().configure(MutableMap.builder()
                    .putIfNotNull(Aggregator.PRODUCER, fromEntity)
                    .put(Aggregator.TARGET_SENSOR, publishing)
                    .putIfNotNull(Aggregator.SOURCE_SENSOR, aggregating)
                    .putIfNotNull(MapAggregator.KEY_SENSOR, keySensor)
                    .putIfNotNull(MapAggregator.VALUE_SENSOR, valueSensor)
                    .putIfNotNull(Aggregator.FROM_CHILDREN, fromChildren)
                    .putIfNotNull(Aggregator.FROM_MEMBERS, fromMembers)
                    .putIfNotNull(Aggregator.TRANSFORMATION, computingSupplier.get())
                    .putIfNotNull(Aggregator.FROM_HARDCODED_PRODUCERS, fromHardcodedProducers)
                    .putIfNotNull(Aggregator.EXCLUDE_BLANK, excludingBlank)
                    .putIfNotNull(Aggregator.ENTITY_FILTER, entityFilter)
                    .putIfNotNull(Aggregator.VALUE_FILTER, valueFilter)
                    .putIfNotNull(Aggregator.DEFAULT_MEMBER_VALUE, defaultValueForUnreportedSensors)
                    .build());
}
 
Example #9
Source File: TransformingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllowCyclicPublishing() throws Exception {
    app.enrichers().add(EnricherSpec.create(Transformer.class)
            .configure(Transformer.SOURCE_SENSOR, intSensorA)
            .configure(Transformer.TARGET_SENSOR, intSensorA)
            .configure(Transformer.ALLOW_CYCLIC_PUBLISHING, true)
            .configure(Transformer.TRANSFORMATION_FROM_VALUE, new Function<Integer, Object>() {
                @Override public Object apply(Integer input) {
                    if (input != null && input < 10) {
                        return input + 1;
                    } else {
                        return Entities.UNCHANGED;
                    }
                }}));

    app.sensors().set(intSensorA, 3);

    EntityAsserts.assertAttributeEqualsEventually(app, intSensorA, 10);
    EntityAsserts.assertAttributeEqualsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), app, intSensorA, 10);
}
 
Example #10
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnricherSpecPropagatesSpecificSensor() throws Exception {
    app.enrichers().add(EnricherSpec.create(Propagator.class)
            .configure(MutableMap.builder()
                    .putIfNotNull(Propagator.PRODUCER, entity)
                    .putIfNotNull(Propagator.PROPAGATING, ImmutableList.of(TestEntity.NAME))
                    .build()));

    // name propagated
    entity.sensors().set(TestEntity.NAME, "foo");
    EntityAsserts.assertAttributeEqualsEventually(app, TestEntity.NAME, "foo");
    
    // sequence not propagated
    entity.sensors().set(TestEntity.SEQUENCE, 2);
    EntityAsserts.assertAttributeEqualsContinually(MutableMap.of("timeout", 100), app, TestEntity.SEQUENCE, null);
}
 
Example #11
Source File: ReducerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicReducer(){
    entity.enrichers().add(EnricherSpec.create(Reducer.class).configure(
            MutableMap.of(
            Reducer.SOURCE_SENSORS, ImmutableList.of(STR1, STR2),
            Reducer.PRODUCER, entity,
            Reducer.TARGET_SENSOR, STR3,
            Reducer.REDUCER_FUNCTION, new Concatenator())
        )
    );

    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 #12
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotifiedOfRecovery() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));
    
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    // Make the entity fail
    e1.sensors().set(TestEntity.SERVICE_UP, false);

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);

    // And make the entity recover
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    assertHasEventEventually(HASensors.ENTITY_RECOVERED, Predicates.<Object>equalTo(e1), null);
    assertEquals(events.size(), 2, "events="+events);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example #13
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration") // Has a 1 second wait
public void testOnFireAfterDelay() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
        .configure(ServiceFailureDetector.SERVICE_ON_FIRE_STABILIZATION_DELAY, Duration.ONE_SECOND));
    
    // Make the entity fail
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(e1, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    
    e1.sensors().set(TestEntity.SERVICE_UP, false);

    assertEquals(e1.getAttribute(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
    Time.sleep(Duration.millis(100));
    assertEquals(e1.getAttribute(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
}
 
Example #14
Source File: RebindEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeWeightedDeltaEnricher() throws Exception {
    origApp.enrichers().add(EnricherSpec.create(TimeWeightedDeltaEnricher.class)
            .configure("producer", origApp)
            .configure("source", INT_METRIC)
            .configure("target", DOUBLE_METRIC)
            .configure("unitMillis", 1000));
    
    final TestApplication newApp = rebind();

    // TODO When doing two setAttributes in rapid succession, the test sometimes fails;
    // my hypothesis is that the two events had exactly the same timestamp.
    Asserts.succeedsEventually(new Runnable() {
        private int counter;
        @Override
        public void run() {
            newApp.sensors().set(INT_METRIC, counter++);
            assertNotNull(newApp.getAttribute(DOUBLE_METRIC));
        }});
}
 
Example #15
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 #16
Source File: DeltaEnrichersTests.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testVariableTimeWeightedDeltaEnricher() {
    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));
    
    delta.onEvent(intSensor.newEvent(producer, 0), 1000);
    delta.onEvent(intSensor.newEvent(producer, 0), 3000);
    assertEquals(producer.getAttribute(deltaSensor), 0d);
    delta.onEvent(intSensor.newEvent(producer, 3), 6000);
    assertEquals(producer.getAttribute(deltaSensor), 1d);
    delta.onEvent(intSensor.newEvent(producer, 7), 8000);
    assertEquals(producer.getAttribute(deltaSensor), 2d);
    delta.onEvent(intSensor.newEvent(producer, 12), 8500);
    assertEquals(producer.getAttribute(deltaSensor), 10d);
    delta.onEvent(intSensor.newEvent(producer, 15), 10500);
    assertEquals(producer.getAttribute(deltaSensor), 1.5d);
}
 
Example #17
Source File: UpdatingMapTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotRemovingIfResultIsNull() throws Exception {
    Entity entity = app.createAndManageChild(EntitySpec.create(BasicApplication.class)
            .enricher(EnricherSpec.create(UpdatingMap.class)
                    .configure(UpdatingMap.SOURCE_SENSOR.getName(), mySensor.getName())
                    .configure(UpdatingMap.TARGET_SENSOR, mapSensor)
                    .configure(UpdatingMap.REMOVING_IF_RESULT_IS_NULL, false)
                    .configure(UpdatingMap.COMPUTING, Functions.forMap(MutableMap.of("v1", "valIsV1"), null))));

    
    entity.sensors().set(mySensor, "v1");
    EntityAsserts.assertAttributeEqualsEventually(entity, mapSensor, ImmutableMap.of("mySensor", "valIsV1"));

    entity.sensors().set(mySensor, "different");
    EntityAsserts.assertAttributeEqualsEventually(entity, mapSensor, MutableMap.of("mySensor", null));
}
 
Example #18
Source File: YamlTimeWeightedDeltaEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * TODO BROOKLYN-272, Disabled, because fails non-deterministically in jenkins (e.g. brooklyn-server-pull-requests # 732)
 * 
 * The problem is that the enricher's subscription uses "notifyOfInitialValue", 
 * so another thread will execute with that value. If the other thread executes after we've 
 * done onEvent(2000), but before we do the assertion, then the test will fail (because the 
 * other thread will have set the sensor's initial value to null).
 * 
 * This is just an issue with the way we've written the test, rather than for production
 * usage. In production, all events would go to the enricher sequentially.
 * 
 * We wrote the test like this because we want to inject specific timestamps.
 * We *could* refactor LocalSubscriptionManager to be configured with a 
 * {@link com.google.common.base.Ticker} that we can explicitly supply and configure.
 * That's a bigger change than I'd like to make right at this moment!
 */
@Test(groups={"Broken"})
public void testMonospaceTimeWeightedDeltaEnricher() {
    @SuppressWarnings("unchecked")
    YamlTimeWeightedDeltaEnricher<Integer> delta = producer.enrichers().add(EnricherSpec.create(YamlTimeWeightedDeltaEnricher.class)
        .configure(YamlTimeWeightedDeltaEnricher.PRODUCER, producer)
        .configure(YamlTimeWeightedDeltaEnricher.SOURCE_SENSOR, intSensor)
        .configure(YamlTimeWeightedDeltaEnricher.TARGET_SENSOR, deltaSensor));
    
    delta.onEvent(newIntSensorEvent(0, 0));
    assertEquals(producer.getAttribute(deltaSensor), null);
    delta.onEvent(newIntSensorEvent(0, 1000));
    assertEquals(producer.getAttribute(deltaSensor), 0d);
    delta.onEvent(newIntSensorEvent(1, 2000));
    assertEquals(producer.getAttribute(deltaSensor), 1d);
    delta.onEvent(newIntSensorEvent(3, 3000));
    assertEquals(producer.getAttribute(deltaSensor), 2d);
    delta.onEvent(newIntSensorEvent(8, 4000));
    assertEquals(producer.getAttribute(deltaSensor), 5d);
}
 
Example #19
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public <T> void testDoesNotDoRegexMatchingWhenSensorsSpecified() throws Exception {
    AttributeSensor<String> sensor = Sensors.newStringSensor("mysensor");
    AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    entity.sensors().set(intPort, 1234);
    entity.sensors().set(sensor, "127.0.0.1:1234");
    portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(sensor)));

    assertAttributeEqualsEventually("mysensor.mapped.public", "mypublichost:5678");
    assertAttributeEqualsContinually("int.endpoint.mapped.public", null, VERY_SHORT_WAIT);
}
 
Example #20
Source File: HaPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceFailureDetectorWorksAfterRebind() throws Exception {
    origEntity.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));

    // rebind
    TestApplication newApp = rebind();
    final TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class));

    newApp.getManagementContext().getSubscriptionManager().subscribe(newEntity, HASensors.ENTITY_FAILED, eventListener);

    newEntity.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(newEntity, Lifecycle.RUNNING);
    
    // trigger the failure
    newEntity.sensors().set(TestEntity.SERVICE_UP, false);

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(newEntity), null);
    assertEquals(events.size(), 1, "events="+events);
}
 
Example #21
Source File: OnPublicNetworkEnricherRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public <T> void testRebind() throws Exception {
    origEntity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    
    origEntity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(Attributes.MAIN_URI)));

    rebind();
    TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
    PortForwardManager newPortForwardManager = (PortForwardManager) mgmt().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
    SshMachineLocation newMachine = (SshMachineLocation) mgmt().getLocationManager().getLocation(origMachine.getId());
    
    newEntity.sensors().set(Attributes.MAIN_URI, URI.create("http://127.0.0.1:1234/my/path"));
    newPortForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), newMachine, 1234);
    newEntity.addLocations(ImmutableList.of(newMachine));
    
    EntityAsserts.assertAttributeEqualsEventually(newEntity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "http://mypublichost:5678/my/path");
}
 
Example #22
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotifiedOfRecoveryFromProblems() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));
    
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    // Make the entity fail
    ServiceProblemsLogic.updateProblemsIndicator(e1, "test", "foo");

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);

    // And make the entity recover
    ServiceProblemsLogic.clearProblemsIndicator(e1, "test");
    assertHasEventEventually(HASensors.ENTITY_RECOVERED, Predicates.<Object>equalTo(e1), null);
    assertEquals(events.size(), 2, "events="+events);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example #23
Source File: OnSubnetNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public <T> void testTransformsAllMatchingSensors() throws Exception {
    AttributeSensor<URI> stronglyTypedUri = Sensors.newSensor(URI.class, "strongly.typed.uri");
    AttributeSensor<String> stringUri = Sensors.newStringSensor("string.uri");
    AttributeSensor<URL> stronglyTypedUrl = Sensors.newSensor(URL.class, "strongly.typed.url");
    AttributeSensor<String> stringUrl = Sensors.newStringSensor("string.url");
    AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port");
    AttributeSensor<String> stringPort = Sensors.newStringSensor("string.port");
    AttributeSensor<HostAndPort> hostAndPort = Sensors.newSensor(HostAndPort.class, "hostAndPort.endpoint");
    AttributeSensor<String> stringHostAndPort = Sensors.newStringSensor("stringHostAndPort.endpoint");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, privateIp);
    entity.sensors().set(stronglyTypedUri, URI.create("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(stringUri, "http://"+publicIp+":1234/my/path");
    entity.sensors().set(stronglyTypedUrl, new URL("http://"+publicIp+":1234/my/path"));
    entity.sensors().set(stringUrl, "http://"+publicIp+":1234/my/path");
    entity.sensors().set(intPort, 1234);
    entity.sensors().set(stringPort, "1234");
    entity.sensors().set(hostAndPort, HostAndPort.fromParts(""+publicIp+"", 1234));
    entity.sensors().set(stringHostAndPort, ""+publicIp+":1234");
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnSubnetNetworkEnricher.class));

    assertAttributeEqualsEventually("strongly.typed.uri.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("string.uri.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("strongly.typed.url.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("string.url.mapped.subnet", "http://"+privateIp+":1234/my/path");
    assertAttributeEqualsEventually("int.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("string.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("hostAndPort.endpoint.mapped.subnet", ""+privateIp+":1234");
    assertAttributeEqualsEventually("stringHostAndPort.endpoint.mapped.subnet", ""+privateIp+":1234");
}
 
Example #24
Source File: TimeFractionDeltaEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConverts100NanosTimeBlocks() {
    @SuppressWarnings("unchecked")
    TimeFractionDeltaEnricher<Integer> enricher = producer.enrichers().add(EnricherSpec.create(TimeFractionDeltaEnricher.class)
            .configure("producer", producer)
            .configure("source", intSensor)
            .configure("target", fractionSensor)
            .configure("durationPerOrigUnit", Duration.nanos(100)));
    
    enricher.onEvent(new BasicSensorEvent<Integer>(intSensor, producer, 0, 1000000L));
    enricher.onEvent(new BasicSensorEvent<Integer>(intSensor, producer, 10000000, 1001000L));
    assertEquals(producer.getAttribute(fractionSensor), 1d);
}
 
Example #25
Source File: ServiceFailureDetectorStabilizationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration") // Because slow
public void testNotifiedOfRecoveryAfterStabilisationDelay() throws Exception {
    final int stabilisationDelay = 1000;
    
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
            .configure(ServiceFailureDetector.ENTITY_RECOVERED_STABILIZATION_DELAY, Duration.of(stabilisationDelay)));
    
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
    events.clear();

    e1.sensors().set(TestEntity.SERVICE_UP, true);
    assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD));
    assertHasEventEventually(HASensors.ENTITY_RECOVERED, Predicates.<Object>equalTo(e1), null);
}
 
Example #26
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnricherSpecThrowsOnPropagatesAndPropagatesAllSet() throws Exception {
    try {
        app.enrichers().add(EnricherSpec.create(Propagator.class)
                .configure(MutableMap.builder()
                        .put(Propagator.PRODUCER, entity)
                        .put(Propagator.PROPAGATING, ImmutableList.of(TestEntity.NAME))
                        .put(Propagator.PROPAGATING_ALL, true)
                        .build()));
    } catch (Exception e) {
        IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class);
        if (ise == null) throw e;
    }
}
 
Example #27
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testReportsFailureWhenAlreadyDownOnRegisteringPolicy() throws Exception {
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    e1.sensors().set(TestEntity.SERVICE_UP, false);

    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
        .configure(ServiceFailureDetector.ENTITY_FAILED_ONLY_IF_PREVIOUSLY_UP, false));

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
}
 
Example #28
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * The sensorVal must include port 1234, so that it will be converted to mypublichost:5678
 */
@Test(dataProvider = "variants")
public <T> void testSensorTransformed(Timing setUri, Timing createAssociation, Timing addLocation, 
        AttributeSensor<T> sensor, T sensorVal, String targetSensorName, String expectedVal) throws Exception {
    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    if (setUri == Timing.BEFORE) {
        entity.sensors().set(sensor, sensorVal);
    }
    if (createAssociation == Timing.BEFORE) {
        portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
    }
    if (addLocation == Timing.BEFORE) {
        entity.addLocations(ImmutableList.of(machine));
    }
    
    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(sensor)));

    if (setUri == Timing.AFTER) {
        entity.sensors().set(sensor, sensorVal);
    }
    if (createAssociation == Timing.AFTER) {
        portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
    }
    if (addLocation == Timing.AFTER) {
        entity.addLocations(ImmutableList.of(machine));
    }
    
    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(targetSensorName), expectedVal);
    EntityAsserts.assertAttributeEquals(entity, sensor, sensorVal);
}
 
Example #29
Source File: EnricherConfigTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigCannotBeSetAfterApplicationIsStarted() throws Exception {
    MyEnricher enricher = app.enrichers().add(EnricherSpec.create(MyEnricher.class)
            .configure(MyEnricher.STR_KEY, "origval"));
    
    try {
        enricher.config().set(MyEnricher.STR_KEY,"newval");
        fail();
    } catch (UnsupportedOperationException e) {
        // success
    }
    
    assertEquals(enricher.getConfig(MyEnricher.STR_KEY), "origval");
}
 
Example #30
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public <T> void testTransformsToAddressInSensor() throws Exception {
    AttributeSensor<String> stringUri = Sensors.newStringSensor("string.uri");

    entity.sensors().set(Attributes.ADDRESS, "1.1.1.1");
    entity.sensors().set(stringUri, "http://127.0.0.1:1234/my/path");
    entity.addLocations(ImmutableList.of(machine));

    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.ADDRESS_SENSOR, Attributes.ADDRESS));

    assertAttributeEqualsEventually("string.uri.mapped.public", "http://1.1.1.1:1234/my/path");
}