org.apache.brooklyn.core.sensor.Sensors Java Examples

The following examples show how to use org.apache.brooklyn.core.sensor.Sensors. 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: ElectPrimaryPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(@SuppressWarnings("deprecation") org.apache.brooklyn.api.entity.EntityLocal entity) {
    super.setEntity(entity);
    
    checkAndMaybeAddEffector(entity);
    checkQuorums(entity);
    
    Collection<? extends Object> sensorsToPropagate = config().get(PROPAGATE_PRIMARY_SENSORS);
    if (sensorsToPropagate!=null) {
        List<Sensor<?>> realSensors = MutableList.of();
        for (Object s: sensorsToPropagate) {
            if (s instanceof String) s = Sensors.newSensor(Object.class, (String) s);
            if (s instanceof Sensor) {
                realSensors.add((Sensor<?>)s);
            } else {
                throw new IllegalArgumentException("Config "+PROPAGATE_PRIMARY_SENSORS.getName()+" had invalid entry "
                    + "'"+s+"'; expected string or sensor");
            }
        }
        entity.enrichers().add(EnricherSpec.create(PropagatePrimaryEnricher.class)
            .configure(PropagatePrimaryEnricher.PROPAGATING, realSensors));
    }
    
    addSubscriptions(entity);
    rescanRequest("policy initialization");
}
 
Example #2
Source File: InvokeEffectorOnCollectionSensorChangeTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapValueUsedAsArgumentDirectly() {
    @SuppressWarnings("serial")
    AttributeSensor<Collection<Map<String, String>>> sensor = Sensors.newSensor(new TypeToken<Collection<Map<String, String>>>() {},
            "testMapValueUsedAsArgumentDirectly");
    final Set<Map<String, String>> input1 = ImmutableSet.<Map<String, String>>of(
            ImmutableMap.of("a", "1"),
            ImmutableMap.of("b", "2"));
    final Set<Map<String, String>> input2 = ImmutableSet.<Map<String, String>>of(
            ImmutableMap.of("b", "2"),
            ImmutableMap.of("c", "3"),
            ImmutableMap.of("d", "4"));

    testEntity.sensors().set(sensor, input1);
    addSetChangePolicy(sensor, true, true);

    testEntity.sensors().set(sensor, input2);
    Asserts.eventually(new ConfigBagMapSupplier(onAddedParameters),
            Predicates.<Collection<Map<String, Object>>>equalTo(ImmutableSet.<Map<String, Object>>of(
                    ImmutableMap.<String, Object>of("c", "3"),
                    ImmutableMap.<String, Object>of("d", "4"))));
    Asserts.eventually(new ConfigBagMapSupplier(onRemovedParameters),
            Predicates.<Collection<Map<String, Object>>>equalTo(ImmutableSet.<Map<String, Object>>of(
                    ImmutableMap.<String, Object>of("a", "1"))));

}
 
