org.apache.brooklyn.api.entity.EntityLocal Java Examples

The following examples show how to use org.apache.brooklyn.api.entity.EntityLocal. 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: RebindExceptionHandlerImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onAddEnricherFailed(EntityLocal entity, Enricher enricher, Exception e) {
    Exceptions.propagateIfFatal(e);
    String errmsg = "problem adding enricher "+enricher.getId()+" ("+enricher+") to entity "+entity.getId()+" ("+entity+")";

    switch (addPolicyFailureMode) {
    case FAIL_FAST:
        throw new IllegalStateException("Rebind: aborting due to "+errmsg, e);
    case FAIL_AT_END:
        addPolicyFailures.add(new IllegalStateException(errmsg, e));
        break;
    case CONTINUE:
        warn(errmsg+"; continuing", e);
        break;
    default:
        throw new IllegalStateException("Unexpected state '"+addPolicyFailureMode+"' for addPolicyFailureMode");
    }
}
 
Example #2
Source File: ServiceStateLogic.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    if (suppressDuplicates==null) {
        // only publish on changes, unless it is configured otherwise
        suppressDuplicates = true;
    }

    Map<String, ?> notifyOfInitialValue = ImmutableMap.of("notifyOfInitialValue", Boolean.TRUE);
    subscriptions().subscribe(notifyOfInitialValue, entity, SERVICE_PROBLEMS, this);
    subscriptions().subscribe(notifyOfInitialValue, entity, SERVICE_UP, this);
    subscriptions().subscribe(notifyOfInitialValue, entity, SERVICE_STATE_EXPECTED, this);
    
    highlightTriggers(MutableList.of(SERVICE_PROBLEMS, SERVICE_UP, SERVICE_STATE_EXPECTED), null);
}
 
Example #3
Source File: AutoScalerPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    if (!config().getRaw(RESIZE_OPERATOR).isPresentAndNonNull()) {
        Preconditions.checkArgument(entity instanceof Resizable, "Provided entity "+entity+" must be an instance of Resizable, because no custom-resizer operator supplied");
    }
    super.setEntity(entity);
    this.poolEntity = entity;
    
    if (getMetric() != null) {
        Entity entityToSubscribeTo = (getEntityWithMetric() != null) ? getEntityWithMetric() : entity;
        subscriptions().subscribe(entityToSubscribeTo, getMetric(), metricEventHandler);
        highlightTriggers(getMetric(), entityToSubscribeTo);
    } else {
        highlightTriggers("Listening for standard size and pool hot/cold sensors (no specific metric)");
    }
    subscriptions().subscribe(poolEntity, getPoolColdSensor(), utilizationEventHandler);
    subscriptions().subscribe(poolEntity, getPoolHotSensor(), utilizationEventHandler);
    subscriptions().subscribe(poolEntity, getPoolOkSensor(), utilizationEventHandler);
    subscriptions().subscribe(poolEntity, DynamicCluster.GROUP_SIZE, poolEventHandler);
}
 
Example #4
Source File: FollowTheSunPolicy.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    checkArgument(entity instanceof FollowTheSunPool, "Provided entity must be a FollowTheSunPool");
    super.setEntity(entity);
    this.poolEntity = (FollowTheSunPool) entity;
    
    // Detect when containers are added to or removed from the pool.
    subscriptions().subscribe(poolEntity, FollowTheSunPool.CONTAINER_ADDED, eventHandler);
    subscriptions().subscribe(poolEntity, FollowTheSunPool.CONTAINER_REMOVED, eventHandler);
    subscriptions().subscribe(poolEntity, FollowTheSunPool.ITEM_ADDED, eventHandler);
    subscriptions().subscribe(poolEntity, FollowTheSunPool.ITEM_REMOVED, eventHandler);
    subscriptions().subscribe(poolEntity, FollowTheSunPool.ITEM_MOVED, eventHandler);
    
    // Take heed of any extant containers.
    for (Entity container : poolEntity.getContainerGroup().getMembers()) {
        onContainerAdded(container, false);
    }
    for (Entity item : poolEntity.getItemGroup().getMembers()) {
        onItemAdded((Movable)item, false);
    }

    scheduleLatencyReductionJig();
}
 
