You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by al...@apache.org on 2016/06/08 20:23:36 UTC
[6/8] brooklyn-server git commit: Rename PublicNetworkFaceEnricher to
OnPublicNetworkEnricher
Rename PublicNetworkFaceEnricher to OnPublicNetworkEnricher
And change package to o.a.b.core.network.*
Project: http://git-wip-us.apache.org/repos/asf/brooklyn-server/repo
Commit: http://git-wip-us.apache.org/repos/asf/brooklyn-server/commit/70aceb39
Tree: http://git-wip-us.apache.org/repos/asf/brooklyn-server/tree/70aceb39
Diff: http://git-wip-us.apache.org/repos/asf/brooklyn-server/diff/70aceb39
Branch: refs/heads/master
Commit: 70aceb39311fbd9e18bdd3a3436b3f97e183b0f7
Parents: b1dc7d0
Author: Aled Sage <al...@gmail.com>
Authored: Tue Jun 7 14:43:38 2016 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Tue Jun 7 14:43:38 2016 +0100
----------------------------------------------------------------------
.../access/PublicNetworkFaceEnricher.java | 492 ------------------
.../core/network/OnPublicNetworkEnricher.java | 496 +++++++++++++++++++
.../PublicNetworkFaceEnricherRebindTest.java | 69 ---
.../access/PublicNetworkFaceEnricherTest.java | 323 ------------
.../OnPublicNetworkEnricherRebindTest.java | 72 +++
.../network/OnPublicNetworkEnricherTest.java | 326 ++++++++++++
6 files changed, 894 insertions(+), 884 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/70aceb39/core/src/main/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricher.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricher.java b/core/src/main/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricher.java
deleted file mode 100644
index 449692b..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricher.java
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.location.access;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.Collection;
-
-import org.apache.brooklyn.api.entity.Entity;
-import org.apache.brooklyn.api.entity.EntityLocal;
-import org.apache.brooklyn.api.location.Location;
-import org.apache.brooklyn.api.location.MachineLocation;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.Sensor;
-import org.apache.brooklyn.api.sensor.SensorEvent;
-import org.apache.brooklyn.api.sensor.SensorEventListener;
-import org.apache.brooklyn.config.ConfigKey;
-import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.enricher.AbstractEnricher;
-import org.apache.brooklyn.core.entity.AbstractEntity;
-import org.apache.brooklyn.core.location.Machines;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.util.core.flags.TypeCoercions;
-import org.apache.brooklyn.util.exceptions.Exceptions;
-import org.apache.brooklyn.util.guava.Maybe;
-import org.apache.brooklyn.util.net.Networking;
-import org.apache.brooklyn.util.text.StringPredicates;
-import org.apache.brooklyn.util.text.Strings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Lists;
-import com.google.common.net.HostAndPort;
-import com.google.common.reflect.TypeToken;
-
-/**
- * Can be added to an entity so that it advertises its mapped ports (according to the port-mappings
- * recorded in the PortForwardManager). This can be used with sensors of type URI, HostAndPort
- * or plain integer port values. The port-mappings is retrieved by looking up the entity's machine
- * and the private port, in the PortForwardManager's recorded port-mappings.
- *
- * For example, to configure each Tomcat node to publish its mapped uri, and to use that sensor
- * in Nginx for the target servers:
- * <pre>
- * {@code
- * services:
- * - type: cluster
- * id: cluster
- * brooklyn.config:
- * memberSpec:
- * $brooklyn:entitySpec:
- * type: org.apache.brooklyn.entity.webapp.tomcat.TomcatServer
- * brooklyn.enrichers:
- * - type: org.apache.brooklyn.core.location.access.PublicNetworkFaceEnricher
- * brooklyn.config:
- * sensor: main.uri
- * - type: org.apache.brooklyn.entity.proxy.nginx.NginxController
- * brooklyn.config:
- * member.sensor.hostandport: $brooklyn:sensor("main.uri.mapped.public")
- * serverPool: cluster
- * }
- * </pre>
- */
-@Beta
-public class PublicNetworkFaceEnricher extends AbstractEnricher {
-
- // TODO Is this the best package for the enricher?
- //
- // TODO Need more logging, particularly for when the value has *not* been transformed.
- //
- // TODO What if the sensor has an unrelated hostname - we will currently still transform this!
- // That seems acceptable: if the user configures it to look at the sensor, then we can make
- // assumptions that the sensor's value will need translated.
- //
- // TODO If there is no port-mapping, should we advertise the original sensor value?
- // That would allow the enricher to be used for an entity in a private network, and for
- // it to be a no-op in a public cloud (so the same blueprint can be used in both).
- // However I don't think we should publish the original value: it could be the association
- // just hasn't been created yet. If we publish the wrong (i.e. untransformed) value, that
- // will cause other entity's using attributeWhenReady to immediately trigger.
-
- private static final Logger LOG = LoggerFactory.getLogger(PublicNetworkFaceEnricher.class);
-
- @SuppressWarnings("serial")
- public static final ConfigKey<AttributeSensor<?>> SENSOR = ConfigKeys.newConfigKey(
- new TypeToken<AttributeSensor<?>>() {},
- "sensor",
- "The sensor whose mapped value is to be re-published (with suffix \"mapped.public\"); "
- + "either 'sensor' or 'sensors' should be specified");
-
- @SuppressWarnings("serial")
- public static ConfigKey<Collection<? extends AttributeSensor<?>>> SENSORS = ConfigKeys.newConfigKey(
- new TypeToken<Collection<? extends AttributeSensor<?>>>() {},
- "sensors",
- "The multiple sensors whose mapped values are to be re-published (with suffix \"mapped.public\"); "
- + "if neither 'sensor' or 'sensors' is specified, defaults to 'mapAll'");
-
- public static ConfigKey<String> MAP_MATCHING = ConfigKeys.newStringConfigKey(
- "mapMatching",
- "Whether to map all, based on a sensor naming convention (re-published with suffix \"mapped.public\"); "
- + "if neither 'sensor' or 'sensors' is specified, defaults to matchin case-insensitive suffix of "
- + "'port', 'uri', 'url' or 'endpoint' ",
- "(?i).*(port|uri|url|endpoint)");
-
- @SuppressWarnings("serial")
- public static ConfigKey<Function<? super String, String>> SENSOR_NAME_CONVERTER = ConfigKeys.newConfigKey(
- new TypeToken<Function<? super String, String>>() {},
- "sensorNameConverter",
- "The converter to use, to map from the original sensor name to the re-published sensor name",
- new SensorNameConverter("public"));
-
- public static final ConfigKey<PortForwardManager> PORT_FORWARD_MANAGER = ConfigKeys.newConfigKey(
- PortForwardManager.class,
- "portForwardManager",
- "The PortForwardManager storing the port-mappings; if null, the global instance will be used");
-
- public static class SensorNameConverter implements Function<String, String> {
- private final String network;
-
- public SensorNameConverter(String network) {
- this.network = network;
- }
-
- @Override
- public String apply(String input) {
- if (input == null) throw new NullPointerException("Sensor name must not be null");
- String lowerInput = input.toLowerCase();
- if (lowerInput.endsWith("uri")) {
- return input + ".mapped." + network;
- } else if (lowerInput.endsWith("url")) {
- return input + ".mapped." + network;
- } else if (lowerInput.endsWith("endpoint")) {
- return input + ".mapped." + network;
- } else if (lowerInput.endsWith("port")) {
- String prefix = input.substring(0, input.length() - "port".length());
- if (prefix.endsWith(".")) prefix = prefix.substring(0, prefix.length() - 1);
- return prefix + ".endpoint.mapped." + network;
- } else {
- return input + ".mapped." + network;
- }
- }
- }
-
- protected Collection<AttributeSensor<?>> sensors;
- protected Optional<Predicate<Sensor<?>>> mapMatching;
- protected Function<? super String, String> sensorNameConverter;
- protected PortForwardManager.AssociationListener pfmListener;
-
- @Override
- public void setEntity(final EntityLocal entity) {
- super.setEntity(entity);
-
- checkConfig();
- sensors = resolveSensorsConfig();
- if (sensors.isEmpty()) {
- mapMatching = Optional.of(resolveMapMatchingConfig());
- } else {
- mapMatching = Optional.absent();
- }
- sensorNameConverter = getRequiredConfig(SENSOR_NAME_CONVERTER);
-
- /*
- * 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[] {PublicNetworkFaceEnricher.this, metadata, machine.get(), entity});
- tryTransformAll();
- }
- @Override
- public void onAssociationDeleted(PortForwardManager.AssociationMetadata metadata) {
- // no-op
- }
- };
- getPortForwardManager().addAssociationListener(pfmListener, Predicates.alwaysTrue());
-
- subscriptions().subscribe(entity, AbstractEntity.LOCATION_ADDED, new SensorEventListener<Location>() {
- @Override public void onEvent(SensorEvent<Location> event) {
- LOG.debug("{} attempting transformations, triggered by location-added {}, to {}", new Object[] {PublicNetworkFaceEnricher.this, event.getValue(), entity});
- tryTransformAll();
- }});
-
- for (AttributeSensor<?> sensor : sensors) {
- subscriptions().subscribe(entity, sensor, new SensorEventListener<Object>() {
- @Override public void onEvent(SensorEvent<Object> event) {
- LOG.debug("{} attempting transformations, triggered by sensor-event {}->{}, to {}",
- new Object[] {PublicNetworkFaceEnricher.this, event.getSensor().getName(), event.getValue(), entity});
- tryTransform((AttributeSensor<?>)event.getSensor());
- }});
- }
- if (mapMatching.isPresent()) {
- Sensor<?> wildcardSensor = null;
- subscriptions().subscribe(entity, wildcardSensor, new SensorEventListener<Object>() {
- @Override public void onEvent(SensorEvent<Object> event) {
- if (mapMatching.get().apply(event.getSensor())) {
- LOG.debug("{} attempting transformations, triggered by sensor-event {}->{}, to {}",
- new Object[] {PublicNetworkFaceEnricher.this, event.getSensor().getName(), event.getValue(), entity});
- tryTransform((AttributeSensor<?>)event.getSensor());
- }
- }});
- }
-
- tryTransformAll();
- }
-
- @Override
- public void destroy() {
- try {
- if (pfmListener != null) {
- getPortForwardManager().removeAssociationListener(pfmListener);
- }
- } finally {
- super.destroy();
- }
- }
-
- protected void tryTransformAll() {
- if (!isRunning()) {
- return;
- }
- Maybe<MachineLocation> machine = getMachine();
- if (machine.isAbsent()) {
- return;
- }
- for (AttributeSensor<?> sensor : sensors) {
- try {
- tryTransform(machine.get(), sensor);
- } catch (Exception e) {
- // TODO Avoid repeated logging
- Exceptions.propagateIfFatal(e);
- LOG.warn("Problem transforming sensor "+sensor+" of "+entity, e);
- }
- }
- if (mapMatching.isPresent()) {
- for (Sensor<?> sensor : entity.getEntityType().getSensors()) {
- if (sensor instanceof AttributeSensor && mapMatching.get().apply(sensor)) {
- try {
- tryTransform(machine.get(), (AttributeSensor<?>)sensor);
- } catch (Exception e) {
- // TODO Avoid repeated logging
- Exceptions.propagateIfFatal(e);
- LOG.warn("Problem transforming sensor "+sensor+" of "+entity, e);
- }
- }
- }
- }
- }
-
- protected void tryTransform(AttributeSensor<?> sensor) {
- if (!isRunning()) {
- return;
- }
- Maybe<MachineLocation> machine = getMachine();
- if (machine.isAbsent()) {
- return;
- }
- tryTransform(machine.get(), sensor);
- }
-
- protected void tryTransform(MachineLocation machine, AttributeSensor<?> sensor) {
- Object sensorVal = entity.sensors().get(sensor);
- if (sensorVal == null) {
- return;
- }
- Maybe<String> newVal = transformVal(machine, sensor, sensorVal);
- if (newVal.isAbsent()) {
- return;
- }
- AttributeSensor<String> mappedSensor = Sensors.newStringSensor(sensorNameConverter.apply(sensor.getName()));
- if (newVal.get().equals(entity.sensors().get(mappedSensor))) {
- // ignore duplicate
- return;
- }
- LOG.debug("{} publishing value {} for transformed sensor {}, of entity {}",
- new Object[] {this, newVal.get(), sensor, entity});
- entity.sensors().set(mappedSensor, newVal.get());
- }
-
- protected Maybe<String> transformVal(MachineLocation machine, AttributeSensor<?> sensor, Object sensorVal) {
- if (sensorVal == null) {
- return Maybe.absent();
- } else if (isPort(sensorVal)) {
- int port = toInteger(sensorVal);
- return transformPort(entity, machine, port);
- } else if (isUri(sensorVal)) {
- return transformUri(entity, machine, sensorVal.toString());
- } else if (isHostAndPort(sensorVal)) {
- return transformHostAndPort(entity, machine, sensorVal.toString());
- } else {
- // no-op; unrecognised type
- return Maybe.absent();
- }
- }
-
- protected boolean isUri(Object sensorVal) {
- if (sensorVal instanceof URI || sensorVal instanceof URL) {
- return true;
- }
- try {
- URI uri = new URI(sensorVal.toString());
- return uri.getScheme() != null;
- } catch (URISyntaxException e) {
- return false;
- }
- }
-
- protected boolean isPort(Object sensorVal) {
- if (sensorVal instanceof Integer || sensorVal instanceof Long) {
- return Networking.isPortValid(((Number)sensorVal).intValue());
- } else if (sensorVal instanceof CharSequence) {
- return sensorVal.toString().trim().matches("[0-9]+");
- } else {
- return false;
- }
- }
-
- protected int toInteger(Object sensorVal) {
- if (sensorVal instanceof Number) {
- return ((Number)sensorVal).intValue();
- } else if (sensorVal instanceof CharSequence) {
- return Integer.parseInt(sensorVal.toString().trim());
- } else {
- throw new IllegalArgumentException("Expected number but got "+sensorVal+" of type "+(sensorVal != null ? sensorVal.getClass() : null));
- }
- }
-
- protected boolean isHostAndPort(Object sensorVal) {
- if (sensorVal instanceof HostAndPort) {
- return true;
- } else if (sensorVal instanceof String) {
- try {
- HostAndPort hostAndPort = HostAndPort.fromString((String)sensorVal);
- return hostAndPort.hasPort();
- } catch (IllegalArgumentException e) {
- return false;
- }
- }
- return false;
- }
-
- protected Maybe<String> transformUri(Entity source, MachineLocation machine, String sensorVal) {
- URI uri = URI.create(sensorVal);
- int port = uri.getPort();
- if (port == -1 && "http".equalsIgnoreCase(uri.getScheme())) port = 80;
- if (port == -1 && "https".equalsIgnoreCase(uri.getScheme())) port = 443;
-
- if (port != -1) {
- HostAndPort publicTarget = getPortForwardManager().lookup(machine, port);
- if (publicTarget == null) {
- LOG.trace("network-facing enricher not transforming {} URI {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
- return Maybe.absent();
- }
- if (!publicTarget.hasPort()) {
- LOG.debug("network-facing enricher not transforming {} URI {}, because no port in public-target {} for {}", new Object[] {source, sensorVal, publicTarget, machine});
- return Maybe.absent();
- }
- URI result;
- try {
- result = new URI(uri.getScheme(), uri.getUserInfo(), publicTarget.getHostText(), publicTarget.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
- } catch (URISyntaxException e) {
- LOG.debug("Error transforming URI "+uri+", using target "+publicTarget+"; rethrowing");
- throw Exceptions.propagateAnnotated("Error transforming URI "+uri+", using target "+publicTarget, e);
- }
- return Maybe.of(result.toString());
- } else {
- LOG.debug("sensor mapper not transforming URI "+uri+" because no port defined");
- return Maybe.absent();
- }
- }
-
- protected Maybe<String> transformHostAndPort(Entity source, MachineLocation machine, String sensorVal) {
- HostAndPort hostAndPort = HostAndPort.fromString(sensorVal);
- if (hostAndPort.hasPort()) {
- int port = hostAndPort.getPort();
- HostAndPort publicTarget = getPortForwardManager().lookup(machine, port);
- if (publicTarget == null) {
- LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
- return Maybe.absent();
- }
- return Maybe.of(publicTarget.toString());
- } else {
- LOG.debug("network-facing enricher not transforming {} host-and-port {} because defines no port", source, hostAndPort);
- return Maybe.absent();
- }
- }
-
- protected Maybe<String> transformPort(Entity source, MachineLocation machine, int sensorVal) {
- if (Networking.isPortValid(sensorVal)) {
- HostAndPort publicTarget = getPortForwardManager().lookup(machine, sensorVal);
- if (publicTarget == null) {
- LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
- return Maybe.absent();
- }
- return Maybe.of(publicTarget.toString());
- } else {
- LOG.debug("network-facing enricher not transforming {} port {} because not a valid port", source, sensorVal);
- return Maybe.absent();
- }
- }
-
- protected Maybe<MachineLocation> getMachine() {
- return Machines.findUniqueMachineLocation(entity.getLocations());
- }
-
- protected PortForwardManager getPortForwardManager() {
- PortForwardManager portForwardManager = config().get(PORT_FORWARD_MANAGER);
- if (portForwardManager == null) {
- portForwardManager = (PortForwardManager) getManagementContext().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
- }
- return portForwardManager;
- }
-
- protected void checkConfig() {
- AttributeSensor<?> sensor = getConfig(SENSOR);
- Collection<? extends AttributeSensor<?>> sensors = getConfig(SENSORS);
- Maybe<Object> rawMapMatching = config().getRaw(MAP_MATCHING);
- String mapMatching = config().get(MAP_MATCHING);
-
- if (sensor != null && sensors != null && sensors.isEmpty()) {
- throw new IllegalStateException(this+" must not have both 'sensor' and 'sensors' config");
- } else if (sensor == null && (sensors == null || sensors.isEmpty())) {
- if (Strings.isBlank(mapMatching)) {
- throw new IllegalStateException(this+" requires one of 'sensor' or 'sensors' config (when 'mapMatching' is explicitly blank)");
- }
- } else if (rawMapMatching.isPresent()) {
- throw new IllegalStateException(this+" must not have explicit 'mapMatching', and either of 'sensor' or 'sensors' config");
- }
- }
-
- protected Collection<AttributeSensor<?>> resolveSensorsConfig() {
- AttributeSensor<?> sensor = getConfig(SENSOR);
- Collection<? extends AttributeSensor<?>> sensors = getConfig(SENSORS);
-
- Collection<AttributeSensor<?>> result = Lists.newArrayList();
- if (sensor != null) {
- AttributeSensor<?> typedSensor = (AttributeSensor<?>) entity.getEntityType().getSensor(sensor.getName());
- result.add(typedSensor != null ? typedSensor : sensor);
- }
- if (sensors != null) {
- for (Object s : sensors) {
- AttributeSensor<?> coercedSensor = TypeCoercions.coerce(s, AttributeSensor.class);
- AttributeSensor<?> typedSensor = (AttributeSensor<?>) entity.getEntityType().getSensor(coercedSensor.getName());
- result.add(typedSensor != null ? typedSensor : sensor);
- }
- }
- return result;
- }
-
- protected Predicate<Sensor<?>> resolveMapMatchingConfig() {
- String regex = getConfig(MAP_MATCHING);
- final Predicate<CharSequence> namePredicate = StringPredicates.matchesRegex(regex);
- return new Predicate<Sensor<?>>() {
- @Override public boolean apply(Sensor<?> input) {
- return input != null && namePredicate.apply(input.getName());
- }
- };
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/70aceb39/core/src/main/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricher.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricher.java b/core/src/main/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricher.java
new file mode 100644
index 0000000..5013ebb
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricher.java
@@ -0,0 +1,496 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.network;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Collection;
+
+import org.apache.brooklyn.api.entity.Entity;
+import org.apache.brooklyn.api.entity.EntityLocal;
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.MachineLocation;
+import org.apache.brooklyn.api.sensor.AttributeSensor;
+import org.apache.brooklyn.api.sensor.Sensor;
+import org.apache.brooklyn.api.sensor.SensorEvent;
+import org.apache.brooklyn.api.sensor.SensorEventListener;
+import org.apache.brooklyn.config.ConfigKey;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.enricher.AbstractEnricher;
+import org.apache.brooklyn.core.entity.AbstractEntity;
+import org.apache.brooklyn.core.location.Machines;
+import org.apache.brooklyn.core.location.access.PortForwardManager;
+import org.apache.brooklyn.core.location.access.PortForwardManagerLocationResolver;
+import org.apache.brooklyn.core.location.access.PortForwardManager.AssociationListener;
+import org.apache.brooklyn.core.location.access.PortForwardManager.AssociationMetadata;
+import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.util.core.flags.TypeCoercions;
+import org.apache.brooklyn.util.exceptions.Exceptions;
+import org.apache.brooklyn.util.guava.Maybe;
+import org.apache.brooklyn.util.net.Networking;
+import org.apache.brooklyn.util.text.StringPredicates;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Lists;
+import com.google.common.net.HostAndPort;
+import com.google.common.reflect.TypeToken;
+
+/**
+ * Can be added to an entity so that it advertises its mapped ports (according to the port-mappings
+ * recorded in the PortForwardManager). This can be used with sensors of type URI, HostAndPort
+ * or plain integer port values. The port-mappings is retrieved by looking up the entity's machine
+ * and the private port, in the PortForwardManager's recorded port-mappings.
+ *
+ * For example, to configure each Tomcat node to publish its mapped uri, and to use that sensor
+ * in Nginx for the target servers:
+ * <pre>
+ * {@code
+ * services:
+ * - type: cluster
+ * id: cluster
+ * brooklyn.config:
+ * memberSpec:
+ * $brooklyn:entitySpec:
+ * type: org.apache.brooklyn.entity.webapp.tomcat.TomcatServer
+ * brooklyn.enrichers:
+ * - type: org.apache.brooklyn.core.location.access.PublicNetworkFaceEnricher
+ * brooklyn.config:
+ * sensor: main.uri
+ * - type: org.apache.brooklyn.entity.proxy.nginx.NginxController
+ * brooklyn.config:
+ * member.sensor.hostandport: $brooklyn:sensor("main.uri.mapped.public")
+ * serverPool: cluster
+ * }
+ * </pre>
+ */
+@Beta
+public class OnPublicNetworkEnricher extends AbstractEnricher {
+
+ // TODO Is this the best package for the enricher?
+ //
+ // TODO Need more logging, particularly for when the value has *not* been transformed.
+ //
+ // TODO What if the sensor has an unrelated hostname - we will currently still transform this!
+ // That seems acceptable: if the user configures it to look at the sensor, then we can make
+ // assumptions that the sensor's value will need translated.
+ //
+ // TODO If there is no port-mapping, should we advertise the original sensor value?
+ // That would allow the enricher to be used for an entity in a private network, and for
+ // it to be a no-op in a public cloud (so the same blueprint can be used in both).
+ // However I don't think we should publish the original value: it could be the association
+ // just hasn't been created yet. If we publish the wrong (i.e. untransformed) value, that
+ // will cause other entity's using attributeWhenReady to immediately trigger.
+
+ private static final Logger LOG = LoggerFactory.getLogger(OnPublicNetworkEnricher.class);
+
+ @SuppressWarnings("serial")
+ public static final ConfigKey<AttributeSensor<?>> SENSOR = ConfigKeys.newConfigKey(
+ new TypeToken<AttributeSensor<?>>() {},
+ "sensor",
+ "The sensor whose mapped value is to be re-published (with suffix \"mapped.public\"); "
+ + "either 'sensor' or 'sensors' should be specified");
+
+ @SuppressWarnings("serial")
+ public static ConfigKey<Collection<? extends AttributeSensor<?>>> SENSORS = ConfigKeys.newConfigKey(
+ new TypeToken<Collection<? extends AttributeSensor<?>>>() {},
+ "sensors",
+ "The multiple sensors whose mapped values are to be re-published (with suffix \"mapped.public\"); "
+ + "if neither 'sensor' or 'sensors' is specified, defaults to 'mapAll'");
+
+ public static ConfigKey<String> MAP_MATCHING = ConfigKeys.newStringConfigKey(
+ "mapMatching",
+ "Whether to map all, based on a sensor naming convention (re-published with suffix \"mapped.public\"); "
+ + "if neither 'sensor' or 'sensors' is specified, defaults to matchin case-insensitive suffix of "
+ + "'port', 'uri', 'url' or 'endpoint' ",
+ "(?i).*(port|uri|url|endpoint)");
+
+ @SuppressWarnings("serial")
+ public static ConfigKey<Function<? super String, String>> SENSOR_NAME_CONVERTER = ConfigKeys.newConfigKey(
+ new TypeToken<Function<? super String, String>>() {},
+ "sensorNameConverter",
+ "The converter to use, to map from the original sensor name to the re-published sensor name",
+ new SensorNameConverter("public"));
+
+ public static final ConfigKey<PortForwardManager> PORT_FORWARD_MANAGER = ConfigKeys.newConfigKey(
+ PortForwardManager.class,
+ "portForwardManager",
+ "The PortForwardManager storing the port-mappings; if null, the global instance will be used");
+
+ public static class SensorNameConverter implements Function<String, String> {
+ private final String network;
+
+ public SensorNameConverter(String network) {
+ this.network = network;
+ }
+
+ @Override
+ public String apply(String input) {
+ if (input == null) throw new NullPointerException("Sensor name must not be null");
+ String lowerInput = input.toLowerCase();
+ if (lowerInput.endsWith("uri")) {
+ return input + ".mapped." + network;
+ } else if (lowerInput.endsWith("url")) {
+ return input + ".mapped." + network;
+ } else if (lowerInput.endsWith("endpoint")) {
+ return input + ".mapped." + network;
+ } else if (lowerInput.endsWith("port")) {
+ String prefix = input.substring(0, input.length() - "port".length());
+ if (prefix.endsWith(".")) prefix = prefix.substring(0, prefix.length() - 1);
+ return prefix + ".endpoint.mapped." + network;
+ } else {
+ return input + ".mapped." + network;
+ }
+ }
+ }
+
+ protected Collection<AttributeSensor<?>> sensors;
+ protected Optional<Predicate<Sensor<?>>> mapMatching;
+ protected Function<? super String, String> sensorNameConverter;
+ protected PortForwardManager.AssociationListener pfmListener;
+
+ @Override
+ public void setEntity(final EntityLocal entity) {
+ super.setEntity(entity);
+
+ checkConfig();
+ sensors = resolveSensorsConfig();
+ if (sensors.isEmpty()) {
+ mapMatching = Optional.of(resolveMapMatchingConfig());
+ } else {
+ mapMatching = Optional.absent();
+ }
+ sensorNameConverter = getRequiredConfig(SENSOR_NAME_CONVERTER);
+
+ /*
+ * 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());
+
+ subscriptions().subscribe(entity, AbstractEntity.LOCATION_ADDED, new SensorEventListener<Location>() {
+ @Override public void onEvent(SensorEvent<Location> event) {
+ LOG.debug("{} attempting transformations, triggered by location-added {}, to {}", new Object[] {OnPublicNetworkEnricher.this, event.getValue(), entity});
+ tryTransformAll();
+ }});
+
+ for (AttributeSensor<?> sensor : sensors) {
+ subscriptions().subscribe(entity, sensor, new SensorEventListener<Object>() {
+ @Override public void onEvent(SensorEvent<Object> event) {
+ LOG.debug("{} attempting transformations, triggered by sensor-event {}->{}, to {}",
+ new Object[] {OnPublicNetworkEnricher.this, event.getSensor().getName(), event.getValue(), entity});
+ tryTransform((AttributeSensor<?>)event.getSensor());
+ }});
+ }
+ if (mapMatching.isPresent()) {
+ Sensor<?> wildcardSensor = null;
+ subscriptions().subscribe(entity, wildcardSensor, new SensorEventListener<Object>() {
+ @Override public void onEvent(SensorEvent<Object> event) {
+ if (mapMatching.get().apply(event.getSensor())) {
+ LOG.debug("{} attempting transformations, triggered by sensor-event {}->{}, to {}",
+ new Object[] {OnPublicNetworkEnricher.this, event.getSensor().getName(), event.getValue(), entity});
+ tryTransform((AttributeSensor<?>)event.getSensor());
+ }
+ }});
+ }
+
+ tryTransformAll();
+ }
+
+ @Override
+ public void destroy() {
+ try {
+ if (pfmListener != null) {
+ getPortForwardManager().removeAssociationListener(pfmListener);
+ }
+ } finally {
+ super.destroy();
+ }
+ }
+
+ protected void tryTransformAll() {
+ if (!isRunning()) {
+ return;
+ }
+ Maybe<MachineLocation> machine = getMachine();
+ if (machine.isAbsent()) {
+ return;
+ }
+ for (AttributeSensor<?> sensor : sensors) {
+ try {
+ tryTransform(machine.get(), sensor);
+ } catch (Exception e) {
+ // TODO Avoid repeated logging
+ Exceptions.propagateIfFatal(e);
+ LOG.warn("Problem transforming sensor "+sensor+" of "+entity, e);
+ }
+ }
+ if (mapMatching.isPresent()) {
+ for (Sensor<?> sensor : entity.getEntityType().getSensors()) {
+ if (sensor instanceof AttributeSensor && mapMatching.get().apply(sensor)) {
+ try {
+ tryTransform(machine.get(), (AttributeSensor<?>)sensor);
+ } catch (Exception e) {
+ // TODO Avoid repeated logging
+ Exceptions.propagateIfFatal(e);
+ LOG.warn("Problem transforming sensor "+sensor+" of "+entity, e);
+ }
+ }
+ }
+ }
+ }
+
+ protected void tryTransform(AttributeSensor<?> sensor) {
+ if (!isRunning()) {
+ return;
+ }
+ Maybe<MachineLocation> machine = getMachine();
+ if (machine.isAbsent()) {
+ return;
+ }
+ tryTransform(machine.get(), sensor);
+ }
+
+ protected void tryTransform(MachineLocation machine, AttributeSensor<?> sensor) {
+ Object sensorVal = entity.sensors().get(sensor);
+ if (sensorVal == null) {
+ return;
+ }
+ Maybe<String> newVal = transformVal(machine, sensor, sensorVal);
+ if (newVal.isAbsent()) {
+ return;
+ }
+ AttributeSensor<String> mappedSensor = Sensors.newStringSensor(sensorNameConverter.apply(sensor.getName()));
+ if (newVal.get().equals(entity.sensors().get(mappedSensor))) {
+ // ignore duplicate
+ return;
+ }
+ LOG.debug("{} publishing value {} for transformed sensor {}, of entity {}",
+ new Object[] {this, newVal.get(), sensor, entity});
+ entity.sensors().set(mappedSensor, newVal.get());
+ }
+
+ protected Maybe<String> transformVal(MachineLocation machine, AttributeSensor<?> sensor, Object sensorVal) {
+ if (sensorVal == null) {
+ return Maybe.absent();
+ } else if (isPort(sensorVal)) {
+ int port = toInteger(sensorVal);
+ return transformPort(entity, machine, port);
+ } else if (isUri(sensorVal)) {
+ return transformUri(entity, machine, sensorVal.toString());
+ } else if (isHostAndPort(sensorVal)) {
+ return transformHostAndPort(entity, machine, sensorVal.toString());
+ } else {
+ // no-op; unrecognised type
+ return Maybe.absent();
+ }
+ }
+
+ protected boolean isUri(Object sensorVal) {
+ if (sensorVal instanceof URI || sensorVal instanceof URL) {
+ return true;
+ }
+ try {
+ URI uri = new URI(sensorVal.toString());
+ return uri.getScheme() != null;
+ } catch (URISyntaxException e) {
+ return false;
+ }
+ }
+
+ protected boolean isPort(Object sensorVal) {
+ if (sensorVal instanceof Integer || sensorVal instanceof Long) {
+ return Networking.isPortValid(((Number)sensorVal).intValue());
+ } else if (sensorVal instanceof CharSequence) {
+ return sensorVal.toString().trim().matches("[0-9]+");
+ } else {
+ return false;
+ }
+ }
+
+ protected int toInteger(Object sensorVal) {
+ if (sensorVal instanceof Number) {
+ return ((Number)sensorVal).intValue();
+ } else if (sensorVal instanceof CharSequence) {
+ return Integer.parseInt(sensorVal.toString().trim());
+ } else {
+ throw new IllegalArgumentException("Expected number but got "+sensorVal+" of type "+(sensorVal != null ? sensorVal.getClass() : null));
+ }
+ }
+
+ protected boolean isHostAndPort(Object sensorVal) {
+ if (sensorVal instanceof HostAndPort) {
+ return true;
+ } else if (sensorVal instanceof String) {
+ try {
+ HostAndPort hostAndPort = HostAndPort.fromString((String)sensorVal);
+ return hostAndPort.hasPort();
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ protected Maybe<String> transformUri(Entity source, MachineLocation machine, String sensorVal) {
+ URI uri = URI.create(sensorVal);
+ int port = uri.getPort();
+ if (port == -1 && "http".equalsIgnoreCase(uri.getScheme())) port = 80;
+ if (port == -1 && "https".equalsIgnoreCase(uri.getScheme())) port = 443;
+
+ if (port != -1) {
+ HostAndPort publicTarget = getPortForwardManager().lookup(machine, port);
+ if (publicTarget == null) {
+ LOG.trace("network-facing enricher not transforming {} URI {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
+ return Maybe.absent();
+ }
+ if (!publicTarget.hasPort()) {
+ LOG.debug("network-facing enricher not transforming {} URI {}, because no port in public-target {} for {}", new Object[] {source, sensorVal, publicTarget, machine});
+ return Maybe.absent();
+ }
+ URI result;
+ try {
+ result = new URI(uri.getScheme(), uri.getUserInfo(), publicTarget.getHostText(), publicTarget.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
+ } catch (URISyntaxException e) {
+ LOG.debug("Error transforming URI "+uri+", using target "+publicTarget+"; rethrowing");
+ throw Exceptions.propagateAnnotated("Error transforming URI "+uri+", using target "+publicTarget, e);
+ }
+ return Maybe.of(result.toString());
+ } else {
+ LOG.debug("sensor mapper not transforming URI "+uri+" because no port defined");
+ return Maybe.absent();
+ }
+ }
+
+ protected Maybe<String> transformHostAndPort(Entity source, MachineLocation machine, String sensorVal) {
+ HostAndPort hostAndPort = HostAndPort.fromString(sensorVal);
+ if (hostAndPort.hasPort()) {
+ int port = hostAndPort.getPort();
+ HostAndPort publicTarget = getPortForwardManager().lookup(machine, port);
+ if (publicTarget == null) {
+ LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
+ return Maybe.absent();
+ }
+ return Maybe.of(publicTarget.toString());
+ } else {
+ LOG.debug("network-facing enricher not transforming {} host-and-port {} because defines no port", source, hostAndPort);
+ return Maybe.absent();
+ }
+ }
+
+ protected Maybe<String> transformPort(Entity source, MachineLocation machine, int sensorVal) {
+ if (Networking.isPortValid(sensorVal)) {
+ HostAndPort publicTarget = getPortForwardManager().lookup(machine, sensorVal);
+ if (publicTarget == null) {
+ LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
+ return Maybe.absent();
+ }
+ return Maybe.of(publicTarget.toString());
+ } else {
+ LOG.debug("network-facing enricher not transforming {} port {} because not a valid port", source, sensorVal);
+ return Maybe.absent();
+ }
+ }
+
+ protected Maybe<MachineLocation> getMachine() {
+ return Machines.findUniqueMachineLocation(entity.getLocations());
+ }
+
+ protected PortForwardManager getPortForwardManager() {
+ PortForwardManager portForwardManager = config().get(PORT_FORWARD_MANAGER);
+ if (portForwardManager == null) {
+ portForwardManager = (PortForwardManager) getManagementContext().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
+ }
+ return portForwardManager;
+ }
+
+ protected void checkConfig() {
+ AttributeSensor<?> sensor = getConfig(SENSOR);
+ Collection<? extends AttributeSensor<?>> sensors = getConfig(SENSORS);
+ Maybe<Object> rawMapMatching = config().getRaw(MAP_MATCHING);
+ String mapMatching = config().get(MAP_MATCHING);
+
+ if (sensor != null && sensors != null && sensors.isEmpty()) {
+ throw new IllegalStateException(this+" must not have both 'sensor' and 'sensors' config");
+ } else if (sensor == null && (sensors == null || sensors.isEmpty())) {
+ if (Strings.isBlank(mapMatching)) {
+ throw new IllegalStateException(this+" requires one of 'sensor' or 'sensors' config (when 'mapMatching' is explicitly blank)");
+ }
+ } else if (rawMapMatching.isPresent()) {
+ throw new IllegalStateException(this+" must not have explicit 'mapMatching', and either of 'sensor' or 'sensors' config");
+ }
+ }
+
+ protected Collection<AttributeSensor<?>> resolveSensorsConfig() {
+ AttributeSensor<?> sensor = getConfig(SENSOR);
+ Collection<? extends AttributeSensor<?>> sensors = getConfig(SENSORS);
+
+ Collection<AttributeSensor<?>> result = Lists.newArrayList();
+ if (sensor != null) {
+ AttributeSensor<?> typedSensor = (AttributeSensor<?>) entity.getEntityType().getSensor(sensor.getName());
+ result.add(typedSensor != null ? typedSensor : sensor);
+ }
+ if (sensors != null) {
+ for (Object s : sensors) {
+ AttributeSensor<?> coercedSensor = TypeCoercions.coerce(s, AttributeSensor.class);
+ AttributeSensor<?> typedSensor = (AttributeSensor<?>) entity.getEntityType().getSensor(coercedSensor.getName());
+ result.add(typedSensor != null ? typedSensor : sensor);
+ }
+ }
+ return result;
+ }
+
+ protected Predicate<Sensor<?>> resolveMapMatchingConfig() {
+ String regex = getConfig(MAP_MATCHING);
+ final Predicate<CharSequence> namePredicate = StringPredicates.matchesRegex(regex);
+ return new Predicate<Sensor<?>>() {
+ @Override public boolean apply(Sensor<?> input) {
+ return input != null && namePredicate.apply(input.getName());
+ }
+ };
+ }
+}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/70aceb39/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherRebindTest.java b/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherRebindTest.java
deleted file mode 100644
index 9606a29..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherRebindTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.location.access;
-
-import java.net.URI;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.core.entity.Attributes;
-import org.apache.brooklyn.core.entity.EntityAsserts;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.net.HostAndPort;
-
-public class PublicNetworkFaceEnricherRebindTest extends RebindTestFixtureWithApp {
-
- private TestEntity origEntity;
- private SshMachineLocation origMachine;
-
- @BeforeMethod(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
- origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class));
- origMachine = origApp.newLocalhostProvisioningLocation().obtain();
- }
-
- @Test
- public <T> void testRebind() throws Exception {
- origEntity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
-
- origEntity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, Attributes.MAIN_URI));
-
- rebind();
- TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
- PortForwardManager newPortForwardManager = (PortForwardManager) mgmt().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
- SshMachineLocation newMachine = (SshMachineLocation) mgmt().getLocationManager().getLocation(origMachine.getId());
-
- newEntity.sensors().set(Attributes.MAIN_URI, URI.create("http://127.0.0.1:1234/my/path"));
- newPortForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), newMachine, 1234);
- newEntity.addLocations(ImmutableList.of(newMachine));
-
- EntityAsserts.assertAttributeEqualsEventually(newEntity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "http://mypublichost:5678/my/path");
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/70aceb39/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherTest.java b/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherTest.java
deleted file mode 100644
index cb9226b..0000000
--- a/core/src/test/java/org/apache/brooklyn/core/location/access/PublicNetworkFaceEnricherTest.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.brooklyn.core.location.access;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertFalse;
-
-import java.net.URI;
-import java.net.URL;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.brooklyn.api.entity.EntitySpec;
-import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.sensor.AttributeSensor;
-import org.apache.brooklyn.api.sensor.EnricherSpec;
-import org.apache.brooklyn.core.entity.Attributes;
-import org.apache.brooklyn.core.entity.EntityAsserts;
-import org.apache.brooklyn.core.sensor.Sensors;
-import org.apache.brooklyn.core.test.BrooklynAppUnitTestSupport;
-import org.apache.brooklyn.core.test.entity.TestEntity;
-import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.time.Duration;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import com.google.common.base.Function;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.net.HostAndPort;
-
-public class PublicNetworkFaceEnricherTest extends BrooklynAppUnitTestSupport {
-
- private static final Duration VERY_SHORT_WAIT = Duration.millis(100);
-
- private TestEntity entity;
- private SshMachineLocation machine;
- private PortForwardManager portForwardManager;
-
- @BeforeMethod(alwaysRun=true)
- @Override
- public void setUp() throws Exception {
- super.setUp();
- entity = app.createAndManageChild(EntitySpec.create(TestEntity.class));
- machine = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
- .configure("address", "127.0.0.1"));
- portForwardManager = (PortForwardManager) mgmt.getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
- }
-
- @DataProvider(name = "variants")
- public static Object[][] provideVariants() {
- AttributeSensor<HostAndPort> hostAndPortSensor = Sensors.newSensor(HostAndPort.class, "test.endpoint");
- List<Object[]> result = Lists.newArrayList();
- for (Timing setSensor : Timing.values()) {
- for (Timing createAssociation : Timing.values()) {
- for (Timing addLocation : Timing.values()) {
- result.add(new Object[] {setSensor, createAssociation, addLocation, Attributes.MAIN_URI,
- URI.create("http://127.0.0.1:1234/my/path"), "main.uri.mapped.public", "http://mypublichost:5678/my/path"});
- result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME,
- "http://127.0.0.1:1234/my/path", "test.name.mapped.public", "http://mypublichost:5678/my/path"});
- result.add(new Object[] {setSensor, createAssociation, addLocation, Attributes.HTTP_PORT,
- 1234, "http.endpoint.mapped.public", "mypublichost:5678"});
- result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME,
- "1234", "test.name.mapped.public", "mypublichost:5678"});
- result.add(new Object[] {setSensor, createAssociation, addLocation, TestEntity.NAME,
- "127.0.0.1:1234", "test.name.mapped.public", "mypublichost:5678"});
- result.add(new Object[] {setSensor, createAssociation, addLocation, hostAndPortSensor,
- HostAndPort.fromString("127.0.0.1:1234"), "test.endpoint.mapped.public", "mypublichost:5678"});
- }
- }
- }
- return result.toArray(new Object[result.size()][]);
- }
-
- @DataProvider(name = "invalidVariants")
- public static Object[][] provideInvalidVariants() {
- AttributeSensor<HostAndPort> hostAndPortSensor = Sensors.newSensor(HostAndPort.class, "test.hostAndPort");
- List<Object[]> result = Lists.newArrayList();
- result.add(new Object[] {Attributes.MAIN_URI, (URI)null});
- result.add(new Object[] {TestEntity.NAME, "127.0.0.1:1234/my/path"}); // must have scheme
- result.add(new Object[] {Attributes.HTTP_PORT, null});
- result.add(new Object[] {Attributes.HTTP_PORT, 1234567});
- result.add(new Object[] {TestEntity.NAME, null});
- result.add(new Object[] {TestEntity.NAME, "1234567"});
- result.add(new Object[] {TestEntity.NAME, "thisHasNoPort"});
- result.add(new Object[] {TestEntity.NAME, "portIsTooBig:1234567"});
- result.add(new Object[] {hostAndPortSensor, (HostAndPort)null});
- return result.toArray(new Object[result.size()][]);
- }
-
- enum Timing {
- BEFORE,
- AFTER;
- }
-
- /**
- * The sensorVal must include port 1234, so that it will be converted to mypublichost:5678
- */
- @Test(dataProvider = "variants")
- public <T> void testSensorTransformed(Timing setUri, Timing createAssociation, Timing addLocation,
- AttributeSensor<T> sensor, T sensorVal, String targetSensorName, String expectedVal) throws Exception {
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- if (setUri == Timing.BEFORE) {
- entity.sensors().set(sensor, sensorVal);
- }
- if (createAssociation == Timing.BEFORE) {
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
- }
- if (addLocation == Timing.BEFORE) {
- entity.addLocations(ImmutableList.of(machine));
- }
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, sensor));
-
- if (setUri == Timing.AFTER) {
- entity.sensors().set(sensor, sensorVal);
- }
- if (createAssociation == Timing.AFTER) {
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
- }
- if (addLocation == Timing.AFTER) {
- entity.addLocations(ImmutableList.of(machine));
- }
-
- EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(targetSensorName), expectedVal);
- EntityAsserts.assertAttributeEquals(entity, sensor, sensorVal);
- }
-
-
- @Test(dataProvider = "invalidVariants")
- public <T> void testIgnoresWhenInvalidAttribute(AttributeSensor<T> sensor, T sensorVal) throws Exception {
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(sensor, sensorVal);
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, sensor));
-
- EntityAsserts.assertAttributeEqualsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), entity, Sensors.newStringSensor(sensor.getName()+".mapped.public"), null);
- }
-
- @Test
- public <T> void testTransformsDefaultHttp80() throws Exception {
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(Attributes.MAIN_URI, URI.create("http://127.0.0.1/my/path"));
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 80);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, Attributes.MAIN_URI));
-
- EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "http://mypublichost:5678/my/path");
- }
-
- @Test
- public <T> void testTransformsDefaultHttps443() throws Exception {
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(Attributes.MAIN_URI, URI.create("https://127.0.0.1/my/path"));
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 443);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, Attributes.MAIN_URI));
-
- EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "https://mypublichost:5678/my/path");
- }
-
- @Test
- public void testIgnoresWhenNoMapping() throws Exception {
- // Creates associate for a non-matching port
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(Attributes.HTTP_PORT, 1234);
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 4321);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, Attributes.HTTP_PORT));
-
- EntityAsserts.assertAttributeEqualsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), entity, Sensors.newStringSensor(Attributes.HTTP_PORT.getName()+".mapped.public"), null);
- }
-
- @Test
- public void testIgnoresWhenNoMachine() throws Exception {
- // Does not call entity.addLocation
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(Attributes.HTTP_PORT, 1234);
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, Attributes.HTTP_PORT));
-
- EntityAsserts.assertAttributeEqualsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), entity, Sensors.newStringSensor(Attributes.HTTP_PORT.getName()+".mapped.public"), null);
- }
-
- @Test
- public void testIgnoresWithNoPort() throws Exception {
- // Sensor value does not have any port number
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(TestEntity.NAME, "myval");
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class)
- .configure(PublicNetworkFaceEnricher.SENSOR, TestEntity.NAME));
-
- EntityAsserts.assertAttributeEqualsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), entity, Sensors.newStringSensor(TestEntity.NAME.getName()+".mapped.public"), null);
- }
-
- @Test
- public <T> void testTransformsAllMatchingSensors() throws Exception {
- AttributeSensor<URI> stronglyTypedUri = Sensors.newSensor(URI.class, "strongly.typed.uri");
- AttributeSensor<String> stringUri = Sensors.newStringSensor("string.uri");
- AttributeSensor<URL> stronglyTypedUrl = Sensors.newSensor(URL.class, "strongly.typed.url");
- AttributeSensor<String> stringUrl = Sensors.newStringSensor("string.url");
- AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port");
- AttributeSensor<String> stringPort = Sensors.newStringSensor("string.port");
- AttributeSensor<HostAndPort> hostAndPort = Sensors.newSensor(HostAndPort.class, "hostAndPort.endpoint");
- AttributeSensor<String> stringHostAndPort = Sensors.newStringSensor("stringHostAndPort.endpoint");
-
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(stronglyTypedUri, URI.create("http://127.0.0.1:1234/my/path"));
- entity.sensors().set(stringUri, "http://127.0.0.1:1234/my/path");
- entity.sensors().set(stronglyTypedUrl, new URL("http://127.0.0.1:1234/my/path"));
- entity.sensors().set(stringUrl, "http://127.0.0.1:1234/my/path");
- entity.sensors().set(intPort, 1234);
- entity.sensors().set(stringPort, "1234");
- entity.sensors().set(hostAndPort, HostAndPort.fromParts("127.0.0.1", 1234));
- entity.sensors().set(stringHostAndPort, "127.0.0.1:1234");
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class));
-
- assertAttributeEqualsEventually("strongly.typed.uri.mapped.public", "http://mypublichost:5678/my/path");
- assertAttributeEqualsEventually("string.uri.mapped.public", "http://mypublichost:5678/my/path");
- assertAttributeEqualsEventually("strongly.typed.url.mapped.public", "http://mypublichost:5678/my/path");
- assertAttributeEqualsEventually("string.url.mapped.public", "http://mypublichost:5678/my/path");
- assertAttributeEqualsEventually("int.endpoint.mapped.public", "mypublichost:5678");
- assertAttributeEqualsEventually("string.endpoint.mapped.public", "mypublichost:5678");
- assertAttributeEqualsEventually("hostAndPort.endpoint.mapped.public", "mypublichost:5678");
- assertAttributeEqualsEventually("stringHostAndPort.endpoint.mapped.public", "mypublichost:5678");
- }
-
- @Test
- public <T> void testIgnoresNonMatchingSensors() throws Exception {
- AttributeSensor<URI> sensor1 = Sensors.newSensor(URI.class, "my.different");
- AttributeSensor<URL> sensor2 = Sensors.newSensor(URL.class, "my.different2");
- AttributeSensor<String> sensor3 = Sensors.newStringSensor("my.different3");
- AttributeSensor<Integer> sensor4 = Sensors.newIntegerSensor("my.different4");
- AttributeSensor<HostAndPort> sensor5 = Sensors.newSensor(HostAndPort.class, "my.different5");
-
- entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
- entity.sensors().set(sensor1, URI.create("http://127.0.0.1:1234/my/path"));
- entity.sensors().set(sensor2, new URL("http://127.0.0.1:1234/my/path"));
- entity.sensors().set(sensor3, "http://127.0.0.1:1234/my/path");
- entity.sensors().set(sensor4, 1234);
- entity.sensors().set(sensor5, HostAndPort.fromParts("127.0.0.1", 1234));
- portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
- entity.addLocations(ImmutableList.of(machine));
-
- entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class));
-
- Asserts.succeedsContinually(ImmutableMap.of("timeout", VERY_SHORT_WAIT), new Runnable() {
- @Override public void run() {
- Map<AttributeSensor<?>, Object> allSensors = entity.sensors().getAll();
- String errMsg = "sensors="+allSensors;
- for (AttributeSensor<?> sensor : allSensors.keySet()) {
- String name = sensor.getName();
- assertFalse(name.startsWith("my.different") && sensor.getName().contains("public"), errMsg);
- }
- }});
- }
-
- protected void assertAttributeEqualsEventually(String sensorName, String expectedVal) throws Exception {
- try {
- EntityAsserts.assertAttributeEqualsEventually(entity, Sensors.newStringSensor(sensorName), expectedVal);
- } catch (Exception e) {
- throw new Exception("Failed assertion for sensor '"+sensorName+"'; attributes are "+entity.sensors().getAll(), e);
- }
- }
-
- @Test
- public void testSensorNameConverter() throws Exception {
- PublicNetworkFaceEnricher enricher = entity.enrichers().add(EnricherSpec.create(PublicNetworkFaceEnricher.class));
- Function<? super String, String> converter = enricher.getConfig(PublicNetworkFaceEnricher.SENSOR_NAME_CONVERTER);
-
- Map<String, String> testCases = ImmutableMap.<String, String>builder()
- .put("my.uri", "my.uri.mapped.public")
- .put("myuri", "myuri.mapped.public")
- .put("my.UrI", "my.UrI.mapped.public")
- .put("my.url", "my.url.mapped.public")
- .put("myurl", "myurl.mapped.public")
- .put("my.endpoint", "my.endpoint.mapped.public")
- .put("myendpoint", "myendpoint.mapped.public")
- .put("my.port", "my.endpoint.mapped.public")
- .put("myport", "my.endpoint.mapped.public")
- .build();
-
- for (Map.Entry<String, String> entry : testCases.entrySet()) {
- assertEquals(converter.apply(entry.getKey()), entry.getValue(), "input="+entry.getKey());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/70aceb39/core/src/test/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricherRebindTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricherRebindTest.java b/core/src/test/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricherRebindTest.java
new file mode 100644
index 0000000..1a7c584
--- /dev/null
+++ b/core/src/test/java/org/apache/brooklyn/core/network/OnPublicNetworkEnricherRebindTest.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.core.network;
+
+import java.net.URI;
+
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.api.sensor.EnricherSpec;
+import org.apache.brooklyn.core.entity.Attributes;
+import org.apache.brooklyn.core.entity.EntityAsserts;
+import org.apache.brooklyn.core.location.access.PortForwardManager;
+import org.apache.brooklyn.core.location.access.PortForwardManagerLocationResolver;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
+import org.apache.brooklyn.core.network.OnPublicNetworkEnricher;
+import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.net.HostAndPort;
+
+public class OnPublicNetworkEnricherRebindTest extends RebindTestFixtureWithApp {
+
+ private TestEntity origEntity;
+ private SshMachineLocation origMachine;
+
+ @BeforeMethod(alwaysRun=true)
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class));
+ origMachine = origApp.newLocalhostProvisioningLocation().obtain();
+ }
+
+ @Test
+ public <T> void testRebind() throws Exception {
+ origEntity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
+
+ origEntity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
+ .configure(OnPublicNetworkEnricher.SENSOR, Attributes.MAIN_URI));
+
+ rebind();
+ TestEntity newEntity = (TestEntity) Iterables.getOnlyElement(newApp.getChildren());
+ PortForwardManager newPortForwardManager = (PortForwardManager) mgmt().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
+ SshMachineLocation newMachine = (SshMachineLocation) mgmt().getLocationManager().getLocation(origMachine.getId());
+
+ newEntity.sensors().set(Attributes.MAIN_URI, URI.create("http://127.0.0.1:1234/my/path"));
+ newPortForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), newMachine, 1234);
+ newEntity.addLocations(ImmutableList.of(newMachine));
+
+ EntityAsserts.assertAttributeEqualsEventually(newEntity, Sensors.newStringSensor(Attributes.MAIN_URI.getName()+".mapped.public"), "http://mypublichost:5678/my/path");
+ }
+}