private TestApplication rebind() throws Exception { RebindTestUtils.waitForPersisted(app); TestApplication result = (TestApplication) RebindTestUtils.rebind(mementoDir, getClass().getClassLoader()); newManagementContext = result.getManagementContext(); return result; }
// Integration test because requires ssh'ing (and takes about 5 seconds) // See also SoftwareProcessEntityTest.testCustomInstallDirX for a lot more mocked variants @Test(groups = "Integration") public void testCanInstallMultipleVersionsOnSameMachine() throws Exception { managementContext .getBrooklynProperties() .put(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath()); MyService entity = app.createAndManageChild( EntitySpec.create(MyService.class) .configure(SoftwareProcess.SUGGESTED_VERSION, "0.1.0")); MyService entity2 = app.createAndManageChild( EntitySpec.create(MyService.class) .configure(SoftwareProcess.SUGGESTED_VERSION, "0.2.0")); app.start(ImmutableList.of(machine127)); String installDir1 = entity.getAttribute(SoftwareProcess.INSTALL_DIR); String installDir2 = entity2.getAttribute(SoftwareProcess.INSTALL_DIR); assertNotEquals(installDir1, installDir2); assertTrue(installDir1.contains("0.1.0"), "installDir1=" + installDir1); assertTrue(installDir2.contains("0.2.0"), "installDir2=" + installDir2); assertTrue(new File(new File(installDir1), "myfile").isFile()); assertTrue(new File(new File(installDir2), "myfile").isFile()); }
@BeforeMethod(alwaysRun = true) public void setUp() throws Exception { events = new CopyOnWriteArrayList<SensorEvent<FailureDescriptor>>(); managementContext = Entities.newManagementContext(); app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext); app.getManagementContext() .getSubscriptionManager() .subscribe( app, HASensors.CONNECTION_FAILED, new SensorEventListener<FailureDescriptor>() { @Override public void onEvent(SensorEvent<FailureDescriptor> event) { events.add(event); } }); app.getManagementContext() .getSubscriptionManager() .subscribe( app, HASensors.CONNECTION_RECOVERED, new SensorEventListener<FailureDescriptor>() { @Override public void onEvent(SensorEvent<FailureDescriptor> event) { events.add(event); } }); serverSocketAddress = startServerSocket(); }
@Test public void testServiceReplacerWorksAfterRebind() throws Exception { Location origLoc = origManagementContext .getLocationManager() .createLocation(LocationSpec.create(SimulatedLocation.class)); DynamicCluster origCluster = origApp.createAndManageChild( EntitySpec.create(DynamicCluster.class) .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class)) .configure(DynamicCluster.INITIAL_SIZE, 3)); origApp.start(ImmutableList.<Location>of(origLoc)); origCluster.addPolicy( PolicySpec.create(ServiceReplacer.class) .configure(ServiceReplacer.FAILURE_SENSOR_TO_MONITOR, HASensors.ENTITY_FAILED)); // rebind TestApplication newApp = rebind(); final DynamicCluster newCluster = (DynamicCluster) Iterables.find(newApp.getChildren(), Predicates.instanceOf(DynamicCluster.class)); // stimulate the policy final Set<Entity> initialMembers = ImmutableSet.copyOf(newCluster.getMembers()); final TestEntity e1 = (TestEntity) Iterables.get(initialMembers, 1); newApp .getManagementContext() .getSubscriptionManager() .subscribe(e1, HASensors.ENTITY_FAILED, eventListener); newApp .getManagementContext() .getSubscriptionManager() .subscribe(e1, HASensors.ENTITY_RECOVERED, eventListener); e1.emit(HASensors.ENTITY_FAILED, new FailureDescriptor(e1, "simulate failure")); // Expect e1 to be replaced Asserts.succeedsEventually( new Runnable() { @Override public void run() { Set<Entity> newMembers = Sets.difference(ImmutableSet.copyOf(newCluster.getMembers()), initialMembers); Set<Entity> removedMembers = Sets.difference(initialMembers, ImmutableSet.copyOf(newCluster.getMembers())); assertEquals(removedMembers, ImmutableSet.of(e1)); assertEquals(newMembers.size(), 1); assertEquals( ((TestEntity) Iterables.getOnlyElement(newMembers)).getCallHistory(), ImmutableList.of("start")); // TODO e1 not reporting "start" after rebind because callHistory is a field rather than // an attribute, so was not persisted Asserts.assertEqualsIgnoringOrder(e1.getCallHistory(), ImmutableList.of("stop")); assertFalse(Entities.isManaged(e1)); } }); }
@BeforeMethod public void setUp() throws Exception { app = new TestApplication(); entity = new ExampleJavaEntity(app); app.startManagement(); app.start(ImmutableList.of(new SimulatedLocation())); }
@Test(groups = "Integration") public void testMachine127InHome() throws Exception { MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(machine127)); String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR); assertTrue( installDir.startsWith(Os.home() + "/brooklyn-managed-processes/installs/"), "installed in " + installDir); }
@Test(groups = "Integration") public void testLocalhostInTmp() throws Exception { MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(localhost)); String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR); assertTrue( installDir.startsWith("/tmp/brooklyn-" + Os.user() + "/installs/"), "installed in " + installDir); }
@Test(groups = "Integration") public void testLocalhostInCustom() throws Exception { localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath()); MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(localhost)); String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR); assertTrue( installDir.startsWith(tempDataDir.getAbsolutePath() + "/installs/"), "installed in " + installDir); }
@Test(groups = {"Integration"}) public void testRedisClusterReplicates() throws Exception { final String key = "mykey"; final String val = "1234567890"; cluster = app.createAndManageChild( EntitySpec.create(RedisCluster.class).configure(DynamicCluster.INITIAL_SIZE, 3)); app.start(ImmutableList.of(loc)); EntityTestUtils.assertAttributeEqualsEventually(cluster, Startable.SERVICE_UP, true); RedisStore master = cluster.getMaster(); List<RedisSlave> slaves = ImmutableList.<RedisSlave>copyOf((Collection) cluster.getSlaves().getMembers()); assertEquals(slaves.size(), 3); JedisSupport viaMaster = new JedisSupport(master); viaMaster.writeData(key, val); assertEquals(viaMaster.readData(key), val); for (RedisSlave slave : slaves) { final JedisSupport viaSlave = new JedisSupport(slave); Asserts.succeedsEventually( new Callable<Void>() { @Override public Void call() throws Exception { assertEquals(viaSlave.readData(key), val); return null; } }); } // Check that stopping slave will not stop anything else // (it used to stop master because wasn't supplying port!) slaves.get(0).stop(); EntityTestUtils.assertAttributeEqualsEventually(slaves.get(0), Startable.SERVICE_UP, false); assertEquals(master.getAttribute(Startable.SERVICE_UP), Boolean.TRUE); for (RedisSlave slave : slaves.subList(1, slaves.size())) { assertEquals(slave.getAttribute(Startable.SERVICE_UP), Boolean.TRUE); } // Check that stopping cluster will stop everything cluster.stop(); EntityTestUtils.assertAttributeEqualsEventually(cluster, Startable.SERVICE_UP, false); assertEquals(master.getAttribute(Startable.SERVICE_UP), Boolean.FALSE); for (RedisSlave slave : slaves) { assertEquals(slave.getAttribute(Startable.SERVICE_UP), Boolean.FALSE); } }
@Test(groups = "Integration") public void testCopyResourceCreatingParentDir() throws Exception { File tempDataDirSub = new File(tempDataDir, "subdir"); File tempDest = new File(tempDataDirSub, "tempDest.txt"); String tempLocalContent = "abc"; File tempLocal = new File(tempDataDir, "tempLocal.txt"); Files.write(tempLocalContent, tempLocal, Charsets.UTF_8); localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath()); MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(localhost)); // First confirm would get exception in createeParentDir==false try { entity .getDriver() .copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), false); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); fail("Should have failed to create " + tempDest); } catch (SshException e) { // success } finally { Os.deleteRecursively(tempDataDirSub); } // Copy to absolute path try { entity .getDriver() .copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath(), true); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); } finally { Os.deleteRecursively(tempDataDirSub); } // Copy to absolute path String runDir = entity.getDriver().getRunDir(); String tempDataDirRelativeToRunDir = "subdir"; String tempDestRelativeToRunDir = Os.mergePaths(tempDataDirRelativeToRunDir, "tempDest.txt"); File tempDestInRunDir = new File(Os.mergePaths(runDir, tempDestRelativeToRunDir)); try { entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDestRelativeToRunDir, true); assertEquals( Files.readLines(tempDestInRunDir, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); } finally { Os.deleteRecursively(new File(runDir, tempDataDirRelativeToRunDir)); } }
@Test(groups = "Integration") @Deprecated public void testMachineInCustomFromDataDir() throws Exception { managementContext .getBrooklynProperties() .put(BrooklynConfigKeys.BROOKLYN_DATA_DIR, tempDataDir.getAbsolutePath()); MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(machine127)); String installDir = entity.getAttribute(SoftwareProcess.INSTALL_DIR); assertTrue( installDir.startsWith(tempDataDir.getAbsolutePath() + "/installs/"), "installed in " + installDir); }
@Test(groups = "Integration") public void testJavaStartStopSshDriverStartsAndStopsApp() { final MyEntity entity = app.createAndManageChild(EntitySpecs.spec(MyEntity.class)); app.start(ImmutableList.of(localhost)); Asserts.succeedsEventually( MutableMap.of("timeout", TIMEOUT_MS), new Runnable() { public void run() { assertTrue(entity.getAttribute(SoftwareProcess.SERVICE_UP)); } }); entity.stop(); assertFalse(entity.getAttribute(SoftwareProcess.SERVICE_UP)); }
@Test(groups = "Integration") // Because slow public void testRecoversThenDownUpResetsStabilisationCount() throws Exception { final long stabilisationDelay = 1000; app.addPolicy( PolicySpec.create(ConnectionFailureDetector.class) .configure(ConnectionFailureDetector.ENDPOINT, serverSocketAddress) .configure( ConnectionFailureDetector.CONNECTION_RECOVERED_STABILIZATION_DELAY, Duration.of(stabilisationDelay))); stopServerSocket(); assertHasEventEventually(HASensors.CONNECTION_FAILED, Predicates.<Object>equalTo(app), null); events.clear(); startServerSocket(); assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD)); stopServerSocket(); Thread.sleep(POLL_PERIOD + OVERHEAD); startServerSocket(); assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD)); assertHasEventEventually(HASensors.CONNECTION_RECOVERED, Predicates.<Object>equalTo(app), null); }
@Test public void testCreateRespectsFlagInMap() { TestEntity entity2 = app.createAndManageChild( TestEntity.Spec.newInstance().configure(MutableMap.of("confName", "baz"))); assertEquals(entity2.getConfig(TestEntity.CONF_NAME), "baz"); }
@Test public void testCreateRespectsConfigKey() { TestEntity entity2 = app.createAndManageChild( TestEntity.Spec.newInstance().configure(TestEntity.CONF_NAME, "foo")); assertEquals(entity2.getConfig(TestEntity.CONF_NAME), "foo"); }
/** Test that an AMQP client can connect to and use the broker. */ @Test(groups = {"Integration", "WIP"}) public void testClientConnection() throws Exception { rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class)); rabbit.start(ImmutableList.of(testLocation)); EntityTestUtils.assertAttributeEqualsEventually(rabbit, Startable.SERVICE_UP, true); byte[] content = "MessageBody".getBytes(Charsets.UTF_8); String queue = "queueName"; Channel producer = null; Channel consumer = null; try { producer = getAmqpChannel(rabbit); consumer = getAmqpChannel(rabbit); producer.queueDeclare(queue, true, false, false, ImmutableMap.<String, Object>of()); producer.queueBind(queue, AmqpExchange.DIRECT, queue); producer.basicPublish(AmqpExchange.DIRECT, queue, null, content); QueueingConsumer queueConsumer = new QueueingConsumer(consumer); consumer.basicConsume(queue, true, queueConsumer); QueueingConsumer.Delivery delivery = queueConsumer.nextDelivery(60 * 1000l); // one minute timeout assertEquals(delivery.getBody(), content); } finally { closeSafely(producer, 10 * 1000); closeSafely(consumer, 10 * 1000); } }
@Test public void testDoesNotCreateDriverAfterRebind() throws Exception { origE = app.createAndManageChild(EntitySpec.create(MyService.class)); // the entity skips enricher initialization, do it explicitly origE.addEnricher(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp()); MyProvisioningLocation origLoc = mgmt.getLocationManager() .createLocation( LocationSpec.create(MyProvisioningLocation.class).displayName("mylocname")); app.start(ImmutableList.of(origLoc)); assertEquals( origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING); EntityTestUtils.assertAttributeEqualsEventually( origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); ServiceStateLogic.setExpectedState(origE, Lifecycle.ON_FIRE); EntityTestUtils.assertAttributeEqualsEventually( origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE); newApp = (TestApplication) rebind(); MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren()); assertNull( newE.getDriver(), "driver should not be initialized because entity is in a permanent failure"); }
@BeforeMethod(alwaysRun = true) public void setUp() throws Exception { for (int i = 0; i < 5; i++) System.gc(); loc = new SimulatedLocation(); app = ApplicationBuilder.newManagedApp(TestApplication.class); mgmt = app.getManagementContext(); }
@AfterMethod(alwaysRun = true) public void tearDown() throws Exception { if (localManagementContext != null) Entities.destroyAll(localManagementContext); if (app != null) Entities.destroyAll(app.getManagementContext()); if (persister != null) persister.stop(); if (objectStore != null) objectStore.deleteCompletely(); persister = null; }
@Test public void testCanSetAttribute() { entity = new ExampleJavaEntity(app); app.manage(entity); entity.setAttribute(ExampleJavaEntity.MY_SENSOR1, "myval"); assertEquals(entity.getAttribute(ExampleJavaEntity.MY_SENSOR1), "myval"); }
/** Test that the broker starts up and sets SERVICE_UP correctly. */ @Test(groups = {"Integration", "WIP"}) public void canStartupAndShutdown() throws Exception { rabbit = app.createAndManageChild(EntitySpec.create(RabbitBroker.class)); rabbit.start(ImmutableList.of(testLocation)); EntityTestUtils.assertAttributeEqualsEventually(rabbit, Startable.SERVICE_UP, true); rabbit.stop(); assertFalse(rabbit.getAttribute(Startable.SERVICE_UP)); }
@AfterMethod(alwaysRun = true) @Override public void tearDown() throws Exception { super.tearDown(); if (newApp != null) Entities.destroyAll(newApp.getManagementContext()); if (newManagementContext != null) Entities.destroyAll(newManagementContext); if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir); }
@Test public void testGetEffector() throws Exception { TestEntity entity2 = app.createAndManageChild(EntitySpecs.spec(TestEntity.class)); Effector<?> effector = entity2.getEntityType().getEffector("myEffector"); Effector<?> effector2 = entity2.getEntityType().getEffector("identityEffector", Object.class); assertEquals(effector.getName(), "myEffector"); assertEquals(effector2.getName(), "identityEffector"); }
@Test public void testGetChildrenAndParentsReturnsProxies() { TestEntity child = (TestEntity) Iterables.get(app.getChildren(), 0); Application parent = (Application) child.getParent(); assertIsProxy(child); assertIsProxy(parent); }
@Test(groups = "Integration") public void testCopyResource() throws Exception { File tempDest = new File(tempDataDir, "tempDest.txt"); String tempLocalContent = "abc"; File tempLocal = new File(tempDataDir, "tempLocal.txt"); Files.write(tempLocalContent, tempLocal, Charsets.UTF_8); localhost.setConfig(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath()); MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)); app.start(ImmutableList.of(localhost)); // Copy local file entity.getDriver().copyResource(tempLocal, tempDest.getAbsolutePath()); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); tempDest.delete(); // Copy local file using url entity.getDriver().copyResource(tempLocal.toURI().toString(), tempDest.getAbsolutePath()); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); tempDest.delete(); // Copy reader entity.getDriver().copyResource(new StringReader(tempLocalContent), tempDest.getAbsolutePath()); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); tempDest.delete(); // Copy stream entity .getDriver() .copyResource( ByteSource.wrap(tempLocalContent.getBytes()).openStream(), tempDest.getAbsolutePath()); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); tempDest.delete(); // Copy known-size stream entity .getDriver() .copyResource( new KnownSizeInputStream( Streams.newInputStreamWithContents(tempLocalContent), tempLocalContent.length()), tempDest.getAbsolutePath()); assertEquals(Files.readLines(tempDest, Charsets.UTF_8), ImmutableList.of(tempLocalContent)); tempDest.delete(); }
@Test public void testCanSetConfig() { entity = new ExampleJavaEntity(MutableMap.of("displayName", "myName", "myConfig1", "myVal1"), app); app.manage(entity); assertEquals(entity.getDisplayName(), "myName"); assertEquals(entity.getConfig(ExampleJavaEntity.MY_CONFIG1), "myVal1"); }
@BeforeMethod(alwaysRun = true) public void setUp() throws Exception { loc = new LocalhostMachineProvisioningLocation(); app = ApplicationBuilder.newManagedApp(TestApplication.class); entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)); app.start(ImmutableList.of(loc)); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue( new MockResponse() .setResponseCode(200) .addHeader("content-type: application/json") .setBody("{\"foo\":\"myfoo\"}")); } server.play(); baseUrl = server.getUrl("/"); }
@BeforeMethod public void setUpTestEntity() throws Exception { app = ApplicationBuilder.newManagedApp(TestApplication.class); entity = new AbstractEntity(app) {}; Entities.startManagement(entity); listener = new EntitySubscriptionTest.RecordingSensorEventListener(); app.getSubscriptionContext().subscribe(entity, SENSOR_ADDED, listener); app.getSubscriptionContext().subscribe(entity, SENSOR_REMOVED, listener); }
@Test(groups = "Integration") // Has a 1 second wait public void testNotNotifiedOfFailuresForHealthy() throws Exception { // Create members before and after the policy is registered, to test both scenarios app.addPolicy( PolicySpec.create(ConnectionFailureDetector.class) .configure(ConnectionFailureDetector.ENDPOINT, serverSocketAddress)); assertNoEventsContinually(); }
@Test public void testReportsFailureWhenAlreadyDownOnRegisteringPolicy() throws Exception { stopServerSocket(); app.addPolicy( PolicySpec.create(ConnectionFailureDetector.class) .configure(ConnectionFailureDetector.ENDPOINT, serverSocketAddress)); assertHasEventEventually(HASensors.CONNECTION_FAILED, Predicates.<Object>equalTo(app), null); }