Example #5
Source File: InvokeEffectorOnCollectionSensorChange.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    /*
     * A warning to future modifiers of this method: it is called on rebind
     * so any changes must be compatible with existing persisted state.
     */
    super.setEntity(entity);
    Sensor<? extends Collection<?>> sensor =
            checkNotNull(getConfig(TRIGGER_SENSOR), "Value required for " + TRIGGER_SENSOR.getName());

    checkArgument(Strings.isNonBlank(getConfig(PARAMETER_NAME)), "Value required for " + PARAMETER_NAME.getName());

    // Fail straight away if neither effector is found.
    if (getEffector(getOnAddedEffector()).isAbsentOrNull() &&
            getEffector(getOnRemovedEffector()).isAbsentOrNull()) {
        throw new IllegalArgumentException("Value required for one or both of " + ON_ADDED_EFFECTOR_NAME.getName() +
                " and " + ON_REMOVED_EFFECTOR_NAME.getName());
    }

    // Initialise `present` before subscribing.
    Collection<?> current = entity.sensors().get(getTriggerSensor());
    synchronized (updateLock) {
        previous = (current != null) ? new HashSet<>(current) : Collections.emptySet();
    }
    subscriptions().subscribe(entity, sensor, this);
}
 
Example #6
Source File: BasicJcloudsLocationCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    ConfigKey<Object> subkey = BrooklynConfigKeys.PROVISIONING_PROPERTIES.subKey(JcloudsLocationConfig.JCLOUDS_LOCATION_CUSTOMIZERS.getName());
    // newInstance handles the case that provisioning properties is null.
    ConfigBag provisioningProperties = ConfigBag.newInstance(entity.config().get(BrooklynConfigKeys.PROVISIONING_PROPERTIES));
    Collection<JcloudsLocationCustomizer> existingCustomizers = provisioningProperties.get(JcloudsLocationConfig.JCLOUDS_LOCATION_CUSTOMIZERS);
    List<? super JcloudsLocationCustomizer> merged;
    if (existingCustomizers == null) {
        merged = ImmutableList.<JcloudsLocationCustomizer>of(this);
    } else {
        merged = Lists.newArrayListWithCapacity(1 + existingCustomizers.size());
        merged.addAll(existingCustomizers);
        merged.add(this);
    }
    LOG.debug("{} set location customizers on {}: {}", new Object[]{this, entity, Iterables.toString(merged)});
    entity.config().set(subkey, merged);
}
 
Example #7
Source File: SshFeedIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testAddedEarly() throws Exception {
    final TestEntity entity2 = app.addChild(EntitySpec.create(TestEntity.class)
        .location(machine)
        .addInitializer(new EntityInitializer() {
            @Override
            public void apply(EntityLocal entity) {
                SshFeed.builder()
                    .entity(entity)
                    .onlyIfServiceUp()
                    .poll(new CommandPollConfig<String>(SENSOR_STRING)
                        .command("echo hello")
                        .onSuccess(SshValueFunctions.stdout()))
                    .build();
            }
        }));

    // TODO would be nice to hook in and assert no errors
    EntityAsserts.assertAttributeEqualsContinually(entity2, SENSOR_STRING, null);

    entity2.sensors().set(Attributes.SERVICE_UP, true);
    EntityAsserts.assertAttributeEventually(entity2, SENSOR_STRING, StringPredicates.containsLiteral("hello"));
}
 
Example #8
Source File: SinusoidalLoadGenerator.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(final EntityLocal entity) {
    super.setEntity(entity);
    
    executor.scheduleAtFixedRate(new Runnable() {
        @Override public void run() {
            try {
                long time = System.currentTimeMillis();
                double val = getRequiredConfig(SIN_AMPLITUDE) * (1 + Math.sin( (1.0*time) / getRequiredConfig(SIN_PERIOD_MS) * Math.PI * 2  - Math.PI/2 )) / 2;
                entity.sensors().set(getRequiredConfig(TARGET), val);
            } catch (Throwable t) {
                LOG.warn("Error generating sinusoidal-load metric", t);
                throw Throwables.propagate(t);
            }
        }

    }, 0, getRequiredConfig(PUBLISH_PERIOD_MS), TimeUnit.MILLISECONDS);
}
 
