org.apache.brooklyn.core.config.ConfigKeys Java Examples

The following examples show how to use org.apache.brooklyn.core.config.ConfigKeys. 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: FixedListMachineProvisioningLocationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testMachineConfigRestoredToDefaultsOnRelease() throws Exception {
    ConfigKey<String> mykey = ConfigKeys.newStringConfigKey("mykey");
    
    boolean origContains = machine.config().getBag().getAllConfig().containsKey("mykey");
    SshMachineLocation obtained = provisioner.obtain();
    obtained.config().set(mykey, "myNewVal");
    Object obtainedVal = obtained.config().getBag().getAllConfig().get("mykey");
    
    provisioner.release(obtained);
    boolean releasedContains = machine.config().getBag().getAllConfig().containsKey("mykey");
    releasedContains |= (machine.config().get(mykey) != null);
    
    assertEquals(obtained, machine);
    assertFalse(origContains);
    assertEquals(obtainedVal, "myNewVal");
    assertFalse(releasedContains);
}
 
Example #2
Source File: InboundPortsUtilsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRequiredOpenPortsGetsDynamicallyAddedPortBasedKeys() {
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));

    PortAttributeSensorAndConfigKey newTestConfigKeyPort = ConfigKeys.newPortSensorAndConfigKey("new.test.config.port.string.first", "port", "7777+");
    PortAttributeSensorAndConfigKey newTestConfigKeyPort2 = ConfigKeys.newPortSensorAndConfigKey("new.test.config.port.string.second", "port");

    ConfigKey<Object> newTestConfigKeyObject = ConfigKeys.newConfigKey(Object.class, "new.test.config.object");
    ConfigKey<String> newTestConfigKeyString = ConfigKeys.newStringConfigKey("new.test.config.key.string");
    entity.config().set(newTestConfigKeyPort, PortRanges.fromString("8888+"));
    entity.config().set(newTestConfigKeyPort2, PortRanges.fromInteger(9999));
    entity.config().set(newTestConfigKeyObject, PortRanges.fromInteger(2222));
    entity.config().set(newTestConfigKeyString, "foo.bar");

    Collection<Integer> dynamicRequiredOpenPorts = InboundPortsUtils.getRequiredOpenPorts(entity, ImmutableSet.<ConfigKey<?>>of(), true, null);
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(8888));
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(9999));
    Assert.assertTrue(dynamicRequiredOpenPorts.contains(2222));
}
 
Example #3
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeferredDslChainingOnConfigNoFunction() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:config(\"targetValue\").getNonExistent()");
    ConfigKey<TestDslSupplierValue> targetValueKey = ConfigKeys.newConfigKey(TestDslSupplierValue.class, "targetValue");
    app.config().set(targetValueKey, new TestDslSupplierValue());
    try {
        assertEquals(getConfigEventually(app, DEST), app.getId());
        Asserts.shouldHaveFailedPreviously("Expected to fail because method does not exist");
    } catch (Exception e) {
        Asserts.expectedFailureContains(e, "No such function 'getNonExistent'");
        Asserts.expectedFailureDoesNotContain(e, "$brooklyn:$brooklyn:");
    }
}
 
Example #4
Source File: LoadBalancingPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void onContainerAdded(NodeType newContainer, boolean rebalanceNow) {
    Preconditions.checkArgument(newContainer instanceof BalanceableContainer, "Added container must be a BalanceableContainer");
    if (LOG.isTraceEnabled()) LOG.trace("{} recording addition of container {}", this, newContainer);
    // Low and high thresholds for the metric we're interested in are assumed to be present
    // in the container's configuration.
    Number lowThreshold = newContainer.getConfig(ConfigKeys.newConfigKey(Number.class, lowThresholdConfigKeyName));
    Number highThreshold = newContainer.getConfig(ConfigKeys.newConfigKey(Number.class, highThresholdConfigKeyName));
    if (lowThreshold == null || highThreshold == null) {
        LOG.warn(
            "Balanceable container '"+newContainer+"' does not define low- and high- threshold configuration keys: '"+
            lowThresholdConfigKeyName+"' and '"+highThresholdConfigKeyName+"', skipping");
        return;
    }
    
    model.onContainerAdded(newContainer, lowThreshold.doubleValue(), highThreshold.doubleValue());
    
    // Note: no need to scan the container for items; they will appear via the ITEM_ADDED events.
    // Also, must abide by any item-filters etc defined in the pool.
    
    if (rebalanceNow) scheduleRebalance();
}
 
