Return-Path: X-Original-To: archive-asf-public-internal@cust-asf2.ponee.io Delivered-To: archive-asf-public-internal@cust-asf2.ponee.io Received: from cust-asf.ponee.io (cust-asf.ponee.io [163.172.22.183]) by cust-asf2.ponee.io (Postfix) with ESMTP id EDCA9200B25 for ; Wed, 8 Jun 2016 13:08:21 +0200 (CEST) Received: by cust-asf.ponee.io (Postfix) id EC5A4160A2E; Wed, 8 Jun 2016 11:08:21 +0000 (UTC) Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by cust-asf.ponee.io (Postfix) with SMTP id E6793160A29 for ; Wed, 8 Jun 2016 13:08:20 +0200 (CEST) Received: (qmail 15026 invoked by uid 500); 8 Jun 2016 11:08:20 -0000 Mailing-List: contact dev-help@brooklyn.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@brooklyn.apache.org Delivered-To: mailing list dev@brooklyn.apache.org Received: (qmail 15015 invoked by uid 99); 8 Jun 2016 11:08:19 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 08 Jun 2016 11:08:19 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id B4E57DFC7E; Wed, 8 Jun 2016 11:08:19 +0000 (UTC) From: neykov To: dev@brooklyn.apache.org Reply-To: dev@brooklyn.apache.org References: In-Reply-To: Subject: [GitHub] brooklyn-server pull request #177: Adds PublicNetworkFaceEnricher Content-Type: text/plain Message-Id: <20160608110819.B4E57DFC7E@git1-us-west.apache.org> Date: Wed, 8 Jun 2016 11:08:19 +0000 (UTC) archived-at: Wed, 08 Jun 2016 11:08:22 -0000 Github user neykov commented on a diff in the pull request: https://github.com/apache/brooklyn-server/pull/177#discussion_r66236021 --- Diff: 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: + *
    + * {@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
    + * }
    + * 
+ */ +@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> SENSOR = ConfigKeys.newConfigKey( + new TypeToken>() {}, + "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>> SENSORS = ConfigKeys.newConfigKey( + new TypeToken>>() {}, + "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 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> SENSOR_NAME_CONVERTER = ConfigKeys.newConfigKey( + new TypeToken>() {}, + "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 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 { + 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> sensors; + protected Optional>> mapMatching; + protected Function 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 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() { + @Override public void onEvent(SensorEvent 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() { + @Override public void onEvent(SensorEvent 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() { + @Override public void onEvent(SensorEvent 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 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 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; --- End diff -- On stop all IP/hostname sensors are removed. The port forwards are also lost presumably? Is it better to null the mapped sensors as well? --- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastructure@apache.org or file a JIRA ticket with INFRA. ---