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

The following examples show how to use org.apache.brooklyn.core.entity.Entities#isNoLongerManaged() . 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: ElectPrimaryEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public Object call() throws Exception {
    String demoteEffectorName = params.get(DEMOTE_EFFECTOR_NAME);
    Effector<?> eff = entity().getEffector(demoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(entity(), eff, params) ).asTask().getUnchecked();
    }
    EntityInternal oldPrimary = (EntityInternal)params.getStringKey("oldPrimary");
    if (oldPrimary==null) return "Nothing to demote; no old primary";
    if (Entities.isNoLongerManaged(oldPrimary)) return "Entity to demote is gone";
    // could bail out if stopping or stopped; demotion may take a while
    // but demotion might simply be setting metadata.
    // ideally the "isRunning" check would take place within old.demote
    // (but that's currently not easy in yaml)
    eff = oldPrimary.getEffector(demoteEffectorName);
    if (eff!=null) {
        return DynamicTasks.queue( Effectors.invocation(oldPrimary, eff, params) ).asTask().getUnchecked();
    }
    if (params.containsKey(DEMOTE_EFFECTOR_NAME)) {
        throw new IllegalStateException("Key "+DEMOTE_EFFECTOR_NAME.getName()+" set as "+demoteEffectorName+
            " but that effector isn't available on this entity or old primary "+oldPrimary);
    }
    return "No demotion effector '"+demoteEffectorName+"'; nothing to do";
}
 
Example 2
Source File: AttributePollHandler.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void setSensor(Object v) {
    if (Entities.isNoLongerManaged(entity)) {
        if (Tasks.isInterrupted()) return;
        log.warn(""+entity+" is not managed; feed "+this+" setting "+sensor+" to "+v+" at this time is not supported ("+Tasks.current()+")");
    }
    
    if (v == FeedConfig.UNCHANGED) {
        // nothing
    } else if (v == FeedConfig.REMOVE) {
        ((EntityInternal)entity).sensors().remove(sensor);
        feed.onRemoveSensor(sensor);
    } else if (sensor == FeedConfig.NO_SENSOR) {
        // nothing
    } else {
        Object coercedV = TypeCoercions.coerce(v, sensor.getType());
        if (suppressDuplicates && Objects.equal(coercedV, entity.getAttribute(sensor))) {
            // no change; nothing
        } else {
            entity.sensors().set(sensor, coercedV);
            feed.onPublishSensor(sensor, coercedV);
        }
    }
}
 
Example 3
Source File: SshCommandEffector.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public String callMany(Collection<Entity> targets, ConfigBag params) {
    TaskBuilder<Object> ptb = Tasks.builder().parallel(true).displayName("effector "+effector.getName()+" ssh to targets");
    for (Entity target: targets) {
        if (Entities.isNoLongerManaged(target)) continue;
        
        Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
        if (state==Lifecycle.STOPPING || state==Lifecycle.STOPPED) continue;

        Maybe<SshMachineLocation> machine = Locations.findUniqueSshMachineLocation(target.getLocations());
        if (machine.isAbsent()) continue;
        
        SshEffectorTaskFactory<String> t = makePartialTaskFactory(params, target);
        t.summary("effector "+effector.getName()+" at "+target); 
        t.machine( machine.get() );
        
        ptb.add(t.newTask());
    }
    queue(ptb.build()).getUnchecked();
    return null;
}
 
Example 4
Source File: ElectPrimaryPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void rescanImpl() throws InterruptedException {
    String contextString;
    synchronized (rescanTriggers) {
        while (rescanInProgress) {
            Tasks.setBlockingDetails("Waiting for ongoing scan to complete");
            rescanTriggers.wait();
            Tasks.resetBlockingDetails();
        }
        if (rescanTriggers.isEmpty()) {
            if (log.isTraceEnabled()) {
                log.trace("Policy "+this+" scheduled rescan unnecessary, trigger already handled");
            }
            return;
        }
        contextString = Strings.join(rescanTriggers, ", ");
        rescanTriggers.clear();
        rescanInProgress = true;
    }
    String code = null;
    try {
        String effName = config().get(EFFECTOR_NAME);
        if (log.isTraceEnabled()) {
            log.trace("Policy "+this+" got event: "+contextString+"; triggering rescan with "+effName);
        }
        Task<?> task = Effectors.invocation(entity, Preconditions.checkNotNull( ((EntityInternal)entity).getEffector(effName) ), config().getBag()).asTask();
        BrooklynTaskTags.addTagDynamically(task, BrooklynTaskTags.NON_TRANSIENT_TASK_TAG);
        
        highlight("lastScan", "Running "+effName+" on "+contextString, task);
        
        Object result = DynamicTasks.get(task);
        if (result instanceof Map) code = Strings.toString( ((Map<?,?>)result).get("code") );
        
        if (ElectPrimaryEffector.ResultCode.NEW_PRIMARY_ELECTED.name().equalsIgnoreCase(code)) {
            highlightAction("New primary elected: "+((Map<?,?>)result).get("primary"), null);
        }
        if (ElectPrimaryEffector.ResultCode.NO_PRIMARY_AVAILABLE.name().equalsIgnoreCase(code)) {
            highlightViolation("No primary available");
        }
    } catch (Throwable e) {
        Exceptions.propagateIfFatal(e);
        if (Entities.isNoLongerManaged(entity)) throw Exceptions.propagate(e);
        
        Throwable root = Throwables.getRootCause(e);
        if (root instanceof UserFacingException) {
            // prefer user-facing root cause to history; mainly for SelectionModeStrictFailed.
            // possibly not right if it's another (eg exposition on why promote failed)
            e = root;
        }
        if (e instanceof UserFacingException) {
            log.warn("Error running policy "+this+" on "+entity+": "+Exceptions.collapseText(e));
        } else {
            log.warn("Error running policy "+this+" on "+entity+": "+Exceptions.collapseText(e), e);
        }
    }
    
    synchronized (rescanTriggers) {
        rescanTriggers.notifyAll();
        rescanInProgress = false;
    }
}
 