Example #3
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public <T> void testIgnoresNonMatchingSensors() throws Exception {
    AttributeSensor<URI> sensor1 = Sensors.newSensor(URI.class, "my.different");
    AttributeSensor<URL> sensor2 = Sensors.newSensor(URL.class, "my.different2");
    AttributeSensor<String> sensor3 = Sensors.newStringSensor("my.different3");
    AttributeSensor<Integer> sensor4 = Sensors.newIntegerSensor("my.different4");
    AttributeSensor<HostAndPort> sensor5 = Sensors.newSensor(HostAndPort.class, "my.different5");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    entity.sensors().set(sensor1, URI.create("http://127.0.0.1:1234/my/path"));
    entity.sensors().set(sensor2, new URL("http://127.0.0.1:1234/my/path"));
    entity.sensors().set(sensor3, "http://127.0.0.1:1234/my/path");
    entity.sensors().set(sensor4, 1234);
    entity.sensors().set(sensor5, HostAndPort.fromParts("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));

    Map<AttributeSensor<?>, Object> allSensors = entity.sensors().getAll();
    String errMsg = "sensors="+allSensors;
    for (AttributeSensor<?> sensor : allSensors.keySet()) {
        String name = sensor.getName();
        assertFalse(name.startsWith("my.different") && sensor.getName().contains("public"), errMsg);
    }
}
 
Example #4
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 #5
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Assumes that the {@link DockerContainer} entities have display names of "mysql" and "wordpress",
 * and that they use ports 3306 and 80 respectively.
 */
protected void runWordpress(String yaml, String randomId) throws Exception {
    Entity app = createStartWaitAndLogApplication(yaml);
    Entities.dumpInfo(app);

    Iterable<DockerContainer> containers = Entities.descendantsAndSelf(app, DockerContainer.class);
    DockerContainer mysql = Iterables.find(containers, EntityPredicates.displayNameEqualTo("mysql"));
    DockerContainer wordpress = Iterables.find(containers, EntityPredicates.displayNameEqualTo("wordpress"));

    String mysqlPublicPort = assertAttributeEventuallyNonNull(mysql, Sensors.newStringSensor("docker.port.3306.mapped.public"));
    assertReachableEventually(HostAndPort.fromString(mysqlPublicPort));
    assertAttributeEquals(mysql, KubernetesPod.KUBERNETES_NAMESPACE, "brooklyn");
    assertAttributeEquals(mysql, KubernetesPod.KUBERNETES_SERVICE, "wordpress-mysql-" + randomId);

    String wordpressPublicPort = assertAttributeEventuallyNonNull(wordpress, Sensors.newStringSensor("docker.port.80.mapped.public"));
    assertReachableEventually(HostAndPort.fromString(wordpressPublicPort));
    assertAttributeEquals(wordpress, KubernetesPod.KUBERNETES_NAMESPACE, "brooklyn");
    assertAttributeEquals(wordpress, KubernetesPod.KUBERNETES_SERVICE, "wordpress-" + randomId);

    // TODO more assertions (e.g. wordpress can successfully reach the database)
}
 
Example #6
Source File: ConfigYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeferredSupplierToAttributeWhenReady() throws Exception {
    String yaml = Joiner.on("\n").join(
            "services:",
            "- type: org.apache.brooklyn.core.test.entity.TestEntity",
            "  brooklyn.config:",
            "    test.confName: $brooklyn:attributeWhenReady(\"myOtherSensor\")");

    final Entity app = createStartWaitAndLogApplication(yaml);
    final TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());

    // Attribute not yet set; non-blocking will return promptly without the value
    assertTrue(entity.config().getNonBlocking(TestEntity.CONF_NAME).isAbsent());

    // Now set the attribute: get will return once that has happened
    executor.submit(new Callable<Object>() {
        @Override
        public Object call() {
            return entity.sensors().set(Sensors.newStringSensor("myOtherSensor"), "myOther");
        }});
    assertEquals(entity.config().get(TestEntity.CONF_NAME), "myOther");

    // Non-blocking calls will now return with the value
    assertEquals(entity.config().getNonBlocking(TestEntity.CONF_NAME).get(), "myOther");
}
 
Example #7
Source File: PrimaryRunningEnricher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    Entity primary = entity.getAttribute( Sensors.newSensor(Entity.class, config().get(PRIMARY_SENSOR_NAME)) );
    if (primary==null) {
        ServiceNotUpLogic.updateNotUpIndicator(entity, "primary.enricher", "no primary found");
        ServiceProblemsLogic.updateProblemsIndicator(entity, "primary.enricher", "no primary found");
    } else if (Lifecycle.RUNNING.equals(primary.getAttribute(Attributes.SERVICE_STATE_ACTUAL)) &&
            Boolean.TRUE.equals(primary.getAttribute(Attributes.SERVICE_UP))) {
        if (ServiceStateLogic.getMapSensorEntry(entity, Attributes.SERVICE_PROBLEMS, "primary.enricher")!=null) {
            log.info("Primary "+primary+" at "+entity+" detected as healthy");
            ServiceProblemsLogic.clearProblemsIndicator(entity, "primary.enricher");
            ServiceNotUpLogic.clearNotUpIndicator(entity, "primary.enricher");
        }
    } else {
        log.warn("Primary "+primary+" at "+entity+" detected as down or otherwise unhealthy");
        ServiceProblemsLogic.updateProblemsIndicator(entity, "primary.enricher", "Primary "+primary+" not in healthy state");
    }
}
 
