org.apache.brooklyn.core.entity.trait.Startable Java Examples

The following examples show how to use org.apache.brooklyn.core.entity.trait.Startable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractAbstractControllerTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateCalledWhenServerPoolGroupSwapped() {
    // Second cluster with one child
    DynamicCluster cluster2 = app.addChild(EntitySpec.create(DynamicCluster.class)
            .configure("initialSize", 1)
            .configure("memberSpec", EntitySpec.create(TestEntity.class).impl(WebServerEntity.class)));
    cluster2.start(ImmutableList.of());
    
    Entity child = Iterables.getOnlyElement(cluster2.getMembers());
    child.sensors().set(WebServerEntity.HTTP_PORT, 1234);
    child.sensors().set(Startable.SERVICE_UP, true);

    // Reconfigure the controller to point at the new cluster
    controller.changeServerPool(cluster2.getId());
    assertEquals(controller.config().get(LoadBalancer.SERVER_POOL), cluster2);
    assertEventuallyAddressesMatchCluster(cluster2);

    // And remove all children; expect all addresses to go away
    cluster2.resize(0);
    assertEventuallyAddressesMatchCluster(cluster2);
}
 
Example #2
Source File: MachineDetailsGoogleComputeLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void doTest(Location loc) throws Exception {
    Entity testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class));
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(testEntity, Startable.SERVICE_UP, true);

    SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get();
    MachineDetails machine = app.getExecutionContext()
            .submit(BasicMachineDetails.taskForSshMachineLocation(sshLoc))
            .getUnchecked();
    LOG.info("Found the following at {}: {}", loc, machine);
    assertNotNull(machine);
    OsDetails details = machine.getOsDetails();
    assertNotNull(details);
    assertNotNull(details.getArch());
    assertNotNull(details.getName());
    assertNotNull(details.getVersion());
    assertFalse(details.getArch().startsWith("architecture:"));
    assertFalse(details.getName().startsWith("name:"));
    assertFalse(details.getVersion().startsWith("version:"));
}
 
Example #3
Source File: ChildEntityCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(JcloudsLocation location, ComputeService computeService, JcloudsMachineLocation machine) {
    EntitySpec<?> spec = config().get(CHILD_ENTITY_SPEC);
    Boolean create = config().get(CREATE_CHILD_ENTITY);
    Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT);
    Entity parent = getCallerContext(machine);

    if (Boolean.TRUE.equals(create) && spec != null) {
        LOG.info("Creating child entity for {} in {}", parent, machine);
        Entity child = getBrooklynManagementContext().getEntityManager().createEntity(spec);
        child.setParent(parent);
        Task<Void> start = Entities.invokeEffectorWithArgs(parent, child, Startable.START, ImmutableList.of(machine));
        if (!start.blockUntilEnded(timeout)) {
            throw new IllegalStateException(String.format("Timed out while starting child entity for %s", parent));
        }
    }
}
 
Example #4
Source File: DynamicRegionsFabricImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void removeRegion(String id) {
    Entity entity = getManagementContext().getEntityManager().getEntity(id);
    Preconditions.checkNotNull(entity, "No entity found for %s", id);
    Preconditions.checkArgument(this.equals(entity.getParent()), "Wrong parent (%s) for %s", entity.getParent(), entity);
    Collection<Location> childLocations = entity.getLocations();
    
    if (entity instanceof Startable) {
        try {
            Entities.invokeEffector(this, entity, Startable.STOP).get();
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            log.warn("Error stopping "+entity+" ("+e+"); proceeding to remove it anyway");
            log.debug("Error stopping "+entity+" ("+e+"); proceeding to remove it anyway", e);
        }
    }
    removeChild(entity);
    removeLocations(childLocations);
}
 
