org.apache.brooklyn.core.entity.lifecycle.ServiceStateLogic Java Examples

The following examples show how to use org.apache.brooklyn.core.entity.lifecycle.ServiceStateLogic. 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: HaPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testServiceFailureDetectorWorksAfterRebind() throws Exception {
    origEntity.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));

    // rebind
    TestApplication newApp = rebind();
    final TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class));

    newApp.getManagementContext().getSubscriptionManager().subscribe(newEntity, HASensors.ENTITY_FAILED, eventListener);

    newEntity.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(newEntity, Lifecycle.RUNNING);
    
    // trigger the failure
    newEntity.sensors().set(TestEntity.SERVICE_UP, false);

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(newEntity), null);
    assertEquals(events.size(), 1, "events="+events);
}
 
Example #2
Source File: EntityAsyncTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
    ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator(this, START.getName(), "starting");
    
    try {
        for (int i = 0; i < config().get(INITIAL_SIZE); i++) {
            addChild(EntitySpec.create(AsyncEntity.class));
        }
        StartableMethods.start(this, locations);
        
    } catch (Throwable t) {
        ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator(this, START.getName(), Exceptions.collapseText(t));
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}
 
Example #3
Source File: SimpleShellCommandDeprecatedIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void shouldFailUsingSuccessfulExitAsDefaultCondition() {
    TestEntity testEntity = app.createAndManageChild(EntitySpec.create(TestEntity.class).location(TestApplication.LOCALHOST_MACHINE_SPEC));

    SimpleShellCommandTest uptime = app.createAndManageChild(EntitySpec.create(SimpleShellCommandTest.class)
        .configure(TARGET_ENTITY, testEntity)
        .configure(COMMAND, "ls /tmp/bogus-" + Identifiers.randomLong()));

    try {
        app.start(ImmutableList.<Location>of());
    } catch (Throwable t) {
        // Used to be "but found 1", I'm getting "but found 2". Could be OS specific.
        Asserts.expectedFailureContains(t, "exit code expected equals 0 but found ");
    }

    assertThat(uptime.sensors().get(SERVICE_UP)).isFalse()
        .withFailMessage("Service should be down");
    assertThat(ServiceStateLogic.getExpectedState(uptime)).isEqualTo(Lifecycle.ON_FIRE)
        .withFailMessage("Service should be marked on fire");
}
 
Example #4
Source File: FailingEntityImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
    getConfig(LISTENER).onEvent(this, "stop", new Object[0]);
    if (getConfig(FAIL_ON_STOP) || (getConfig(FAIL_ON_STOP_CONDITION) != null && getConfig(FAIL_ON_STOP_CONDITION).apply(this))) {
        if (Boolean.TRUE.equals(getConfig(SET_SERVICE_DOWN_ON_FAILURE))) {
            ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
            sensors().set(SERVICE_UP, false);
            ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
        }
        
        callHistory.add("stop");
        getConfig(EXEC_ON_FAILURE).apply(this);
        throw fail("Simulating entity stop failure for test");
    }
    super.stop();
}
 
Example #5
Source File: RiakClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() {
    super.doStart();
    connectSensors();

    try {
        Duration delay = getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER);
        Tasks.setBlockingDetails("Sleeping for "+delay+" before advertising cluster available");
        Time.sleep(delay);
    } finally {
        Tasks.resetBlockingDetails();
    }

    //FIXME: add a quorum to tolerate failed nodes before setting on fire.
    @SuppressWarnings("unchecked")
    Optional<Entity> anyNode = Iterables.tryFind(getMembers(), Predicates.and(
            Predicates.instanceOf(RiakNode.class),
            EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
            EntityPredicates.attributeEqualTo(RiakNode.SERVICE_UP, true)));
    if (anyNode.isPresent()) {
        sensors().set(IS_CLUSTER_INIT, true);
    } else {
        log.warn("No Riak Nodes are found on the cluster: {}. Initialization Failed", getId());
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
    }
}
 