Example #8
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 #9
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeferredDslAttributeFacadeCrossAppFails() throws Exception {
    final Entity app0 = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName());
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:attributeWhenReady(\"targetEntity\").attributeWhenReady(\"entity.id\")");
    AttributeSensor<Entity> targetEntitySensor = Sensors.newSensor(Entity.class, "targetEntity");
    app.sensors().set(targetEntitySensor, app0);
    try {
        getConfigEventually(app, DEST);
        Asserts.shouldHaveFailedPreviously("Cross-app DSL not allowed");
    } catch (ExecutionException e) {
        Asserts.expectedFailureContains(e, "not in scope 'global'");
    }
}
 
Example #10
Source File: DslAndRebindYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDslChildWhereIdRetrievedFromAttributeWhenReadyDsl() throws Exception {
    Entity testEntity = setupAndCheckTestEntityInBasicYamlWith(
            "  id: x",
            "  brooklyn.config:",
            "    test.confObject: $brooklyn:child(attributeWhenReady(\"mySensor\"))",
            "  brooklyn.children:",
            "  - type: " + TestEntity.class.getName(),
            "    id: x");
    Entity childEntity = Iterables.getOnlyElement(testEntity.getChildren());
    testEntity.sensors().set(Sensors.newStringSensor("mySensor"), "x");
    Assert.assertEquals(getConfigInTask(testEntity, TestEntity.CONF_OBJECT), childEntity);
    
    Entity e2 = rebind(testEntity);
    Entity child2 = Iterables.getOnlyElement(e2.getChildren());
    Assert.assertEquals(getConfigInTask(e2, TestEntity.CONF_OBJECT), child2);
}
 
Example #11
Source File: ApplicationResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public List<EntityDetail> fetch(String entityIds, String extraSensorsS) {
    List<String> extraSensorNames = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(extraSensorsS);
    List<AttributeSensor<?>> extraSensors = extraSensorNames.stream().map((s) -> Sensors.newSensor(Object.class, s)).collect(Collectors.toList());
    
    List<EntityDetail> entitySummaries = Lists.newArrayList();
    for (Entity application : mgmt().getApplications()) {
        entitySummaries.add(addSensorsByName((EntityDetail)fromEntity(application, false, -1, null, null), application, extraSensors));
    }

    if (Strings.isNonBlank(entityIds)) {
        List<String> extraEntities = JavaStringEscapes.unwrapOptionallyQuotedJavaStringList(entityIds);
        for (String entityId: extraEntities) {
            Entity entity = mgmt().getEntityManager().getEntity(entityId.trim());
            while (entity != null && entity.getParent() != null) {
                if (Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_ENTITY, entity)) {
                    entitySummaries.add(addSensorsByName((EntityDetail)fromEntity(entity, false, -1, null, null), entity, extraSensors));
                }
                entity = entity.getParent();
            }
        }
    }
    return entitySummaries;
}
 
Example #12
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 #13
Source File: SshCommandSensorYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSshCommandSensorWithEffectorInEnv() throws Exception {
    RecordingSshTool.setCustomResponse(".*myCommand.*", new RecordingSshTool.CustomResponse(0, "myResponse", null));
    
    Entity app = createAndStartApplication(
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName(),
        "services:",
        "- type: " + VanillaSoftwareProcess.class.getName(),
        "  brooklyn.config:",
        "    onbox.base.dir.skipResolution: true",
        "  brooklyn.initializers:",
        "  - type: org.apache.brooklyn.core.sensor.ssh.SshCommandSensor",
        "    brooklyn.config:",
        "      name: mySensor",
        "      command: myCommand",
        "      period: 10ms",
        "      onlyIfServiceUp: false");
    waitForApplicationTasks(app);

    VanillaSoftwareProcess entity = (VanillaSoftwareProcess) Iterables.getOnlyElement(app.getChildren());
    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor("mySensor"), "myResponse");
}
 