Example #5
Source File: SpecParameterParsingOsgiTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testOsgiClassScanned() {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH);
    addCatalogItems(CatalogScanOsgiTest.bomForLegacySiblingLibraries());
    
    RegisteredType item = mgmt().getTypeRegistry().get(OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_MORE_ENTITY);
    AbstractBrooklynObjectSpec<?,?> spec = createSpec(item);
    List<SpecParameter<?>> inputs = spec.getParameters();
    if (inputs.isEmpty()) Assert.fail("no inputs (if you're in the IDE, mvn clean install may need to be run to rebuild osgi test JARs)");
    
    Set<SpecParameter<?>> actual = ImmutableSet.copyOf(inputs);
    Set<SpecParameter<?>> expected = ImmutableSet.<SpecParameter<?>>of(
            new BasicSpecParameter<>("more_config", false, ConfigKeys.newStringConfigKey("more_config")),
            new BasicSpecParameter<>(AbstractEntity.DEFAULT_DISPLAY_NAME.getName(), false, AbstractEntity.DEFAULT_DISPLAY_NAME));
    assertEquals(actual, expected);
}
 
Example #6
Source File: DslAndRebindYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDslLocationInEntity() throws Exception {
    String yaml = Joiner.on("\n").join(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    config1: $brooklyn:location()",
            "    config2: $brooklyn:location(\"0\")",
            "  location: localhost");
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    Location loc = Iterables.getOnlyElement(app.getLocations());
    
    assertEquals(getConfigInTask(app, ConfigKeys.newConfigKey(Object.class, "config1")), loc);
    assertEquals(getConfigInTask(app, ConfigKeys.newConfigKey(Object.class, "config2")), loc);
}
 
Example #7
Source File: EntityConfigTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testChildConfigBagInheritsUnmatchedAtParent() throws Exception {
    EntityInternal entity = mgmt.getEntityManager().createEntity(EntitySpec.create(MyEntity.class)
            .configure("mychildentity.myconfig", "myval1")
            .configure("mychildconfigflagname", "myval2")
            .configure("notThere", "notThereVal"));

    EntityInternal child = mgmt.getEntityManager().createEntity(EntitySpec.create(MyChildEntity.class)
            .parent(entity));

    assertEquals(child.config().getBag().getAllConfigAsConfigKeyMap(), ImmutableMap.of(MyChildEntity.MY_CHILD_CONFIG, "myval1", 
        ConfigKeys.newConfigKey(Object.class, "mychildconfigflagname"), "myval2",
        ConfigKeys.newConfigKey(Object.class, "notThere"), "notThereVal"));
    assertEquals(child.config().getBag().getAllConfig(), ImmutableMap.of("mychildentity.myconfig", "myval1", "mychildconfigflagname", "myval2", "notThere", "notThereVal"));
    assertEquals(child.config().getLocalBag().getAllConfig(), ImmutableMap.of());
}
 
Example #8
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 #9
Source File: ObjectsYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallingPasswordHasher() throws Exception {
    Entity testEntity = setupAndCheckTestEntityInBasicYamlWith(
        "  brooklyn.config:",
        "    brooklyn.password: mypassword",
        "    brooklyn.password.sha256:",
        "    brooklyn.password.salt: $brooklyn:entityId()",
        "    brooklyn.password.sha256:",
        "      $brooklyn:object:",
        "        type: "+PasswordHasher.class.getName(),
        "        factoryMethod.name: sha256",
        "        factoryMethod.args:",
        "        - $brooklyn:config(\"brooklyn.password.salt\")",
        "        - $brooklyn:config(\"brooklyn.password\")");

    String salt = (String) testEntity.config().get(ConfigKeys.newConfigKey(Object.class, "brooklyn.password.salt"));
    String sha256 = (String) testEntity.config().get(ConfigKeys.newConfigKey(Object.class, "brooklyn.password.sha256"));

    assertEquals(salt, testEntity.getId());
    assertEquals(sha256, PasswordHasher.sha256(salt, "mypassword"));
}
 
Example #10
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddChildrenWithConfigAtRootAndParams() throws Exception {
    Entity child = makeAppAndAddChild(true, MutableMap.of("p.param1", "call"),
        // note no '|' indicator
        "blueprint_yaml:",  
        "  services:", 
        "  - type: "+BasicEntity.class.getName(),
        "  brooklyn.config:",
        "    p.child: child",
        "    p.param1: call",
        "    p.param2: blueprint",
        "    p.param3: blueprint");
    
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.child")), "child");
    // this is the order of precedence
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param1")), "call");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param2")), "default");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param3")), "blueprint");
}
 