Example #9
Source File: PercentageEnricher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    sourceCurrentSensor = Preconditions.checkNotNull(config().get(SOURCE_CURRENT_SENSOR), "Can't add percentage enricher to entity %s as it has no %s", entity, SOURCE_CURRENT_SENSOR.getName());
    sourceTotalSensor = Preconditions.checkNotNull(config().get(SOURCE_TOTAL_SENSOR), "Can't add percentage enricher to entity %s as it has no %s", entity, SOURCE_TOTAL_SENSOR.getName());
    targetSensor = Preconditions.checkNotNull(config().get(TARGET_SENSOR), "Can't add percentage enricher to entity %s as it has no %s", entity, TARGET_SENSOR.getName());
    producer = Objects.firstNonNull(config().get(PRODUCER), entity);

    if (targetSensor.equals(sourceCurrentSensor) && entity.equals(producer)) {
        throw new IllegalArgumentException("Can't add percentage enricher to entity " + entity + " as cycle detected with " + SOURCE_CURRENT_SENSOR.getName());
    }
    if (targetSensor.equals(sourceTotalSensor) && entity.equals(producer)) {
        throw new IllegalArgumentException("Can't add percentage enricher to entity " + entity + " as cycle detected with " + SOURCE_TOTAL_SENSOR.getName());
    }

    subscriptions().subscribe(MutableMap.of("notifyOfInitialValue", true), producer, sourceCurrentSensor, this);
    subscriptions().subscribe(MutableMap.of("notifyOfInitialValue", true), producer, sourceTotalSensor, this);

    if (RendererHints.getHintsFor(targetSensor).isEmpty()) {
        RendererHints.register(targetSensor, RendererHints.displayValue(MathFunctions.percent(2)));
    }
}
 
Example #10
Source File: RebindExceptionHandlerImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void onAddFeedFailed(EntityLocal entity, Feed feed, Exception e) {
    Exceptions.propagateIfFatal(e);
    String errmsg = "problem adding feed "+feed.getId()+" ("+feed+") to entity "+entity.getId()+" ("+entity+")";

    switch (addPolicyFailureMode) {
    case FAIL_FAST:
        throw new IllegalStateException("Rebind: aborting due to "+errmsg, e);
    case FAIL_AT_END:
        addPolicyFailures.add(new IllegalStateException(errmsg, e));
        break;
    case CONTINUE:
        warn(errmsg+"; continuing", e);
        break;
    default:
        throw new IllegalStateException("Unexpected state '"+addPolicyFailureMode+"' for addPolicyFailureMode");
    }
}
 
Example #11
Source File: DurationSinceSensor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    epochSensor = Sensors.newLongSensor(sensor.getName() + ".epoch");

    if (entity.sensors().get(epochSensor) == null) {
        Long epoch = epochSupplier.get();
        if (epoch == null) {
            epoch = CURRENT_TIME_SUPPLIER.get();
        }
        entity.sensors().set(epochSensor, epoch);
    }

    FunctionFeed feed = FunctionFeed.builder()
            .entity(entity)
            .poll(new FunctionPollConfig<>(sensor).callable(new UpdateTimeSince(entity)))
            .period(period)
            .build();

    entity.addFeed(feed);
}
 
Example #12
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    if (!entity.getApplication().equals(entity)) {
        throw new RuntimeException("SeaCloudsInitializerPolicy must be attached to an application");
    }

    parseMonitoringRules();
    parseAgreements();
    setupObserverInitializerPayload();
    setupGrafanaInitializerPayload();
    // Overriding the default START/STOP behaivour to include the aditional tasks required by
    // SeaClouds while keeping the original behaviour. It allows to initialize and clean-up SeaClouds
    // components when an application is added/removed.
    ((EntityInternal) entity).getMutableEntityType().addSensor(SLA_ID);
    ((EntityInternal) entity).getMutableEntityType().addSensor(T4C_IDS);
    ((EntityInternal) entity).getMutableEntityType().addEffector(newStartEffector());
    ((EntityInternal) entity).getMutableEntityType().addEffector(newStopEffector());

}
 
Example #13
Source File: WinRmFeedLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Live")
public void testAddedEarly() throws Exception {
    final TestEntity entity2 = app.addChild(EntitySpec.create(TestEntity.class)
        .location(machine)
        .addInitializer(new EntityInitializer() {
            @Override
            public void apply(EntityLocal entity) {
                CmdFeed.builder()
                    .entity(entity)
                    .onlyIfServiceUp()
                    .poll(new CommandPollConfig<String>(SENSOR_STRING)
                        .command("echo hello")
                        .onSuccess(SshValueFunctions.stdout()))
                    .build();
            }
        }));

    // TODO would be nice to hook in and assert no errors
    EntityAsserts.assertAttributeEqualsContinually(entity2, SENSOR_STRING, null);

    entity2.sensors().set(Attributes.SERVICE_UP, true);
    EntityAsserts.assertAttributeEventually(entity2, SENSOR_STRING, StringPredicates.containsLiteral("hello"));
}
 