Example #6
Source File: MongoDBReplicaSetImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Initialises the replica set with the given server as primary if {@link #mustInitialise} is true,
 * otherwise schedules the addition of a new secondary.
 */
private void serverAdded(MongoDBServer server) {
    try {
        LOG.debug("Server added: {}. SERVICE_UP: {}", server, server.sensors().get(MongoDBServer.SERVICE_UP));

        // Set the primary if the replica set hasn't been initialised.
        if (mustInitialise.compareAndSet(true, false)) {
            if (LOG.isInfoEnabled())
                LOG.info("First server up in {} is: {}", getName(), server);
            boolean replicaSetInitialised = server.initializeReplicaSet(getName(), nextMemberId.getAndIncrement());
            if (replicaSetInitialised) {
                sensors().set(PRIMARY_ENTITY, server);
                sensors().set(Startable.SERVICE_UP, true);
            } else {
                ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator(this, "initialization", "replicaset failed to initialize");
                ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
            }
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("Scheduling addition of member to {}: {}", getName(), server);
            addSecondaryWhenPrimaryIsNonNull(server);
        }
    } catch (Exception e) {
        ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator(server, "Failed to update replicaset", e);
    }
}
 
Example #7
Source File: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testWaitForServiceUpDefaultsToNotChecking() throws Exception {
    DynamicCluster cluster = app.addChild(EntitySpec.create(DynamicCluster.class)
            .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
            .configure("initialSize", 1));

    // Indicate that the cluster is not healthy 
    ServiceStateLogic.updateMapSensorEntry(cluster, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, "simulateNotUpKey", "myVal");

    // Start - expect it to complete promptly
    Stopwatch stopwatch = Stopwatch.createStarted();
    app.start(ImmutableList.of());
    Duration startTime = Duration.of(stopwatch);
    LOG.info("start-time "+startTime);
    assertTrue(startTime.isShorterThan(Asserts.DEFAULT_LONG_TIMEOUT), "startTime="+startTime);

    // Should be on-fire
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_UP, false);

    // Clearing the notUp indicator should allow it to recover
    ServiceStateLogic.updateMapSensorEntry(cluster, ServiceStateLogic.SERVICE_NOT_UP_INDICATORS, "simulateNotUpKey", Entities.REMOVE);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_UP, true);
}
 
Example #8
Source File: MongoDBShardedDeploymentImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
    try {
        final MongoDBRouterCluster routers = getAttribute(ROUTER_CLUSTER);
        final MongoDBShardCluster shards = getAttribute(SHARD_CLUSTER);
        List<DynamicCluster> clusters = ImmutableList.of(getAttribute(CONFIG_SERVER_CLUSTER), routers, shards);
        Entities.invokeEffectorList(this, clusters, Startable.START, ImmutableMap.of("locations", locations))
                .get();

        if (config().getRaw(MongoDBShardedDeployment.CO_LOCATED_ROUTER_GROUP).isPresent()) {
            policies().add(PolicySpec.create(ColocatedRouterTrackingPolicy.class)
                    .displayName("Co-located router tracker")
                    .configure("group", getConfig(MongoDBShardedDeployment.CO_LOCATED_ROUTER_GROUP)));
        }

        ServiceNotUpLogic.clearNotUpIndicator(this, Attributes.SERVICE_STATE_ACTUAL);
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } catch (Exception e) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        // no need to log here; the effector invocation should do that
        throw Exceptions.propagate(e);
    }
}
 
Example #9
Source File: DependentConfigurationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributeWhenReadyAbortsWhenAlreadyOnFireByDefault() throws Exception {
    ServiceStateLogic.setExpectedState(entity, Lifecycle.ON_FIRE);
    EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    
    final Task<String> t = submit(DependentConfiguration.builder()
            .attributeWhenReady(entity, TestEntity.NAME)
            .build());

    try {
        assertDoneEventually(t);
        fail();
    } catch (Exception e) {
        if (!e.toString().contains("Aborted waiting for ready")) throw e;
    }
}
 