Example #11
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitySpecInUnmatchedConfig() throws Exception {
    String yaml =
            "services:\n"+
            "- serviceType: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "  brooklyn.config:\n"+
            "   key.does.not.match:\n"+
            "     $brooklyn:entitySpec:\n"+
            "       type: org.apache.brooklyn.core.test.entity.TestEntity\n"+
            "       brooklyn.config:\n"+
            "         test.confName: inchildspec\n";
    
    Application app = (Application) createStartWaitAndLogApplication(yaml);
    TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren());
    Object entitySpecOrSupplier = entity.config().getBag().getStringKey("key.does.not.match");
    if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_PERSIST_ENTITY_SPEC_AS_SUPPLIER)) {
        Asserts.assertInstanceOf(entitySpecOrSupplier, DeferredSupplier.class);
        entitySpecOrSupplier = entity.config().get(ConfigKeys.newConfigKey(Object.class, "key.does.not.match"));
    }
    EntitySpec<?> entitySpec = (EntitySpec<?>) entitySpecOrSupplier;
    assertEquals(entitySpec.getType(), TestEntity.class);
    assertEquals(entitySpec.getConfig(), ImmutableMap.of(TestEntity.CONF_NAME, "inchildspec"));
}
 
Example #12
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddChildrenAcceptsJson() throws Exception {
    Entity child = makeAppAndAddChild(false, MutableMap.<String,String>of(),
        // note no '|' indicator
        "blueprint_yaml:",  
        "  services:",
        "  - type: "+BasicEntity.class.getName(),
        "    brooklyn.config:",
        "      p.child: child"
        );
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.child")), "child");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.parent")), "parent");
    // param1 from parent
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param1")), "parent");
    // param2 not set
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param2")), null);
}
 
Example #13
Source File: EmptySoftwareProcessYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testProvisioningProperties() throws Exception {
    Entity app = createAndStartApplication(
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName(),
        "    myLocConfig: myval",
        "services:",
        "- type: "+EmptySoftwareProcess.class.getName(),
        "  brooklyn.config:",
        "    provisioning.properties:",
        "      minRam: 16384");
    waitForApplicationTasks(app);

    log.info("App started:");
    Dumper.dumpInfo(app);
    
    EmptySoftwareProcess entity = (EmptySoftwareProcess) app.getChildren().iterator().next();
    Map<String, Object> pp = entity.getConfig(EmptySoftwareProcess.PROVISIONING_PROPERTIES);
    assertEquals(pp.get("minRam"), 16384);
    
    MachineLocation machine = Locations.findUniqueMachineLocation(entity.getLocations()).get();
    assertEquals(machine.config().get(ConfigKeys.newConfigKey(Object.class, "myLocConfig")), "myval");
    assertEquals(machine.config().get(ConfigKeys.newConfigKey(Object.class, "minRam")), 16384);
}
 
Example #14
Source File: DslAndRebindYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDslLocation() throws Exception {
    // TODO Doesn't work with `$brooklyn:location(0)`, only works if 0 is in quotes!
    
    String yaml = Joiner.on("\n").join(
            "location: localhost",
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    config1: $brooklyn:location()",
            "    config2: $brooklyn:location(\"0\")",
            "  brooklyn.children:",
            "  - type: " + DoNothingSoftwareProcess.class.getName(),
            "    brooklyn.config:",
            "      config1: $brooklyn:location()",
            "      config2: $brooklyn:location(\"0\")",
            "  - type: " + TestEntity.class.getName(),
            "    brooklyn.config:",
            "      config1: $brooklyn:location()",
            "      config2: $brooklyn:location(\"0\")");

    Application app = (Application) createStartWaitAndLogApplication(yaml);
    DoNothingSoftwareProcess softwareProcess = Iterables.getOnlyElement(Iterables.filter(app.getChildren(), DoNothingSoftwareProcess.class));
    TestEntity testEntity = Iterables.getOnlyElement(Iterables.filter(app.getChildren(), TestEntity.class));

    Location appLoc = Iterables.getOnlyElement(app.getLocations());
    assertEquals(getConfigInTask(app, ConfigKeys.newConfigKey(Object.class, "config1")), appLoc);
    assertEquals(getConfigInTask(app, ConfigKeys.newConfigKey(Object.class, "config2")), appLoc);

    Location softwareProcessLoc = Iterables.getOnlyElement(softwareProcess.getLocations());
    assertEquals(getConfigInTask(softwareProcess, ConfigKeys.newConfigKey(Object.class, "config1")), softwareProcessLoc);
    assertEquals(getConfigInTask(softwareProcess, ConfigKeys.newConfigKey(Object.class, "config2")), softwareProcessLoc);
    
    assertEquals(getConfigInTask(testEntity, ConfigKeys.newConfigKey(Object.class, "config1")), appLoc);
    assertEquals(getConfigInTask(testEntity, ConfigKeys.newConfigKey(Object.class, "config2")), appLoc);
}
 
