http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java deleted file mode 100644 index 2f0e336..0000000 --- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/MyEntityImpl.java +++ /dev/null @@ -1,126 +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 brooklyn.entity.basic.lifecycle; - -import java.util.List; - -import brooklyn.entity.basic.SoftwareProcess; -import brooklyn.entity.basic.SoftwareProcessDriver; -import brooklyn.entity.basic.SoftwareProcessImpl; -import brooklyn.entity.java.JavaSoftwareProcessSshDriver; - -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.location.basic.SshMachineLocation; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.ResourceUtils; -import org.apache.brooklyn.util.core.flags.SetFromFlag; -import org.apache.brooklyn.util.text.Identifiers; - -public class MyEntityImpl extends SoftwareProcessImpl implements MyEntity { - @Override - public Class<?> getDriverInterface() { - return MyEntityDriver.class; - } - - @Override - protected void connectSensors() { - super.connectSensors(); - connectServiceUpIsRunning(); - } - - @Override - protected void disconnectSensors() { - super.disconnectSensors(); - disconnectServiceUpIsRunning(); - } - - public interface MyEntityDriver extends SoftwareProcessDriver {} - - public static class MyEntitySshDriver extends JavaSoftwareProcessSshDriver implements MyEntityDriver { - - @SetFromFlag("version") - public static final ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "0.1"); - - public MyEntitySshDriver(MyEntityImpl entity, SshMachineLocation machine) { - super(entity, machine); - } - - @Override - protected String getLogFileLocation() { - return getRunDir()+"/nohup.out"; - } - - @Override - public void install() { - String resourceName = "/"+MyEntityApp.class.getName().replace(".", "/")+".class"; - ResourceUtils r = ResourceUtils.create(this); - if (r.getResourceFromUrl(resourceName) == null) - throw new IllegalStateException("Cannot find resource "+resourceName); - String tmpFile = "/tmp/brooklyn-test-MyEntityApp-"+Identifiers.makeRandomId(6)+".class"; - int result = getMachine().installTo(resourceName, tmpFile); - if (result!=0) throw new IllegalStateException("Cannot install "+resourceName+" to "+tmpFile); - String saveAs = "classes/"+MyEntityApp.class.getPackage().getName().replace(".", "/")+"/"+MyEntityApp.class.getSimpleName()+".class"; - newScript(INSTALLING). - failOnNonZeroResultCode(). - body.append( - "curl -L \"file://"+tmpFile+"\" --create-dirs -o "+saveAs+" || exit 9" - ).execute(); - } - - @Override - public void customize() { - newScript(CUSTOMIZING) - .execute(); - } - - @Override - public void launch() { - newScript(MutableMap.of("usePidFile", true), LAUNCHING) - .body.append( - String.format("nohup java -classpath %s/classes $JAVA_OPTS %s &", getInstallDir(), MyEntityApp.class.getName()) - ).execute(); - } - - @Override - public boolean isRunning() { - //TODO use PID instead - return newScript(MutableMap.of("usePidFile", true), CHECK_RUNNING) - .execute() == 0; - } - - @Override - public void stop() { - newScript(MutableMap.of("usePidFile", true), STOPPING) - .execute(); - } - - @Override - public void kill() { - newScript(MutableMap.of("usePidFile", true), KILLING) - .execute(); - } - - @Override - protected List<String> getCustomJavaConfigOptions() { - return MutableList.<String>builder().addAll(super.getCustomJavaConfigOptions()).add("-Dabc=def").build(); - } - } -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java deleted file mode 100644 index 4ef2bde..0000000 --- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/NaiveScriptRunnerTest.java +++ /dev/null @@ -1,252 +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 brooklyn.entity.basic.lifecycle; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - -import org.apache.brooklyn.api.location.NoMachinesAvailableException; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags; -import org.apache.brooklyn.core.mgmt.BrooklynTaskTags.WrappedStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.task.BasicExecutionContext; -import org.apache.brooklyn.util.core.task.BasicExecutionManager; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.repeat.Repeater; -import org.apache.brooklyn.util.time.Duration; - -import com.google.common.base.Throwables; - -@Test -public class NaiveScriptRunnerTest { - - private static final Logger log = LoggerFactory.getLogger(NaiveScriptRunnerTest.class); - - List<String> commands = new ArrayList<String>(); - - @BeforeMethod - private void setup() { commands.clear(); } - - @SuppressWarnings("rawtypes") - private NaiveScriptRunner newMockRunner(final int result) { - return new NaiveScriptRunner() { - @Override - public int execute(List<String> script, String summaryForLogging) { - return execute(new MutableMap(), script, summaryForLogging); - } - @Override - public int execute(Map flags, List<String> script, String summaryForLogging) { - commands.addAll(script); - return result; - } - }; - } - - @SuppressWarnings("rawtypes") - public static NaiveScriptRunner newLocalhostRunner() { - return new NaiveScriptRunner() { - LocalhostMachineProvisioningLocation location = new LocalhostMachineProvisioningLocation(); - @Override - public int execute(List<String> script, String summaryForLogging) { - return execute(new MutableMap(), script, summaryForLogging); - } - @SuppressWarnings("unchecked") - @Override - public int execute(Map flags, List<String> script, String summaryForLogging) { - try { - Map flags2 = MutableMap.of("logPrefix", "test"); - flags2.putAll(flags); - return location.obtain().execScript(flags2, summaryForLogging, script); - } catch (NoMachinesAvailableException e) { - throw Throwables.propagate(e); - } - } - }; - }; - - public void testHeadBodyFootAndResult() { - ScriptHelper h = new ScriptHelper(newMockRunner(101), "mock"); - int result = h.header. - append("h1", "h2").body.append("b1", "b2").footer.append("f1", "f2"). - execute(); - Assert.assertEquals(result, 101); - Assert.assertEquals(commands, Arrays.asList("h1", "h2", "b1", "b2", "f1", "f2"), "List wrong: "+commands); - } - - public void testFailOnNonZero() { - ScriptHelper h = new ScriptHelper(newMockRunner(106), "mock"); - boolean succeededWhenShouldntHave = false; - try { - h.body.append("ignored"). - failOnNonZeroResultCode(). // will happen - execute(); - succeededWhenShouldntHave = true; - } catch (Exception e) { - log.info("ScriptHelper non-zero causes return code: "+e); - } - if (succeededWhenShouldntHave) Assert.fail("succeeded when shouldn't have"); - } - - public void testFailOnNonZeroDontFailIfZero() { - int result = new ScriptHelper(newMockRunner(0), "mock").body.append("ignored"). - failOnNonZeroResultCode(). // will happen - execute(); - Assert.assertEquals(result, 0); - } - - - @Test(groups = "Integration") - public void testFailingCommandFailsEarly() { - ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("curl road://to/nowhere", "exit 11"). - gatherOutput(); - int result = script.execute(); - // should get _1_ from curl failing, not 11 from us - // TODO not sure why though! - Assert.assertEquals(1, result); - } - - // TODO a good way to indicate when downloads fail, as that is quite a common case - // but i think we need quite a bit of scaffolding to detect that problem (without inspecting logs) ... - - @Test(groups = "Integration") - public void testGatherOutputStdout() { - ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("echo `echo foo``echo bar`", "exit 8"). - gatherOutput(); - int result = script.execute(); - Assert.assertEquals(8, result); - if (!script.getResultStdout().contains("foobar")) - Assert.fail("STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+ - "\nSTDERR:\n"+script.getResultStderr()); - } - - @Test(groups = "Integration") - public void testGatherOutputStderr() { - ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("set -x", "curl road://to/nowhere || exit 11"). - gatherOutput(); - int result = script.execute(); - Assert.assertEquals(11, result); - if (!script.getResultStderr().contains("road")) - Assert.fail("STDERR does not contain expected text 'road'.\n"+script.getResultStderr()+ - "\nSTDOUT:\n"+script.getResultStdout()); - } - - @Test(groups = "Integration") - public void testGatherOutuputNotEnabled() { - ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("echo foo", "exit 11"); - int result = script.execute(); - Assert.assertEquals(11, result); - boolean succeededWhenShouldNotHave = false; - try { - script.getResultStdout(); - succeededWhenShouldNotHave = true; - } catch (Exception e) { /* expected */ } - if (succeededWhenShouldNotHave) Assert.fail("Should have failed"); - } - - @Test(groups = "Integration") - public void testStreamsInTask() { - final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq"). - gatherOutput(); - Assert.assertNull(script.peekTask()); - Task<Integer> task = script.newTask(); - Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task)); - Assert.assertFalse(Tasks.isQueuedOrSubmitted(task)); - WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN); - Assert.assertNotNull(in); - Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get()); - Assert.assertTrue(in.streamSize.get() > 0); - Assert.assertNotNull(script.peekTask()); - } - - @Test(groups = "Integration") - public void testAutoQueueAndRuntimeStreamsInTask() { - final ScriptHelper script = new ScriptHelper(newLocalhostRunner(), "mock"). - body.append("echo `echo foo``echo bar`", "grep absent-text badfile_which_does_not_exist_blaahblahasdewq"). - gatherOutput(); - Task<Integer> submitter = Tasks.<Integer>builder().body(new Callable<Integer>() { - public Integer call() { - int result = script.execute(); - return result; - } - }).build(); - BasicExecutionManager em = new BasicExecutionManager("tests"); - BasicExecutionContext ec = new BasicExecutionContext(em); - try { - Assert.assertNull(script.peekTask()); - ec.submit(submitter); - // soon there should be a task which is submitted - Assert.assertTrue(Repeater.create("get script").every(Duration.millis(10)).limitTimeTo(Duration.FIVE_SECONDS).until(new Callable<Boolean>() { - public Boolean call() { - return (script.peekTask() != null) && Tasks.isQueuedOrSubmitted(script.peekTask()); - } - }).run()); - Task<Integer> task = script.peekTask(); - Assert.assertTrue(BrooklynTaskTags.streams(task).size() >= 3, "Expected at least 3 streams: "+BrooklynTaskTags.streams(task)); - // stdin should be populated - WrappedStream in = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDIN); - Assert.assertNotNull(in); - Assert.assertTrue(in.streamContents.get().contains("echo foo"), "Expected 'echo foo' but had: "+in.streamContents.get()); - Assert.assertTrue(in.streamSize.get() > 0); - - // out and err should exist - WrappedStream out = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDOUT); - WrappedStream err = BrooklynTaskTags.stream(task, BrooklynTaskTags.STREAM_STDERR); - Assert.assertNotNull(out); - Assert.assertNotNull(err); - - // it should soon finish, with exit code - Integer result = task.getUnchecked(Duration.TEN_SECONDS); - Assert.assertNotNull(result); - Assert.assertTrue(result > 0, "Expected non-zero exit code: "+result); - // and should contain foobar in stdout - if (!script.getResultStdout().contains("foobar")) - Assert.fail("Script STDOUT does not contain expected text 'foobar'.\n"+script.getResultStdout()+ - "\nSTDERR:\n"+script.getResultStderr()); - if (!out.streamContents.get().contains("foobar")) - Assert.fail("Task STDOUT does not contain expected text 'foobar'.\n"+out.streamContents.get()+ - "\nSTDERR:\n"+script.getResultStderr()); - // and "No such file or directory" in stderr - if (!script.getResultStderr().contains("No such file or directory")) - Assert.fail("Script STDERR does not contain expected text 'No such ...'.\n"+script.getResultStdout()+ - "\nSTDERR:\n"+script.getResultStderr()); - if (!err.streamContents.get().contains("No such file or directory")) - Assert.fail("Task STDERR does not contain expected text 'No such...'.\n"+out.streamContents.get()+ - "\nSTDERR:\n"+script.getResultStderr()); - } finally { - em.shutdownNow(); - } - } - - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java deleted file mode 100644 index f0288f3..0000000 --- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/ScriptHelperTest.java +++ /dev/null @@ -1,159 +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 brooklyn.entity.basic.lifecycle; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport; -import org.apache.brooklyn.entity.trait.Startable; -import org.apache.brooklyn.sensor.feed.function.FunctionFeed; -import org.apache.brooklyn.sensor.feed.function.FunctionPollConfig; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.time.Duration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.TestException; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.SoftwareProcess; -import brooklyn.entity.basic.SoftwareProcessEntityTest; -import brooklyn.entity.basic.SoftwareProcessEntityTest.MyService; -import brooklyn.entity.basic.SoftwareProcessEntityTest.MyServiceImpl; - -import org.apache.brooklyn.location.basic.FixedListMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.base.Functions; -import com.google.common.collect.ImmutableList; - -public class ScriptHelperTest extends BrooklynAppUnitTestSupport { - - private static final Logger log = LoggerFactory.getLogger(ScriptHelperTest.class); - - private SshMachineLocation machine; - private FixedListMachineProvisioningLocation<SshMachineLocation> loc; - boolean shouldFail = false; - int failCount = 0; - - @BeforeMethod(alwaysRun=true) - @SuppressWarnings("unchecked") - @Override - public void setUp() throws Exception { - super.setUp(); - loc = mgmt.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)); - machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class) - .configure("address", "localhost")); - loc.addMachine(machine); - } - - @Test - public void testCheckRunningForcesInessential() { - MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class, MyServiceInessentialDriverImpl.class)); - - entity.start(ImmutableList.of(loc)); - SimulatedInessentialIsRunningDriver driver = (SimulatedInessentialIsRunningDriver) entity.getDriver(); - Assert.assertTrue(driver.isRunning()); - - EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true); - EntityTestUtils.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, true); - - log.debug("up, now cause failure"); - - driver.setFailExecution(true); - EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false); - - log.debug("caught failure, now clear"); - driver.setFailExecution(false); - EntityTestUtils.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true); - } - - public static class MyServiceInessentialDriverImpl extends MyServiceImpl { - - @Override public Class<?> getDriverInterface() { - return SimulatedInessentialIsRunningDriver.class; - } - - @Override - protected void connectSensors() { - super.connectSensors(); - connectServiceUpIsRunning(); - } - - @Override - public void connectServiceUpIsRunning() { -// super.connectServiceUpIsRunning(); - // run more often - FunctionFeed.builder() - .entity(this) - .period(Duration.millis(10)) - .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING) - .onException(Functions.constant(Boolean.FALSE)) - .callable(new Callable<Boolean>() { - public Boolean call() { - return getDriver().isRunning(); - } - })) - .build(); - } - } - - public static class SimulatedInessentialIsRunningDriver extends SoftwareProcessEntityTest.SimulatedDriver { - private boolean failExecution = false; - - public SimulatedInessentialIsRunningDriver(EntityLocal entity, SshMachineLocation machine) { - super(entity, machine); - } - - @Override - public boolean isRunning() { - return newScript(CHECK_RUNNING) - .execute() == 0; - } - - @Override - public int execute(List<String> script, String summaryForLogging) { - if (failExecution) { - throw new TestException("Simulated driver exception"); - } - return 0; - } - - @SuppressWarnings("rawtypes") - @Override - public int execute(Map flags2, List<String> script, String summaryForLogging) { - if (failExecution) { - throw new TestException("Simulated driver exception"); - } - return 0; - } - - public void setFailExecution(boolean failExecution) { - this.failExecution = failExecution; - } - - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java b/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java deleted file mode 100644 index 48bc72c..0000000 --- a/software/base/src/test/java/brooklyn/entity/basic/lifecycle/StartStopSshDriverTest.java +++ /dev/null @@ -1,170 +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 brooklyn.entity.basic.lifecycle; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.core.test.entity.TestApplicationImpl; -import org.apache.brooklyn.core.test.entity.TestEntity; -import org.apache.brooklyn.core.test.entity.TestEntityImpl; -import org.apache.brooklyn.entity.core.BrooklynConfigKeys; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.collections.MutableList; -import org.apache.brooklyn.util.collections.MutableSet; -import org.apache.brooklyn.util.core.internal.ssh.SshTool; -import org.apache.brooklyn.util.core.internal.ssh.cli.SshCliTool; -import org.apache.brooklyn.util.core.internal.ssh.sshj.SshjTool; -import org.apache.brooklyn.util.stream.StreamGobbler; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver; - -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -public class StartStopSshDriverTest { - - public class BasicStartStopSshDriver extends AbstractSoftwareProcessSshDriver { - public BasicStartStopSshDriver(EntityLocal entity, SshMachineLocation machine) { - super(entity, machine); - } - public boolean isRunning() { return true; } - public void stop() {} - public void kill() {} - public void install() {} - public void customize() {} - public void launch() {} - } - - private static class ThreadIdTransformer implements Function<ThreadInfo, Long> { - @Override - public Long apply(ThreadInfo t) { - return t.getThreadId(); - } - } - - private TestApplication app; - private TestEntity entity; - private SshMachineLocationWithSshTool sshMachineLocation; - private AbstractSoftwareProcessSshDriver driver; - - @SuppressWarnings("rawtypes") - protected static class SshMachineLocationWithSshTool extends SshMachineLocation { - private static final long serialVersionUID = 1L; - - SshTool lastTool; - public SshMachineLocationWithSshTool(Map flags) { super(flags); } - public SshTool connectSsh(Map args) { - SshTool result = super.connectSsh(args); - lastTool = result; - return result; - } - } - - @BeforeMethod(alwaysRun = true) - public void setUp() { - app = new TestApplicationImpl(); - entity = new TestEntityImpl(app); - Entities.startManagement(app); - sshMachineLocation = new SshMachineLocationWithSshTool(ImmutableMap.of("address", "localhost")); - driver = new BasicStartStopSshDriver(entity, sshMachineLocation); - } - - @Test(groups="Integration") - public void testExecuteDoesNotLeaveRunningStreamGobblerThread() { - List<ThreadInfo> existingThreads = getThreadsCalling(StreamGobbler.class); - final List<Long> existingThreadIds = getThreadId(existingThreads); - - List<String> script = Arrays.asList("echo hello"); - driver.execute(script, "mytest"); - - Asserts.succeedsEventually(ImmutableMap.of("timeout", 10*1000), new Runnable() { - @Override - public void run() { - List<ThreadInfo> currentThreads = getThreadsCalling(StreamGobbler.class); - Set<Long> currentThreadIds = MutableSet.copyOf(getThreadId(currentThreads)); - - currentThreadIds.removeAll(existingThreadIds); - assertEquals(currentThreadIds, ImmutableSet.<Long>of()); - } - }); - } - - @Test(groups="Integration") - public void testSshScriptHeaderUsedWhenSpecified() { - entity.setConfig(BrooklynConfigKeys.SSH_CONFIG_SCRIPT_HEADER, "#!/bin/bash -e\necho hello world"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - driver.execute(ImmutableMap.of("out", out), Arrays.asList("echo goodbye"), "test"); - String s = out.toString(); - assertTrue(s.contains("goodbye"), "should have said goodbye: "+s); - assertTrue(s.contains("hello world"), "should have said hello: "+s); - assertTrue(sshMachineLocation.lastTool instanceof SshjTool, "expect sshj tool, got "+ - (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool); - } - - @Test(groups="Integration") - public void testSshCliPickedUpWhenSpecified() { - entity.setConfig(BrooklynConfigKeys.SSH_TOOL_CLASS, SshCliTool.class.getName()); - driver.execute(Arrays.asList("echo hi"), "test"); - assertTrue(sshMachineLocation.lastTool instanceof SshCliTool, "expect CLI tool, got "+ - (sshMachineLocation.lastTool!=null ? ""+sshMachineLocation.lastTool.getClass()+":" : "") + sshMachineLocation.lastTool); - } - - private List<ThreadInfo> getThreadsCalling(Class<?> clazz) { - String clazzName = clazz.getCanonicalName(); - List<ThreadInfo> result = MutableList.of(); - ThreadMXBean threadMxbean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] threads = threadMxbean.dumpAllThreads(false, false); - - for (ThreadInfo thread : threads) { - StackTraceElement[] stackTrace = thread.getStackTrace(); - for (StackTraceElement stackTraceElement : stackTrace) { - if (clazzName == stackTraceElement.getClassName()) { - result.add(thread); - break; - } - } - } - return result; - } - - private ImmutableList<Long> getThreadId(List<ThreadInfo> existingThreads) { - return FluentIterable.from(existingThreads).transform(new ThreadIdTransformer()).toList(); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java deleted file mode 100644 index e69abc2..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynClusterIntegrationTest.java +++ /dev/null @@ -1,97 +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 brooklyn.entity.brooklynnode; - -import java.io.File; -import java.util.List; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.util.javalang.JavaClassNames; -import org.apache.brooklyn.util.net.Networking; -import org.apache.brooklyn.util.os.Os; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; - -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -public class BrooklynClusterIntegrationTest extends BrooklynAppUnitTestSupport { - - private static final Logger LOG = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class); - - private File pseudoBrooklynPropertiesFile; - private File pseudoBrooklynCatalogFile; - private File persistenceDir; - private LocalhostMachineProvisioningLocation loc; - private List<LocalhostMachineProvisioningLocation> locs; - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties"); - pseudoBrooklynPropertiesFile.delete(); - - pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog"); - pseudoBrooklynCatalogFile.delete(); - - loc = app.newLocalhostProvisioningLocation(); - locs = ImmutableList.of(loc); - } - - @AfterMethod(alwaysRun=true) - @Override - public void tearDown() throws Exception { - try { - super.tearDown(); - } finally { - if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete(); - if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete(); - if (persistenceDir != null) Os.deleteRecursively(persistenceDir); - } - } - - @Test(groups="Integration") - public void testCanStartAndStop() throws Exception { - BrooklynCluster cluster = app.createAndManageChild(EntitySpec.create(BrooklynCluster.class) - .configure(BrooklynCluster.INITIAL_SIZE, 1) - .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC) - .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE)); - app.start(locs); - Entity brooklynNode = Iterables.find(cluster.getMembers(), Predicates.instanceOf(BrooklynNode.class)); - LOG.info("started "+app+" containing "+cluster+" for "+JavaClassNames.niceClassAndMethod()); - - EntityTestUtils.assertAttributeEqualsEventually(cluster, BrooklynNode.SERVICE_UP, true); - EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); - - cluster.stop(); - EntityTestUtils.assertAttributeEquals(cluster, BrooklynNode.SERVICE_UP, false); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java deleted file mode 100644 index fb4a99f..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeIntegrationTest.java +++ /dev/null @@ -1,630 +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 brooklyn.entity.brooklynnode; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.File; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; - -import org.apache.brooklyn.api.effector.Effector; -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.internal.EntityLocal; -import org.apache.brooklyn.core.internal.BrooklynProperties; -import org.apache.brooklyn.core.objs.proxy.EntityProxyImpl; -import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.entity.lifecycle.Lifecycle; -import org.apache.brooklyn.entity.stock.BasicApplication; -import org.apache.brooklyn.entity.stock.BasicApplicationImpl; -import org.apache.brooklyn.sensor.feed.http.JsonFunctions; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.test.HttpTestUtils; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.core.http.HttpTool; -import org.apache.brooklyn.util.core.http.HttpToolResponse; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.guava.Functionals; -import org.apache.brooklyn.util.javalang.JavaClassNames; -import org.apache.brooklyn.util.net.Networking; -import org.apache.brooklyn.util.net.Urls; -import org.apache.brooklyn.util.os.Os; -import org.apache.brooklyn.util.text.Strings; -import org.apache.brooklyn.util.time.Duration; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.HttpClient; -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 brooklyn.entity.basic.SoftwareProcess.StopSoftwareParameters.StopMode; -import brooklyn.entity.brooklynnode.BrooklynNode.DeployBlueprintEffector; -import brooklyn.entity.brooklynnode.BrooklynNode.ExistingFileBehaviour; -import brooklyn.entity.brooklynnode.BrooklynNode.StopNodeAndKillAppsEffector; - -import org.apache.brooklyn.location.basic.LocalhostMachineProvisioningLocation; -import org.apache.brooklyn.location.basic.Locations; -import org.apache.brooklyn.location.basic.PortRanges; -import org.apache.brooklyn.location.basic.SshMachineLocation; - -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; - -/** - * This test needs to able to access the binary artifact in order to run. - * The default behaviour is to take this from maven, which works pretty well if you're downloading from hosted maven. - * <p> - * This class has been updated so that it does not effect or depend on the contents of ~/.brooklyn/brooklyn.properties . - * <p> - * If you wish to supply your own version (useful if testing changes locally!), you'll need to force download of this file. - * The simplest way is to install: - * <ul> - * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/BrooklynNode-${VERSION}.tar.gz - for snapshot versions (filename is default format due to lack of filename in sonatype inferencing; - * note on case-sensitive systems it might have to be all in lower case!) - * <li>file://$HOME/.brooklyn/repository/BrooklynNode/${VERSION}/brooklyn-${VERSION}-dist.tar.gz - for release versions, filename should match that in maven central - * </ul> - * In both cases, remember that you may also need to wipe the local apps cache ($BROOKLYN_DATA_DIR/installs/BrooklynNode). - * The following commands may be useful: - * <p> - * <code> - * cp ~/.m2/repository/org/apache/brooklyn/brooklyn-dist/0.7.0-SNAPSHOT/brooklyn-dist-0.7.0-SNAPSHOT-dist.tar.gz ~/.brooklyn/repository/BrooklynNode/0.7.0-SNAPSHOT/BrooklynNode-0.7.0-SNAPSHOT.tar.gz - * rm -rf /tmp/brooklyn-`whoami`/installs/BrooklynNode* - * </code> - */ -public class BrooklynNodeIntegrationTest extends BrooklynAppUnitTestSupport { - - private static final Logger log = LoggerFactory.getLogger(BrooklynNodeIntegrationTest.class); - - private File pseudoBrooklynPropertiesFile; - private File pseudoBrooklynCatalogFile; - private File persistenceDir; - private LocalhostMachineProvisioningLocation loc; - private List<LocalhostMachineProvisioningLocation> locs; - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties"); - pseudoBrooklynPropertiesFile.delete(); - - pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog"); - pseudoBrooklynCatalogFile.delete(); - - loc = app.newLocalhostProvisioningLocation(); - locs = ImmutableList.of(loc); - } - - @AfterMethod(alwaysRun=true) - @Override - public void tearDown() throws Exception { - try { - super.tearDown(); - } finally { - if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete(); - if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete(); - if (persistenceDir != null) Os.deleteRecursively(persistenceDir); - } - } - - protected EntitySpec<BrooklynNode> newBrooklynNodeSpecForTest() { - // poor man's way to output which test is running - log.info("Creating entity spec for "+JavaClassNames.callerNiceClassAndMethod(1)); - - return EntitySpec.create(BrooklynNode.class) - .configure(BrooklynNode.WEB_CONSOLE_BIND_ADDRESS, Networking.ANY_NIC) - .configure(BrooklynNode.ON_EXISTING_PROPERTIES_FILE, ExistingFileBehaviour.DO_NOT_USE); - - /* yaml equivalent, for testing: - -location: localhost -services: -- type: brooklyn.entity.brooklynnode.BrooklynNode - bindAddress: 127.0.0.1 - onExistingProperties: do_not_use - -# some other options - enabledHttpProtocols: [ https ] - managementPassword: s3cr3t - brooklynLocalPropertiesContents: | - brooklyn.webconsole.security.https.required=true - brooklyn.webconsole.security.users=admin - brooklyn.webconsole.security.user.admin.password=s3cr3t - brooklyn.location.localhost.enabled=false - - */ - } - - @Test(groups="Integration") - public void testCanStartAndStop() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); - - brooklynNode.stop(); - EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); - } - - @Test(groups="Integration") - public void testSetsGlobalBrooklynPropertiesFromContents() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) - .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_CONTENTS, "abc=def")); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); - } - - @Test(groups="Integration") - public void testSetsLocalBrooklynPropertiesFromContents() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) - .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, "abc=def")); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); - } - - @Test(groups="Integration") - public void testSetsBrooklynPropertiesFromUri() throws Exception { - File brooklynPropertiesSourceFile = File.createTempFile("brooklynnode-test", ".properties"); - Files.write("abc=def", brooklynPropertiesSourceFile, Charsets.UTF_8); - - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_REMOTE_PATH, pseudoBrooklynPropertiesFile.getAbsolutePath()) - .configure(BrooklynNode.BROOKLYN_GLOBAL_PROPERTIES_URI, brooklynPropertiesSourceFile.toURI().toString())); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(pseudoBrooklynPropertiesFile, Charsets.UTF_8), ImmutableList.of("abc=def")); - } - - @Test(groups="Integration") - public void testSetsBrooklynCatalogFromContents() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath()) - .configure(BrooklynNode.BROOKLYN_CATALOG_CONTENTS, "<catalog/>")); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("<catalog/>")); - } - - @Test(groups="Integration") - public void testSetsBrooklynCatalogFromUri() throws Exception { - File brooklynCatalogSourceFile = File.createTempFile("brooklynnode-test", ".catalog"); - Files.write("abc=def", brooklynCatalogSourceFile, Charsets.UTF_8); - - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_CATALOG_REMOTE_PATH, pseudoBrooklynCatalogFile.getAbsolutePath()) - .configure(BrooklynNode.BROOKLYN_CATALOG_URI, brooklynCatalogSourceFile.toURI().toString())); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(pseudoBrooklynCatalogFile, Charsets.UTF_8), ImmutableList.of("abc=def")); - } - - @Test(groups="Integration") - public void testCopiesResources() throws Exception { - File sourceFile = File.createTempFile("brooklynnode-test", ".properties"); - Files.write("abc=def", sourceFile, Charsets.UTF_8); - File tempDir = Files.createTempDir(); - File expectedFile = new File(tempDir, "myfile.txt"); - - try { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath()) - .configure(BrooklynNode.COPY_TO_RUNDIR, ImmutableMap.of(sourceFile.getAbsolutePath(), "${RUN}/myfile.txt"))); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(expectedFile, Charsets.UTF_8), ImmutableList.of("abc=def")); - } finally { - expectedFile.delete(); - tempDir.delete(); - sourceFile.delete(); - } - } - - @Test(groups="Integration") - public void testCopiesClasspathEntriesInConfigKey() throws Exception { - String content = "abc=def"; - File classpathEntry1 = File.createTempFile("first", ".properties"); - File classpathEntry2 = File.createTempFile("second", ".properties"); - Files.write(content, classpathEntry1, Charsets.UTF_8); - Files.write(content, classpathEntry2, Charsets.UTF_8); - File tempDir = Files.createTempDir(); - File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName()); - File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName()); - - try { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath()) - .configure(BrooklynNode.CLASSPATH, ImmutableList.of(classpathEntry1.getAbsolutePath(), classpathEntry2.getAbsolutePath())) - ); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content)); - assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content)); - } finally { - expectedFile1.delete(); - expectedFile2.delete(); - tempDir.delete(); - classpathEntry1.delete(); - classpathEntry2.delete(); - } - } - - @Test(groups="Integration") - public void testCopiesClasspathEntriesInBrooklynProperties() throws Exception { - String content = "abc=def"; - File classpathEntry1 = File.createTempFile("first", ".properties"); - File classpathEntry2 = File.createTempFile("second", ".properties"); - Files.write(content, classpathEntry1, Charsets.UTF_8); - Files.write(content, classpathEntry2, Charsets.UTF_8); - File tempDir = Files.createTempDir(); - File expectedFile1 = new File(new File(tempDir, "lib"), classpathEntry1.getName()); - File expectedFile2 = new File(new File(tempDir, "lib"), classpathEntry2.getName()); - - try { - String propName = BrooklynNode.CLASSPATH.getName(); - String propValue = classpathEntry1.toURI().toString() + "," + classpathEntry2.toURI().toString(); - ((BrooklynProperties)app.getManagementContext().getConfig()).put(propName, propValue); - - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.RUN_DIR, tempDir.getAbsolutePath()) - ); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - assertEquals(Files.readLines(expectedFile1, Charsets.UTF_8), ImmutableList.of(content)); - assertEquals(Files.readLines(expectedFile2, Charsets.UTF_8), ImmutableList.of(content)); - } finally { - expectedFile1.delete(); - expectedFile2.delete(); - tempDir.delete(); - classpathEntry1.delete(); - classpathEntry2.delete(); - } - } - - // TODO test that the classpath set above is actually used - - @Test(groups="Integration") - public void testSetsBrooklynWebConsolePort() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.HTTP_PORT, PortRanges.fromString("45000+"))); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - Integer httpPort = brooklynNode.getAttribute(BrooklynNode.HTTP_PORT); - URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - assertTrue(httpPort >= 45000 && httpPort < 54100, "httpPort="+httpPort); - assertEquals((Integer)webConsoleUri.getPort(), httpPort); - HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 200, 401); - } - - @Test(groups="Integration") - public void testStartsAppOnStartup() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName())); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - waitForApps(webConsoleUri, 1); - String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); - List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class); - assertEquals(appType, ImmutableList.of(BasicApplication.class.getName())); - } - - protected static void waitForApps(String webConsoleUri) { - HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri+"/v1/applications", 200, 403); - HttpTestUtils.assertHttpStatusCodeEventuallyEquals(webConsoleUri+"/v1/applications", 200); - } - - // TODO Should introduce startup stages and let the client select which stage it expects to be complete - protected void waitForApps(final URI webConsoleUri, final int num) { - waitForApps(webConsoleUri.toString()); - - // e.g. [{"id":"UnBqPcqg","spec":{"name":"Application (UnBqPcqg)","type":"brooklyn.entity.basic.BasicApplication","locations":["pOL4NtiW"]},"status":"RUNNING","links":{"self":"/v1/applications/UnBqPcqg","entities":"/v1/applications/UnBqPcqg/entities"}}] - Asserts.succeedsEventually(new Runnable() { - @Override - public void run() { - //Wait all apps to become managed - String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); - List<String> appIds = parseJsonList(appsContent, ImmutableList.of("id"), String.class); - assertEquals(appIds.size(), num); - - // and then to start - List<String> statuses = parseJsonList(appsContent, ImmutableList.of("status"), String.class); - for (String status : statuses) { - assertEquals(status, Lifecycle.RUNNING.toString().toUpperCase()); - } - }}); - } - - @Test(groups="Integration") - public void testStartsAppViaEffector() throws Exception { - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest()); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - // note there is also a test for this in DeployApplication - final URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - waitForApps(webConsoleUri.toString()); - - final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance() - .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName()) - .getAllConfig()).get(); - - String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); - List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class); - assertEquals(appType, ImmutableList.of(BasicApplication.class.getName())); - - HttpTestUtils.assertContentEventuallyMatches( - webConsoleUri.toString()+"/v1/applications/"+id+"/entities/"+id+"/sensors/service.state", - "\"?(running|RUNNING)\"?"); - } - - @Test(groups="Integration") - public void testUsesLocation() throws Exception { - String brooklynPropertiesContents = - "brooklyn.location.named.mynamedloc=localhost:(name=myname)\n"+ - //force lat+long so test will work when offline - "brooklyn.location.named.mynamedloc.latitude=123\n"+ - "brooklyn.location.named.mynamedloc.longitude=45.6\n"; - - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, brooklynPropertiesContents) - .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName()) - .configure(BrooklynNode.LOCATIONS, "named:mynamedloc")); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - waitForApps(webConsoleUri, 1); - - // Check that "mynamedloc" has been picked up from the brooklyn.properties - String locsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations"); - List<String> locNames = parseJsonList(locsContent, ImmutableList.of("name"), String.class); - assertTrue(locNames.contains("mynamedloc"), "locNames="+locNames); - - // Find the id of the concrete location instance of the app - String appsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); - List<String[]> appLocationIds = parseJsonList(appsContent, ImmutableList.of("spec", "locations"), String[].class); - String appLocationId = Iterables.getOnlyElement(appLocationIds)[0]; // app.getManagementContext().getLocationRegistry() - - // Check that the concrete location is of the required type - String locatedLocationsContent = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/locations/usage/LocatedLocations"); - assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "name"), String.class), "myname"); - assertEquals(parseJson(locatedLocationsContent, ImmutableList.of(appLocationId, "longitude"), Double.class), 45.6, 0.00001); - } - - @Test(groups="Integration") - public void testAuthenticationAndHttps() throws Exception { - String adminPassword = "p4ssw0rd"; - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.ENABLED_HTTP_PROTOCOLS, ImmutableList.of("https")) - .configure(BrooklynNode.MANAGEMENT_PASSWORD, adminPassword) - .configure(BrooklynNode.BROOKLYN_LOCAL_PROPERTIES_CONTENTS, - Strings.lines( - "brooklyn.webconsole.security.https.required=true", - "brooklyn.webconsole.security.users=admin", - "brooklyn.webconsole.security.user.admin.password="+adminPassword, - "brooklyn.location.localhost.enabled=false") ) - ); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - Assert.assertTrue(webConsoleUri.toString().startsWith("https://"), "web console not https: "+webConsoleUri); - Integer httpsPort = brooklynNode.getAttribute(BrooklynNode.HTTPS_PORT); - Assert.assertTrue(httpsPort!=null && httpsPort >= 8443 && httpsPort <= 8500); - Assert.assertTrue(webConsoleUri.toString().contains(""+httpsPort), "web console not using right https port ("+httpsPort+"): "+webConsoleUri); - HttpTestUtils.assertHttpStatusCodeEquals(webConsoleUri.toString(), 401); - - HttpClient http = HttpTool.httpClientBuilder() - .trustAll() - .uri(webConsoleUri) - .laxRedirect(true) - .credentials(new UsernamePasswordCredentials("admin", adminPassword)) - .build(); - HttpToolResponse response = HttpTool.httpGet(http, webConsoleUri, MutableMap.<String,String>of()); - Assert.assertEquals(response.getResponseCode(), 200); - } - - @Test(groups="Integration") - public void testStopPlainThrowsException() throws Exception { - BrooklynNode brooklynNode = setUpBrooklynNodeWithApp(); - - // Not using annotation with `expectedExceptions = PropagatedRuntimeException.class` because want to - // ensure exception comes from stop. On jenkins, was seeing setUpBrooklynNodeWithApp fail in - // testStopAndKillAppsEffector; so can't tell if this method was really passing! - try { - brooklynNode.stop(); - fail("Expected "+brooklynNode+" stop to fail, because has app"); - } catch (Exception e) { - IllegalStateException ise = Exceptions.getFirstThrowableOfType(e, IllegalStateException.class); - if (ise != null && ise.toString().contains("Can't stop instance with running applications")) { - // success - } else { - throw e; - } - } finally { - try { - brooklynNode.invoke(BrooklynNode.STOP_NODE_AND_KILL_APPS, ImmutableMap.of(StopNodeAndKillAppsEffector.TIMEOUT.getName(), Duration.THIRTY_SECONDS)).getUnchecked(); - } catch (Exception e) { - log.warn("Error in stopNodeAndKillApps for "+brooklynNode+" (continuing)", e); - } - } - } - - @Test(groups="Integration") - public void testStopAndKillAppsEffector() throws Exception { - createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_AND_KILL_APPS); - } - - @Test(groups="Integration") - public void testStopButLeaveAppsEffector() throws Exception { - createNodeAndExecStopEffector(BrooklynNode.STOP_NODE_BUT_LEAVE_APPS); - } - - @Test(groups="Integration") - public void testStopAndRestartProcess() throws Exception { - persistenceDir = Files.createTempDir(); - BrooklynNode brooklynNode = app.createAndManageChild(newBrooklynNodeSpecForTest() - .configure(BrooklynNode.EXTRA_LAUNCH_PARAMETERS, "--persist auto --persistenceDir "+persistenceDir.getAbsolutePath()) - .configure(BrooklynNode.APP, BasicApplicationImpl.class.getName())); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - File pidFile = new File(getDriver(brooklynNode).getPidFile()); - URI webConsoleUri = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI); - - waitForApps(webConsoleUri, 1); - - // Stop just the process; will not have unmanaged entity unless machine was being terminated - brooklynNode.invoke(BrooklynNode.STOP, ImmutableMap.<String, Object>of( - BrooklynNode.StopSoftwareParameters.STOP_MACHINE_MODE.getName(), StopMode.NEVER, - BrooklynNode.StopSoftwareParameters.STOP_PROCESS_MODE.getName(), StopMode.ALWAYS)).getUnchecked(); - - assertTrue(Entities.isManaged(brooklynNode)); - assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running"); - - // Clear the startup app so it's not started second time, in addition to the rebind state - // TODO remove this once the startup app is created only if no previous persistence state - brooklynNode.config().set(BrooklynNode.APP, (String)null); - ((EntityLocal)brooklynNode).setAttribute(BrooklynNode.APP, null); - - // Restart the process; expect persisted state to have been restored, so apps still known about - brooklynNode.invoke(BrooklynNode.RESTART, ImmutableMap.<String, Object>of( - BrooklynNode.RestartSoftwareParameters.RESTART_MACHINE.getName(), "false")).getUnchecked(); - - waitForApps(webConsoleUri.toString()); - String apps = HttpTestUtils.getContent(webConsoleUri.toString()+"/v1/applications"); - List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class); - assertEquals(appType, ImmutableList.of(BasicApplication.class.getName())); - } - - private void createNodeAndExecStopEffector(Effector<?> eff) throws Exception { - BrooklynNode brooklynNode = setUpBrooklynNodeWithApp(); - File pidFile = new File(getDriver(brooklynNode).getPidFile()); - assertTrue(isPidRunning(pidFile)); - - brooklynNode.invoke(eff, Collections.<String, Object>emptyMap()).getUnchecked(); - - // Note can't use driver.isRunning to check shutdown; can't invoke scripts on an unmanaged entity - EntityTestUtils.assertAttributeEquals(brooklynNode, BrooklynNode.SERVICE_UP, false); - - // unmanaged if the machine is destroyed - ie false on localhost (this test by default), but true in the cloud -// assertFalse(Entities.isManaged(brooklynNode)); - - assertFalse(isPidRunning(pidFile), "pid in "+pidFile+" still running"); - } - - private boolean isPidRunning(File pidFile) throws Exception { - SshMachineLocation machine = loc.obtain(); - try { - int result = machine.execScript("check-pid", ImmutableList.of( - "test -f "+pidFile+" || exit 1", - "ps -p `cat "+pidFile+"`")); - return result == 0; - } finally { - loc.release(machine); - Locations.unmanage(machine); - } - } - - private BrooklynNodeSshDriver getDriver(BrooklynNode brooklynNode) { - try { - EntityProxyImpl entityProxy = (EntityProxyImpl)Proxy.getInvocationHandler(brooklynNode); - Method getDriver = BrooklynNodeImpl.class.getMethod("getDriver"); - return (BrooklynNodeSshDriver)entityProxy.invoke(brooklynNode, getDriver, new Object[]{}); - } catch (Throwable e) { - throw Exceptions.propagate(e); - } - } - - private BrooklynNode setUpBrooklynNodeWithApp() throws InterruptedException, - ExecutionException { - BrooklynNode brooklynNode = app.createAndManageChild(EntitySpec.create(BrooklynNode.class) - .configure(BrooklynNode.NO_WEB_CONSOLE_AUTHENTICATION, Boolean.TRUE)); - app.start(locs); - log.info("started "+app+" containing "+brooklynNode+" for "+JavaClassNames.niceClassAndMethod()); - - EntityTestUtils.assertAttributeEqualsEventually(brooklynNode, BrooklynNode.SERVICE_UP, true); - - String baseUrl = brooklynNode.getAttribute(BrooklynNode.WEB_CONSOLE_URI).toString(); - waitForApps(baseUrl); - - final String id = brooklynNode.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance() - .configure(DeployBlueprintEffector.BLUEPRINT_TYPE, BasicApplication.class.getName()) - .getAllConfig()).get(); - - String entityUrl = Urls.mergePaths(baseUrl, "v1/applications/", id, "entities", id); - - Entity mirror = brooklynNode.addChild(EntitySpec.create(BrooklynEntityMirror.class) - .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, entityUrl) - .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, id)); - Entities.manage(mirror); - - assertEquals(brooklynNode.getChildren().size(), 1); - return brooklynNode; - } - - private <T> T parseJson(String json, List<String> elements, Class<T> clazz) { - Function<String, T> func = Functionals.chain( - JsonFunctions.asJson(), - JsonFunctions.walk(elements), - JsonFunctions.cast(clazz)); - return func.apply(json); - } - - private <T> List<T> parseJsonList(String json, List<String> elements, Class<T> clazz) { - Function<String, List<T>> func = Functionals.chain( - JsonFunctions.asJson(), - JsonFunctions.forEach(Functionals.chain( - JsonFunctions.walk(elements), - JsonFunctions.cast(clazz)))); - return func.apply(json); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java deleted file mode 100644 index 1745c38..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/BrooklynNodeTest.java +++ /dev/null @@ -1,138 +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 brooklyn.entity.brooklynnode; - -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.List; - -import org.apache.brooklyn.api.entity.EntitySpec; -import org.apache.brooklyn.api.entity.drivers.downloads.DownloadResolver; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.core.test.entity.TestApplication; -import org.apache.brooklyn.entity.core.Attributes; -import org.apache.brooklyn.entity.core.Entities; -import org.apache.brooklyn.entity.trait.Startable; -import org.apache.brooklyn.sensor.feed.ConfigToAttributes; -import org.apache.brooklyn.test.Asserts; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.collections.MutableSet; -import org.apache.brooklyn.util.time.Duration; -import org.apache.brooklyn.util.time.Time; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -import org.apache.brooklyn.location.basic.SshMachineLocation; - -public class BrooklynNodeTest { - - // TODO Need test for copying/setting classpath - - private TestApplication app; - private SshMachineLocation loc; - - public static class SlowStopBrooklynNode extends BrooklynNodeImpl { - public SlowStopBrooklynNode() {} - - @Override - protected void postStop() { - super.postStop(); - - //Make sure UnmanageTask will wait for the STOP effector to complete. - Time.sleep(Duration.FIVE_SECONDS); - } - - } - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - app = TestApplication.Factory.newManagedInstanceForTests(); - loc = new SshMachineLocation(MutableMap.of("address", "localhost")); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (app != null) Entities.destroyAll(app.getManagementContext()); - } - - @Test - public void testGeneratesCorrectSnapshotDownload() throws Exception { - String version = "0.0.1-SNAPSHOT"; - String expectedUrl = "https://repository.apache.org/service/local/artifact/maven/redirect?r=snapshots&g=org.apache.brooklyn&v="+version+"&a=brooklyn-dist&c=dist&e=tar.gz"; - runTestGeneratesCorrectDownloadUrl(version, expectedUrl); - } - - @Test - public void testGeneratesCorrectReleaseDownload() throws Exception { - String version = "0.0.1"; - String expectedUrl = "http://search.maven.org/remotecontent?filepath=org/apache/brooklyn/brooklyn-dist/"+version+"/brooklyn-dist-"+version+"-dist.tar.gz"; - runTestGeneratesCorrectDownloadUrl(version, expectedUrl); - } - - private void runTestGeneratesCorrectDownloadUrl(String version, String expectedUrl) throws Exception { - // TODO Using BrooklynNodeImpl directly, because want to instantiate a BroolynNodeSshDriver. - // Really want to make that easier to test, without going through "wrong" code path for creating entity. - BrooklynNodeImpl entity = new BrooklynNodeImpl(); - entity.setConfig(BrooklynNode.SUGGESTED_VERSION, version); - entity.setParent(app); - Entities.manage(entity); - ConfigToAttributes.apply(entity); - BrooklynNodeSshDriver driver = new BrooklynNodeSshDriver(entity, loc); - - DownloadResolver resolver = Entities.newDownloader(driver); - List<String> urls = resolver.getTargets(); - - System.out.println("urls="+urls); - assertTrue(urls.contains(expectedUrl), "urls="+urls); - } - - @Test(groups = "Integration") - public void testUnmanageOnStop() throws Exception { - final BrooklynNode node = app.addChild(EntitySpec.create(BrooklynNode.class).impl(SlowStopBrooklynNode.class)); - Entities.manage(node); - assertTrue(Entities.isManaged(node), "Entity " + node + " must be managed."); - node.invoke(Startable.STOP, ImmutableMap.<String,Object>of()).asTask().getUnchecked(); - //The UnmanageTask will unblock after the STOP effector completes, so we are competing with it here. - Asserts.succeedsEventually(new Runnable() { - @Override - public void run() { - assertFalse(Entities.isManaged(node)); - } - }); - } - - - @Test - public void testCanStartSameNode() throws Exception { - // not very interesting as do not have REST when run in this project - // but test BrooklynNodeRestTest in downstream project does - BrooklynNode bn = app.createAndManageChild(EntitySpec.create(BrooklynNode.class, SameBrooklynNodeImpl.class)); - bn.start(MutableSet.<Location>of()); - - Assert.assertEquals(bn.getAttribute(Attributes.SERVICE_UP), (Boolean)true); - // no URI - Assert.assertNull(bn.getAttribute(BrooklynNode.WEB_CONSOLE_URI)); - } - -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java deleted file mode 100644 index 53712ab..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/CallbackEntityHttpClient.java +++ /dev/null @@ -1,101 +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 brooklyn.entity.brooklynnode; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.util.core.http.HttpToolResponse; -import org.apache.brooklyn.util.core.http.HttpTool.HttpClientBuilder; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; - -import brooklyn.entity.brooklynnode.EntityHttpClient; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -public class CallbackEntityHttpClient implements EntityHttpClient { - public static class Request { - private Entity entity; - private String method; - private String path; - private Map<String, String> params; - public Request(Entity entity, String method, String path, Map<String, String> params) { - this.entity = entity; - this.method = method; - this.path = path; - this.params = params; - } - public Entity getEntity() { - return entity; - } - public String getMethod() { - return method; - } - public String getPath() { - return path; - } - public Map<String, String> getParams() { - return params; - } - } - private Function<Request, String> callback; - private Entity entity; - - public CallbackEntityHttpClient(Entity entity, Function<Request, String> callback) { - this.entity = entity; - this.callback = callback; - } - - @Override - public HttpClientBuilder getHttpClientForBrooklynNode() { - throw new IllegalStateException("Method call not expected"); - } - - @Override - public HttpToolResponse get(String path) { - String result = callback.apply(new Request(entity, HttpGet.METHOD_NAME, path, Collections.<String, String>emptyMap())); - return new HttpToolResponse(HttpStatus.SC_OK, null, result.getBytes(), 0, 0, 0); - } - - @Override - public HttpToolResponse post(String path, Map<String, String> headers, byte[] body) { - throw new IllegalStateException("Method call not expected"); - } - - @Override - public HttpToolResponse post(String path, Map<String, String> headers, Map<String, String> formParams) { - String result = callback.apply(new Request(entity, HttpPost.METHOD_NAME, path, formParams)); - return new HttpToolResponse(HttpStatus.SC_OK, Collections.<String, List<String>>emptyMap(), result.getBytes(), 0, 0, 0); - } - - @Override - public HttpToolResponse delete(String path, Map<String, String> headers) { - throw new IllegalStateException("Method call not expected"); - } - - @Override - public EntityHttpClient responseSuccess(Predicate<Integer> successPredicate) { - throw new IllegalStateException("Method call not expected"); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java deleted file mode 100644 index 4a8cbb0..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/MockBrooklynNode.java +++ /dev/null @@ -1,71 +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 brooklyn.entity.brooklynnode; - -import java.util.Collection; - -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.entity.core.AbstractEntity; -import org.apache.brooklyn.sensor.core.BasicAttributeSensor; - -import brooklyn.entity.brooklynnode.CallbackEntityHttpClient.Request; -import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityModeEffectorBody; -import brooklyn.entity.brooklynnode.effector.SetHighAvailabilityPriorityEffectorBody; - -import com.google.common.base.Function; -import com.google.common.reflect.TypeToken; - -public class MockBrooklynNode extends AbstractEntity implements BrooklynNode { - @SuppressWarnings("serial") - public static final ConfigKey<Function<Request, String>> HTTP_CLIENT_CALLBACK = ConfigKeys.newConfigKey(new TypeToken<Function<Request, String>>(){}, "httpClientCallback"); - public static final AttributeSensor<Integer> HA_PRIORITY = new BasicAttributeSensor<Integer>(Integer.class, "priority"); - - @Override - public void init() { - super.init(); - getMutableEntityType().addEffector(SetHighAvailabilityPriorityEffectorBody.SET_HIGH_AVAILABILITY_PRIORITY); - getMutableEntityType().addEffector(SetHighAvailabilityModeEffectorBody.SET_HIGH_AVAILABILITY_MODE); - setAttribute(HA_PRIORITY, 0); - } - - @Override - public EntityHttpClient http() { - return new CallbackEntityHttpClient(this, getConfig(HTTP_CLIENT_CALLBACK)); - } - - @Override - public void start(Collection<? extends Location> locations) { - } - - @Override - public void stop() { - } - - @Override - public void restart() { - } - - @Override - public void populateServiceNotUpDiagnostics() { - // no-op - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/64c2b2e5/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java ---------------------------------------------------------------------- diff --git a/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java b/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java deleted file mode 100644 index dc35de0..0000000 --- a/software/base/src/test/java/brooklyn/entity/brooklynnode/SameBrooklynNodeImpl.java +++ /dev/null @@ -1,96 +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 brooklyn.entity.brooklynnode; - -import java.net.URI; -import java.util.Collection; - -import brooklyn.entity.brooklynnode.BrooklynNodeImpl.DeployBlueprintEffectorBody; - -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.entity.core.AbstractEntity; -import org.apache.brooklyn.sensor.feed.http.HttpFeed; -import org.apache.brooklyn.sensor.feed.http.HttpPollConfig; -import org.apache.brooklyn.sensor.feed.http.HttpValueFunctions; - -/** Implementation of BrooklynNode which just presents the node where this is running, for convenience; - * - * start/stop/restart have no effect; - * sensors are connected; - * deploy blueprint assumes that a REST endpoint is available */ -public class SameBrooklynNodeImpl extends AbstractEntity implements BrooklynNode { - - private HttpFeed httpFeed; - - @Override - public void start(Collection<? extends Location> locations) { - connectSensors(); - } - - @Override - public void stop() { - disconnectSensors(); - } - - @Override - public void restart() { - return; - } - - - @Override - public void init() { - super.init(); - getMutableEntityType().addEffector(DeployBlueprintEffectorBody.DEPLOY_BLUEPRINT); - } - - protected void connectSensors() { - URI webConsoleUri = getManagementContext().getManagementNodeUri().orNull(); - setAttribute(WEB_CONSOLE_URI, webConsoleUri); - - if (webConsoleUri != null) { - httpFeed = HttpFeed.builder() - .entity(this) - .period(200) - .baseUri(webConsoleUri) - .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD)) - .poll(new HttpPollConfig<Boolean>(SERVICE_UP) - .onSuccess(HttpValueFunctions.responseCodeEquals(200)) - .setOnFailureOrException(false)) - .build(); - - } else { - setAttribute(SERVICE_UP, true); - } - } - - protected void disconnectSensors() { - if (httpFeed != null) httpFeed.stop(); - } - - @Override - public EntityHttpClient http() { - throw new UnsupportedOperationException(); - } - - @Override - public void populateServiceNotUpDiagnostics() { - // no-op - } -}
