http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/BrooklynYamlTypeInstantiatorTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/BrooklynYamlTypeInstantiatorTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/BrooklynYamlTypeInstantiatorTest.java deleted file mode 100644 index c76731b..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/BrooklynYamlTypeInstantiatorTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import org.apache.brooklyn.api.mgmt.classloading.BrooklynClassLoadingContext; -import org.apache.brooklyn.api.policy.Policy; -import org.apache.brooklyn.camp.brooklyn.spi.creation.BrooklynYamlTypeInstantiator; -import org.apache.brooklyn.camp.brooklyn.spi.creation.BrooklynYamlTypeInstantiator.Factory; -import org.apache.brooklyn.camp.brooklyn.spi.creation.BrooklynYamlTypeInstantiator.InstantiatorFromKey; -import org.apache.brooklyn.core.mgmt.classloading.JavaBrooklynClassLoadingContext; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.apache.brooklyn.policy.ha.ServiceRestarter; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.javalang.JavaClassNames; -import org.apache.brooklyn.util.time.Duration; - -public class BrooklynYamlTypeInstantiatorTest extends AbstractYamlTest { - - protected BrooklynClassLoadingContext loader() { - return JavaBrooklynClassLoadingContext.create(mgmt()); - } - - @Test - public void testLoadPolicySpecProgrammatically() { - Factory loader = new BrooklynYamlTypeInstantiator.Factory(loader(), "test:"+JavaClassNames.niceClassAndMethod()); - InstantiatorFromKey decoL = loader.from(MutableMap.of("some_type", ServiceRestarter.class.getName())).prefix("some"); - - Assert.assertTrue(decoL.getConfigMap().isEmpty()); - Assert.assertEquals(decoL.getTypeName().get(), ServiceRestarter.class.getName()); - Assert.assertEquals(decoL.getType(), ServiceRestarter.class); - - Object sl1 = decoL.newInstance(); - Assert.assertTrue(sl1 instanceof ServiceRestarter); - - Policy sl2 = decoL.newInstance(Policy.class); - Assert.assertTrue(sl2 instanceof ServiceRestarter); - } - - @Test - public void testLoadPolicySpecWithBrooklynConfig() { - Factory loader = new BrooklynYamlTypeInstantiator.Factory(loader(), "test:"+JavaClassNames.niceClassAndMethod()); - InstantiatorFromKey decoL = loader.from(MutableMap.of("some_type", ServiceRestarter.class.getName(), - "brooklyn.config", MutableMap.of("failOnRecurringFailuresInThisDuration", Duration.seconds(42)))).prefix("some"); - Policy sl2 = decoL.newInstance(Policy.class); - Assert.assertEquals(sl2.getConfig(ServiceRestarter.FAIL_ON_RECURRING_FAILURES_IN_THIS_DURATION).toSeconds(), 42); - } - - @Test(groups = "WIP") - public void testLoadPolicySpecWithFlag() { - Factory loader = new BrooklynYamlTypeInstantiator.Factory(loader(), "test:"+JavaClassNames.niceClassAndMethod()); - InstantiatorFromKey decoL = loader.from(MutableMap.of("some_type", ServiceRestarter.class.getName(), - "failOnRecurringFailuresInThisDuration", Duration.seconds(42))).prefix("some"); - Policy sl2 = decoL.newInstance(Policy.class); - Assert.assertEquals(sl2.getConfig(ServiceRestarter.FAIL_ON_RECURRING_FAILURES_IN_THIS_DURATION).toSeconds(), 42); - } - -}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java deleted file mode 100644 index ff89c25..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/ByonLocationsYamlTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; - -import java.io.StringReader; -import java.util.Map; -import java.util.Set; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.MachineLocation; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.location.LocationPredicates; -import org.apache.brooklyn.core.location.Machines; -import org.apache.brooklyn.core.location.access.PortForwardManager; -import org.apache.brooklyn.core.location.cloud.CloudLocationConfig; -import org.apache.brooklyn.entity.software.base.DoNothingSoftwareProcess; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; - -import com.google.api.client.repackaged.com.google.common.base.Joiner; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.net.HostAndPort; - -import org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation; -import org.apache.brooklyn.location.ssh.SshMachineLocation; -import org.apache.brooklyn.location.winrm.WinRmMachineLocation; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.net.UserAndHostAndPort; - -public class ByonLocationsYamlTest extends AbstractYamlTest { - private static final Logger log = LoggerFactory.getLogger(ByonLocationsYamlTest.class); - - @Test - @SuppressWarnings("unchecked") - public void testByonSpec() throws Exception { - String yaml = Joiner.on("\n").join( - "location: byon(user=myuser,mykey=myval,hosts=\"1.1.1.1\")", - "services:", - "- serviceType: org.apache.brooklyn.entity.stock.BasicApplication"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(app.getLocations(), 0); - - Set<SshMachineLocation> machines = loc.getAvailable(); - SshMachineLocation machine = Iterables.getOnlyElement(machines); - assertMachine(machine, UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 22), ImmutableMap.of("mykey", "myval")); - } - - @Test - @SuppressWarnings("unchecked") - public void testByonMachine() throws Exception { - String yaml = Joiner.on("\n").join( - "location:", - " byon:", - " hosts:", - " - ssh: 1.1.1.1:8022", - " privateAddresses: [10.0.0.1]", - " password: mypassword", - " user: myuser", - " mykey: myval", - "services:", - "- serviceType: org.apache.brooklyn.entity.stock.BasicApplication"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - FixedListMachineProvisioningLocation<SshMachineLocation> loc = (FixedListMachineProvisioningLocation<SshMachineLocation>) Iterables.get(app.getLocations(), 0); - - Set<SshMachineLocation> machines = loc.getAvailable(); - SshMachineLocation machine = Iterables.getOnlyElement(machines); - assertMachine(machine, UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 8022), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval")); - assertEquals(machine.getPrivateAddresses(), ImmutableSet.of("10.0.0.1")); - } - - @Test - @SuppressWarnings("unchecked") - public void testByonWindowsMachine() throws Exception { - String yaml = Joiner.on("\n").join( - "location:", - " byon:", - " hosts:", - " - winrm: 1.1.1.1:8985", - " privateAddresses: [10.0.0.1]", - " password: mypassword", - " user: myuser", - " mykey: myval", - " osFamily: windows", - "services:", - "- serviceType: org.apache.brooklyn.entity.stock.BasicApplication"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - FixedListMachineProvisioningLocation<WinRmMachineLocation> loc = (FixedListMachineProvisioningLocation<WinRmMachineLocation>) Iterables.get(app.getLocations(), 0); - - Set<WinRmMachineLocation> machines = loc.getAvailable(); - WinRmMachineLocation machine = Iterables.getOnlyElement(machines); - assertMachine(machine, UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 8985), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval")); - assertEquals(machine.getPrivateAddresses(), ImmutableSet.of("10.0.0.1")); - } - - @Test - @SuppressWarnings("unchecked") - public void testByonMultiMachine() throws Exception { - String yaml = Joiner.on("\n").join( - "location:", - " byon:", - " hosts:", - " - ssh: 1.1.1.1:8022", - " privateAddresses: [10.0.0.1]", - " password: mypassword", - " user: myuser", - " mykey: myval1", - " - ssh: 1.1.1.2:8022", - " privateAddresses: [10.0.0.2]", - " password: mypassword", - " user: myuser", - " mykey: myval2", - " - winrm: 1.1.1.3:8985", - " privateAddresses: [10.0.0.3]", - " password: mypassword", - " user: myuser", - " mykey: myval3", - " osFamily: windows", - "services:", - "- serviceType: org.apache.brooklyn.entity.stock.BasicApplication"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - FixedListMachineProvisioningLocation<MachineLocation> loc = (FixedListMachineProvisioningLocation<MachineLocation>) Iterables.get(app.getLocations(), 0); - - Set<MachineLocation> machines = loc.getAvailable(); - assertEquals(machines.size(), 3, "machines="+machines); - SshMachineLocation machine1 = (SshMachineLocation) Iterables.find(machines, LocationPredicates.configEqualTo(ConfigKeys.newStringConfigKey("mykey"), "myval1")); - SshMachineLocation machine2 = (SshMachineLocation) Iterables.find(machines, LocationPredicates.configEqualTo(ConfigKeys.newStringConfigKey("mykey"), "myval2")); - WinRmMachineLocation machine3 = (WinRmMachineLocation) Iterables.find(machines, Predicates.instanceOf(WinRmMachineLocation.class)); - - assertMachine(machine1, UserAndHostAndPort.fromParts("myuser", "1.1.1.1", 8022), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval1")); - assertEquals(machine1.getPrivateAddresses(), ImmutableSet.of("10.0.0.1")); - - assertMachine(machine2, UserAndHostAndPort.fromParts("myuser", "1.1.1.2", 8022), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval2")); - assertEquals(machine2.getPrivateAddresses(), ImmutableSet.of("10.0.0.2")); - - assertMachine(machine3, UserAndHostAndPort.fromParts("myuser", "1.1.1.3", 8985), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval3")); - assertEquals(machine3.getPrivateAddresses(), ImmutableSet.of("10.0.0.3")); - } - - @Test - @SuppressWarnings("unchecked") - public void testByonPortMapping() throws Exception { - String yaml = Joiner.on("\n").join( - "location:", - " byon:", - " hosts:", - " - ssh: 1.1.1.1:22", - " privateAddresses: [10.0.0.1]", - " tcpPortMappings: {22: \"83.222.229.1:12001\", 8080: \"83.222.229.1:12002\"}", - " password: mypassword", - " user: myuser", - " mykey: myval1", - " - winrm: 1.1.1.2:8985", - " privateAddresses: [10.0.0.2]", - " tcpPortMappings: {8985: \"83.222.229.2:12003\", 8080: \"83.222.229.2:12004\"}", - " password: mypassword", - " user: myuser", - " mykey: myval2", - " osFamily: windows", - "services:", - "- serviceType: org.apache.brooklyn.entity.stock.BasicApplication"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - FixedListMachineProvisioningLocation<MachineLocation> loc = (FixedListMachineProvisioningLocation<MachineLocation>) Iterables.get(app.getLocations(), 0); - PortForwardManager pfm = (PortForwardManager) mgmt().getLocationRegistry().resolve("portForwardManager(scope=global)"); - - Set<MachineLocation> machines = loc.getAvailable(); - assertEquals(machines.size(), 2, "machines="+machines); - SshMachineLocation machine1 = (SshMachineLocation) Iterables.find(machines, LocationPredicates.configEqualTo(ConfigKeys.newStringConfigKey("mykey"), "myval1")); - WinRmMachineLocation machine2 = (WinRmMachineLocation) Iterables.find(machines, Predicates.instanceOf(WinRmMachineLocation.class)); - - assertMachine(machine1, UserAndHostAndPort.fromParts("myuser", "83.222.229.1", 12001), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval1")); - assertEquals(machine1.getPrivateAddresses(), ImmutableSet.of("10.0.0.1")); - assertEquals(pfm.lookup(machine1, 22), HostAndPort.fromParts("83.222.229.1", 12001)); - assertEquals(pfm.lookup(machine1, 8080), HostAndPort.fromParts("83.222.229.1", 12002)); - assertNull(pfm.lookup(machine1, 12345)); - - assertMachine(machine2, UserAndHostAndPort.fromParts("myuser", "83.222.229.2", 12003), ImmutableMap.of( - SshMachineLocation.PASSWORD.getName(), "mypassword", - "mykey", "myval2")); - assertEquals(machine2.getPrivateAddresses(), ImmutableSet.of("10.0.0.2")); - assertEquals(pfm.lookup(machine2, 8985), HostAndPort.fromParts("83.222.229.2", 12003)); - assertEquals(pfm.lookup(machine2, 8080), HostAndPort.fromParts("83.222.229.2", 12004)); - assertNull(pfm.lookup(machine2, 12345)); - } - - @Test - @SuppressWarnings("unchecked") - public void testPassesInboundPortsToMachineAndRemovesOnceMachineReleased() throws Exception { - String yaml = Joiner.on("\n").join( - "location:", - " byon:", - " hosts:", - " - ssh: 1.1.1.1:22", - " password: mypassword", - " user: myuser", - "services:", - "- type: org.apache.brooklyn.entity.software.base.DoNothingSoftwareProcess", - " brooklyn.config:", - " requiredOpenLoginPorts: [22, 1024]"); - - Entity app = createStartWaitAndLogApplication(new StringReader(yaml)); - DoNothingSoftwareProcess entity = (DoNothingSoftwareProcess) Iterables.find(Entities.descendants(app), Predicates.instanceOf(DoNothingSoftwareProcess.class)); - FixedListMachineProvisioningLocation<MachineLocation> loc = (FixedListMachineProvisioningLocation<MachineLocation>) Iterables.get(app.getLocations(), 0); - - // Machine should have been given the inbound-ports - SshMachineLocation machine = Machines.findUniqueMachineLocation(entity.getLocations(), SshMachineLocation.class).get(); - Asserts.assertEqualsIgnoringOrder((Iterable<?>)machine.config().get(CloudLocationConfig.INBOUND_PORTS), ImmutableList.of(22, 1024)); - - // Stop the entity; should release the machine - entity.stop(); - MachineLocation availableMachine = Iterables.getOnlyElement(loc.getAvailable()); - assertEquals(availableMachine, machine); - assertNull(machine.config().get(CloudLocationConfig.INBOUND_PORTS)); - } - - private void assertMachine(SshMachineLocation machine, UserAndHostAndPort conn, Map<String, ?> config) { - assertEquals(machine.getAddress().getHostAddress(), conn.getHostAndPort().getHostText()); - assertEquals(machine.getPort(), conn.getHostAndPort().getPort()); - assertEquals(machine.getUser(), conn.getUser()); - for (Map.Entry<String, ?> entry : config.entrySet()) { - Object actualVal = machine.getConfig(ConfigKeys.newConfigKey(Object.class, entry.getKey())); - assertEquals(actualVal, entry.getValue()); - } - } - - private void assertMachine(WinRmMachineLocation machine, UserAndHostAndPort conn, Map<String, ?> config) { - assertEquals(machine.getAddress().getHostAddress(), conn.getHostAndPort().getHostText()); - assertEquals(machine.getConfig(WinRmMachineLocation.WINRM_PORT), (Integer) conn.getHostAndPort().getPort()); - assertEquals(machine.getUser(), conn.getUser()); - for (Map.Entry<String, ?> entry : config.entrySet()) { - Object actualVal = machine.getConfig(ConfigKeys.newConfigKey(Object.class, entry.getKey())); - assertEquals(actualVal, entry.getValue()); - } - } - - @Override - protected Logger getLogger() { - return log; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DependentConfigPollingYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DependentConfigPollingYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DependentConfigPollingYamlTest.java deleted file mode 100644 index 10df5f0..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DependentConfigPollingYamlTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import static org.testng.Assert.assertTrue; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.base.Joiner; -import com.google.common.collect.Iterables; - -@Test -public class DependentConfigPollingYamlTest extends AbstractYamlTest { - private static final Logger log = LoggerFactory.getLogger(DependentConfigPollingYamlTest.class); - - private ExecutorService executor; - - @BeforeMethod(alwaysRun = true) - @Override - public void setUp() { - super.setUp(); - executor = Executors.newCachedThreadPool(); - } - - @AfterMethod(alwaysRun = true) - @Override - public void tearDown() { - if (executor != null) executor.shutdownNow(); - super.tearDown(); - } - - // Test for BROOKLYN-214. Previously, the brief Tasks.resolving would cause a thread to be - // leaked. This was because it would call into BrooklynDslDeferredSupplier.get, which would - // wait on a synchronized block and thus not be interruptible - the thread would be consumed - // forever, until the attributeWhenReady returned true! - // - // Integration test, because takes several seconds. - @Test(groups="Integration") - public void testResolveAttributeWhenReadyWithTimeoutDoesNotLeaveThreadRunning() throws Exception { - String yaml = Joiner.on("\n").join( - "services:", - "- type: org.apache.brooklyn.core.test.entity.TestEntity", - " id: myentity", - " brooklyn.config:", - " test.confName: $brooklyn:entity(\"myentity\").attributeWhenReady(\"mysensor\")"); - - final Entity app = createAndStartApplication(yaml); - final TestEntity entity = (TestEntity) Iterables.getOnlyElement(app.getChildren()); - - // Cause a thread to block, getting the config - previousy (before fixing 214) this would be in - // the synchronized block if BrooklynDslDeferredSupplier.get(). - // The sleep is to ensure we really did get into the locking code. - executor.submit(new Callable<Object>() { - public Object call() { - return entity.config().get(TestEntity.CONF_NAME); - }}); - Thread.sleep(100); - - // Try to resolve the value many times, each in its own task, but with a short timeout for each. - final int numIterations = 20; - final int preNumThreads = Thread.activeCount(); - - for (int i = 0; i < numIterations; i++) { - // Same as RestValueResolver.getImmediateValue - Tasks.resolving(entity.config().getRaw(TestEntity.CONF_NAME).get()) - .as(Object.class) - .defaultValue("UNRESOLVED") - .timeout(Duration.millis(100)) - .context(entity) - .swallowExceptions() - .get(); - } - - // Confirm we haven't left threads behind. - Asserts.succeedsEventually(new Runnable() { - public void run() { - int postNumThreads = Thread.activeCount(); - String msg = "pre="+preNumThreads+"; post="+postNumThreads+"; iterations="+numIterations; - log.info(msg); - assertTrue(postNumThreads < preNumThreads + (numIterations / 2), msg); - }}); - } - - @Override - protected Logger getLogger() { - return log; - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DslAndRebindYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DslAndRebindYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DslAndRebindYamlTest.java deleted file mode 100644 index 354e0a0..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/DslAndRebindYamlTest.java +++ /dev/null @@ -1,515 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import java.io.File; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.brooklyn.api.entity.Application; -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.ha.MementoCopyMode; -import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.api.sensor.Sensor; -import org.apache.brooklyn.camp.brooklyn.spi.dsl.BrooklynDslDeferredSupplier; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityAsserts; -import org.apache.brooklyn.core.entity.EntityInternal; -import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext; -import org.apache.brooklyn.core.mgmt.persist.BrooklynPersistenceUtils; -import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils; -import org.apache.brooklyn.core.sensor.Sensors; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.entity.group.DynamicCluster; -import org.apache.brooklyn.util.collections.MutableSet; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.guava.Maybe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.io.Files; - -@Test -public class DslAndRebindYamlTest extends AbstractYamlTest { - - private static final Logger log = LoggerFactory.getLogger(DslAndRebindYamlTest.class); - - protected ClassLoader classLoader = getClass().getClassLoader(); - protected File mementoDir; - protected Set<ManagementContext> mgmtContexts = MutableSet.of(); - protected ExecutorService executor; - - @Override - protected LocalManagementContext newTestManagementContext() { - if (mementoDir != null) throw new IllegalStateException("already created mgmt context"); - mementoDir = Files.createTempDir(); - mementoDir.deleteOnExit(); - LocalManagementContext mgmt = RebindTestUtils.newPersistingManagementContext(mementoDir, classLoader, 1); - mgmtContexts.add(mgmt); - return mgmt; - } - - @BeforeMethod(alwaysRun = true) - @Override - public void setUp() { - super.setUp(); - executor = Executors.newSingleThreadExecutor(); - } - - @AfterMethod(alwaysRun = true) - @Override - public void tearDown() { - if (executor != null) executor.shutdownNow(); - for (ManagementContext mgmt : mgmtContexts) Entities.destroyAll(mgmt); - super.tearDown(); - mementoDir = null; - mgmtContexts.clear(); - } - - @Override - protected Logger getLogger() { - return log; - } - - public Application rebind(Application app) throws Exception { - RebindTestUtils.waitForPersisted(app); - Application result = RebindTestUtils.rebind(mementoDir, getClass().getClassLoader()); - mgmtContexts.add(result.getManagementContext()); - return result; - } - - - protected Entity setupAndCheckTestEntityInBasicYamlWith(String... extras) throws Exception { - Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml", extras)); - waitForApplicationTasks(app); - - Assert.assertEquals(app.getDisplayName(), "test-entity-basic-template"); - - log.info("App started:"); - Entities.dumpInfo(app); - - Assert.assertTrue(app.getChildren().iterator().hasNext(), "Expected app to have child entity"); - Entity entity = app.getChildren().iterator().next(); - Assert.assertTrue(entity instanceof TestEntity, "Expected TestEntity, found " + entity.getClass()); - - return entity; - } - - public static <T> T getConfigInTask(final Entity entity, final ConfigKey<T> key) { - return Entities.submit(entity, Tasks.<T>builder().body(new Callable<T>() { - @Override - public T call() throws Exception { - return entity.getConfig(key); - } - }).build()).getUnchecked(); - } - - protected <T> Future<T> getConfigInTaskAsync(final Entity entity, final ConfigKey<T> key) { - // Wait for the attribute to be ready in a new Task - Callable<T> configGetter = new Callable<T>() { - @Override - public T call() throws Exception { - T s = getConfigInTask(entity, key); - getLogger().info("getConfig {}={}", key, s); - return s; - } - }; - return executor.submit(configGetter); - } - - @Test - public void testDslAttributeWhenReady() throws Exception { - Entity testEntity = entityWithAttributeWhenReady(); - ((EntityInternal) testEntity).sensors().set(Sensors.newStringSensor("foo"), "bar"); - Assert.assertEquals(getConfigInTask(testEntity, TestEntity.CONF_NAME), "bar"); - } - - @Test - public void testDslAttributeWhenReadyRebindWhenResolved() throws Exception { - Entity testEntity = entityWithAttributeWhenReady(); - ((EntityInternal) testEntity).sensors().set(Sensors.newStringSensor("foo"), "bar"); - - Application app2 = rebind(testEntity.getApplication()); - Entity e2 = Iterables.getOnlyElement(app2.getChildren()); - - Assert.assertEquals(getConfigInTask(e2, TestEntity.CONF_NAME), "bar"); - } - - @Test - public void testDslAttributeWhenReadyWhenNotYetResolved() throws Exception { - Entity testEntity = entityWithAttributeWhenReady(); - - Application app2 = rebind(testEntity.getApplication()); - Entity e2 = Iterables.getOnlyElement(app2.getChildren()); - - // Wait for the attribute to be ready in a new Task - Future<String> stringFuture = getConfigInTaskAsync(e2, TestEntity.CONF_NAME); - - // Check that the Task is still waiting for attribute to be ready - Assert.assertFalse(stringFuture.isDone()); - - // Set the sensor; expect that to complete - e2.sensors().set(Sensors.newStringSensor("foo"), "bar"); - String s = stringFuture.get(10, TimeUnit.SECONDS); // Timeout just for sanity - Assert.assertEquals(s, "bar"); - } - - @Test - public void testDslAttributeWhenReadyPersistedAsDeferredSupplier() throws Exception { - doDslAttributeWhenReadyPersistedAsDeferredSupplier(false); - } - - @Test - public void testDslAttributeWhenReadyPersistedWithoutLeakingResolvedValue() throws Exception { - doDslAttributeWhenReadyPersistedAsDeferredSupplier(true); - } - - protected void doDslAttributeWhenReadyPersistedAsDeferredSupplier(boolean resolvedBeforeRebind) throws Exception { - Entity testEntity = entityWithAttributeWhenReady(); - - if (resolvedBeforeRebind) { - testEntity.sensors().set(Sensors.newStringSensor("foo"), "bar"); - Assert.assertEquals(getConfigInTask(testEntity, TestEntity.CONF_NAME), "bar"); - } - - // Persist and rebind - Application app2 = rebind(testEntity.getApplication()); - Entity e2 = Iterables.getOnlyElement(app2.getChildren()); - - Maybe<Object> maybe = ((EntityInternal) e2).config().getLocalRaw(TestEntity.CONF_NAME); - Assert.assertTrue(maybe.isPresentAndNonNull()); - Assert.assertTrue(BrooklynDslDeferredSupplier.class.isInstance(maybe.get())); - BrooklynDslDeferredSupplier<?> deferredSupplier = (BrooklynDslDeferredSupplier<?>) maybe.get(); - Assert.assertEquals(deferredSupplier.toString(), "$brooklyn:entity(\"x\").attributeWhenReady(\"foo\")"); - - // Assert the persisted state itself is as expected, and not too big - BrooklynMementoRawData raw = BrooklynPersistenceUtils.newStateMemento(app2.getManagementContext(), MementoCopyMode.LOCAL); - String persistedStateForE2 = raw.getEntities().get(e2.getId()); - Matcher matcher = Pattern.compile(".*\\<test.confName\\>(.*)\\<\\/test.confName\\>.*", Pattern.DOTALL) - .matcher(persistedStateForE2); - Assert.assertTrue(matcher.find()); - String testConfNamePersistedState = matcher.group(1); - - Assert.assertNotNull(testConfNamePersistedState); - // should be about 200 chars long, something like: - // - // <test.confName> - // <org.apache.brooklyn.camp.brooklyn.spi.dsl.methods.DslComponent_-AttributeWhenReady> - // <component> - // <componentId>x</componentId> - // <scope>GLOBAL</scope> - // </component> - // <sensorName>foo</sensorName> - // </org.apache.brooklyn.camp.brooklyn.spi.dsl.methods.DslComponent_-AttributeWhenReady> - // </test.confName> - - Assert.assertTrue(testConfNamePersistedState.length() < 400, "persisted state too long: " + testConfNamePersistedState); - - Assert.assertFalse(testConfNamePersistedState.contains("bar"), "value 'bar' leaked in persisted state"); - } - - @Test - public void testDslAttributeWhenReadyInEntitySpecWhenNotYetResolved() throws Exception { - doDslAttributeWhenReadyInEntitySpec(false); - } - - @Test - public void testDslAttributeWhenReadyInEntitySpecWhenAlreadyResolved() throws Exception { - doDslAttributeWhenReadyInEntitySpec(true); - } - - protected void doDslAttributeWhenReadyInEntitySpec(boolean resolvedBeforeRebind) throws Exception { - String yaml = "location: localhost\n" + - "name: Test Cluster\n" + - "services:\n" + - "- type: org.apache.brooklyn.entity.group.DynamicCluster\n" + - " id: test-cluster\n" + - " initialSize: 0\n" + - " memberSpec:\n" + - " $brooklyn:entitySpec:\n" + - " type: org.apache.brooklyn.core.test.entity.TestEntity\n" + - " brooklyn.config:\n" + - " test.confName: $brooklyn:component(\"test-cluster\").attributeWhenReady(\"sensor\")"; - - final Entity testEntity = createAndStartApplication(yaml); - DynamicCluster cluster = (DynamicCluster) Iterables.getOnlyElement(testEntity.getApplication().getChildren()); - cluster.resize(1); - Assert.assertEquals(cluster.getMembers().size(), 1); - - if (resolvedBeforeRebind) { - cluster.sensors().set(Sensors.newStringSensor("sensor"), "bar"); - } - - // Persist and rebind - Application app2 = rebind(cluster.getApplication()); - DynamicCluster cluster2 = (DynamicCluster) Iterables.getOnlyElement(app2.getApplication().getChildren()); - - // Assert the persisted state itself is as expected, and not too big - BrooklynMementoRawData raw = BrooklynPersistenceUtils.newStateMemento(app2.getManagementContext(), MementoCopyMode.LOCAL); - String persistedStateForE2 = raw.getEntities().get(cluster2.getId()); - String expectedTag = "org.apache.brooklyn.camp.brooklyn.spi.dsl.methods.DslComponent_-AttributeWhenReady"; - Matcher matcher = Pattern.compile(".*\\<"+expectedTag+"\\>(.*)\\<\\/"+expectedTag+"\\>.*", Pattern.DOTALL) - .matcher(persistedStateForE2); - Assert.assertTrue(matcher.find(), persistedStateForE2); - String testConfNamePersistedState = matcher.group(1); - Assert.assertNotNull(testConfNamePersistedState); - - // Can re-size to create a new member entity - cluster2.resize(2); - Assert.assertEquals(cluster2.getMembers().size(), 2); - - // Both the existing and the new member should have the DeferredSupplier config - for (Entity member : Iterables.filter(cluster2.getChildren(), TestEntity.class)) { - Maybe<Object> maybe = ((EntityInternal)member).config().getLocalRaw(TestEntity.CONF_NAME); - Assert.assertTrue(maybe.isPresentAndNonNull()); - BrooklynDslDeferredSupplier<?> deferredSupplier = (BrooklynDslDeferredSupplier<?>) maybe.get(); - Assert.assertEquals(deferredSupplier.toString(), "$brooklyn:entity(\"test-cluster\").attributeWhenReady(\"sensor\")"); - } - - if (resolvedBeforeRebind) { - // All members should resolve their config - for (Entity member : Iterables.filter(cluster2.getChildren(), TestEntity.class)) { - String val = getConfigInTask(member, TestEntity.CONF_NAME); - Assert.assertEquals(val, "bar"); - } - } else { - List<Future<String>> futures = Lists.newArrayList(); - - // All members should have unresolved values - for (Entity member : Iterables.filter(cluster2.getChildren(), TestEntity.class)) { - // Wait for the attribute to be ready in a new Task - Future<String> stringFuture = getConfigInTaskAsync(member, TestEntity.CONF_NAME); - futures.add(stringFuture); - - // Check that the Task is still waiting for attribute to be ready - Thread.sleep(100); - Assert.assertFalse(stringFuture.isDone()); - } - - // After setting the sensor, all those values should now resolve - cluster2.sensors().set(Sensors.newStringSensor("sensor"), "bar"); - - for (Future<String> future : futures) { - String s = future.get(10, TimeUnit.SECONDS); // Timeout just for sanity - Assert.assertEquals(s, "bar"); - } - } - } - - private Entity entityWithAttributeWhenReady() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.confName: $brooklyn:component(\"x\").attributeWhenReady(\"foo\")"); - } - - private void doTestOnEntityWithSensor(Entity testEntity, Sensor<?> expectedSensor) throws Exception { - doTestOnEntityWithSensor(testEntity, expectedSensor, true); - } - - private void doTestOnEntityWithSensor(Entity testEntity, Sensor<?> expectedSensor, boolean inTask) throws Exception { - @SuppressWarnings("rawtypes") - ConfigKey<Sensor> configKey = ConfigKeys.newConfigKey(Sensor.class, "test.sensor"); - Sensor<?> s; - s = inTask ? getConfigInTask(testEntity, configKey) : testEntity.getConfig(configKey); - Assert.assertEquals(s, expectedSensor); - Application app2 = rebind(testEntity.getApplication()); - Entity te2 = Iterables.getOnlyElement(app2.getChildren()); - s = inTask ? getConfigInTask(te2, configKey) : te2.getConfig(configKey); - Assert.assertEquals(s, expectedSensor); - } - - @Test - public void testDslSensorFromClass() throws Exception { - doTestOnEntityWithSensor(entityWithSensorFromClass(), Attributes.SERVICE_UP); - // without context it can still find it - doTestOnEntityWithSensor(entityWithSensorFromClass(), Attributes.SERVICE_UP, false); - } - - @Test - public void testDslSensorLocal() throws Exception { - doTestOnEntityWithSensor(entityWithSensorLocal(), TestEntity.SEQUENCE); - // here without context it makes one up, so type info (and description etc) not present; - // but context is needed to submit the DslDeferredSupplier object, so this would fail -// doTestOnEntityWithSensor(entityWithSensorAdHoc(), Sensors.newSensor(Object.class, TestEntity.SEQUENCE.getName()), false); - } - - @Test - public void testDslSensorAdHoc() throws Exception { - doTestOnEntityWithSensor(entityWithSensorAdHoc(), Sensors.newSensor(Object.class, "sensor.foo")); - // here context has no impact, but it is needed to submit the DslDeferredSupplier object so this would fail -// doTestOnEntityWithSensor(entityWithSensorAdHoc(), Sensors.newSensor(Object.class, "sensor.foo"), false); - } - - private Entity entityWithSensorFromClass() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.sensor: $brooklyn:sensor(\"" + Attributes.class.getName() + "\", \"" + Attributes.SERVICE_UP.getName() + "\")"); - } - - private Entity entityWithSensorLocal() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.sensor: $brooklyn:sensor(\"" + TestEntity.SEQUENCE.getName() + "\")"); - } - - private Entity entityWithSensorAdHoc() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.sensor: $brooklyn:sensor(\"sensor.foo\")"); - } - - - @Test - public void testDslConfigFromRoot() throws Exception { - Entity testEntity = entityWithConfigFromRoot(); - Assert.assertEquals(getConfigInTask(testEntity, TestEntity.CONF_NAME), "bar"); - } - - @Test - public void testDslConfigFromRootRebind() throws Exception { - Entity testEntity = entityWithConfigFromRoot(); - Application app2 = rebind(testEntity.getApplication()); - Entity e2 = Iterables.getOnlyElement(app2.getChildren()); - - Assert.assertEquals(getConfigInTask(e2, TestEntity.CONF_NAME), "bar"); - } - - private Entity entityWithConfigFromRoot() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.confName: $brooklyn:component(\"x\").config(\"foo\")", - "brooklyn.config:", - " foo: bar"); - } - - - @Test - public void testDslFormatString() throws Exception { - Entity testEntity = entityWithFormatString(); - Assert.assertEquals(getConfigInTask(testEntity, TestEntity.CONF_NAME), "hello world"); - } - - @Test - public void testDslFormatStringRebind() throws Exception { - Entity testEntity = entityWithFormatString(); - Application app2 = rebind(testEntity.getApplication()); - Entity e2 = Iterables.getOnlyElement(app2.getChildren()); - - Assert.assertEquals(getConfigInTask(e2, TestEntity.CONF_NAME), "hello world"); - } - - private Entity entityWithFormatString() throws Exception { - return setupAndCheckTestEntityInBasicYamlWith( - " id: x", - " brooklyn.config:", - " test.confName: $brooklyn:formatString(\"hello %s\", \"world\")"); - } - - - /* - - type: org.apache.brooklyn.enricher.stock.Transformer - brooklyn.config: - enricher.sourceSensor: $brooklyn:sensor("mongodb.server.replicaSet.primary.endpoint") - enricher.targetSensor: $brooklyn:sensor("justtheport") - enricher.transformation: $brooklyn:function.regexReplacement("^.*:", "") - - type: org.apache.brooklyn.enricher.stock.Transformer - brooklyn.config: - enricher.sourceSensor: $brooklyn:sensor("mongodb.server.replicaSet.primary.endpoint") - enricher.targetSensor: $brooklyn:sensor("directport") - enricher.targetValue: $brooklyn:regexReplacement($brooklyn:attributeWhenReady("mongodb.server.replicaSet.primary.endpoint"), "^.*:", "foo") - */ - - @Test - public void testRegexReplacementWithStrings() throws Exception { - Entity testEntity = setupAndCheckTestEntityInBasicYamlWith( - " brooklyn.config:", - " test.regex.config: $brooklyn:regexReplacement(\"somefooname\", \"foo\", \"bar\")" - ); - Assert.assertEquals("somebarname", testEntity.getConfig(ConfigKeys.newStringConfigKey("test.regex.config"))); - } - - @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"))); - } - - @Test - public void testRegexReplacementFunctionWithStrings() throws Exception { - Entity testEntity = setupAndCheckTestEntityInBasicYamlWith( - " brooklyn.enrichers:", - " - type: org.apache.brooklyn.enricher.stock.Transformer", - " brooklyn.config:", - " enricher.sourceSensor: $brooklyn:sensor(\"test.name\")", - " enricher.targetSensor: $brooklyn:sensor(\"test.name.transformed\")", - " enricher.transformation: $brooklyn:function.regexReplacement(\"foo\", \"bar\")" - ); - testEntity.sensors().set(TestEntity.NAME, "somefooname"); - AttributeSensor<String> transformedSensor = Sensors.newStringSensor("test.name.transformed"); - EntityAsserts.assertAttributeEqualsEventually(testEntity, transformedSensor, "somebarname"); - } - - @Test - public void testRegexReplacementFunctionWithAttributeWhenReady() throws Exception { - Entity testEntity = setupAndCheckTestEntityInBasicYamlWith( - " brooklyn.enrichers:", - " - type: org.apache.brooklyn.enricher.stock.Transformer", - " brooklyn.config:", - " enricher.sourceSensor: $brooklyn:sensor(\"test.name\")", - " enricher.targetSensor: $brooklyn:sensor(\"test.name.transformed\")", - " enricher.transformation: $brooklyn:function.regexReplacement($brooklyn:attributeWhenReady(\"test.pattern\"), $brooklyn:attributeWhenReady(\"test.replacement\"))" - ); - testEntity.sensors().set(Sensors.newStringSensor("test.pattern"), "foo"); - testEntity.sensors().set(Sensors.newStringSensor("test.replacement"), "bar"); - testEntity.sensors().set(TestEntity.NAME, "somefooname"); - AttributeSensor<String> transformedSensor = Sensors.newStringSensor("test.name.transformed"); - EntityAsserts.assertAttributeEqualsEventually(testEntity, transformedSensor, "somebarname"); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java deleted file mode 100644 index 0554917..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptySoftwareProcessYamlTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import java.util.Iterator; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.BrooklynConfigKeys; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityAsserts; -import org.apache.brooklyn.entity.software.base.EmptySoftwareProcess; -import org.apache.brooklyn.location.ssh.SshMachineLocation; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.collections.Jsonya; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; - -@Test -public class EmptySoftwareProcessYamlTest extends AbstractYamlTest { - private static final Logger log = LoggerFactory.getLogger(EnrichersYamlTest.class); - - @Test(groups="Integration") - public void testProvisioningProperties() throws Exception { - Entity app = createAndStartApplication( - "location: localhost", - "services:", - "- type: "+EmptySoftwareProcess.class.getName(), - " provisioning.properties:", - " minRam: 16384"); - waitForApplicationTasks(app); - - log.info("App started:"); - Entities.dumpInfo(app); - - EmptySoftwareProcess entity = (EmptySoftwareProcess) app.getChildren().iterator().next(); - Map<String, Object> pp = entity.getConfig(EmptySoftwareProcess.PROVISIONING_PROPERTIES); - Assert.assertEquals(pp.get("minRam"), 16384); - } - - @Test(groups="Integration") - public void testProvisioningPropertiesViaJsonya() throws Exception { - Entity app = createAndStartApplication( - Jsonya.newInstance() - .put("location", "localhost") - .at("services").list() - .put("type", EmptySoftwareProcess.class.getName()) - .at("provisioning.properties").put("minRam", 16384) - .root().toString()); - waitForApplicationTasks(app); - - log.info("App started:"); - Entities.dumpInfo(app); - - EmptySoftwareProcess entity = (EmptySoftwareProcess) app.getChildren().iterator().next(); - Map<String, Object> pp = entity.getConfig(EmptySoftwareProcess.PROVISIONING_PROPERTIES); - Assert.assertEquals(pp.get("minRam"), 16384); - } - - // for https://github.com/brooklyncentral/brooklyn/issues/1377 - @Test(groups="Integration") - public void testWithAppAndEntityLocations() throws Exception { - Entity app = createAndStartApplication( - "services:", - "- type: "+EmptySoftwareProcess.class.getName(), - " location: localhost:(name=localhost on entity)", - "location: byon:(hosts=\"127.0.0.1\", name=loopback on app)"); - waitForApplicationTasks(app); - Entities.dumpInfo(app); - - Assert.assertEquals(app.getLocations().size(), 1); - Assert.assertEquals(app.getChildren().size(), 1); - Entity entity = app.getChildren().iterator().next(); - - Location appLocation = app.getLocations().iterator().next(); - Assert.assertEquals(appLocation.getDisplayName(), "loopback on app"); - - Assert.assertEquals(entity.getLocations().size(), 2); - Iterator<Location> entityLocationIterator = entity.getLocations().iterator(); - Assert.assertEquals(entityLocationIterator.next().getDisplayName(), "localhost on entity"); - Location actualMachine = entityLocationIterator.next(); - Assert.assertTrue(actualMachine instanceof SshMachineLocation, "wrong location: "+actualMachine); - // TODO this, below, probably should be 'localhost on entity', see #1377 - Assert.assertEquals(actualMachine.getParent().getDisplayName(), "localhost on entity"); - } - - @Test(groups="Integration") - public void testNoSshing() throws Exception { - Entity app = createAndStartApplication( - "location: byon:(hosts=\"1.2.3.4\")", - "services:", - "- type: "+EmptySoftwareProcess.class.getName(), - " brooklyn.config:", - " sshMonitoring.enabled: false", - " "+BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION.getName()+": true"); - waitForApplicationTasks(app); - - EmptySoftwareProcess entity = Iterables.getOnlyElement(Entities.descendants(app, EmptySoftwareProcess.class)); - EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true); - EntityAsserts.assertAttributeEqualsContinually(entity, Attributes.SERVICE_UP, true); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptyWindowsProcessYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptyWindowsProcessYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptyWindowsProcessYamlTest.java deleted file mode 100644 index 77043c7..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EmptyWindowsProcessYamlTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.core.entity.Attributes; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityAsserts; -import org.apache.brooklyn.entity.software.base.EmptyWindowsProcess; -import org.apache.brooklyn.location.winrm.WinRmMachineLocation; -import org.testng.annotations.Test; - -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - -@Test -public class EmptyWindowsProcessYamlTest extends AbstractYamlTest { - - @Test(groups="Integration") - public void testNoWinrm() throws Exception { - Entity app = createAndStartApplication( - "location: byon:(hosts=\"1.2.3.4\",osFamily=windows)", - "services:", - "- type: "+EmptyWindowsProcess.class.getName(), - " brooklyn.config:", - " winrmMonitoring.enabled: false"); - waitForApplicationTasks(app); - - EmptyWindowsProcess entity = Iterables.getOnlyElement(Entities.descendants(app, EmptyWindowsProcess.class)); - EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true); - EntityAsserts.assertAttributeEqualsContinually(entity, Attributes.SERVICE_UP, true); - - Iterables.find(entity.getLocations(), Predicates.instanceOf(WinRmMachineLocation.class)); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EnrichersYamlTest.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EnrichersYamlTest.java b/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EnrichersYamlTest.java deleted file mode 100644 index cf9f204..0000000 --- a/brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/EnrichersYamlTest.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.camp.brooklyn; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.sensor.Enricher; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.entity.Entities; -import org.apache.brooklyn.core.entity.EntityAdjuncts; -import org.apache.brooklyn.core.entity.EntityInternal; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.core.test.policy.TestEnricher; -import org.apache.brooklyn.enricher.stock.Propagator; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.collections.MutableMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import com.google.common.base.Predicates; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -@Test -public class EnrichersYamlTest extends AbstractYamlTest { - private static final Logger log = LoggerFactory.getLogger(EnrichersYamlTest.class); - - @Test - public void testWithAppEnricher() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-app-with-enricher.yaml")); - waitForApplicationTasks(app); - Assert.assertEquals(app.getDisplayName(), "test-app-with-enricher"); - - log.info("App started:"); - Entities.dumpInfo(app); - - Assert.assertEquals(EntityAdjuncts.getNonSystemEnrichers(app).size(), 1); - final Enricher enricher = EntityAdjuncts.getNonSystemEnrichers(app).iterator().next(); - Assert.assertTrue(enricher instanceof TestEnricher, "enricher="+enricher); - Assert.assertEquals(enricher.getConfig(TestEnricher.CONF_NAME), "Name from YAML"); - Assert.assertEquals(enricher.getConfig(TestEnricher.CONF_FROM_FUNCTION), "$brooklyn: is a fun place"); - - Entity target = ((EntityInternal)app).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() { - public Entity call() { - return enricher.getConfig(TestEnricher.TARGET_ENTITY); - }}).get(); - Assert.assertNotNull(target); - Assert.assertEquals(target.getDisplayName(), "testentity"); - Assert.assertEquals(target, app.getChildren().iterator().next()); - Entity targetFromFlag = ((EntityInternal)app).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() { - public Entity call() { - return enricher.getConfig(TestEnricher.TARGET_ENTITY_FROM_FLAG); - }}).get(); - Assert.assertEquals(targetFromFlag, target); - Map<?, ?> leftoverProperties = ((TestEnricher) enricher).getLeftoverProperties(); - Assert.assertEquals(leftoverProperties.get("enricherLiteralValue1"), "Hello"); - Assert.assertEquals(leftoverProperties.get("enricherLiteralValue2"), "World"); - Assert.assertEquals(leftoverProperties.size(), 2); - } - - @Test - public void testWithEntityEnricher() throws Exception { - final Entity app = createAndStartApplication(loadYaml("test-entity-with-enricher.yaml")); - waitForApplicationTasks(app); - Assert.assertEquals(app.getDisplayName(), "test-entity-with-enricher"); - - log.info("App started:"); - Entities.dumpInfo(app); - - Assert.assertEquals(EntityAdjuncts.getNonSystemEnrichers(app).size(), 0); - Assert.assertEquals(app.getChildren().size(), 1); - final Entity child = app.getChildren().iterator().next(); - Asserts.eventually(new Supplier<Integer>() { - @Override - public Integer get() { - return EntityAdjuncts.getNonSystemEnrichers(child).size(); - } - }, Predicates.<Integer> equalTo(1)); - final Enricher enricher = EntityAdjuncts.getNonSystemEnrichers(child).iterator().next(); - Assert.assertNotNull(enricher); - Assert.assertTrue(enricher instanceof TestEnricher, "enricher=" + enricher + "; type=" + enricher.getClass()); - Assert.assertEquals(enricher.getConfig(TestEnricher.CONF_NAME), "Name from YAML"); - Assert.assertEquals(enricher.getConfig(TestEnricher.CONF_FROM_FUNCTION), "$brooklyn: is a fun place"); - - Assert.assertEquals(((TestEnricher) enricher).getLeftoverProperties(), - ImmutableMap.of("enricherLiteralValue1", "Hello", "enricherLiteralValue2", "World")); - } - - @Test - public void testPropagatingEnricher() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-propagating-enricher.yaml")); - waitForApplicationTasks(app); - Assert.assertEquals(app.getDisplayName(), "test-propagating-enricher"); - - log.info("App started:"); - Entities.dumpInfo(app); - TestEntity entity = (TestEntity)app.getChildren().iterator().next(); - entity.sensors().set(TestEntity.NAME, "New Name"); - Asserts.eventually(Entities.attributeSupplier(app, TestEntity.NAME), Predicates.<String>equalTo("New Name")); - } - - @Test - public void testPropogateChildSensor() throws Exception { - Entity app = createAndStartApplication(loadYaml("test-entity-basic-template.yaml", - " brooklyn.config:", - " test.confName: parent entity", - " id: parentId", - " brooklyn.enrichers:", - " - enricherType: org.apache.brooklyn.enricher.stock.Propagator", - " brooklyn.config:", - " enricher.producer: $brooklyn:component(\"childId\")", - " enricher.propagating.propagatingAll: true", - " brooklyn.children:", - " - serviceType: org.apache.brooklyn.core.test.entity.TestEntity", - " id: childId", - " brooklyn.config:", - " test.confName: Child Name")); - waitForApplicationTasks(app); - - log.info("App started:"); - Entities.dumpInfo(app); - Assert.assertEquals(app.getChildren().size(), 1); - final Entity parentEntity = app.getChildren().iterator().next(); - Assert.assertTrue(parentEntity instanceof TestEntity, "Expected parent entity to be TestEntity, found:" + parentEntity); - Assert.assertEquals(parentEntity.getChildren().size(), 1); - Entity childEntity = parentEntity.getChildren().iterator().next(); - Assert.assertTrue(childEntity instanceof TestEntity, "Expected child entity to be TestEntity, found:" + childEntity); - Asserts.eventually(new Supplier<Integer>() { - @Override - public Integer get() { - return EntityAdjuncts.getNonSystemEnrichers(parentEntity).size(); - } - }, Predicates.<Integer>equalTo(1)); - Enricher enricher = EntityAdjuncts.getNonSystemEnrichers(parentEntity).iterator().next(); - Asserts.assertTrue(enricher instanceof Propagator, "Expected enricher to be Propagator, found:" + enricher); - final Propagator propagator = (Propagator)enricher; - Entity producer = ((EntityInternal)parentEntity).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() { - public Entity call() { - return propagator.getConfig(Propagator.PRODUCER); - }}).get(); - Assert.assertEquals(producer, childEntity); - Asserts.assertTrue(Boolean.valueOf(propagator.getConfig(Propagator.PROPAGATING_ALL)), "Expected Propagator.PROPAGATING_ALL to be true"); - ((TestEntity)childEntity).sensors().set(TestEntity.NAME, "New Name"); - Asserts.eventually(Entities.attributeSupplier(parentEntity, TestEntity.NAME), Predicates.<String>equalTo("New Name")); - } - - @Test - public void testMultipleEnricherReferences() throws Exception { - final Entity app = createAndStartApplication(loadYaml("test-referencing-enrichers.yaml")); - waitForApplicationTasks(app); - - Entity entity1 = null, entity2 = null, child1 = null, child2 = null, grandchild1 = null, grandchild2 = null; - - Assert.assertEquals(app.getChildren().size(), 2); - for (Entity child : app.getChildren()) { - if (child.getDisplayName().equals("entity 1")) - entity1 = child; - if (child.getDisplayName().equals("entity 2")) - entity2 = child; - } - Assert.assertNotNull(entity1); - Assert.assertNotNull(entity2); - - Assert.assertEquals(entity1.getChildren().size(), 2); - for (Entity child : entity1.getChildren()) { - if (child.getDisplayName().equals("child 1")) - child1 = child; - if (child.getDisplayName().equals("child 2")) - child2 = child; - } - Assert.assertNotNull(child1); - Assert.assertNotNull(child2); - - Assert.assertEquals(child1.getChildren().size(), 2); - for (Entity child : child1.getChildren()) { - if (child.getDisplayName().equals("grandchild 1")) - grandchild1 = child; - if (child.getDisplayName().equals("grandchild 2")) - grandchild2 = child; - } - Assert.assertNotNull(grandchild1); - Assert.assertNotNull(grandchild2); - - ImmutableSet<Enricher> enrichers = new ImmutableSet.Builder<Enricher>() - .add(getEnricher(app)) - .add(getEnricher(entity1)) - .add(getEnricher(entity2)) - .add(getEnricher(child1)) - .add(getEnricher(child2)) - .add(getEnricher(grandchild1)) - .add(getEnricher(grandchild2)) - .build(); - - Map<ConfigKey<Entity>, Entity> keyToEntity = new ImmutableMap.Builder<ConfigKey<Entity>, Entity>() - .put(TestReferencingEnricher.TEST_APPLICATION, app) - .put(TestReferencingEnricher.TEST_ENTITY_1, entity1) - .put(TestReferencingEnricher.TEST_ENTITY_2, entity2) - .put(TestReferencingEnricher.TEST_CHILD_1, child1) - .put(TestReferencingEnricher.TEST_CHILD_2, child2) - .put(TestReferencingEnricher.TEST_GRANDCHILD_1, grandchild1) - .put(TestReferencingEnricher.TEST_GRANDCHILD_2, grandchild2) - .build(); - - for (Enricher enricher : enrichers) - checkReferences(enricher, keyToEntity); - } - - private void checkReferences(final Enricher enricher, Map<ConfigKey<Entity>, Entity> keyToEntity) throws Exception { - for (final ConfigKey<Entity> key : keyToEntity.keySet()) { - final Entity entity = keyToEntity.get(key); // Grab an entity whose execution context we can use - Entity fromConfig = ((EntityInternal)entity).getExecutionContext().submit(MutableMap.of(), new Callable<Entity>() { - @Override - public Entity call() throws Exception { - return (Entity) enricher.getConfig(key); - } - }).get(); - Assert.assertEquals(fromConfig, keyToEntity.get(key)); - } - } - - private Enricher getEnricher(Entity entity) { - List<Enricher> enrichers = EntityAdjuncts.getNonSystemEnrichers(entity); - Assert.assertEquals(enrichers.size(), 1, "Wrong number of enrichers: "+enrichers); - Enricher enricher = enrichers.iterator().next(); - Assert.assertTrue(enricher instanceof TestReferencingEnricher, "Wrong enricher: "+enricher); - return enricher; - } - - @Override - protected Logger getLogger() { - return log; - } - -}