Example #5
Source File: SequenceEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSequenceIncrementAndGetEffector() throws Exception {
    sequence = app.addChild(EntitySpec.create(SequenceEntity.class));
    app.start(ImmutableList.of(loc1));

    assertAttributeEqualsEventually(sequence, Startable.SERVICE_UP, true);

    assertEquals(sequence.get(), Integer.valueOf(1));

    Integer nextValue = sequence.invoke(SequenceEntity.INCREMENT_AND_GET, ImmutableMap.<String, Object>of()).getUnchecked();
    assertEquals(nextValue, Integer.valueOf(2));

    nextValue = sequence.invoke(SequenceEntity.INCREMENT_AND_GET, ImmutableMap.<String, Object>of()).getUnchecked();
    assertEquals(nextValue, Integer.valueOf(3));

    assertEquals(sequence.get(), Integer.valueOf(3));
    assertAttributeEquals(sequence, SequenceEntity.SEQUENCE_VALUE, 3);
}
 
Example #6
Source File: EffectorBasicTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeEffectorErrorCollapsedNicely() {
    FailingEntity entity = createFailingEntity();
    Task<Void> task = entity.invoke(Startable.START, MutableMap.of("locations", locs));
    Exception e = assertTaskFails( task );
    // normal collapse should report where we started
    String collapsed = Exceptions.collapseText(e);
    Assert.assertFalse(Strings.containsLiteral(collapsed, "Propagated"), "Error too verbose: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "invoking"), "Error not verbose enough: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "start"), "Error not verbose enough: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "FailingEntity"), "Error not verbose enough: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, entity.getId()), "Error not verbose enough: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "Simulating"), "Error not verbose enough: "+collapsed);
    // in the context of the task we should not report where we started;
    // it instead of
    //    Error invoking start at FailingEntityImpl{id=wv6KwsPh}: Simulating entity stop failure for test
    // show
    //   Simulating entity start failure for test
    collapsed = Exceptions.collapseTextInContext(e, task);
    Assert.assertFalse(Strings.containsLiteral(collapsed, "Propagated"), "Error too verbose: "+collapsed);
    Assert.assertFalse(Strings.containsLiteral(collapsed, "invoking"), "Error too verbose: "+collapsed);
    Assert.assertFalse(Strings.containsLiteral(collapsed, "FailingEntity"), "Error too verbose: "+collapsed);
    Assert.assertFalse(Strings.containsLiteral(collapsed, entity.getId()), "Error too verbose: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "start"), "Error not verbose enough: "+collapsed);
    Assert.assertTrue(Strings.containsLiteral(collapsed, "Simulating"), "Error not verbose enough: "+collapsed);
}
 
Example #7
Source File: MongoDBClientSshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
private AbstractMongoDBServer getServer() {
    AbstractMongoDBServer server = entity.getConfig(MongoDBClient.SERVER);
    MongoDBShardedDeployment deployment = entity.getConfig(MongoDBClient.SHARDED_DEPLOYMENT);
    if (server == null) {
        Preconditions.checkNotNull(deployment, "Either server or shardedDeployment must be specified for %s", this);
        server = DependentConfiguration.builder()
                .attributeWhenReady(deployment.getRouterCluster(), MongoDBRouterCluster.ANY_ROUTER)
                .blockingDetails("any available router")
                .runNow();
        DependentConfiguration.builder()
                .attributeWhenReady(server, MongoDBRouter.SHARD_COUNT)
                .readiness(MathPredicates.<Integer>greaterThan(0))
                .runNow();
    } else {
        if (deployment != null) {
            log.warn("Server and ShardedDeployment defined for {}; using server ({} instead of {})", 
                    new Object[] {this, server, deployment});
        }
        DependentConfiguration.builder()
                .attributeWhenReady(server, Startable.SERVICE_UP)
                .readiness(Predicates.equalTo(true))
                .runNow();
    }
    return server;
}
 
Example #8
Source File: KafkaIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Test that we can start a  broker and zookeeper together.
 */
@Test(groups = "Integration")
public void testBrokerPlusZookeeper() {
    final KafkaZooKeeper zookeeper = app.createAndManageChild(EntitySpec.create(KafkaZooKeeper.class));
    final KafkaBroker broker = app.createAndManageChild(EntitySpec.create(KafkaBroker.class).configure(KafkaBroker.ZOOKEEPER, zookeeper));

    zookeeper.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(ImmutableMap.of("timeout", 60 * 1000), zookeeper, Startable.SERVICE_UP, true);

    broker.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(ImmutableMap.of("timeout", 60*1000), broker, Startable.SERVICE_UP, true);

    zookeeper.stop();
    assertFalse(zookeeper.getAttribute(Startable.SERVICE_UP));

    broker.stop();
    assertFalse(broker.getAttribute(Startable.SERVICE_UP));
}
 
