Java Code Examples for org.apache.brooklyn.api.sensor.SensorEvent#getSource()

The following examples show how to use org.apache.brooklyn.api.sensor.SensorEvent#getSource() . 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: FollowTheSunPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    if (LOG.isTraceEnabled()) LOG.trace("{} received event {}", FollowTheSunPolicy.this, event);
    Entity source = event.getSource();
    Object value = event.getValue();
    Sensor<?> sensor = event.getSensor();
    
    if (sensor.equals(itemUsageMetric)) {
        onItemMetricUpdated((Movable)source, (Map<? extends Movable, Double>) value, true);
    } else if (sensor.equals(Attributes.LOCATION_CHANGED)) {
        onContainerLocationUpdated(source, true);
    } else if (sensor.equals(FollowTheSunPool.CONTAINER_ADDED)) {
        onContainerAdded((Entity) value, true);
    } else if (sensor.equals(FollowTheSunPool.CONTAINER_REMOVED)) {
        onContainerRemoved((Entity) value, true);
    } else if (sensor.equals(FollowTheSunPool.ITEM_ADDED)) {
        onItemAdded((Movable) value, true);
    } else if (sensor.equals(FollowTheSunPool.ITEM_REMOVED)) {
        onItemRemoved((Movable) value, true);
    } else if (sensor.equals(FollowTheSunPool.ITEM_MOVED)) {
        ContainerItemPair pair = (ContainerItemPair) value;
        onItemMoved((Movable)pair.item, pair.container, true);
    }
}
 
Example 2
Source File: ItemsInContainersGroupImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    Entity source = event.getSource();
    Object value = event.getValue();
    Sensor sensor = event.getSensor();
    
    if (sensor.equals(AbstractGroup.MEMBER_ADDED)) {
        onContainerAdded((Entity) value);
    } else if (sensor.equals(AbstractGroup.MEMBER_REMOVED)) {
        onContainerRemoved((Entity) value);
    } else if (sensor.equals(Movable.CONTAINER)) {
        onItemMoved((Movable)source, (BalanceableContainer<?>) value);
    } else {
        throw new IllegalStateException("Unhandled event type "+sensor+": "+event);
    }
}
 
Example 3
Source File: MySqlClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Boolean> event) {
    final MySqlNode node = (MySqlNode) event.getSource();
    if (Boolean.TRUE.equals(event.getValue()) &&
            // We are interested in SERVICE_PROCESS_IS_RUNNING only while haven't come online yet.
            // Probably will get several updates while replication is initialized so an additional
            // check is needed whether we have already seen this.
            Boolean.FALSE.equals(node.getAttribute(MySqlNode.SERVICE_UP)) &&
            !Boolean.TRUE.equals(node.getAttribute(NODE_REPLICATION_INITIALIZED))) {

        // Events executed sequentially so no need to synchronize here.
        node.sensors().set(NODE_REPLICATION_INITIALIZED, Boolean.TRUE);

        final Runnable nodeInitTaskBody;
        if (MySqlClusterUtils.IS_MASTER.apply(node)) {
            nodeInitTaskBody = new InitMasterTaskBody(cluster, node);
        } else {
            nodeInitTaskBody = new InitSlaveTaskBody(cluster, node, lock);
        }

        DynamicTasks.submitTopLevelTask(TaskBuilder.builder()
                .displayName("setup master-slave replication")
                .body(nodeInitTaskBody)
                .tag(BrooklynTaskTags.NON_TRANSIENT_TASK_TAG)
                .build(),
                node);
    }
}
 
Example 4
Source File: MySqlClusterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Entity> event) {
    MySqlCluster cluster = (MySqlCluster) event.getSource();
    Entity node = event.getValue();
    String slaveAddress = cluster.getAttribute(SLAVE_ID_ADDRESS_MAPPING).remove(node.getId());
    if (slaveAddress != null) {
        // Could already be gone if stopping the entire app - let it throw an exception
        MySqlNode master = (MySqlNode) Iterables.find(cluster.getMembers(), MySqlClusterUtils.IS_MASTER);
        String username = MySqlClusterUtils.validateSqlParam(cluster.getConfig(SLAVE_USERNAME));
        MySqlClusterUtils.executeSqlOnNodeAsync(master, String.format("DROP USER '%s'@'%s';", username, slaveAddress));
    }
}
 
Example 5
Source File: CreateUserPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Location> event) {
    final Entity entity = event.getSource();
    final Location loc = event.getValue();
    if (loc instanceof SshMachineLocation) {
        addUserAsync(entity, (SshMachineLocation)loc);
    }
}
 
Example 6
Source File: AdvertiseWinrmLoginPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Location> event) {
    final Entity entity = event.getSource();
    final Location loc = event.getValue();
    if (loc instanceof WinRmMachineLocation) {
        advertiseUserAsync(entity, (WinRmMachineLocation)loc);
    }
}
 