Example #14
Source File: SoftwareProcessEntityLatchTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void doTestLatchBlocks(ConfigKey<Boolean> latch, List<String> preLatchEvents, Object latchValue, Function<? super MyService, Void> customAssertFn) throws Exception {
    final AttributeSensor<Object> latchSensor = Sensors.newSensor(Object.class, "latch");
    final MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
            .configure(ConfigKeys.newConfigKey(Object.class, latch.getName()), (Object)DependentConfiguration.attributeWhenReady(app, latchSensor)));

    final Task<Void> task;
    final Task<Void> startTask = Entities.invokeEffector(app, app, MyService.START, ImmutableMap.of("locations", ImmutableList.of(loc)));
    if (latch != SoftwareProcess.STOP_LATCH) {
        task = startTask;
    } else {
        startTask.get(Duration.THIRTY_SECONDS);
        task = Entities.invokeEffector(app, app, MyService.STOP);
    }

    assertEffectorBlockingDetailsEventually(entity, task.getDisplayName(), "Waiting for config " + latch.getName());
    assertDriverEventsEquals(entity, preLatchEvents);
    assertFalse(task.isDone());

    app.sensors().set(latchSensor, latchValue);

    customAssertFn.apply(entity);

    task.get(Duration.THIRTY_SECONDS);
    assertDriverEventsEquals(entity, getLatchPostTasks(latch));
}
 
Example #15
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnricherSpecPropagatesSpecificSensorAndMapsOthers() throws Exception {
    final AttributeSensor<String> ANOTHER_ATTRIBUTE = Sensors.newStringSensor("another.attribute", "");
    
    app.enrichers().add(EnricherSpec.create(Propagator.class)
            .configure(MutableMap.builder()
                    .putIfNotNull(Propagator.PRODUCER, entity)
                    .putIfNotNull(Propagator.SENSOR_MAPPING, ImmutableMap.of(TestEntity.NAME, ANOTHER_ATTRIBUTE))
                    .putIfNotNull(Propagator.PROPAGATING, ImmutableList.of(TestEntity.SEQUENCE))
                    .build()));

    // name propagated as alternative sensor
    entity.sensors().set(TestEntity.NAME, "foo");
    EntityAsserts.assertAttributeEqualsEventually(app, ANOTHER_ATTRIBUTE, "foo");
    
    // sequence also propagated
    entity.sensors().set(TestEntity.SEQUENCE, 2);
    EntityAsserts.assertAttributeEqualsEventually(app, TestEntity.SEQUENCE, 2);

    // name not propagated as original sensor
    EntityAsserts.assertAttributeEqualsContinually(MutableMap.of("timeout", 100), app, TestEntity.NAME, null);
}
 
Example #16
Source File: AbstractEntity.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Map<AttributeSensor<?>, Object> getAll() {
    Map<AttributeSensor<?>, Object> result = Maps.newLinkedHashMap();
    Map<String, Object> attribs = attributesInternal.asMap();
    for (Map.Entry<String,Object> entry : attribs.entrySet()) {
        AttributeSensor<?> attribKey = (AttributeSensor<?>) entityType.getSensor(entry.getKey());
        if (attribKey == null) {
            // Most likely a race: e.g. persister thread calling getAllAttributes; writer thread
            // has written attribute value and is in process of calling entityType.addSensorIfAbsent(attribute)
            // Just use a synthetic AttributeSensor, rather than ignoring value.
            // TODO If it's not a race, then don't log.warn every time!
            LOG.warn("When retrieving all attributes of {}, no AttributeSensor for attribute {} (creating synthetic)", AbstractEntity.this, entry.getKey());
            attribKey = Sensors.newSensor(Object.class, entry.getKey());
        }
        result.put(attribKey, entry.getValue());
    }
    return result;
}
 