Example #9
Source File: SoftwareProcessRestartIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "errorPhase", groups = "Integration")
public void testEntityOnFireAfterRestartingWhenLaunchCommandFails(ConfigKey<String> key) {
    VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class)
            .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true")
            .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "true")
            .configure(key, "exit 1"));
    try {
        app.start(ImmutableList.of(app.newLocalhostProvisioningLocation()));
        Asserts.shouldHaveFailedPreviously("entity has launch command that does not complete successfully");
    } catch (Exception e) {
        // expected
    }

    LastTwoServiceStatesListener listener = new LastTwoServiceStatesListener();
    entity.subscriptions().subscribe(entity, Attributes.SERVICE_STATE_ACTUAL, listener);

    EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    entity.invoke(Startable.RESTART, ImmutableMap.<String, Object>of(
            SoftwareProcess.RestartSoftwareParameters.RESTART_CHILDREN.getName(), false,
            SoftwareProcess.RestartSoftwareParameters.RESTART_MACHINE.getName(), false));

    List<Lifecycle> expected = ImmutableList.of(Lifecycle.STARTING, Lifecycle.ON_FIRE);
    Asserts.eventually(listener, Predicates.equalTo(expected));
}
 
Example #10
Source File: InfrastructureDeploymentTestCaseTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoDeploymentLocation() {
    EntitySpec<TestInfrastructure> infrastructureSpec = EntitySpec.create(TestInfrastructure.class);
    infrastructureSpec.configure(DEPLOYMENT_LOCATION_SENSOR, infrastructureLoc);

    List<EntitySpec<? extends Startable>> testSpecs = ImmutableList.<EntitySpec<? extends Startable>>of(EntitySpec.create(BasicApplication.class));

    InfrastructureDeploymentTestCase infrastructureDeploymentTestCase = app.createAndManageChild(EntitySpec.create(InfrastructureDeploymentTestCase.class));
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.INFRASTRUCTURE_SPEC, infrastructureSpec);
    infrastructureDeploymentTestCase.config().set(InfrastructureDeploymentTestCase.ENTITY_SPEC_TO_DEPLOY, testSpecs);

    try {
        app.start(ImmutableList.of(app.newSimulatedLocation()));
        Asserts.shouldHaveFailedPreviously();
    } catch (Throwable throwable) {
        Asserts.expectedFailure(throwable);
    }

    assertThat(infrastructureDeploymentTestCase.sensors().get(SERVICE_UP)).isFalse();
}
 
Example #11
Source File: SolrServerIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a core can be created and used with SolrJ client.
 */
@Test(groups = "Integration")
public void testConnection() throws Exception {
    solr = app.createAndManageChild(EntitySpec.create(SolrServer.class)
            .configure(SolrServer.SOLR_CORE_CONFIG, ImmutableMap.of("example", "classpath://solr/example.tgz")));
    app.start(ImmutableList.of(testLocation));

    EntityAsserts.assertAttributeEqualsEventually(solr, Startable.SERVICE_UP, true);

    SolrJSupport client = new SolrJSupport(solr, "example");

    Iterable<SolrDocument> results = client.getDocuments();
    assertTrue(Iterables.isEmpty(results));

    client.addDocument(MutableMap.<String, Object>of("id", "1", "description", "first"));
    client.addDocument(MutableMap.<String, Object>of("id", "2", "description", "second"));
    client.addDocument(MutableMap.<String, Object>of("id", "3", "description", "third"));
    client.commit();

    results = client.getDocuments();
    assertEquals(Iterables.size(results), 3);
}
 
Example #12
Source File: StormEc2LiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Test that can install, start and use a Storm cluster: 1 nimbus, 1 zookeeper, 1 supervisor (worker node).
 */