Example 7
Source File: FollowTheSunPoolImpl.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 {}", FollowTheSunPoolImpl.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((Entity) 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((Entity) 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(source);
        } else {
            onContainerDown(source);
        }
    } else if (sensor.equals(Movable.CONTAINER)) {
        onItemMoved(source, (Entity) value);
    } else {
        throw new IllegalStateException("Unhandled event type "+sensor+": "+event);
    }
}
 
Example 8
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);
    }
}
 
Example 9
Source File: AbstractMultipleSensorAggregator.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    Entity e = event.getSource();
    if (entityFilter.apply(e)) {
        synchronized (values) {
            Map<Entity,Object> vs = values.get(event.getSensor().getName());
            if (vs==null) {
                LOG.debug(this+" received event when no entry for sensor ("+event+"); likely just added or removed, and will initialize subsequently if needed");
            } else {
                vs.put(e, event.getValue());
            }
        }
        onUpdated();
    }
}
 
Example 10
Source File: Aggregator.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<T> event) {
    Entity e = event.getSource();
    synchronized (values) {
        if (values.containsKey(e)) {
            values.put(e, event.getValue());
        } else {
            if (LOG.isDebugEnabled()) LOG.debug("{} received event for unknown producer ({}); presumably that producer has recently been removed", this, e);
        }
    }
    onUpdated();
}
 
Example 11
Source File: AbstractSubscriptionManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @see SubscriptionManager#subscribe(Map, Entity, Sensor, SensorEventListener) */
@Override
public final  <T> SubscriptionHandle subscribeToChildren(Map<String, Object> flags, final Entity parent, Sensor<T> sensor, SensorEventListener<? super T> listener) {
    Predicate<SensorEvent<T>> eventFilter = new Predicate<SensorEvent<T>>() {
        @Override
        public boolean apply(SensorEvent<T> input) {
            return parent != null && input.getSource() != null && parent.equals(input.getSource().getParent());
        }
    };
    flags.put("eventFilter", eventFilter);
    return subscribe(flags, null, sensor, listener);
}
 
Example 12
Source File: ServiceReplacer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected synchronized void onDetectedFailure(SensorEvent<Object> event) {
    final Entity failedEntity = event.getSource();
    final Object reason = event.getValue();
    String violationText = "Failure detected at "+failedEntity+(reason!=null ? " ("+reason+")" : "");
    
    if (isSuspended()) {
        highlightViolation(violationText+" but policy is suspended");
        LOG.warn("ServiceReplacer suspended, so not acting on failure detected at "+failedEntity+" ("+reason+", child of "+entity+")");
        return;
    }


    Integer failOnNumRecurringFailures = getConfig(FAIL_ON_NUM_RECURRING_FAILURES);
    long failOnRecurringFailuresInThisDuration = getConfig(FAIL_ON_RECURRING_FAILURES_IN_THIS_DURATION);
    long oldestPermitted = currentTimeMillis() - failOnRecurringFailuresInThisDuration;
    // trim old ones
    for (Iterator<Long> iter = consecutiveReplacementFailureTimes.iterator(); iter.hasNext();) {
        Long timestamp = iter.next();
        if (timestamp < oldestPermitted) {
            iter.remove();
        } else {
            break;
        }
    }
    
    if (consecutiveReplacementFailureTimes.size() >= failOnNumRecurringFailures) {
        highlightViolation(violationText+" but too many recent failures detected: "
            + consecutiveReplacementFailureTimes.size()+" in "+failOnRecurringFailuresInThisDuration+" exceeds limit of "+failOnNumRecurringFailures);
        LOG.error("ServiceReplacer not acting on failure detected at "+failedEntity+" ("+reason+", child of "+entity+"), because too many recent replacement failures");
        return;
    }
    
    highlightViolation(violationText+", triggering replacement");
    LOG.warn("ServiceReplacer acting on failure detected at "+failedEntity+" ("+reason+", child of "+entity+")");
    Task<?> t = getExecutionContext().submit("Replace member on failure", () -> {
            try {
                Entities.invokeEffectorWithArgs(entity, entity, MemberReplaceable.REPLACE_MEMBER, failedEntity.getId()).get();
                consecutiveReplacementFailureTimes.clear();
            } catch (Exception e) {
                if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) != null) {
                    LOG.info("ServiceReplacer: ignoring error reported from stopping failed node "+failedEntity);
                    return;
                }
                highlightViolation(violationText+" and replace attempt failed: "+Exceptions.collapseText(e));
                onReplacementFailed("Replace failure ("+Exceptions.collapseText(e)+") at "+entity+": "+reason);
            }
        });
    highlightAction("Replacing "+failedEntity, t);
}
 
Example 13
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();
    }
}