Example #15
Source File: ExampleXmlTypePlanTransformerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppSpecXmlPlanParse() {
    EntitySpec<? extends Application> appSpec = EntityManagementUtils.createEntitySpecForApplication(mgmt, 
        "<root><a_kid foo=\"bar\"/></root>");
    Application app = EntityManagementUtils.createStarting(mgmt, appSpec).get();
    Dumper.dumpInfo(app);
    Assert.assertEquals(app.getDisplayName(), "root");
    Entity child = Iterables.getOnlyElement(app.getChildren());
    Assert.assertEquals(child.getDisplayName(), "a_kid");
    Assert.assertEquals(child.config().get(ConfigKeys.newStringConfigKey("foo")), "bar");
}
 
Example #16
Source File: ConfigBag.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** current values for all entries in a map where the keys are converted to {@link ConfigKey} instances */
public synchronized Map<ConfigKey<?>, ?> getAllConfigAsConfigKeyMap() {
    Map<ConfigKey<?>,Object> result = MutableMap.of();
    for (Map.Entry<String,Object> entry: config.entrySet()) {
        result.put(ConfigKeys.newConfigKey(Object.class, entry.getKey()), entry.getValue());
    }
    return result;
}
 
Example #17
Source File: LocationConfigUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** checks enablement, by looking at <code>key + ".enabled"</code> */
public static boolean isEnabled(ManagementContext mgmt, String key) {
    ConfigKey<Boolean> k = ConfigKeys.newConfigKeyWithPrefix(key+".", LocationConfigKeys.ENABLED);
    Boolean enabled = mgmt.getConfig().getConfig(k);
    if (enabled!=null) return enabled.booleanValue();
    return true;
}
 
Example #18
Source File: CleanOrphanedLocationsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeletesOrphanedLocationThatLinksToReachable() throws Exception {
    Location referantLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
    Location refereeLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
            .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), referantLoc));
    origApp.addLocations(ImmutableList.of(referantLoc));
    assertTransformDeletes(new Deletions().locations(refereeLoc.getId()));
}
 
Example #19
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddChildrenWithConfig() throws Exception {
    Entity child = makeAppAndAddChild(true, MutableMap.<String,Object>of(),
        "blueprint_yaml: |",
        "  services:", 
        "  - type: "+BasicEntity.class.getName(),
        "    brooklyn.config:",
        "      p.child: $brooklyn:config(\"p.parent\")");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param1")), "default");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.child")), "parent");
}
 
Example #20
Source File: EntityConfigTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInheritedDefault() {
    final Entity e1 = app.addChild(EntitySpec.create(MyBaseEntity.class));
    final Entity e2 = e1.addChild(EntitySpec.create(BasicEntity.class));
    Assert.assertEquals(e2.config().get(MyBaseEntity.SUPER_KEY_1), MyBaseEntity.SUPER_KEY_1.getDefaultValue());
    Assert.assertEquals(e2.config().get(ConfigKeys.newStringConfigKey(MyBaseEntity.SUPER_KEY_1.getName())), MyBaseEntity.SUPER_KEY_1.getDefaultValue());
}
 
Example #21
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")));
}
 
Example #22
Source File: EntitiesYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testUndeclaredItemInBrooklynConfig() throws Exception {
    Entity testEntity = setupAndCheckTestEntityInBasicYamlWith( 
        "  brooklyn.config:",
        "    test.dynamic.confName: Foo Bar");
    Assert.assertEquals(testEntity.getConfig(ConfigKeys.newStringConfigKey("test.dynamic.confName")), "Foo Bar");
}
 
Example #23
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddChildrenInJsonWithParameters() throws Exception {
    Entity child = makeAppAndAddChild(true, MutableMap.<String,String>of(),
        // note no '|' indicator, but there are declared parameters with defaults
        "blueprint_yaml:",  
        "  services:", 
        "  - type: "+BasicEntity.class.getName());
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param1")), "default");
}
 
Example #24
Source File: SoftwareProcessEntityLatchTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Deploy a cluster of 4 SoftwareProcesses, which all share the same CountingLatch instance so
 * that only two can obtain it at a time. The {@link CountingLatch} is uses the default
 * of sleeping for 100ms after acquiring the lock, so it is very likely in a non-contended 
 * machine that we'll hit max concurrency. We assert that the maximum number of things holding
 * the lock at any one time was exactly 2.
 * 
 * This is marked as an "integration" test because it is time-sensitive. If executed on a
 * low-performance machine (e.g. Apache Jenkins, where other docker containers are contending
 * for resources) then it might not get to 2 things holding the lock at the same time.
 */