@Override
protected void doTest(Location loc) throws Exception {
    ZooKeeperNode zookeeper = app.createAndManageChild(EntitySpec.create(ZooKeeperNode.class));
    Storm nimbus = app.createAndManageChild(EntitySpec.create(Storm.class).configure("storm.role",
            Storm.Role.NIMBUS));
    Storm supervisor = app.createAndManageChild(EntitySpec.create(Storm.class).configure("storm.role",
            Storm.Role.SUPERVISOR));
    Storm ui = app.createAndManageChild(EntitySpec.create(Storm.class).configure("storm.role",
            Storm.Role.UI));        
    app.start(ImmutableList.of(loc));
    Entities.dumpInfo(app);

    EntityAsserts.assertAttributeEqualsEventually(zookeeper, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(nimbus, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(supervisor, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(ui, Startable.SERVICE_UP, true);
}
 
Example #13
Source File: ScriptHelperTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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());
    
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
    EntityAsserts.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, true);
    
    log.debug("up, now cause failure");
    
    driver.setFailExecution(true);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, false);
    
    log.debug("caught failure, now clear");
    driver.setFailExecution(false);
    EntityAsserts.assertAttributeEqualsEventually(entity, SoftwareProcess.SERVICE_PROCESS_IS_RUNNING, true);
}
 
Example #14
Source File: CouchDBNodeLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Live", dataProvider = "virtualMachineData")
protected void testOperatingSystemProvider(String imageId, String provider, String region, String description) throws Exception {
    log.info("Testing CouchDB on {}{} using {} ({})", new Object[] { provider, Strings.isNonEmpty(region) ? ":" + region : "", description, imageId });

    Map<String, String> properties = MutableMap.of("imageId", imageId);
    Location testLocation = app.getManagementContext().getLocationRegistry()
            .getLocationManaged(provider + (Strings.isNonEmpty(region) ? ":" + region : ""), properties);

    CouchDBNode couchdb = app.createAndManageChild(EntitySpec.create(CouchDBNode.class)
            .configure("httpPort", "12345+")
            .configure("clusterName", "TestCluster"));
    app.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);

    JcouchdbSupport jcouchdb = new JcouchdbSupport(couchdb);
    jcouchdb.jcouchdbTest();
}
 
Example #15
Source File: ConditionalEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddsConditionalWhenConfigured() throws Exception {
    optional = app.addChild(EntitySpec.create(ConditionalEntity.class)
            .configure(ConditionalEntity.CREATE_CONDITIONAL_ENTITY, true)
            .configure(ConditionalEntity.CONDITIONAL_ENTITY_SPEC, EntitySpec.create(TestEntity.class)));
    app.start(ImmutableList.of(loc1));

    assertEquals(optional.getChildren().size(), 1);
    Entity child = Iterables.getOnlyElement(optional.getChildren());
    assertTrue(child instanceof TestEntity);
    assertEquals(child, optional.sensors().get(ConditionalEntity.CONDITIONAL_ENTITY));

    // The service.isUp sensor will have been propagated by default
    EntityAsserts.assertAttributeEqualsEventually(child, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEqualsEventually(optional, Startable.SERVICE_UP, true);
}
 
Example #16
Source File: ReloadBrooklynPropertiesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testReloadBrooklynPropertiesDeploy() {
    brooklynMgmt.reloadBrooklynProperties();
    CampPlatform reloadedPlatform = brooklynMgmt.getScratchpad().get(BrooklynCampConstants.CAMP_PLATFORM);
    Assert.assertNotNull(reloadedPlatform);
    Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("test-entity-basic-template.yaml"));
    AssemblyTemplate template = reloadedPlatform.pdp().registerDeploymentPlan(input);
    try {
        Assembly assembly = template.getInstantiator().newInstance().instantiate(template, reloadedPlatform);
        LOG.info("Test - created " + assembly);
        final Entity app = brooklynMgmt.getEntityManager().getEntity(assembly.getId());
        LOG.info("App - " + app);
        Assert.assertEquals(app.getDisplayName(), "test-entity-basic-template");
        EntityAsserts.assertAttributeEqualsEventually(app, Startable.SERVICE_UP, true);
    } catch (Exception e) {
        LOG.warn("Unable to instantiate " + template + " (rethrowing): " + e);
        throw Exceptions.propagate(e);
    }
}
 
Example #17
Source File: AbstractWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Checks an entity can start, set SERVICE_UP to true and shutdown again.
 */