Example 5
Source File: SshCommandMembershipTrackingPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void execute(Entity target, String command, String type, String memberId, boolean highlight) {
    if (Entities.isNoLongerManaged(target)) return;
    Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (state==Lifecycle.STOPPING || state==Lifecycle.STOPPED) return;
    
    Collection<? extends Location> locations = Locations.getLocationsCheckingAncestors(target.getLocations(), target);
    Maybe<SshMachineLocation> machine = Machines.findUniqueMachineLocation(locations, SshMachineLocation.class);
    if (machine.isAbsentOrNull()) {
        LOG.debug("No machine available to execute command");
        return;
    }

    LOG.info("Executing command on {}: {}", machine.get(), command);
    String executionDir = config().get(EXECUTION_DIR);
    String sshCommand = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir, target);

    // Set things from the entities defined shell environment, overriding with our config
    Map<String, Object> env = MutableMap.of();
    env.putAll(MutableMap.copyOf(entity.config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));
    env.putAll(MutableMap.copyOf(config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));

    // Add variables describing this invocation
    env.put(EVENT_TYPE, type);
    env.put(MEMBER_ID, memberId);

    // Try to resolve the configuration in the env Map
    try {
        env = (Map<String, Object>) Tasks.resolveDeepValue(env, Object.class, getExecutionContext());
    } catch (InterruptedException | ExecutionException e) {
        throw Exceptions.propagate(e);
    }

    // Execute the command with the serialized environment strings
    ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(getManagementContext());
    SshEffectorTasks.SshEffectorTaskFactory<String> task = SshEffectorTasks.ssh(sshCommand)
            .machine(machine.get())
            .requiringZeroAndReturningStdout()
            .summary("group-" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, type))
            .environmentVariables(serializer.serialize(env));

    Task<String> taskI = DynamicTasks.submit(task.newTask(), target);
    if (highlight) {
        highlightAction("Run at "+machine.get().getAddress().getHostAddress(), taskI);
    }
    String output = taskI.getUnchecked();
    LOG.trace("Command returned: {}", output);
}
 
Example 6
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** update the given key in the given map sensor */
public static <TKey,TVal> void updateMapSensorEntry(Entity entity, AttributeSensor<Map<TKey,TVal>> sensor, final TKey key, final TVal v) {
    /*
     * Important to *not* modify the existing attribute value; must make a copy, modify that, and publish.
     * This is because a Propagator enricher will set this same value on another entity. There was very
     * strange behaviour when this was done for a SERVICE_UP_INDICATORS sensor - the updates done here
     * applied to the attribute of both entities!
     *
     * Need to do this update atomically (i.e. sequentially) because there is no threading control for
     * what is calling updateMapSensorEntity. It is called directly on start, on initialising enrichers,
     * and in event listeners. These calls could be concurrent.
     */
    Function<Map<TKey,TVal>, Maybe<Map<TKey,TVal>>> modifier = new Function<Map<TKey,TVal>, Maybe<Map<TKey,TVal>>>() {
        @Override public Maybe<Map<TKey, TVal>> apply(Map<TKey, TVal> map) {
            boolean created = (map==null);
            if (created) map = MutableMap.of();

            boolean changed;
            if (v == Entities.REMOVE) {
                changed = map.containsKey(key);
                if (changed) {
                    map = MutableMap.copyOf(map);
                    map.remove(key);
                }
            } else {
                TVal oldV = map.get(key);
                if (oldV==null) {
                    changed = (v!=null || !map.containsKey(key));
                } else {
                    changed = !oldV.equals(v);
                }
                if (changed) {
                    map = MutableMap.copyOf(map);
                    map.put(key, v);
                }
            }
            if (changed || created) {
                return Maybe.of(map);
            } else {
                return Maybe.absent();
            }
        }
    };

    if (!Entities.isNoLongerManaged(entity)) {
        entity.sensors().modify(sensor, modifier);
    }
}
 
