subscription = entity.subscriptions().subscribe(source, sensor, new SensorEventListener<T>() { @Override public void onEvent(SensorEvent<T> event) { synchronized (publishedValues) { publishedValues.add(event.getValue()); } }}); for (final AttributeAndSensorCondition abortCondition : abortSensorConditions) { abortSubscriptions.add(entity.subscriptions().subscribe(abortCondition.source, abortCondition.sensor, new SensorEventListener<Object>() { @Override public void onEvent(SensorEvent<Object> event) { if (abortCondition.predicate.apply(event.getValue())) { } finally { if (subscription != null) { entity.subscriptions().unsubscribe(subscription); entity.subscriptions().unsubscribe(handle);
.configure(BlockingEntity.STARTUP_DELAY, STARTUP_TIME))); cluster.subscriptions().subscribe(cluster, AbstractEntity.CHILD_ADDED, new SensorEventListener<Entity>() { @Override public void onEvent(SensorEvent<Entity> event) { if (event.getValue() instanceof BlockingEntity) {
events, WebAppServiceMetrics.REQUEST_COUNT, requestCountAfterKilled, consecutiveEvents, maxIntervalBetweenEvents)); } finally { if (subscriptionHandle != null) entity.subscriptions().unsubscribe(subscriptionHandle); entity.stop();
final List<String> strings = new CopyOnWriteArrayList<String>(); entity.subscriptions().subscribe(entity, SENSOR_INT, new SensorEventListener<Integer>() { @Override public void onEvent(SensorEvent<Integer> event) { ints.add(event.getValue()); }}); entity.subscriptions().subscribe(entity, SENSOR_STRING, new SensorEventListener<String>() { @Override public void onEvent(SensorEvent<String> event) { strings.add(event.getValue());
tmpApp.subscriptions().subscribe(null, mySensor, listener);
@Test public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception { final List<Entity> creationOrder = Lists.newArrayList(); DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class) .configure("initialSize", 0) .configure("memberSpec", EntitySpec.create(TestEntity.class))); cluster.subscriptions().subscribe(cluster, AbstractEntity.CHILD_ADDED, new SensorEventListener<Entity>() { @Override public void onEvent(SensorEvent<Entity> event) { if (event.getValue() instanceof TestEntity) { creationOrder.add(event.getValue()); } }}); cluster.start(ImmutableList.of(loc)); cluster.resize(1); //Prevent the two entities created in the same ms //so that the removal strategy can always choose the //entity created next Thread.sleep(1); cluster.resize(2); Asserts.eventually(Suppliers.ofInstance(creationOrder), CollectionFunctionals.sizeEquals(2)); assertEquals(cluster.getCurrentSize(), (Integer)2); assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers()); // Now stop one cluster.resize(1); assertEquals(cluster.getCurrentSize(), (Integer)1); assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1)); }
/** * Asserts that the entity's value for this attribute changes, by registering a subscription and checking the value. * * @param entity The entity whose attribute will be checked. * @param attribute The attribute to check on the entity. * * @throws AssertionError if the assertion fails. */ public static void assertAttributeChangesEventually(final Entity entity, final AttributeSensor<?> attribute) { final Object origValue = entity.getAttribute(attribute); final AtomicBoolean changed = new AtomicBoolean(); SubscriptionHandle handle = entity.subscriptions().subscribe(entity, attribute, new SensorEventListener<Object>() { @Override public void onEvent(SensorEvent<Object> event) { if (!Objects.equal(origValue, event.getValue())) { changed.set(true); } }}); try { Asserts.succeedsEventually(new Runnable() { @Override public void run() { Asserts.assertTrue(changed.get(), entity + " -> " + attribute + " not changed from "+origValue); }}); } finally { entity.subscriptions().unsubscribe(entity, handle); } }
@Test(groups="Integration") @SuppressWarnings("deprecation") public void testHttpSensorSuppressingDuplicates() throws Exception { RecordingSensorEventListener<String> listener = new RecordingSensorEventListener<>(); entity.subscriptions().subscribe(entity, SENSOR_STRING, listener); HttpRequestSensor<Integer> sensor = new HttpRequestSensor<Integer>(ConfigBag.newInstance() .configure(HttpRequestSensor.SUPPRESS_DUPLICATES, true) .configure(HttpRequestSensor.SENSOR_PERIOD, Duration.millis(1)) .configure(HttpRequestSensor.SENSOR_NAME, SENSOR_STRING.getName()) .configure(HttpRequestSensor.SENSOR_TYPE, STRING_TARGET_TYPE) .configure(HttpRequestSensor.JSON_PATH, "$.myKey") .configure(HttpRequestSensor.SENSOR_URI, serverUrl + "/myKey/myValue")); sensor.apply((org.apache.brooklyn.api.entity.EntityLocal)entity); entity.sensors().set(Attributes.SERVICE_UP, true); EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_STRING, "myValue"); listener.assertHasEventEventually(Predicates.alwaysTrue()); Asserts.succeedsContinually(new Runnable() { @Override public void run() { listener.assertEventCount(1); }}); }
@Test(dataProvider = "errorPhase", groups = "Integration") public void testEntityOnFireAfterRestartingWhenLaunchCommandFails(ConfigKey<String> key) { VanillaSoftwareProcess entity = app.createAndManageChild(EntitySpec.create(VanillaSoftwareProcess.class) .configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true") .configure(VanillaSoftwareProcess.CHECK_RUNNING_COMMAND, "true") .configure(key, "exit 1")); try { app.start(ImmutableList.of(app.newLocalhostProvisioningLocation())); Asserts.shouldHaveFailedPreviously("entity has launch command that does not complete successfully"); } catch (Exception e) { // expected } LastTwoServiceStatesListener listener = new LastTwoServiceStatesListener(); entity.subscriptions().subscribe(entity, Attributes.SERVICE_STATE_ACTUAL, listener); EntityAsserts.assertAttributeEquals(entity, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE); entity.invoke(Startable.RESTART, ImmutableMap.<String, Object>of( SoftwareProcess.RestartSoftwareParameters.RESTART_CHILDREN.getName(), false, SoftwareProcess.RestartSoftwareParameters.RESTART_MACHINE.getName(), false)); List<Lifecycle> expected = ImmutableList.of(Lifecycle.STARTING, Lifecycle.ON_FIRE); Asserts.eventually(listener, Predicates.equalTo(expected)); }
/** * Tests that we get consecutive events with zero workrate, and with suitably small timestamps between them. */ @Test(groups = "Integration", dataProvider = "basicEntities") @SuppressWarnings("rawtypes") public void publishesZeroRequestsPerSecondMetricRepeatedly(final SoftwareProcess entity) { this.entity = entity; log.info("test=publishesZeroRequestsPerSecondMetricRepeatedly; entity="+entity+"; app="+entity.getApplication()); final int maxIntervalBetweenEvents = 4000; // TomcatServerImpl publishes events every 3000ms so this should be enough overhead final int consecutiveEvents = 3; Entities.start(entity.getApplication(), ImmutableList.of(loc)); SubscriptionHandle subscriptionHandle = null; final CopyOnWriteArrayList<SensorEvent<Double>> events = new CopyOnWriteArrayList<>(); try { subscriptionHandle = recordEvents(entity, WebAppService.REQUESTS_PER_SECOND_IN_WINDOW, events); Asserts.succeedsEventually(assertConsecutiveSensorEventsEqual( events, WebAppService.REQUESTS_PER_SECOND_IN_WINDOW, 0.0d, consecutiveEvents, maxIntervalBetweenEvents)); } finally { if (subscriptionHandle != null) entity.subscriptions().unsubscribe(subscriptionHandle); entity.stop(); } }
@Test public void testAppStoppedWhenDurationExpires() { // Using a second app for the subscriber. Otherwise when app is stopped+unmanaged, we might not // receive the last event because all its subscriptions will be closed! final RecordingSensorEventListener<Lifecycle> listener = new RecordingSensorEventListener<>(); Application app2 = mgmt.getEntityManager().createEntity(EntitySpec.create(BasicApplication.class)); app2.subscriptions().subscribe(app, Attributes.SERVICE_STATE_ACTUAL, listener); PolicySpec<StopAfterDurationPolicy> policy = PolicySpec.create(StopAfterDurationPolicy.class) .configure(StopAfterDurationPolicy.LIFETIME, Duration.ONE_MILLISECOND) .configure(StopAfterDurationPolicy.POLL_PERIOD, Duration.ONE_MILLISECOND); app.policies().add(policy); app.start(ImmutableList.of(app.newSimulatedLocation())); Asserts.succeedsEventually(new Runnable() { @Override public void run() { // TODO In tests, have seen duplicate "starting"; and always begins with "stopped"; and have // seen "on-fire" between stopping and stopped! Therefore not using // assertEqualsOrderIgnoringDuplicates. List<Lifecycle> states = ImmutableList.copyOf(listener.getEventValues()); assertContainsOrdered(states, ImmutableList.of(Lifecycle.RUNNING, Lifecycle.STOPPING, Lifecycle.STOPPED)); }}); }
protected <T> void subscribe(Map<String, ?> flags, Entity entity, Sensor<T> attribute, SensorEventListener<? super T> listener) { adjunctEntity.subscriptions().subscribe(flags, entity, attribute, listener); }
protected <T> void subscribe(Entity entity, Sensor<T> attribute, SensorEventListener<? super T> listener) { adjunctEntity.subscriptions().subscribe(entity, attribute, listener); }
@Override public void setEntity(EntityLocal entity) { super.setEntity(entity); entity.subscriptions().subscribe(remoteEntity, remoteSensor, listenerFromValueClosure(code)); } };
@Override public void setEntity(EntityLocal entity) { super.setEntity(entity); entity.subscriptions().subscribe(entity, sensor, listenerFromValueClosure(code)); } };
protected <T> SubscriptionHandle recordEvents(Entity entity, AttributeSensor<T> sensor, final List<SensorEvent<T>> events) { SensorEventListener<T> listener = new SensorEventListener<T>() { @Override public void onEvent(SensorEvent<T> event) { log.info("onEvent: {}", event); events.add(event); } }; return entity.subscriptions().subscribe(entity, sensor, listener); }
protected static RecordingSensorEventListener<Object> subscribeToHaSensors(Entity entity) { RecordingSensorEventListener<Object> listener = new RecordingSensorEventListener<>(); entity.subscriptions().subscribe(entity, HASensors.ENTITY_RECOVERED, listener); entity.subscriptions().subscribe(entity, HASensors.ENTITY_FAILED, listener); return listener; } }
@Override public void setEntity(final EntityLocal entity) { super.setEntity(entity); entity.subscriptions().subscribe(entity, Attributes.SERVICE_STATE_ACTUAL, new LifecycleListener()); entity.subscriptions().subscribe(entity, Sensors.newSensor(Duration.class, getSensorName()), new TimeIsUpListener()); }