@Test(groups = "Integration", dataProvider = "basicEntities")
public void testReportsServiceDownWhenKilled(final SoftwareProcess entity) throws Exception {
    this.entity = entity;
    log.info("test=testReportsServiceDownWithKilled; entity="+entity+"; app="+entity.getApplication());
    
    Entities.start(entity.getApplication(), ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(MutableMap.of("timeout", 120*1000), entity, Startable.SERVICE_UP, true);

    // Stop the underlying entity, but without our entity instance being told!
    killEntityBehindBack(entity);
    log.info("Killed {} behind mgmt's back, waiting for service up false in mgmt context", entity);
    
    EntityAsserts.assertAttributeEqualsEventually(entity, Startable.SERVICE_UP, false);
    
    log.info("success getting service up false in primary mgmt universe");
}
 
Example #18
Source File: AbstractControllerTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsesHostAndPortSensor() throws Exception {
    controller = app.createAndManageChild(EntitySpec.create(TrackingAbstractController.class)
            .configure("serverPool", cluster) 
            .configure("hostAndPortSensor", WebServerEntity.HOST_AND_PORT)
            .configure("domain", "mydomain"));
    controller.start(Arrays.asList(loc));
    
    TestEntity child = cluster.addChild(EntitySpec.create(TestEntity.class));
    cluster.addMember(child);

    List<Collection<String>> u = Lists.newArrayList(controller.getUpdates());
    assertTrue(u.isEmpty(), "expected no updates, but got "+u);
    
    child.sensors().set(Startable.SERVICE_UP, true);
    
    // TODO Ugly sleep to allow AbstractController to detect node having been added
    Thread.sleep(100);
    
    child.sensors().set(WebServerEntity.HOST_AND_PORT, "mymachine:1234");
    assertEventuallyExplicitAddressesMatch(ImmutableList.of("mymachine:1234"));
}
 
Example #19
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public void doTestReleaseEvenIfErrorDuringStop(final Class<? extends SimulatedDriver> driver) throws Exception {
    MyService entity = app.addChild(EntitySpec.create(MyServiceWithCustomDriver.class)
            .configure(MyServiceWithCustomDriver.DRIVER_CLASS, driver));
    
    entity.start(ImmutableList.of(loc));
    Task<Void> t = entity.invoke(Startable.STOP, ImmutableMap.<String, Object>of());
    t.blockUntilEnded();
    
    assertFalse(t.isError(), "Expected parent to succeed, not fail with " + Tasks.getError(t));
    Iterator<Task<?>> failures;
    failures = Tasks.failed(Tasks.descendants(t, true)).iterator();
    Assert.assertTrue(failures.hasNext(), "Expected error in descendants");
    Optional<Task<?>> stopping = Iterables.tryFind(Tasks.children(t), TaskPredicates.displayNameEqualTo("stopping"));
    Assert.assertTrue(stopping.isPresent(), "Could not find stopping task");
    failures = Tasks.failed(Tasks.children(stopping.get())).iterator();
    Assert.assertTrue(failures.hasNext(), "Expected error in child");
    Throwable e = Tasks.getError(failures.next());
    if (e == null || !e.toString().contains("Simulating stop error")) 
        Assert.fail("Wrong error", e);

    Assert.assertEquals(loc.getAvailable(), ImmutableSet.of(machine), "Expected location to be available again");

    Entities.unmanage(entity);
}
 
Example #20
Source File: LoopOverGroupMembersTestCaseImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
    // Let everyone know we're stopping (so that the GUI shows the correct icon).
    sensors().set(Attributes.SERVICE_STATE_ACTUAL, Lifecycle.STOPPING);

    try {
        for (Entity child : this.getChildren()) {
            if (child instanceof Startable) ((Startable) child).stop();
        }

        // Let everyone know we've stopped successfully (changes the icon in the GUI).
        logger.debug("Tasks successfully run. Update state of {} to STOPPED.", this);
        setUpAndRunState(false, Lifecycle.STOPPED);
    } catch (Throwable t) {
        logger.debug("Tasks NOT successfully run. Update state of {} to ON_FIRE.", this);
        setUpAndRunState(false, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}
 
Example #21
Source File: NodeJsWebAppFixtureIntegrationTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Checks an entity can start, set SERVICE_UP to true and shutdown again.
 */
// Broken on Ubuntu 15.04 Vivid, no packages from ppa:chris-lea/node.js available
@Test(groups = {"Integration","Broken"})
public void testCanStartAndStop() {
    LOG.info("test=canStartAndStop; entity="+entity+"; app="+entity.getApplication());

    Entities.start(entity.getApplication(), ImmutableList.of(loc));
    Asserts.succeedsEventually(MutableMap.of("timeout", 120*1000), new Runnable() {
        @Override
        public void run() {
            assertTrue(entity.getAttribute(Startable.SERVICE_UP));
        }});
    
    entity.stop();
    assertFalse(entity.getAttribute(Startable.SERVICE_UP));
}
 
Example #22
Source File: KafkaLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Test that can install, start and use a Kafka cluster with two brokers.
 */
@Override
protected void doTest(Location loc) throws Exception {
    final KafkaCluster cluster = app.createAndManageChild(EntitySpec.create(KafkaCluster.class)
            .configure("startTimeout", 300) // 5 minutes
            .configure("initialSize", 2));
    app.start(ImmutableList.of(loc));

    Asserts.succeedsEventually(MutableMap.of("timeout", 300000l), new Callable<Void>() {
        @Override
        public Void call() {
            assertTrue(cluster.getAttribute(Startable.SERVICE_UP));
            assertTrue(cluster.getZooKeeper().getAttribute(Startable.SERVICE_UP));
            assertEquals(cluster.getCurrentSize().intValue(), 2);
            return null;
        }
    });

    Entities.dumpInfo(cluster);

    KafkaSupport support = new KafkaSupport(cluster);

    support.sendMessage("brooklyn", "TEST_MESSAGE");
    String message = support.getMessage("brooklyn");
    assertEquals(message, "TEST_MESSAGE");
}
 
Example #23
Source File: ZabbixServerImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public void added(Entity member) {
    synchronized (mutex) {
        Optional<Location> location = Iterables.tryFind(member.getLocations(), Predicates.instanceOf(SshMachineLocation.class));
        if (location.isPresent() && member.getAttribute(Startable.SERVICE_UP)) {
            SshMachineLocation machine = (SshMachineLocation) location.get();
            if (!entityLocations.containsKey(machine)) {
                entityLocations.put(machine, member);
                // Configure the Zabbix agent
                List<String> commands = ImmutableList.<String>builder()
                        .add("sed -i.bk 's/\\$HOSTNAME/" + machine.getDisplayName() + "/' /etc/zabbix/zabbix_agentd.conf")
                        .add("zabbix_agentd")
                        .build();
                int result = machine.execCommands("configuring zabbix_agentd", commands);
                if (result == 0) {
                    log.info("zabbix_agentd configured on {} at {}", member, machine);
                } else {
                    log.warn("failed to configure zabbix_agentd on {}, status {}", machine, result);
                }
            }
        } else {
            log.warn("zabbix added({}) called but no location or service not started", member);
        }
    }
}
 
Example #24
Source File: CassandraDatacenterLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected static void assertNodesConsistent(final List<CassandraNode> nodes) {
    final Integer expectedLiveNodeCount = nodes.size();
    // may take some time to be consistent (with new thrift_latency checks on the node,
    // contactability should not be an issue, but consistency still might be)
    Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Runnable() {
        @Override
        public void run() {
            for (Entity n : nodes) {
                CassandraNode node = (CassandraNode) n;
                EntityAsserts.assertAttributeEquals(node, Startable.SERVICE_UP, true);
                String errmsg = "node="+node+"; hostname="+node.getAttribute(Attributes.HOSTNAME)+"; port="+node.getThriftPort();
                assertTrue(isSocketOpen(node), errmsg);
                assertTrue(areVersionsConsistent(node), errmsg);
                EntityAsserts.assertAttributeEquals(node, CassandraNode.LIVE_NODE_COUNT, expectedLiveNodeCount);
            }
        }});
}
 
Example #25
Source File: CassandraDatacenterLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected static void assertSingleTokenConsistent(final List<CassandraNode> nodes) {
    final int numNodes = nodes.size();
    Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Runnable() {
        @Override
        public void run() {
            Set<BigInteger> alltokens = Sets.newLinkedHashSet();
            for (Entity node : nodes) {
                EntityAsserts.assertAttributeEquals(node, Startable.SERVICE_UP, true);
                EntityAsserts.assertConfigEquals(node, CassandraNode.NUM_TOKENS_PER_NODE, 1);
                EntityAsserts.assertAttributeEquals(node, CassandraNode.PEERS, numNodes);
                Set<BigInteger> tokens = node.getAttribute(CassandraNode.TOKENS);
                assertNotNull(tokens);
                alltokens.addAll(tokens);
            }
            assertFalse(alltokens.contains(null), "tokens="+alltokens);
            assertEquals(alltokens.size(), numNodes);
        }});
}
 
