Java Code Examples for org.apache.brooklyn.core.entity.Entities#isManaged()

The following examples show how to use org.apache.brooklyn.core.entity.Entities#isManaged() . 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: ActivityRestTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected void initEntity(int seed) {
    if (entity != null && Entities.isManaged(entity)) {
        Entities.destroy(entity.getApplication());
    }
    
    CreationResult<BasicApplication, Void> app = EntityManagementUtils.createStarting(getManagementContext(),
        EntitySpec.create(BasicApplication.class)
            .child(EntitySpec.create(TestEntityWithEffectors.class)) );
    app.blockUntilComplete();
    entity = Iterables.getOnlyElement( app.get().getChildren() );
    
    SampleManyTasksEffector manyTasksAdder = new SampleManyTasksEffector(ConfigBag.newInstance().configure(SampleManyTasksEffector.RANDOM_SEED, seed));
    effector = manyTasksAdder.getEffector();
    manyTasksAdder.apply((org.apache.brooklyn.api.entity.EntityLocal) entity);
}
 
Example 2
Source File: BasicExecutionManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected boolean deleteTaskNonRecursive(Task<?> task) {
    Set<?> tags = TaskTags.getTagsFast(checkNotNull(task, "task"));
    for (Object tag : tags) {
        synchronized (tasksByTag) {
            Set<Task<?>> tasks = tasksWithTagLiveOrNull(tag);
            if (tasks != null) {
                tasks.remove(task);
                if (tasks.isEmpty()) {
                    tasksByTag.remove(tag);
                }
            }
        }
    }
    Task<?> removed = tasksById.remove(task.getId());
    incompleteTaskIds.remove(task.getId());
    if (removed!=null && removed.isSubmitted() && !removed.isDone(true)) {
        Entity context = BrooklynTaskTags.getContextEntity(removed);
        if (context!=null && !Entities.isManaged(context)) {
            log.debug("Forgetting about active task on unmanagement of "+context+": "+removed);
        } else {
            log.warn("Deleting submitted task before completion: "+removed+"; this task will continue to run in the background outwith "+this+", but perhaps it should have been cancelled?");
        }
    }
    return removed != null;
}
 
Example 3
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void onUpdated() {
    if (entity==null || !Entities.isManaged(entity)) {
        // either invoked during setup or entity has become unmanaged; just ignore
        BrooklynLogging.log(log, BrooklynLogging.levelDebugOrTraceIfReadOnly(entity),
            "Ignoring {} onUpdated when entity is not in valid state ({})", this, entity);
        return;
    }

    // override superclass to publish multiple sensors
    if (getConfig(DERIVE_SERVICE_PROBLEMS)) {
        updateMapSensor(SERVICE_PROBLEMS, computeServiceProblems());
    }

    if (getConfig(DERIVE_SERVICE_NOT_UP)) {
        updateMapSensor(SERVICE_NOT_UP_INDICATORS, computeServiceNotUp());
    }
}
 
Example 4
Source File: StartableMethods.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static void stopSequentially(Iterable<? extends Startable> entities) {
    List<Exception> exceptions = Lists.newArrayList();
    List<Startable> failedEntities = Lists.newArrayList();
    
    for (final Startable entity : entities) {
        if (!Entities.isManaged((Entity)entity)) {
            log.debug("Not stopping {} because it is not managed; continuing", entity);
            continue;
        }
        try {
            TaskAdaptable<Void> task = TaskTags.markInessential(Effectors.invocation((Entity)entity, Startable.STOP, Collections.emptyMap()));
            DynamicTasks.submit(task, (Entity)entity).getUnchecked();
        } catch (Exception e) {
            log.warn("Error stopping "+entity+"; continuing with shutdown", e);
            exceptions.add(e);
            failedEntities.add(entity);
        }
    }
    
    if (exceptions.size() > 0) {
        throw new CompoundRuntimeException("Error stopping "+(failedEntities.size() > 1 ? "entities" : "entity")+": "+failedEntities, exceptions);
    }
}
 
Example 5
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void expireUnmanagedEntityTasks() {
    Iterator<Entry<Entity, Task<?>>> ei;
    synchronized (unmanagedEntitiesNeedingGc) {
        ei = MutableSet.copyOf(unmanagedEntitiesNeedingGc.entrySet()).iterator();
    }
    while (ei.hasNext()) {
        Entry<Entity, Task<?>> ee = ei.next();
        if (Entities.isManaged(ee.getKey())) continue;
        if (ee.getValue()!=null && !ee.getValue().isDone(true)) {
            // wait for the unmanagement task to complete
            continue;
        }
        deleteTasksForEntity(ee.getKey());
        synchronized (unmanagedEntitiesNeedingGc) {
            unmanagedEntitiesNeedingGc.remove(ee.getKey());
        }
    }
}
 