Example #14
Source File: WindowsPerformanceCounterSensors.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    WindowsPerformanceCounterFeed.Builder builder = WindowsPerformanceCounterFeed.builder()
            .period(period)
            .entity(entity);
    for (Map<String, String> sensorConfig : sensors) {
        String name = sensorConfig.get("name");
        String sensorType = sensorConfig.get("sensorType");
        Class<?> clazz;
        try {
            clazz = Strings.isNonEmpty(sensorType)
                    ? ((EntityInternal)entity).getManagementContext().getCatalog().getRootClassLoader().loadClass(sensorType) 
                    : String.class;
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not load type "+sensorType+" for sensor "+name, e);
        }
        builder.addSensor(sensorConfig.get("counter"), Sensors.newSensor(clazz, name, sensorConfig.get("description")));
    }
    entity.addFeed(builder.build());
}
 
Example #15
Source File: Joiner.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    this.producer = getConfig(PRODUCER) == null ? entity: getConfig(PRODUCER);
    this.sourceSensor = (AttributeSensor<T>) getRequiredConfig(SOURCE_SENSOR);
    this.targetSensor = (Sensor<String>) getRequiredConfig(TARGET_SENSOR);

    highlightTriggers(sourceSensor, producer);
    subscriptions().subscribe(producer, sourceSensor, this);

    Object value = producer.getAttribute((AttributeSensor<?>) sourceSensor);
    // TODO would be useful to have a convenience to "subscribeAndThenIfItIsAlreadySetRunItOnce"
    if (value != null) {
        onEvent(new BasicSensorEvent(sourceSensor, producer, value, -1));
    }
}
 
Example #16
Source File: ConditionalSuspendPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    Object target = config().get(SUSPEND_TARGET);
    Preconditions.checkNotNull(target, "Suspend target required");
    Preconditions.checkNotNull(getTargetPolicy(), "Can't find target policy set in " + SUSPEND_TARGET.getName() + ": " + target);
    subscribe();
    uniqueTag = JavaClassNames.simpleClassName(getClass())+":"+getConfig(SUSPEND_SENSOR).getName()+":"+getConfig(RESUME_SENSOR).getName();
}
 
Example #17
Source File: SoftwareProcessImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    subscriptions().subscribe(entity, SERVICE_PROCESS_IS_RUNNING, this);
    subscriptions().subscribe(entity, Attributes.SERVICE_UP, this);
    highlightTriggers(MutableList.of(SERVICE_PROCESS_IS_RUNNING, Attributes.SERVICE_UP), entity);
    onUpdated();
}
 
Example #18
Source File: AbstractSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public AbstractSoftwareProcessSshDriver(EntityLocal entity, SshMachineLocation machine) {
    super(entity, machine);

    // FIXME this assumes we own the location, and causes warnings about configuring location after deployment;
    // better would be to wrap the ssh-execution-provider to supply these flags
    if (getSshFlags()!=null && !getSshFlags().isEmpty())
        machine.configure(getSshFlags());

    // ensure these are set using the routines below, not a global ConfigToAttributes.apply()
    getInstallDir();
    getRunDir();
}
 
Example #19
Source File: SoftwareProcessImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    if (!(entity instanceof SoftwareProcess)) {
        throw new IllegalArgumentException("Expected SoftwareProcess, but got entity "+entity);
    }
    subscriptions().subscribe(ImmutableMap.of("notifyOfInitialValue", true), entity, Attributes.SERVICE_STATE_ACTUAL, this);
    subscriptions().subscribe(ImmutableMap.of("notifyOfInitialValue", true), entity, Attributes.SERVICE_UP, this);
}
 
Example #20
Source File: AbstractInvokeEffectorPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    if (isBusySensorEnabled()) {
        // Republishes when the entity rebinds.
        publishIsBusy();
    }
}
 
Example #21
Source File: AbstractMembershipTrackingPolicy.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    Group group = getGroup();
    if (group != null) {
        if (uniqueTag==null) {
            uniqueTag = JavaClassNames.simpleClassName(this)+":"+group;
        }
        subscribeToGroup(group);
    } else {
        LOG.warn("Deprecated use of "+AbstractMembershipTrackingPolicy.class.getSimpleName()+"; group should be set as config");
    }
}
 
Example #22
Source File: CompositeEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    Maybe<Effector<?>> effectorMaybe = entity.getEntityType().getEffectorByName(effector.getName());
    if (!effectorMaybe.isAbsentOrNull()) {
        Effector<?> original = Effectors.effector(effectorMaybe.get()).name(ORIGINAL_PREFIX + effector.getName()).build();
        ((EntityInternal) entity).getMutableEntityType().addEffector(original);
    }
    super.apply(entity);
}
 