Example #17
Source File: WindowsPerformanceCounterSensorsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRebind() throws Exception {
    String response = generateCounterReponse("mycounter", "myval");
    RecordingWinRmTool.setCustomResponse(".*mycounter.*", new RecordingWinRmTool.CustomResponse(0, response, ""));
            
    Entity entity = app().createAndManageChild(EntitySpec.create(TestEntity.class)
            .addInitializer(new WindowsPerformanceCounterSensors(ConfigBag.newInstance(ImmutableMap.of(
                    WindowsPerformanceCounterSensors.PERIOD, "1ms",
                    WindowsPerformanceCounterSensors.PERFORMANCE_COUNTERS, ImmutableSet.of(
                            ImmutableMap.of(
                                    "name", "mysensor",
                                    "sensorType", java.lang.String.class.getName(), //FIXME
                                    "counter", "\\mycounter")))))));
    
    app().start(ImmutableList.of(loc));
    
    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor("mysensor"), "myval");
    
    rebind();
    
    String response2 = generateCounterReponse("mycounter", "myval2");
    RecordingWinRmTool.setCustomResponse(".*mycounter.*", new RecordingWinRmTool.CustomResponse(0, response2, ""));
    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor("mysensor"), "myval2");
}
 
Example #18
Source File: SensorSummaryTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSensorWithMultipleOpenUrlActionsRegistered() throws IOException {
    AttributeSensor<String> sensor = Sensors.newStringSensor("sensor1");
    entity.sensors().set(sensor, "http://myval");
    RendererHints.register(sensor, RendererHints.namedActionWithUrl());
    RendererHints.register(sensor, RendererHints.namedActionWithUrl());

    SensorSummary summary = SensorTransformer.sensorSummary(entity, sensor, UriBuilder.fromPath("/"));

    assertEquals(summary.getLinks().get("action:open"), URI.create("http://myval"));
}
 
Example #19
Source File: PropagatePrimaryEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void onEvent(SensorEvent<Object> event) {
    Entity primary = entity.getAttribute( Sensors.newSensor(Entity.class, config().get(PRIMARY_SENSOR_NAME)) );
    final Entity lastPrimary = config().get(CURRENT_PROPAGATED_PRODUCER);
    if (!Objects.equal(primary, lastPrimary)) {
        log.debug("Removing propagated items from "+lastPrimary+" at "+entity);
        
        final Propagator propagator = getManagementContext().lookup(config().get(CURRENT_PROPAGATOR_ID), Propagator.class);
        // remove propagator
        if (propagator!=null) {
            entity.enrichers().remove(propagator);
            config().set(CURRENT_PROPAGATOR_ID, (String)null);
        }
        
        // remove propagated sensors
        Collection<? extends Sensor<?>> sensorsToRemove = config().get(PROPAGATING);
        if (sensorsToRemove!=null) {
            for (Sensor<?> s: sensorsToRemove) {
                // TODO - allow strings above also
                if (s instanceof AttributeSensor) {
                    ((EntityInternal)entity).sensors().remove((AttributeSensor<?>)s);
                }
            }
        }            
        
        if (primary!=null) {
            config().set(CURRENT_PROPAGATED_PRODUCER, primary);
            
            // add propagator
            addPropagatorEnricher(primary);
        }
    }
}
 
Example #20
Source File: KubernetesLocationYamlLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Live"})
public void testNetcatServer() throws Exception {
    // Runs as root user (hence not `sudo yum install ...`)
    // breaks if shell.env uses attributeWhenReady, so not doing that - see testNetcatServerWithDslInShellEnv()
    String yaml = Joiner.on("\n").join(
            locationYaml,
            "services:",
            "  - type: " + VanillaSoftwareProcess.class.getName(),
            "    brooklyn.parameters:",
            "      - name: netcat.port",
            "        type: port",
            "        default: 8081",
            "    brooklyn.config:",
            "      install.command: |",
            "        yum install -y nc",
            "      launch.command: |",
            "        echo $MESSAGE | nc -l $NETCAT_PORT &",
            "        echo $! > $PID_FILE",
            "      shell.env:",
            "        MESSAGE: mymessage",
            "        NETCAT_PORT: $brooklyn:attributeWhenReady(\"netcat.port\")",
            "    brooklyn.enrichers:",
            "      - type: " + OnPublicNetworkEnricher.class.getName(),
            "        brooklyn.config:",
            "          " + OnPublicNetworkEnricher.SENSORS.getName() + ":",
            "            - netcat.port");

    Entity app = createStartWaitAndLogApplication(yaml);
    VanillaSoftwareProcess entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, VanillaSoftwareProcess.class));

    String publicMapped = assertAttributeEventuallyNonNull(entity, Sensors.newStringSensor("netcat.endpoint.mapped.public"));
    HostAndPort publicPort = HostAndPort.fromString(publicMapped);

    assertTrue(Networking.isReachable(publicPort), "publicPort=" + publicPort);
}
 