Example #10
Source File: TestSshCommandIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Integration")
public void shouldCaptureStdoutAndStderrOfScript() throws Exception {
    String text = "echo 'a' 'b' && CMDSUFFIX=Suffix && doesNotExist${CMDSUFFIX}";
    Path testScript = createTempScript("script", "echo " + text);

    try {
        TestSshCommand uptime = app.createAndManageChild(EntitySpec.create(TestSshCommand.class)
                .configure(TARGET_ENTITY, testEntity)
                .configure(DOWNLOAD_URL, "file:" + testScript)
                .configure(ASSERT_OUT, makeAssertions(ImmutableMap.of(CONTAINS, "a b")))
                .configure(ASSERT_ERR, makeAssertions(ImmutableMap.of(CONTAINS, "doesNotExistSuffix"))));

            app.start(ImmutableList.<Location>of());

            assertThat(uptime.sensors().get(SERVICE_UP)).isTrue()
                .withFailMessage("Service should be up");
            assertThat(ServiceStateLogic.getExpectedState(uptime)).isEqualTo(Lifecycle.RUNNING)
                .withFailMessage("Service should be marked running");

    } finally {
        Files.delete(testScript);
    }
}
 
Example #11
Source File: UpdatingMap.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Called whenever the values for the set of producers changes (e.g. on an event, or on a member added/removed).
 */
@SuppressWarnings("unchecked")
protected void onUpdated() {
    try {
        Object v = computing.apply(producer.getAttribute(sourceSensor));
        if (v == null && Boolean.TRUE.equals(removingIfResultIsNull)) {
            v = Entities.REMOVE;
        }
        if (v == Entities.UNCHANGED) {
            // nothing
        } else {
            TKey key = this.key;
            if (key==null) key = (TKey) sourceSensor.getName();

            ServiceStateLogic.updateMapSensorEntry(entity, targetSensor, key, (TVal) v);
        }
    } catch (Throwable t) {
        LOG.warn("Error calculating map update for enricher "+this, t);
        throw Exceptions.propagate(t);
    }
}
 
Example #12
Source File: OpenShiftEntityImpl.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
/**
 * It is a temporal method. It will be contains the start effector body. It will be
 * moved to LifeCycle class based on Task. It is the first approach.
 * It does not start the entity children.
 */
protected final void doStart(Collection<? extends Location> locations) {

    ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
    try {
        preStart();
        driver.start();
        log.info("Entity {} was started with driver {}", new Object[]{this, driver});

        postDriverStart();
        connectSensors();
        postStart();
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    } catch (Throwable t) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        log.error("Error error starting entity {}", this);
        throw Exceptions.propagate(t);
    }
}
 
Example #13
Source File: OpenShiftEntityImpl.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
/**
 * To be overridden instead of {@link #stop()}; sub-classes should call {@code super.doStop()}
 * and should add do additional work via tasks, executed using
 * {@link DynamicTasks#queue(String, java.util.concurrent.Callable)}.
 */
protected final void doStop() {

    log.info("Stopping {} in {}", new Object[]{this, getLocationOrNull()});

    if (getAttribute(SERVICE_STATE_ACTUAL)
            .equals(Lifecycle.STOPPED)) {
        log.warn("The entity {} is already stopped", new Object[]{this});
        return;
    }

    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
    try {
        preStop();
        driver.stop();
        postDriverStop();
        postStop();
        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
        log.info("The entity stop operation {} is completed without errors",
                new Object[]{this});
    } catch (Throwable t) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(t);
    }
}
 