Example #26
Source File: CassandraDatacenterLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
protected static void assertVnodeTokensConsistent(final List<CassandraNode> nodes) {
    final int numNodes = nodes.size();
    final int tokensPerNode = Iterables.get(nodes, 0).getNumTokensPerNode();
    
    Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Runnable() {
        @Override
        public void run() {
            Set<BigInteger> alltokens = Sets.newLinkedHashSet();
            for (Entity node : nodes) {
                EntityAsserts.assertAttributeEquals(node, Startable.SERVICE_UP, true);
                EntityAsserts.assertAttributeEquals(node, CassandraNode.PEERS, tokensPerNode*numNodes);
                EntityAsserts.assertConfigEquals(node, CassandraNode.NUM_TOKENS_PER_NODE, 256);
                Set<BigInteger> tokens = node.getAttribute(CassandraNode.TOKENS);
                assertNotNull(tokens);
                assertEquals(tokens.size(), tokensPerNode, "tokens="+tokens);
                alltokens.addAll(tokens);
            }
            assertFalse(alltokens.contains(null));
            assertEquals(alltokens.size(), tokensPerNode*numNodes);
        }});
}
 
Example #27
Source File: JcloudsRebindWithExternalConfigTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected JcloudsLocation newJcloudsLocation(ComputeServiceRegistry computeServiceRegistry) throws Exception {
    ByonComputeServiceStaticRef.setInstance(computeServiceRegistry);
    
    String yaml = Joiner.on("\n").join(
            "location:",
            "  "+LOCATION_CATALOG_ID+":",
            "    identity: $brooklyn:external(\"creds\", \"test-identity\")",
            "    credential: $brooklyn:external(\"creds\", \"test-credential\")",
            "services:\n"+
            "- type: org.apache.brooklyn.entity.stock.BasicApplication");
    
    EntitySpec<?> spec = 
            mgmt().getTypeRegistry().createSpecFromPlan(CampTypePlanTransformer.FORMAT, yaml, RegisteredTypeLoadingContexts.spec(Application.class), EntitySpec.class);
    final Entity app = mgmt().getEntityManager().createEntity(spec);
    app.invoke(Startable.START, ImmutableMap.<String, Object>of()).get();

    JcloudsLocation result = (JcloudsLocation) Iterables.getOnlyElement(app.getLocations());
    assertEquals(result.getIdentity(), "myidentity");
    assertEquals(result.getCredential(), "mycredential");
    
    return result;
}
 