Example 7
Source File: LocalEntityManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * Should ensure that the entity is no longer managed anywhere, remove from all lists.
 * Returns true if the entity has been removed from management; if it was not previously managed (anything else throws exception) 
 */
private boolean unmanageNonRecursive(Entity e) {
    /*
     * When method is synchronized, hit deadlock: 
     * 1. thread called unmanage() on a member of a group, so we got the lock and called group.removeMember;
     *    this ties to synchronize on AbstractGroupImpl.members 
     * 2. another thread was doing AbstractGroupImpl.addMember, which is synchronized on AbstractGroupImpl.members;
     *    it tries to call Entities.manage(child) which calls LocalEntityManager.getEntity(), which is
     *    synchronized on this.
     * 
     * We MUST NOT call alien code from within the management framework while holding locks. 
     * The AbstractGroup.removeMember is effectively alien because a user could override it, and because
     * it is entity specific.
     * 
     * TODO Does getting then removing from groups risk this entity being added to other groups while 
     * this is happening? Should abstractEntity.onManagementStopped or some such remove the entity
     * from its groups?
     */
    
    if (!getLastManagementTransitionMode(e.getId()).isReadOnly()) {
        e.clearParent();
        for (Group group : e.groups()) {
            if (!Entities.isNoLongerManaged(group)) group.removeMember(e);
        }
        if (e instanceof Group) {
            Collection<Entity> members = ((Group)e).getMembers();
            for (Entity member : members) {
                if (!Entities.isNoLongerManaged(member)) ((EntityInternal)member).groups().remove((Group)e);
            }
        }
    } else {
        log.debug("No relations being updated on unmanage of read only {}", e);
    }

    unmanageOwnedLocations(e);

    synchronized (this) {
        Entity proxyE = toProxyEntityIfAvailable(e);
        if (e instanceof Application) {
            applications.remove(proxyE);
            applicationIds.remove(e.getId());
        }

        entities.remove(proxyE);
        entityProxiesById.remove(e.getId());
        entityModesById.remove(e.getId());
        
        Object old = entitiesById.remove(e.getId());

        entityTypes.remove(e.getId());
        if (old==null) {
            log.warn("{} call to stop management of unknown entity (already unmanaged?) {}; ignoring", this, e);
            return false;
        } else if (!old.equals(e)) {
            // shouldn't happen...
            log.error("{} call to stop management of entity {} removed different entity {}", new Object[] { this, e, old });
            return true;
        } else {
            if (log.isDebugEnabled()) log.debug("{} stopped management of entity {}", this, e);
            return true;
        }
    }
}
 