Example #21
Source File: DynamicGroupTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupDetectsChangedEntities() throws Exception {
    final AttributeSensor<String> MY_ATTRIBUTE = Sensors.newStringSensor("test.myAttribute", "My test attribute");
    
    group.setEntityFilter(EntityPredicates.attributeEqualTo(MY_ATTRIBUTE, "yes"));
    group.addSubscription(null, MY_ATTRIBUTE);
    
    assertEqualsIgnoringOrder(group.getMembers(), ImmutableSet.of());
    
    // When changed (such that subscription spots it), then entity added
    e1.sensors().set(MY_ATTRIBUTE, "yes");
    
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            assertEqualsIgnoringOrder(group.getMembers(), ImmutableSet.of(e1));
        }});

    // When it stops matching, entity is removed        
    e1.sensors().set(MY_ATTRIBUTE, "no");
    
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            assertEqualsIgnoringOrder(group.getMembers(), ImmutableSet.of());
        }});
}
 
Example #22
Source File: SensorPropagatingEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropagatingAsDifferentSensor() {
    final AttributeSensor<String> ANOTHER_ATTRIBUTE = Sensors.newStringSensor("another.attribute", "");
    
    app.enrichers().add(Enrichers.builder()
            .propagating(ImmutableMap.of(TestEntity.NAME, ANOTHER_ATTRIBUTE))
            .from(entity)
            .build());

    // name propagated as different attribute
    entity.sensors().set(TestEntity.NAME, "foo");
    EntityAsserts.assertAttributeEqualsEventually(app, ANOTHER_ATTRIBUTE, "foo");
}
 
Example #23
Source File: OnPublicNetworkEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public <T> void testTransformsDefaultHttps443() throws Exception {
    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    entity.sensors().set(Attributes.MAIN_URI, URI.create("https://127.0.0.1/my/path"));
    portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 443);
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(Attributes.MAIN_URI)));

    EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "https://mypublichost:5678/my/path");
}
 
Example #24
Source File: AttributeMapTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testStoredByPathCanBeRetrieved() throws Exception {
    AttributeSensor<String> sensor1 = Sensors.newStringSensor("a", "");
    AttributeSensor<String> sensor2 = Sensors.newStringSensor("b.c", "");

    map.update(ImmutableList.of("a"), "1val");
    map.update(ImmutableList.of("b", "c"), "2val");
    
    assertEquals(map.getValue(sensor1), "1val");
    assertEquals(map.getValue(sensor2), "2val");
    
    assertEquals(map.getValue(ImmutableList.of("a")), "1val");
    assertEquals(map.getValue(ImmutableList.of("b","c")), "2val");
}
 
Example #25
Source File: SaltHighstate.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addStateModuleValue(String id, Entity entity, Map<String, List<Object>> stateInfo,
    String stateModule) {

    if (isSaltInternal(stateModule)) {
        return;
    }
    try {
        final List<Object> stateEntries = stateInfo.get(stateModule);
        String stateFunction = "";
        Map<String, Object> moduleSettings = MutableMap.of();
        for (Object entry : stateEntries) {
            if (entry instanceof Map) {
                moduleSettings.putAll((Map<String, Object>)entry);
            } else {
                stateFunction = entry.toString();
            }
        }

        final String name = sensorName(id, stateModule, stateFunction);
        final AttributeSensor<Map<String, Object>> newSensor =
            Sensors.newSensor(STATE_FUNCTION_TYPE, HIGHSTATE_SENSOR_PREFIX + "." + name, name);
        entity.sensors().set(newSensor, moduleSettings);

        LOG.debug("Sensor set for: {}", moduleSettings);
    } catch (ClassCastException e) {
        LOG.info("Unexpected structure for state module {}, skipping ({})", id + "." + stateModule, e.getMessage());
    }
}
 