Example 6
Source File: CassandraFabricImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean isViableSeed(Entity member) {
    // TODO remove duplication from CassandraClusterImpl.SeedTracker.isViableSeed
    boolean managed = Entities.isManaged(member);
    String hostname = member.getAttribute(Attributes.HOSTNAME);
    boolean serviceUp = Boolean.TRUE.equals(member.getAttribute(Attributes.SERVICE_UP));
    Lifecycle serviceState = member.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    boolean hasFailed = !managed || (serviceState == Lifecycle.ON_FIRE) || (serviceState == Lifecycle.RUNNING && !serviceUp) || (serviceState == Lifecycle.STOPPED);
    boolean result = (hostname != null && !hasFailed);
    if (log.isTraceEnabled()) log.trace("Node {} in Fabric {}: viableSeed={}; hostname={}; serviceUp={}; serviceState={}; hasFailed={}", new Object[] {member, CassandraFabricImpl.this, result, hostname, serviceUp, serviceState, hasFailed});
    return result;
}
 
Example 7
Source File: CassandraDatacenterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean isViableSeed(Entity member) {
    // TODO would be good to reuse the better logic in ServiceFailureDetector
    // (e.g. if that didn't just emit a notification but set a sensor as well?)
    boolean managed = Entities.isManaged(member);
    String hostname = member.getAttribute(Attributes.HOSTNAME);
    boolean serviceUp = Boolean.TRUE.equals(member.getAttribute(Attributes.SERVICE_UP));
    Lifecycle serviceState = member.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    boolean hasFailed = !managed || (serviceState == Lifecycle.ON_FIRE) || (serviceState == Lifecycle.RUNNING && !serviceUp) || (serviceState == Lifecycle.STOPPED);
    boolean result = (hostname != null && !hasFailed);
    if (log.isTraceEnabled()) log.trace("Node {} in Cluster {}: viableSeed={}; hostname={}; serviceUp={}; serviceState={}; hasFailed={}", new Object[] {member, this, result, hostname, serviceUp, serviceState, hasFailed});
    return result;
}
 
Example 8
Source File: AbstractSoftwareProcessWinRmDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected WinRmExecuteHelper newEmptyScript(String taskNamePrefix) {
    if (!Entities.isManaged(getEntity()))
        throw new IllegalStateException(getEntity() + " is no longer managed; cannot create script to run here (" + taskNamePrefix + ")");

    WinRmExecuteHelper s = new WinRmExecuteHelper(this, taskNamePrefix + " " + elvis(entity, this));
    return s;
}
 
Example 9
Source File: SoftwareProcessEntityFeedRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isRunning() {
    if (!Entities.isManaged(entity)) {
        isRunningCalledWhenNotManaged = true;
        throw new IllegalStateException("Entity "+entity+" is not managed in driver.isRunning");
    }
    return true;
}
 
Example 10
Source File: SelectMasterEffectorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void masterFailoverIfNeeded() {
    if (!Entities.isManaged(cluster)) return;
    if (cluster.getAttribute(BrooklynCluster.MASTER_NODE) == null) {
        Collection<Entity> members = cluster.getMembers();
        if (members.size() > 0) {
            for (Entity member : members) {
                if (member.getAttribute(MockBrooklynNode.HA_PRIORITY) == 1) {
                    masterFailover(member);
                    return;
                }
            }
            masterFailover(members.iterator().next());
        }
    }
}
 
Example 11
Source File: MockItemEntityImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    // FIXME How best to indicate this has been entirely stopped, rather than just in-transit?
    if (LOG.isDebugEnabled()) LOG.debug("Mocks: stopping item {} (was in container {})", this, currentContainer);
    _lock.lock();
    try {
        if (currentContainer != null && Entities.isManaged(currentContainer)) currentContainer.removeItem(this);
        currentContainer = null;
        stopped = true;
    } finally {
        _lock.unlock();
    }
}
 