Example 8
Source File: LocalSubscriptionManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void submitPublishEvent(final Subscription s, final SensorEvent<?> event, final boolean isInitialPublicationOfOldValueInCorrectScheduledThread) {
    if (s.eventFilter!=null && !s.eventFilter.apply(event))
        return;
    
    List<Object> tags = getPublishTags(s, event.getSource()).asUnmodifiable();
    
    StringBuilder name = new StringBuilder("sensor ");
    StringBuilder description = new StringBuilder("Sensor ");
    String sensorName = s.sensor==null ? "<null-sensor>" : s.sensor.getName();
    String sourceName = event.getSource()==null ? null : event.getSource().getId();
    if (Strings.isNonBlank(sourceName)) {
        name.append(sourceName);
        name.append(":");
    }
    name.append(sensorName);
    
    description.append(sensorName);
    description.append(" on ");
    description.append(sourceName==null ? "<null-source>" : sourceName);
    description.append(" publishing to ");
    description.append(s.subscriber instanceof Entity ? ((Entity)s.subscriber).getId() : s.subscriber);
    if (Strings.isNonBlank(s.subscriptionDescription)) {
        description.append(", ");
        description.append(s.subscriptionDescription);
    }
    
    if (includeDescriptionForSensorTask(event)) {
        name.append(" ");
        name.append(event.getValue());
        description.append(", value: ");
        description.append(event.getValue());
    }
    Map<String, Object> execFlags = MutableMap.of("tags", tags, 
        "displayName", name.toString(),
        "description", description.toString());
    
    boolean isEntityStarting = s.subscriber instanceof Entity && isInitialPublicationOfOldValueInCorrectScheduledThread;
    // will have entity (and adjunct) execution context from tags, so can skip getting exec context
    final ExecutionContext ec = BrooklynTaskTags.getExecutionContext(tags);
    Runnable deliverer = new Runnable() {
        @Override
        public String toString() {
            if (isInitialPublicationOfOldValueInCorrectScheduledThread) {
                return "LSM.publishInitial("+event+")";
            } else {
                return "LSM.publish("+event+")";
            }
        }
        @Override
        public void run() {
            BasicExecutionContext oldEC = ec instanceof BasicExecutionContext ? BasicExecutionContext.setPerThreadExecutionContext((BasicExecutionContext)ec) : null;
            try {
                
                if (isEntityStarting) {
                    /* don't let sub deliveries start until this is completed;
                     * this is a pragmatic way to ensure the publish events 
                     * if submitted during management starting, aren't executed
                     * until after management is starting.
                     *   without this we can get deadlocks as this goes to publish,
                     * has the attribute sensors lock, and waits on the publish lock
                     * (any of management support, local subs, queueing subs).
                     * meanwhile the management startup has those three locks,
                     * then goes to publish and in the process looks up a sensor value.
                     *   usually this is not an issue because some other task
                     * does something (eg entity.getExecutionContext()) which
                     * also has a wait-on-management-support semantics.
                     */
                    synchronized (((EntityInternal)s.subscriber).getManagementSupport()) {}
                }
                int count = s.eventCount.incrementAndGet();
                if (count > 0 && count % 1000 == 0) LOG.debug("{} events for subscriber {}", count, s);
                
                s.listener.onEvent(event);
            } catch (Throwable t) {
                Exceptions.propagateIfFatal(t);
                if (event!=null && event.getSource()!=null && Entities.isNoLongerManaged(event.getSource())) {
                    LOG.debug("Error processing subscriptions to "+this+", after entity unmanaged: "+t, t);
                } else {
                    LOG.warn("Error processing subscriptions to "+this+": "+t, t);
                }
            } finally {
                BasicExecutionContext.setPerThreadExecutionContext(oldEC);
            }
        }};
    if (!isInitialPublicationOfOldValueInCorrectScheduledThread) {
        em.submit(execFlags, deliverer);
    } else {
        // for initial, caller guarantees he is running in the right thread/context
        // where the above submission would take place, typically the
        // subscriber single threaded executor with the entity context;
        // this allows caller to do extra assertions and bailout steps at the right time
        deliverer.run();
    }
}
 
Example 9
Source File: AttributePollHandler.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected void logProblem(String type, Object val) {
    if (lastWasProblem && currentProblemLoggedAsWarning) {
        if (log.isTraceEnabled())
            log.trace("Recurring "+type+" reading "+this+" in "+getBriefDescription()+": "+val);
    } else {
        long nowTime = System.currentTimeMillis();
        // get a non-volatile value
        Long currentProblemStartTimeCache = currentProblemStartTime;
        long expiryTime = 
                (lastSuccessTime!=null && !isTransitioningOrStopped()) 
                        ? lastSuccessTime+config.getLogWarningGraceTime().toMilliseconds() 
                        : (currentProblemStartTimeCache != null) 
                                ? currentProblemStartTimeCache+config.getLogWarningGraceTimeOnStartup().toMilliseconds() 
                                : nowTime+config.getLogWarningGraceTimeOnStartup().toMilliseconds();
        if (!lastWasProblem) {
            if (expiryTime <= nowTime) {
                currentProblemLoggedAsWarning = true;
                if (entity==null || !Entities.isNoLongerManaged(entity)) {
                    log.warn("Read of " + getBriefDescription() + " gave " + type + ": " + val);
                } else {
                    log.debug("Read of " + getBriefDescription() + " gave " + type + ": " + val);
                }
                if (log.isDebugEnabled() && val instanceof Throwable)
                    log.debug("Trace for "+type+" reading "+getBriefDescription()+": "+val, (Throwable)val);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Read of " + getBriefDescription() + " gave " + type + " (in grace period): " + val);
            }
            lastWasProblem = true;
            currentProblemStartTime = nowTime;
        } else {
            if (expiryTime <= nowTime) {
                currentProblemLoggedAsWarning = true;
                log.warn("Read of " + getBriefDescription() + " gave " + type + 
                        " (grace period expired, occurring for "+Duration.millis(nowTime - currentProblemStartTimeCache)+
                        (config.hasExceptionHandler() ? "" : ", no exception handler set for sensor")+
                        ")"+
                        ": " + val);
                if (log.isDebugEnabled() && val instanceof Throwable)
                    log.debug("Trace for "+type+" reading "+getBriefDescription()+": "+val, (Throwable)val);
            } else {
                if (log.isDebugEnabled()) 
                    log.debug("Recurring {} reading {} in {} (still in grace period): {}", new Object[] {type, this, getBriefDescription(), val});
            }
        }
    }
}