Example #23
Source File: YamlTimeWeightedDeltaEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);
    
    // Check that sourceSensor has been set (rather than triggerSensors)
    getRequiredConfig(SOURCE_SENSOR);
}
 
Example #24
Source File: CreatePasswordSensor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    super.apply(entity);

    boolean isCharacterGroupsPresent = characterGroups != null
            && characterGroups.size() > 0;
    boolean isCharacterGroupsValid = isCharacterGroupsPresent
            && !Iterables.contains(characterGroups, Predicates.isNull())
            && !Iterables.contains(characterGroups, Predicates.equalTo(""));
    boolean isAcceptableCharsPresentAndValid = acceptableChars != null
            && !acceptableChars.isEmpty();

    Preconditions.checkArgument(!isCharacterGroupsPresent || isCharacterGroupsValid, "password.character.groups config key was given but does not contain any valid groups");
    Preconditions.checkArgument(!(isCharacterGroupsPresent && isAcceptableCharsPresentAndValid), "password.chars and password.character.groups both provided - please provide only ONE of them");
    Preconditions.checkArgument(!isCharacterGroupsValid || characterGroups.size() <= passwordLength, "password.length must be longer than the number of entries in password.character.groups");

    String password;
    if (isCharacterGroupsValid) {
        password = Identifiers.makeRandomPassword(passwordLength, characterGroups.toArray(new String[0]));
    } else if (isAcceptableCharsPresentAndValid) {
        password = Identifiers.makeRandomPassword(passwordLength, acceptableChars);
    } else {
        password = Identifiers.makeRandomPassword(passwordLength);
    }

    entity.sensors().set(sensor, password);
}
 
Example #25
Source File: JmxFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    if (getConfig(HELPER) == null) {
        JmxHelper helper = new JmxHelper(entity);
        config().set(HELPER, helper);
        config().set(OWN_HELPER, true);
        config().set(JMX_URI, helper.getUrl());
    }
    super.setEntity(entity);
}
 
Example #26
Source File: AbstractFailureDetector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    if (isRunning()) {
        doStartPolling();
    }
}
 
Example #27
Source File: HttpLatencyDetector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void activateAdditionalEnrichers(EntityLocal entity) {
    Duration rollupWindowSize = getConfig(ROLLUP_WINDOW_SIZE);
    if (rollupWindowSize!=null) {
        entity.enrichers().add(EnricherSpec.create(RollingTimeWindowMeanEnricher.class)
                .configure("producer", entity)
                .configure("source", REQUEST_LATENCY_IN_SECONDS_MOST_RECENT)
                .configure("target", REQUEST_LATENCY_IN_SECONDS_IN_WINDOW)
                .configure("timePeriod", rollupWindowSize));
    }
}
 
Example #28
Source File: HttpLatencyDetector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(EntityLocal entity) {
    super.setEntity(entity);

    initialize();
    startSubscriptions(entity);
    activateAdditionalEnrichers(entity);
    
    updateEnablement();
}
 
Example #29
Source File: WindowsPerformanceCounterFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public WindowsPerformanceCounterFeed build() {
    built = true;
    WindowsPerformanceCounterFeed result = new WindowsPerformanceCounterFeed(this);
    result.setEntity(checkNotNull((EntityLocal)entity, "entity"));
    result.start();
    return result;
}
 
Example #30
Source File: OnPublicNetworkEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void setEntity(final EntityLocal entity) {
    super.setEntity(entity);
    
    /*
     * To find the transformed sensor value we need several things to be set. Therefore 
     * subscribe to all of them, and re-compute whenever any of the change. These are:
     *  - A port-mapping to exist for the relevant machine + private port.
     *  - The entity to have a machine location (so we can lookup the mapped port association).
     *  - The relevant sensors to have a value, which includes the private port.
     */
    pfmListener = new PortForwardManager.AssociationListener() {
        @Override
        public void onAssociationCreated(PortForwardManager.AssociationMetadata metadata) {
            Maybe<MachineLocation> machine = getMachine();
            if (!(machine.isPresent() && machine.get().equals(metadata.getLocation()))) {
                // not related to this entity's machine; ignoring
                return;
            }
            
            LOG.debug("{} attempting transformations, triggered by port-association {}, with machine {} of entity {}", 
                    new Object[] {OnPublicNetworkEnricher.this, metadata, machine.get(), entity});
            tryTransformAll();
        }
        @Override
        public void onAssociationDeleted(PortForwardManager.AssociationMetadata metadata) {
            // no-op
        }
    };
    getPortForwardManager().addAssociationListener(pfmListener, Predicates.alwaysTrue());
}