Example 12
Source File: AsyncApplicationImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected void onUpdated() {
    if (entity == null || !isRunning() || !Entities.isManaged(entity)) {
        // e.g. invoked during setup or entity has become unmanaged; just ignore
        BrooklynLogging.log(LOG, BrooklynLogging.levelDebugOrTraceIfReadOnly(entity),
            "Ignoring {} onUpdated when entity is not in valid state ({})", this, entity);
        return;
    }

    Lifecycle.Transition oldExpectedStateTransition = entity.sensors().get(Attributes.SERVICE_STATE_EXPECTED);
    Lifecycle oldExpectedState = (oldExpectedStateTransition != null) ? oldExpectedStateTransition.getState() : null;
    
    ValueAndReason<Boolean> newServiceUp = computeServiceUp(oldExpectedState);
    ValueAndReason<Lifecycle> newServiceState = computeServiceState(oldExpectedState);
    Lifecycle newExpectedState = computeExpectedState(oldExpectedState, newServiceState.val);

    emit(Attributes.SERVICE_STATE_ACTUAL, newServiceState.val);
    emit(Attributes.SERVICE_UP, newServiceUp.val);
    
    if (Boolean.TRUE.equals(newServiceUp.val)) {
        clearMapSensorEntry(entity, Attributes.SERVICE_NOT_UP_INDICATORS, DEFAULT_UNIQUE_TAG);
    } else {
        updateMapSensorEntry(entity, Attributes.SERVICE_NOT_UP_INDICATORS, DEFAULT_UNIQUE_TAG, newServiceUp.reason);
    }
    if (newServiceState.val != null && newServiceState.val == Lifecycle.ON_FIRE) {
        updateMapSensorEntry(entity, Attributes.SERVICE_PROBLEMS, DEFAULT_UNIQUE_TAG, newServiceState.reason);
    } else {
        clearMapSensorEntry(entity, Attributes.SERVICE_PROBLEMS, DEFAULT_UNIQUE_TAG);
    }
    
    if (oldExpectedState != newExpectedState) {
        // TODO could check no-one else has changed expectedState (e.g. by calling "stop")
        // TODO do we need to subscribe to our own serviceStateExpected, in case someone calls stop?
        getEntity().setExpectedStateAndRecordLifecycleEvent(newExpectedState);
    }
}
 
Example 13
Source File: BrooklynGarbageCollector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private boolean isAssociatedToActiveEntity(Task<?> task) {
    Entity associatedEntity = BrooklynTaskTags.getTargetOrContextEntity(task);
    if (associatedEntity==null) {
        return false;
    }
    // this is associated to an entity; destroy only if the entity is unmanaged
    return Entities.isManaged(associatedEntity);
}
 
Example 14
Source File: EntityManagerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiscardPremanagedFailsIfManaged() {
    try {
        ((EntityManagerInternal)entityManager).discardPremanaged(app);
        Asserts.shouldHaveFailedPreviously();
    } catch (IllegalStateException e) {
        Asserts.expectedFailureContains(e, "Cannot discard", "it or a descendent is already managed");
    }
    
    // Should have had no effect
    Entities.isManaged(app);
}
 
Example 15
Source File: DynamicClusterImpl.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected void doStart() {
    if (isQuarantineEnabled()) {
        QuarantineGroup quarantineGroup = getAttribute(QUARANTINE_GROUP);
        if (quarantineGroup==null || !Entities.isManaged(quarantineGroup)) {
            quarantineGroup = addChild(EntitySpec.create(QuarantineGroup.class).displayName("quarantine"));
            sensors().set(QUARANTINE_GROUP, quarantineGroup);
        }
    }

    int initialSize = getConfig(INITIAL_SIZE).intValue();
    int initialQuorumSize = getInitialQuorumSize();
    Exception internalError = null;

    try {
        resize(initialSize);
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        // Apart from logging, ignore problems here; we extract them below.
        // But if it was this thread that threw the exception (rather than a sub-task), then need
        // to record that failure here.
        LOG.debug("Error resizing "+this+" to size "+initialSize+" (collecting and handling): "+e, e);
        internalError = e;
    }

    Iterable<Task<?>> failed = Tasks.failed(Tasks.children(Tasks.current()));
    boolean noFailed = Iterables.isEmpty(failed);
    boolean severalFailed = Iterables.size(failed) > 1;

    int currentSize = getCurrentSize().intValue();
    if (currentSize < initialQuorumSize) {
        String message;
        if (currentSize == 0 && !noFailed) {
            if (severalFailed)
                message = "All nodes in cluster "+this+" failed";
            else
                message = "Node in cluster "+this+" failed";
        } else {
            message = "On start of cluster " + this + ", failed to get to initial size of " + initialSize
                + "; size is " + getCurrentSize()
                + (initialQuorumSize != initialSize ? " (initial quorum size is " + initialQuorumSize + ")" : "");
        }
        Throwable firstError = Tasks.getError(Maybe.next(failed.iterator()).orNull());
        if (firstError==null && internalError!=null) {
            // only use the internal error if there were no nested task failures
            // (otherwise the internal error should be a wrapper around the nested failures)
            firstError = internalError;
        }
        if (firstError!=null) {
            if (severalFailed) {
                message += "; first failure is: "+Exceptions.collapseText(firstError);
            } else {
                message += ": "+Exceptions.collapseText(firstError);
            }
        }
        throw new IllegalStateException(message, firstError);
        
    } else if (currentSize < initialSize) {
        LOG.warn(
                "On start of cluster {}, size {} reached initial minimum quorum size of {} but did not reach desired size {}; continuing",
                new Object[] { this, currentSize, initialQuorumSize, initialSize });
    }

    for (Policy it : policies()) {
        it.resume();
    }
}
 
Example 16
Source File: GroupPickUpEntitiesTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected boolean checkMembership(Entity e) {
    if (!Entities.isManaged(e)) return false;
    if (!Boxing.unboxSafely(e.getAttribute(Startable.SERVICE_UP), false)) return false;
    return true;
}