Example #14
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    MutableMap<String, String> formParams = MutableMap.of();
    Lifecycle initialState = entity().getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    ServiceStateLogic.setExpectedState(entity(), Lifecycle.STOPPING);
    for (ConfigKey<?> k: new ConfigKey<?>[] { STOP_APPS_FIRST, FORCE_SHUTDOWN_ON_ERROR, SHUTDOWN_TIMEOUT, REQUEST_TIMEOUT, DELAY_FOR_HTTP_RETURN })
        formParams.addIfNotNull(k.getName(), toNullableString(parameters.get(k)));
    try {
        log.debug("Shutting down "+entity()+" with "+formParams);
        HttpToolResponse resp = ((BrooklynNode)entity()).http()
            .post("/v1/server/shutdown",
                ImmutableMap.of("Brooklyn-Allow-Non-Master-Access", "true"),
                formParams);
        if (resp.getResponseCode() != HttpStatus.SC_NO_CONTENT) {
            throw new IllegalStateException("Response code "+resp.getResponseCode());
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new PropagatedRuntimeException("Error shutting down remote node "+entity()+" (in state "+initialState+"): "+Exceptions.collapseText(e), e);
    }
    ServiceNotUpLogic.updateNotUpIndicator(entity(), SHUTDOWN.getName(), "Shutdown of remote node has completed successfuly");
    return null;
}
 
Example #15
Source File: SoftwareProcessEntityRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesNotCreateDriverAfterRebind() throws Exception {
    MyService origE = origApp.createAndManageChild(EntitySpec.create(MyService.class)
            .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
            //the entity skips enricher initialization, do it explicitly
    origE.enrichers().add(ServiceStateLogic.newEnricherForServiceStateFromProblemsAndUp());
    
    MyProvisioningLocation origLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(MyProvisioningLocation.class)
            .displayName("mylocname"));
    origApp.start(ImmutableList.of(origLoc));
    assertEquals(origE.getAttribute(Attributes.SERVICE_STATE_EXPECTED).getState(), Lifecycle.RUNNING);
    EntityAsserts.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);

    ServiceStateLogic.setExpectedState(origE, Lifecycle.ON_FIRE);
    EntityAsserts.assertAttributeEqualsEventually(origE, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);

    newApp = rebind();
    MyService newE = (MyService) Iterables.getOnlyElement(newApp.getChildren());
    assertNull(newE.getDriver(), "driver should not be initialized because entity is in a permanent failure");
}
 
Example #16
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotifiedOfRecovery() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));
    
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    // Make the entity fail
    e1.sensors().set(TestEntity.SERVICE_UP, false);

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);

    // And make the entity recover
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    assertHasEventEventually(HASensors.ENTITY_RECOVERED, Predicates.<Object>equalTo(e1), null);
    assertEquals(events.size(), 2, "events="+events);
    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
}
 
Example #17
Source File: FailingEntityImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void restart() {
    getConfig(LISTENER).onEvent(this, "restart", new Object[0]);
    if (getConfig(FAIL_ON_RESTART) || (getConfig(FAIL_ON_RESTART_CONDITION) != null && getConfig(FAIL_ON_RESTART_CONDITION).apply(this))) {
        if (Boolean.TRUE.equals(getConfig(SET_SERVICE_DOWN_ON_FAILURE))) {
            ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
            sensors().set(SERVICE_UP, false);
            ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
            ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
            ServiceStateLogic.setExpectedStateRunningWithErrors(this);
        }

        callHistory.add("restart");
        getConfig(EXEC_ON_FAILURE).apply(this);
        throw fail("Simulating entity restart failure for test");
    }
    super.restart();
}
 
Example #18
Source File: EntityAsyncTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onCallback(String childId, boolean success) {
    Optional<Entity> child = Iterables.tryFind(getChildren(), EntityPredicates.idEqualTo(childId));
    if (child.isPresent()) {
        ((AsyncEntity)child.get()).onCallback(success);
    } else {
        LOG.warn("Child not found with resourceId '"+childId+"'; not injecting state from callback");
    }
    
    Optional<Entity> unstartedVm = Iterables.tryFind(getChildren(), EntityPredicates.attributeSatisfies(Attributes.SERVICE_STATE_EXPECTED, 
            new Predicate<Lifecycle.Transition>() {
                @Override public boolean apply(Transition input) {
                    return input == null || input.getState() == Lifecycle.STARTING;
                }}));
    
    if (!unstartedVm.isPresent()) {
        // No VMs are still starting; we are finished starting
        ServiceStateLogic.ServiceNotUpLogic.clearNotUpIndicator(this, START.getName());
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    }
}
 
