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

The following examples show how to use org.apache.brooklyn.api.sensor.SensorEvent#getValue() . 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: DynamicClusterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** This can be sensitive to order, e.g. if TestEntity set expected RUNNING before setting SERVICE_UP, 
 * there would be a point when TestEntity is ON_FIRE.
 * <p>
 * There can also be issues if a cluster is resizing from/to 0 while in a RUNNING state.
 * To correct that, use {@link ServiceStateLogic#newEnricherFromChildrenUp()}.
 */
@Test
public void testResizeFromZeroToOneDoesNotGoThroughFailing() throws Exception {
    final DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
        .configure(DynamicCluster.MEMBER_SPEC, EntitySpec.create(TestEntity.class))
        .configure(DynamicCluster.INITIAL_SIZE, 1));
    
    RecordingSensorEventListener<Lifecycle> r = new RecordingSensorEventListener<>();
    app.subscriptions().subscribe(cluster, Attributes.SERVICE_STATE_ACTUAL, r);

    cluster.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(cluster, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING);
    for (SensorEvent<Lifecycle> evt: r.getEvents()) {
        if (evt.getValue()==Lifecycle.ON_FIRE)
            Assert.fail("Should not have published " + Lifecycle.ON_FIRE + " during normal start up: " + r.getEvents());
    }
}
 
Example 2
Source File: ScheduledEffectorPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(SensorEvent<Object> event) {
    super.onEvent(event);

    if (running.get()) {
        if (event.getSensor().getName().equals(INVOKE_AT.getName())) {
            String time = (String) event.getValue();
            if (time != null) {
                schedule(getWaitUntil(time));
            }
        }
        if (event.getSensor().getName().equals(INVOKE_IMMEDIATELY.getName())) {
            Boolean invoke = Boolean.TRUE.equals(event.getValue());
            if (invoke) {
                schedule(Duration.ZERO);
            }
        }
    }
}
 
Example 3
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 4
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 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: RecordingSensorEventListener.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<T> event) {
    if (!suppressDuplicates || events.isEmpty() || !Objects.equals(lastValue, event.getValue())) {
        events.add(event);
        tasks.add(Tasks.current());
        lastValue = event.getValue();
    }
}
 
Example 7
Source File: LocalSubscriptionManager.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected boolean includeDescriptionForSensorTask(SensorEvent<?> event) {
    // just do it for simple/quick things to avoid expensive toStrings
    // (info is rarely useful, but occasionally it will be)
    if (event.getValue()==null) return true;
    Class<?> clazz = event.getValue().getClass();
    if (clazz.isEnum() || clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || 
        clazz.equals(String.class)) return true;
    return false;
}
 
Example 8
Source File: YamlRollingTimeWindowMeanEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected Function<SensorEvent<T>, Double> getTransformation() {
    return new Function<SensorEvent<T>, Double>() {
        @Override
        public Double apply(SensorEvent<T> event) {
            long eventTime = event.getTimestamp();
            if (event.getValue()==null) {
                return null;
            }
            values.addLast(event.getValue());
            timestamps.addLast(eventTime);
            if (eventTime>0) {
                ConfidenceQualifiedNumber average = getAverage(eventTime, 0);

                if (average.confidence > getConfig(CONFIDENCE_REQUIRED_TO_PUBLISH)) { 
                    // without confidence, we might publish wildly varying estimates,
                    // causing spurious resizes, so allow it to be configured, and
                    // by default require a high value

                    // TODO would be nice to include timestamp, etc
                    return average.value; 
                }
            }
            return null;
        }
    };
}
 
Example 9
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 10
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 11
Source File: TimeFractionDeltaEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void onEvent(SensorEvent<T> event, long eventTimestamp) {
    Number current = event.getValue();
    
    if (current == null) {
        // Can't compute a delta; 
        // don't assume current=zero because then things like requestCount->requestsPerSecond is negative!
        // instead don't publish anything
        if (LOG.isTraceEnabled()) LOG.trace("ignoring null value in {}, at {}", new Object[] {this, eventTimestamp});
        return;
    }
    
    if (eventTimestamp > lastTimestamp) {
        if (lastValue == null) {
            // cannot calculate delta with a single value
            if (LOG.isTraceEnabled()) LOG.trace("{} received event but no last value so will not emit, null -> {} at {}", 
                    new Object[] {this, current, eventTimestamp}); 
        } else if (lastTimestamp < 0) {
            LOG.warn("{} has lastValue {} but last timestamp {}; new value is {} at {}; not publishing", 
                    new Object[] {this, lastValue, lastTimestamp, current, eventTimestamp});
        } else {
            long duration = eventTimestamp - lastTimestamp;
            double fraction = toNanos(current.doubleValue() - lastValue.doubleValue(), durationPerOrigUnit.nanos()) / TimeUnit.MILLISECONDS.toNanos(duration);
            entity.sensors().set((AttributeSensor<Double>)target, fraction);
            if (LOG.isTraceEnabled()) LOG.trace("set {} to {}, {} -> {} at {} (previous at {})", 
                    new Object[] {this, fraction, lastValue, current, eventTimestamp, lastTimestamp}); 
        }
        lastValue = current;
        lastTimestamp = eventTimestamp;
    }
}
 
Example 12
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 13
Source File: SoftwareProcessRestartIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Lifecycle> event) {
    synchronized (events) {
        events[0] = events[1];
        events[1] = event.getValue();
    }
}
 
Example 14
Source File: EntityLaunchListener.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(SensorEvent<Lifecycle> event) {
    if (event.getValue() == Lifecycle.RUNNING) {
        Task<?>launchTask = getLatestLaunchTask(enricher.getEntity());
        if (launchTask != null) {
            launchTaskRef.set(launchTask);
            if (!launchTask.isDone()) {
                launchTask.addListener(this, enricher.getEntityExecutionContext());
            }
            if (launchTask.isDone()) {
                run();
            }
        }
    }
}
 
Example 15
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 16
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 17
Source File: RecordingSensorEventListener.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public T apply(SensorEvent<T> input) {
    return input.getValue();
}