Example #28
Source File: DynamicRegionsFabricImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String addRegion(String location) {
    Preconditions.checkNotNull(location, "location");
    Location l = getManagementContext().getLocationRegistry().getLocationManaged(location);
    addLocations(Arrays.asList(l));
    
    Entity e = addCluster(l);
    ((EntityInternal)e).addLocations(Arrays.asList(l));
    if (e instanceof Startable) {
        Task<?> task = e.invoke(Startable.START, ImmutableMap.of("locations", ImmutableList.of(l)));
        task.getUnchecked();
    }
    return e.getId();
}
 
Example #29
Source File: ApplicationLoggingTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
    public void testLogging() throws Exception {
        String loggerName = ApplicationLoggingTest.class.getName();
        ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.INFO;

        Deque<String> ids = new ArrayDeque<>();
        ids.push(app.getId());
        final TestEntityWithLogging entity = app.createAndManageChild(EntitySpec.create(TestEntityWithLogging.class));
        final TestEntityWithLogging child = entity.addChild(EntitySpec.create(EntitySpec.create(TestEntityWithLogging.class)));

        try (LogWatcher watcher = new LogWatcher(loggerName, logLevel, containsMessage(app.getId()))) {
            app.start(ImmutableList.of(app.newSimulatedLocation()));
            assertHealthEventually(app, Lifecycle.RUNNING, true);
            final TaskAdaptable<Void> stopTask = Effectors.invocation(app, Startable.STOP, ImmutableMap.of());
            final String stopId = stopTask.asTask().getId();
            LOG.info("Stop task id is {}", stopId);
            final ExecutionContext executionContext = mgmt.getExecutionContext(app);
            executionContext.submit(stopTask);
            assertHealthEventually(app, Lifecycle.STOPPED, false);

            // Look for output like
//          2018-02-05 16:23:11,485 INFO  K09KEX1U-[y4lgil3hya,xn0fmqrhzd,khx0py82ba]     Hello from entity khx0py82ba
//          2018-02-05 16:23:11,488 INFO  kD8Q76x0-[y4lgil3hya,xn0fmqrhzd]   Hello from entity xn0fmqrhzd
//          2018-02-05 16:23:11,488 INFO  ZsU4OGEp-[y4lgil3hya] Hello world
//          2018-02-05 16:23:11,496 INFO  - Stop task id is pOp03ybS
//          2018-02-05 16:23:11,498 INFO  pOp03ybS-[y4lgil3hya] Goodbye cruel world
//          2018-02-05 16:23:11,499 INFO  c1Pcn3FR-[y4lgil3hya,xn0fmqrhzd]   Goodbye from entity xn0fmqrhzd
//          2018-02-05 16:23:11,500 INFO  eq9akWgK-[y4lgil3hya,xn0fmqrhzd,khx0py82ba]     Goodbye from entity khx0py82ba
            watcher.assertHasEvent(containsMessage(stopId + "-"));
            watcher.assertHasEvent(matchingRegexes(".*" + app.getApplicationId() + ".*Hello world.*"));;
            watcher.assertHasEvent(matchingRegexes(".*" +
                ImmutableList.of(app.getId(), entity.getId()).toString()
                + ".*from entity.*" + entity.getId() + ".*"));
            watcher.assertHasEvent(matchingRegexes(".*" +
                ImmutableList.of(app.getId(), entity.getId(), child.getId()).toString()
                + ".*from entity.*" + child.getId() + ".*"));
        }
    }
 