Example #19
Source File: ApplicationLifecycleStateTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void assertUpAndRunningEventually(Entity entity) {
    try {
        EntityAsserts.assertAttributeEventually(entity, Attributes.SERVICE_NOT_UP_INDICATORS, CollectionFunctionals.<String>mapEmptyOrNull());
        EntityAsserts.assertAttributeEventually(entity, ServiceStateLogic.SERVICE_PROBLEMS, CollectionFunctionals.<String>mapEmptyOrNull());
        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
        EntityAsserts.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, true);
    } catch (Throwable t) {
        Dumper.dumpInfo(entity);
        String err = "(Dumped entity info - see log); entity=" + entity + "; " + 
                "state=" + entity.sensors().get(Attributes.SERVICE_STATE_ACTUAL) + "; " + 
                "up="+entity.sensors().get(Attributes.SERVICE_UP) + "; " +
                "notUpIndicators="+entity.sensors().get(Attributes.SERVICE_NOT_UP_INDICATORS) + "; " +
                "serviceProblems="+entity.sensors().get(Attributes.SERVICE_PROBLEMS);
        throw new AssertionError(err, t);
    }
}
 
Example #20
Source File: SaltEntitySshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void restart() {
    ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.STOPPING);

    try {
        final Set<? extends String> restartStates = getEntity().config().get(SaltConfig.RESTART_STATES);
        LOG.debug("Executing Salt restart with states {}", restartStates);
        if (restartStates.isEmpty()) {
            restartBasedOnStartStates();
        } else {
            applyStates(restartStates);
        }
        ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.RUNNING);
    } catch (Exception e) {
        getEntity().sensors().set(ServiceStateLogic.SERVICE_NOT_UP_DIAGNOSTICS,
                ImmutableMap.<String, Object>of("restart", e.getMessage()));
        ServiceStateLogic.setExpectedState(getEntity(), Lifecycle.ON_FIRE);
    }
}
 
Example #21
Source File: CloudFoundryEntityImpl.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
protected void onUpdated() {
    Boolean isRunning = entity.getAttribute(SERVICE_PROCESS_IS_RUNNING);
    if (Boolean.FALSE.equals(isRunning)) {
        ServiceStateLogic.ServiceNotUpLogic
                .updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING,
                        "The software process for this entity does not appear to be running");
        return;
    }
    if (Boolean.TRUE.equals(isRunning)) {
        ServiceStateLogic.ServiceNotUpLogic
                .clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
        return;
    }
    // no info on "isRunning"
    Boolean isUp = entity.getAttribute(Attributes.SERVICE_UP);
    if (Boolean.TRUE.equals(isUp)) {
        // if service explicitly set up, then don't apply our rule
        ServiceStateLogic.ServiceNotUpLogic
                .clearNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING);
        return;
    }
    // service not up, or no info
    ServiceStateLogic.ServiceNotUpLogic
            .updateNotUpIndicator(entity, SERVICE_PROCESS_IS_RUNNING,
                    "No information on whether this service is running");
}
 
Example #22
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() {
    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
    try {
        for (Policy it : policies()) { it.suspend(); }

        // run shrink without mutex to make things stop even if starting,
        int size = getCurrentSize();
        if (size > 0) { shrink(-size); }

        // run resize with mutex to prevent others from starting things
        resize(0);

        // also stop any remaining stoppable children -- eg those on fire
        // (this ignores the quarantine node which is not stoppable)
        StartableMethods.stop(this);

        ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
    } catch (Exception e) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
        throw Exceptions.propagate(e);
    } finally {
        if (clusterOneAndAllMembersUp != null) clusterOneAndAllMembersUp.stop();
    }
}
 