@Test(groups="Integration", dataProvider="latchAndTaskNamesProvider", timeOut=Asserts.THIRTY_SECONDS_TIMEOUT_MS)
public void testConcurrency(ConfigKey<Boolean> latch, List<String> _ignored) throws Exception {
    LocalhostMachineProvisioningLocation loc = app.newLocalhostProvisioningLocation(ImmutableMap.of("address", "127.0.0.1"));
    
    final int maxConcurrency = 2;
    final ReleaseableLatch latchSemaphore = ReleaseableLatch.Factory.newMaxConcurrencyLatch(maxConcurrency);
    final AttributeSensor<Object> latchSensor = Sensors.newSensor(Object.class, "latch");
    final CountingLatch countingLatch = new CountingLatch(latchSemaphore, maxConcurrency);
    @SuppressWarnings({"unused"})
    DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.INITIAL_SIZE, maxConcurrency*2)
            .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)));
    startTask.get();
    final Task<Void> stopTask = Entities.invokeEffector(app, app, MyService.STOP, ImmutableMap.<String, Object>of());
    stopTask.get();
    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 #25
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredDslChainingWithCustomCallable() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:config(\"customCallableWrapper\").getSupplier().isSupplierCallable()");
    ConfigKey<DslTestSupplierWrapper> customCallableWrapperKey = ConfigKeys.newConfigKey(DslTestSupplierWrapper.class, "customCallableWrapper");
    app.config().set(customCallableWrapperKey, new DslTestSupplierWrapper(new DslTestCallable()));
    assertEquals(getConfigEventually(app, DEST), Boolean.TRUE);
}
 
Example #26
Source File: AddChildrenEffectorYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddChildrenWithServicesBlock() throws Exception {
    Entity child = makeAppAndAddChild(true, MutableMap.of("p.param1", "effector_param"),
        "blueprint_yaml: |",
        "  services:", 
        "  - type: "+BasicEntity.class.getName()
        );
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.parent")), "parent");
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param2")), "default");
    
    Assert.assertEquals(child.getConfig(ConfigKeys.newStringConfigKey("p.param1")), "effector_param");
}
 
Example #27
Source File: LocalManagementContextRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testScratchpadLostOnRebind() throws Exception {
    ConfigKey<String> myKey = ConfigKeys.newStringConfigKey("my");
    origManagementContext.getScratchpad().put(myKey, "key");
    assertEquals(origManagementContext.getScratchpad().get(myKey), "key");
    rebind();
    assertFalse(newManagementContext.getScratchpad().contains(myKey), "Scratchpad lost on rebind");
}
 
Example #28
Source File: RebindEnricherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testReboundConfigDoesNotContainId() throws Exception {
    MyEnricher policy = origApp.enrichers().add(EnricherSpec.create(MyEnricher.class));
    
    newApp = rebind();
    MyEnricher newEnricher = (MyEnricher) Iterables.getOnlyElement(newApp.enrichers());

    assertNull(newEnricher.getConfig(ConfigKeys.newStringConfigKey("id")));
    assertEquals(newEnricher.getId(), policy.getId());
}
 
Example #29
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredDslChainingWithNestedEvaluation() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:config(\"customCallableWrapper\").getSupplier().isSupplierCallable()");
    ConfigKey<TestDslSupplier> customCallableWrapperKey = ConfigKeys.newConfigKey(TestDslSupplier.class, "customCallableWrapper");
    app.config().set(customCallableWrapperKey, new TestDslSupplier(new DslTestSupplierWrapper(new DslTestCallable())));
    assertEquals(getConfigEventually(app, DEST), Boolean.TRUE);
}
 
Example #30
Source File: DslYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeferredDslChainingWithCustomSupplier() throws Exception {
    final Entity app = createAndStartApplication(
            "services:",
            "- type: " + BasicApplication.class.getName(),
            "  brooklyn.config:",
            "    dest: $brooklyn:config(\"customSupplierWrapper\").getSupplier().isSupplierEvaluated()");
    ConfigKey<DslTestSupplierWrapper> customSupplierWrapperKey = ConfigKeys.newConfigKey(DslTestSupplierWrapper.class, "customSupplierWrapper");
    app.config().set(customSupplierWrapperKey, new DslTestSupplierWrapper(new TestDslSupplier(new TestDslSupplierValue())));
    assertEquals(getConfigEventually(app, DEST), Boolean.TRUE);
}