Example #30
Source File: BalanceableWorkerPoolImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    if (LOG.isTraceEnabled()) LOG.trace("{} received event {}", BalanceableWorkerPoolImpl.this, event);
    Entity source = event.getSource();
    Object value = event.getValue();
    Sensor<?> sensor = event.getSensor();
    
    if (sensor.equals(AbstractGroup.MEMBER_ADDED)) {
        if (source.equals(containerGroup)) {
            onContainerAdded((BalanceableContainer<?>) value);
        } else if (source.equals(itemGroup)) {
            onItemAdded((Entity)value);
        } else {
            throw new IllegalStateException("unexpected event source="+source);
        }
    } else if (sensor.equals(AbstractGroup.MEMBER_REMOVED)) {
        if (source.equals(containerGroup)) {
            onContainerRemoved((BalanceableContainer<?>) value);
        } else if (source.equals(itemGroup)) {
            onItemRemoved((Entity) value);
        } else {
            throw new IllegalStateException("unexpected event source="+source);
        }
    } else if (sensor.equals(Startable.SERVICE_UP)) {
        // TODO What if start has failed? Is there a sensor to indicate that?
        if ((Boolean)value) {
            onContainerUp((BalanceableContainer<?>) source);
        } else {
            onContainerDown((BalanceableContainer<?>) source);
        }
    } else if (sensor.equals(Movable.CONTAINER)) {
        onItemMoved(source, (BalanceableContainer<?>) value);
    } else {
        throw new IllegalStateException("Unhandled event type "+sensor+": "+event);
    }
}