Example #23
Source File: CloudFoundryEntityImpl.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void initEnrichers() {
    super.initEnrichers();
    ServiceStateLogic.ServiceNotUpLogic
            .updateNotUpIndicator(this, SERVICE_PROCESS_IS_RUNNING,
                    "No information yet on whether this service is running");
    // add an indicator above so that if is_running comes through, the map is cleared and
    // an update is guaranteed
    addEnricher(EnricherSpec.create(UpdatingNotUpFromServiceProcessIsRunning.class)
            .uniqueTag("service-process-is-running-updating-not-up"));
}
 
Example #24
Source File: DynamicMultiGroupImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void initEnrichers() {
    super.initEnrichers();
    // check states and upness separately so they can be individually replaced if desired
    // problem if any children or members are on fire
    enrichers().add(ServiceStateLogic.newEnricherFromChildrenState()
            .checkChildrenOnly()
            .requireRunningChildren(getConfig(RUNNING_QUORUM_CHECK))
            .suppressDuplicates(true));
    // defaults to requiring at least one member or child who is up
    enrichers().add(ServiceStateLogic.newEnricherFromChildrenUp()
            .checkChildrenOnly()
            .requireUpChildren(getConfig(UP_QUORUM_CHECK))
            .suppressDuplicates(true));
}
 
Example #25
Source File: BasicStartableImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void initEnrichers() {
    super.initEnrichers();
    enrichers().add(ServiceStateLogic.newEnricherFromChildrenUp()
            .checkChildrenOnly()
            .requireUpChildren(QuorumCheck.QuorumChecks.all())
            .suppressDuplicates(true));
}
 
Example #26
Source File: BasicStartableImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    try {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

        // Opportunity to block startup until other dependent components are available
        Object val = config().get(START_LATCH);
        if (val != null) log.debug("{} finished waiting for start-latch; continuing...", this);

        addLocations(locations);
        locations = Locations.getLocationsCheckingAncestors(locations, this);
        log.info("Starting entity "+this+" at "+locations);

        // essentially does StartableMethods.start(this, locations),
        // but optionally filters locations for each child

        Locations.LocationsFilter filter = getConfig(LOCATIONS_FILTER);
        Iterable<Entity> startables = filterStartableManagedEntities(getChildren());
        if (!Iterables.isEmpty(startables)) {
            List<Task<?>> tasks = Lists.newArrayListWithCapacity(Iterables.size(startables));
            for (final Entity entity : startables) {
                Collection<? extends Location> l2 = locations;
                if (filter != null) {
                    l2 = filter.filterForContext(new ArrayList<Location>(locations), entity);
                    log.debug("Child " + entity + " of " + this + " being started in filtered location list: " + l2);
                }
                tasks.add(Entities.invokeEffectorWithArgs(this, entity, Startable.START, l2));
            }
            for (Task<?> t : tasks) {
                t.getUnchecked();
            }
        }
        sensors().set(Attributes.SERVICE_UP, true);
    } finally {
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    }
}
 
Example #27
Source File: RedisClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
protected void initEnrichers() {
    super.initEnrichers();
    ServiceStateLogic.newEnricherFromChildrenUp().
        checkChildrenOnly().
        requireUpChildren(QuorumChecks.all()).
        configure(ComputeServiceIndicatorsFromChildrenAndMembers.IGNORE_ENTITIES_WITH_THESE_SERVICE_STATES, ImmutableSet.<Lifecycle>of()).
        addTo(this);
}
 
Example #28
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration") // Has a 1 second wait
public void testEmitsEntityFailureOnlyIfPreviouslyUp() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));
    
    // Make the entity fail
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);

    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    assertNoEventsContinually();
}
 
Example #29
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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
    e1.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);
    
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));
    
    assertNoEventsContinually();
    assertEquals(e1.getAttribute(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING);
}
 
Example #30
Source File: ServiceFailureDetectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisablingPreviouslyUpRequirementForEntityFailed() throws Exception {
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
        .configure(ServiceFailureDetector.ENTITY_FAILED_ONLY_IF_PREVIOUSLY_UP, false));
    
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING);

    EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE);
    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
}