Example #26
Source File: HttpCommandEffectorHttpBinTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpEffectorWithJsonPathWithPublishSensor() throws Exception {
    new HttpCommandEffector(ConfigBag.newInstance()
            .configure(HttpCommandEffector.EFFECTOR_NAME, "Httpbin")
            .configure(HttpCommandEffector.EFFECTOR_URI, serverUrl + "/get?id=myId")
            .configure(HttpCommandEffector.EFFECTOR_HTTP_VERB, "GET")
            .configure(HttpCommandEffector.JSON_PATH, "$.args.id")
            .configure(HttpCommandEffector.PUBLISH_SENSOR, "result")
    ).apply(entity);

    String val = entity.invoke(EFFECTOR_HTTPBIN, MutableMap.<String,String>of()).get();
    Assert.assertEquals(val, "myId");
    Assert.assertEquals(entity.sensors().get(Sensors.newStringSensor("result")), "myId");
}
 
Example #27
Source File: TestEndpointReachableTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSensorUriReachable() throws Exception {
    URI sensorVal = URI.create("http://"+serverSocketHostAndPort.getHostText()+":"+serverSocketHostAndPort.getPort());
    AttributeSensor<URI> sensor = Sensors.newSensor(URI.class, "test.reachable.endpoint");
    app.createAndManageChild(EntitySpec.create(TestEndpointReachable.class)
            .configure(TestEndpointReachable.TARGET_ENTITY, app)
            .configure(TestEndpointReachable.ENDPOINT_SENSOR, sensor));
    app.sensors().set(sensor, sensorVal);
    app.start(ImmutableList.of(loc));
}
 
Example #28
Source File: EntityRefsYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRefToSelf() throws Exception {
    Entity app = createAndStartApplication(
            "services:",
            "- type: " + TestEntity.class.getName(),
            "  test.confObject: $brooklyn:self()",
            "  test.confName: $brooklyn:self().attributeWhenReady(\"mysensor\")");
    Entity entity = Iterables.getOnlyElement(app.getChildren());
    
    assertEquals(entity.getConfig(TestEntity.CONF_OBJECT), entity);
    
    entity.sensors().set(Sensors.newStringSensor("mysensor"), "myval");
    assertEquals(entity.getConfig(TestEntity.CONF_NAME), "myval");
}
 
Example #29
Source File: AttributeMapTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifyAttributeReturningAbsentDoesNotEmit() throws Exception {
    AttributeSensor<Integer> sensor = Sensors.newIntegerSensor("a", "");
    AttributeSensor<Integer> childSensor = Sensors.newIntegerSensor("a.b", "");
    
    final RecordingSensorEventListener<Object> listener = new RecordingSensorEventListener<>();
    entityImpl.subscriptions().subscribe(entityImpl, sensor, listener);
    
    map.modify(childSensor, Functions.constant(Maybe.<Integer>absent()));
    
    Asserts.succeedsContinually(new Runnable() {
        @Override public void run() {
            assertTrue(Iterables.isEmpty(listener.getEvents()), "events="+listener.getEvents());
        }});
}
 
Example #30
Source File: DslAndRebindYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegexReplacementWithAttributeWhenReady() throws Exception {
    Entity testEntity = setupAndCheckTestEntityInBasicYamlWith(
            "  brooklyn.config:",
            "    test.regex.config: $brooklyn:regexReplacement($brooklyn:attributeWhenReady(\"test.regex.source\"), $brooklyn:attributeWhenReady(\"test.regex.pattern\"), $brooklyn:attributeWhenReady(\"test.regex.replacement\"))"
    );
    testEntity.sensors().set(Sensors.newStringSensor("test.regex.source"), "somefooname");
    testEntity.sensors().set(Sensors.newStringSensor("test.regex.pattern"), "foo");
    testEntity.sensors().set(Sensors.newStringSensor("test.regex.replacement"), "bar");

    Assert.assertEquals("somebarname", testEntity.getConfig(ConfigKeys.newStringConfigKey("test.regex.config")));
}