http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/dynamic/LocationOwner.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/dynamic/LocationOwner.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/dynamic/LocationOwner.java deleted file mode 100644 index 718b97e..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/dynamic/LocationOwner.java +++ /dev/null @@ -1,85 +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.dynamic; - -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.location.LocationDefinition; -import org.apache.brooklyn.api.sensor.AttributeSensor; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.sensor.BasicAttributeSensorAndConfigKey; -import org.apache.brooklyn.core.sensor.Sensors; -import org.apache.brooklyn.util.core.flags.SetFromFlag; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMap; -import com.google.common.reflect.TypeToken; - -/** - * An entity that owns a particular location. - * <p> - * The entity should be able to dynamically create an instance of the required type of location, and will manage - * the lifecycle of the location in parallel with its own. - * - * @param L the location type - * @param E the entity type - */ -@Beta -public interface LocationOwner<L extends Location & DynamicLocation<E, L>, E extends Entity & LocationOwner<L, E>> { - - @SetFromFlag("locationPrefix") - ConfigKey<String> LOCATION_NAME_PREFIX = ConfigKeys.newStringConfigKey( - "entity.dynamicLocation.prefix", "The name prefix for the location owned by this entity", "dynamic"); - - @SetFromFlag("locationSuffix") - ConfigKey<String> LOCATION_NAME_SUFFIX = ConfigKeys.newStringConfigKey( - "entity.dynamicLocation.suffix", "The name suffix for the location owned by this entity"); - - @SetFromFlag("locationName") - BasicAttributeSensorAndConfigKey<String> LOCATION_NAME = new BasicAttributeSensorAndConfigKey<String>(String.class, - "entity.dynamicLocation.name", "The name of the location owned by this entity (default is auto-generated using prefix and suffix keys)"); - - ConfigKey<Map<String, Object>> LOCATION_FLAGS = ConfigKeys.newConfigKey(new TypeToken<Map<String, Object>>() { }, - "entity.dynamicLocation.flags", "Extra creation flags for the Location owned by this entity", - ImmutableMap.<String, Object>of()); - - AttributeSensor<Location> DYNAMIC_LOCATION = Sensors.newSensor(Location.class, - "entity.dynamicLocation", "The location owned by this entity"); - - AttributeSensor<String> LOCATION_SPEC = Sensors.newStringSensor( - "entity.dynamicLocation.spec", "The specification string for the location owned by this entity"); - - AttributeSensor<Boolean> DYNAMIC_LOCATION_STATUS = Sensors.newBooleanSensor( - "entity.dynamicLocation.status", "The status of the location owned by this entity"); - - AttributeSensor<LocationDefinition> LOCATION_DEFINITION = Sensors.newSensor( - LocationDefinition.class, "entity.dynamicLocation.definition", "The location definition for the location owned by this entity"); - - L getDynamicLocation(); - - L createLocation(Map<String, ?> flags); - - boolean isLocationAvailable(); - - void deleteLocation(); - -}
http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/GeoBytesHostGeoLookup.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/GeoBytesHostGeoLookup.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/GeoBytesHostGeoLookup.java deleted file mode 100644 index 3e46720..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/GeoBytesHostGeoLookup.java +++ /dev/null @@ -1,104 +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.geo; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import org.apache.brooklyn.util.net.Networking; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** @deprecated Mar 2015 - the API has changed; GetLocation now discouraged for free access, and valuepairs.txt not supported */ -@Deprecated -public class GeoBytesHostGeoLookup implements HostGeoLookup { - - public static final Logger log = LoggerFactory.getLogger(GeoBytesHostGeoLookup.class); - - /* - curl "http://www.geobytes.com/IpLocator.htm?GetLocation&template=valuepairs.txt&IpAddress=geobytes.com" - known=1 - countryid=254 - country=United States - fips104=US - iso2=US - iso3=USA - ison=840 - internet=US - comment= - regionid=142 - region=Maryland - code=MD - adm1code= - cityid=8909 - city=Baltimore - latitude=39.2894 - longitude=-76.6384 - timezone=-05:00 - dmaid=512 - dma=512 - market=Baltimore - certainty=78 - isproxy=false - mapbytesremaining=Free - */ - - public String getPropertiesLookupUrlForPublicIp(String ip) { - return "http://www.geobytes.com/IpLocator.htm?GetLocation&template=valuepairs.txt&IpAddress="+ip.trim(); - } - - public String getPropertiesLookupUrlForLocalhost() { - return "http://www.geobytes.com/IpLocator.htm?GetLocation&template=valuepairs.txt"; - } - - /** returns URL to get properties for the given address (assuming localhost if address is on a subnet) */ - public String getPropertiesLookupUrlFor(InetAddress address) { - if (Networking.isPrivateSubnet(address)) return getPropertiesLookupUrlForLocalhost(); - return getPropertiesLookupUrlForPublicIp(address.getHostAddress()); - } - - private static boolean LOGGED_GEO_LOOKUP_UNAVAILABLE = false; - - public HostGeoInfo getHostGeoInfo(InetAddress address) throws MalformedURLException, IOException { - String url = getPropertiesLookupUrlFor(address); - if (log.isDebugEnabled()) - log.debug("Geo info lookup for "+address+" at "+url); - Properties props = new Properties(); - try { - props.load( new URL(url).openStream() ); - HostGeoInfo geo = new HostGeoInfo(address.getHostName(), props.getProperty("city")+" ("+props.getProperty("iso2")+")", - Double.parseDouble(props.getProperty("latitude")), Double.parseDouble(props.getProperty("longitude"))); - log.info("Geo info lookup for "+address+" returned: "+geo); - return geo; - } catch (Exception e) { - // may be web not available, or gateway giving us funny crap - if (log.isDebugEnabled()) - log.debug("Geo info lookup for "+address+" failed: "+e); - if (!LOGGED_GEO_LOOKUP_UNAVAILABLE) { - LOGGED_GEO_LOOKUP_UNAVAILABLE = true; - log.info("Geo info lookup unavailable (for "+address+"; cause "+e+")"); - } - return null; - } - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HasHostGeoInfo.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HasHostGeoInfo.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HasHostGeoInfo.java deleted file mode 100644 index 97e64d5..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HasHostGeoInfo.java +++ /dev/null @@ -1,25 +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.geo; - -public interface HasHostGeoInfo { - - HostGeoInfo getHostGeoInfo(); - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoInfo.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoInfo.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoInfo.java deleted file mode 100644 index f99b41d..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoInfo.java +++ /dev/null @@ -1,216 +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.geo; - -import java.io.Serializable; -import java.net.InetAddress; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.location.AddressableLocation; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.core.location.AbstractLocation; -import org.apache.brooklyn.core.location.LocationConfigKeys; -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.internal.BrooklynSystemProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Objects; - -/** - * Encapsulates geo-IP information for a given host. - */ -public class HostGeoInfo implements Serializable { - - private static final long serialVersionUID = -5866759901535266181L; - - public static final Logger log = LoggerFactory.getLogger(HostGeoInfo.class); - - /** the IP address */ - public final String address; - - public final String displayName; - - public final double latitude; - public final double longitude; - - private static Maybe<HostGeoLookup> cachedLookup = null; - - public static HostGeoInfo create(String address, String displayName, double latitude, double longitude) { - return new HostGeoInfo(address, displayName, latitude, longitude); - } - - public static HostGeoInfo fromIpAddress(InetAddress address) { - try { - HostGeoLookup lookup = getDefaultLookup(); - if (lookup!=null) - return lookup.getHostGeoInfo(address); - } catch (Exception e) { - if (log.isDebugEnabled()) - log.debug("unable to look up geo DNS info for "+address, e); - } - return null; - } - - @Nullable - public static HostGeoLookup getDefaultLookup() throws InstantiationException, IllegalAccessException, ClassNotFoundException { - if (cachedLookup==null) { - cachedLookup = Maybe.of(findHostGeoLookupImpl()); - } - return cachedLookup.get(); - } - - public static void clearCachedLookup() { - cachedLookup = null; - } - - /** returns null if cannot be set */ - public static HostGeoInfo fromLocation(Location l) { - if (l==null) return null; - - Location la = l; - HostGeoInfo resultFromLocation = null; - while (la!=null) { - if (la instanceof HasHostGeoInfo) { - resultFromLocation = ((HasHostGeoInfo)l).getHostGeoInfo(); - if (resultFromLocation!=null) break; - } - la = la.getParent(); - } - if (resultFromLocation!=null && l==la) { - // from the location - return resultFromLocation; - } - // resultFromLocation may be inherited, in which case we will copy it later - - InetAddress address = findIpAddress(l); - Object latitude = l.getConfig(LocationConfigKeys.LATITUDE); - Object longitude = l.getConfig(LocationConfigKeys.LONGITUDE); - - if (resultFromLocation!=null && (latitude == null || longitude == null)) { - latitude = resultFromLocation.latitude; - longitude = resultFromLocation.longitude; - } - if (address!=null && (latitude == null || longitude == null)) { - HostGeoInfo geo = fromIpAddress(address); - if (geo==null) return null; - latitude = geo.latitude; - longitude = geo.longitude; - } - - if (latitude==null || longitude==null) - return null; - - Exception error=null; - try { - latitude = TypeCoercions.castPrimitive(latitude, Double.class); - longitude = TypeCoercions.castPrimitive(longitude, Double.class); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - error = e; - } - if (error!=null || !(latitude instanceof Double) || !(longitude instanceof Double)) - throw new IllegalArgumentException("Location "+l+" specifies invalid type of lat/long: " + - "lat="+latitude+" (type "+(latitude==null ? null : latitude.getClass())+"); " + - "lon="+longitude+" (type "+(longitude==null ? null : longitude.getClass())+")", error); - - HostGeoInfo result = new HostGeoInfo(address!=null ? address.getHostAddress() : null, l.getDisplayName(), (Double) latitude, (Double) longitude); - if (l instanceof AbstractLocation) { - ((AbstractLocation)l).setHostGeoInfo(result); - } - return result; - } - - @Deprecated - private static boolean warnedLegacy = false; - - private static HostGeoLookup findHostGeoLookupImpl() throws InstantiationException, IllegalAccessException, ClassNotFoundException { - String type = BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL.getValue(); - if (type==null) { - type = BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL_LEGACY.getValue(); - if (type!=null && !warnedLegacy) { - warnedLegacy = true; - log.warn("Using deprecated host-geo-lookup property "+BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL_LEGACY+"; " - + "set "+BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL+" instead"); - } - } - /* utrace seems more accurate than geobytes, and it gives a report of how many tokens are left; - * but maxmind if it's installed locally is even better (does not require remote lookup), - * so use it if available */ - if (type==null) { - if (MaxMind2HostGeoLookup.getDatabaseReader()!=null) - return new MaxMind2HostGeoLookup(); - log.debug("Using Utrace remote for geo lookup because MaxMind2 is not available"); - return new UtraceHostGeoLookup(); - } - if (type.isEmpty()) return null; - return (HostGeoLookup) Class.forName(type).newInstance(); - } - - public static HostGeoInfo fromEntity(Entity e) { - for (Location l : e.getLocations()) { - HostGeoInfo hgi = fromLocation(l); - if (hgi != null) - return hgi; - } - return null; - } - - public static InetAddress findIpAddress(Location l) { - if (l == null) - return null; - if (l instanceof AddressableLocation) - return ((AddressableLocation) l).getAddress(); - return findIpAddress(l.getParent()); - } - - public HostGeoInfo(String address, String displayName, double latitude, double longitude) { - this.address = address; - this.displayName = displayName==null ? "" : displayName; - this.latitude = latitude; - this.longitude = longitude; - } - - public String getAddress() { - return address; - } - - @Override - public String toString() { - return "HostGeoInfo["+displayName+": "+(address!=null ? address : "(no-address)")+" at ("+latitude+","+longitude+")]"; - } - - @Override - public boolean equals(Object o) { - // Slight cheat: only includes the address + displayName field (displayName to allow overloading localhost etc) - return (o instanceof HostGeoInfo) && Objects.equal(address, ((HostGeoInfo) o).address) - && Objects.equal(displayName, ((HostGeoInfo) o).displayName); - } - - @Override - public int hashCode() { - // Slight cheat: only includes the address + displayName field (displayName to allow overloading localhost etc) - return Objects.hashCode(address, displayName); - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoLookup.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoLookup.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoLookup.java deleted file mode 100644 index ec25e07..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/HostGeoLookup.java +++ /dev/null @@ -1,27 +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.geo; - -import java.net.InetAddress; - -public interface HostGeoLookup { - - public HostGeoInfo getHostGeoInfo(InetAddress address) throws Exception; - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/LocalhostExternalIpLoader.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/LocalhostExternalIpLoader.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/LocalhostExternalIpLoader.java deleted file mode 100644 index f6623fc..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/LocalhostExternalIpLoader.java +++ /dev/null @@ -1,208 +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.geo; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.brooklyn.util.core.ResourceUtils; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.text.StringPredicates; -import org.apache.brooklyn.util.time.Duration; -import org.apache.brooklyn.util.time.Durations; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Predicates; -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -public class LocalhostExternalIpLoader { - - public static final Logger LOG = LoggerFactory.getLogger(LocalhostExternalIpLoader.class); - - /** - * Mutex to guard access to retrievingLocalExternalIp. - */ - private static final Object mutex = new Object(); - /** - * When null there is no ongoing attempt to load the external IP address. Either no attempt has been made or the - * last attempt has been completed. - * When set there is an ongoing attempt to load the external IP address. New attempts to lookup the external IP - * address should wait on this latch instead of making another attempt to load the IP address. - */ - private static CountDownLatch retrievingLocalExternalIp; - /** - * Cached external IP address of localhost. Null if either no attempt has been made to resolve the address or the - * last attempt failed. - */ - private static volatile String localExternalIp; - - private static class IpLoader implements Callable<String> { - private static final Pattern ipPattern = Pattern.compile( - "\\b((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\b"); - final String url; - - protected IpLoader(String url) { - this.url = url; - } - - @Override - public String call() { - String response = ResourceUtils.create(LocalhostExternalIpLoader.class) - .getResourceAsString(url).trim(); - return postProcessResponse(response); - } - - String postProcessResponse(String response) { - Matcher matcher = ipPattern.matcher(response); - boolean matched = matcher.find(); - if (!matched) { - LOG.error("No IP address matched in output from {}: {}", url, response); - return null; - } else { - return matcher.group(); - } - } - } - - @VisibleForTesting - static List<String> getIpAddressWebsites() { - String file = new ResourceUtils(LocalhostExternalIpLoader.class) - .getResourceAsString("classpath://org/apache/brooklyn/location/geo/external-ip-address-resolvers.txt"); - Iterable<String> lines = Splitter.on('\n') - .omitEmptyStrings() - .trimResults() - .split(file); - List<String> urls = Lists.newArrayList(Iterables.filter(lines, Predicates.not(StringPredicates.startsWith("#")))); - Collections.shuffle(urls); - return urls; - } - - @VisibleForTesting - static String getIpAddressFrom(String url) { - return new IpLoader(url).call(); - } - - /** As {@link #getLocalhostIpWithin(Duration)} but returning 127.0.0.1 if not accessible */ - public static String getLocalhostIpQuicklyOrDefault() { - String result = doLoad(Duration.seconds(2)); - if (result==null) return "127.0.0.1"; - return result; - } - - /** As {@link #getLocalhostIpWithin(Duration)} but without the time limit cut-off, failing if the load gives an error. */ - public static String getLocalhostIpWaiting() { - return getLocalhostIpWithin(null); - } - - /** - * Attempts to load the public IP address of localhost, failing if the load - * does not complete within the given duration. - * @return The public IP address of localhost - */ - public static String getLocalhostIpWithin(Duration timeout) { - String result = doLoad(timeout); - if (result == null) { - throw new IllegalStateException("Unable to retrieve external IP for localhost; network may be down or slow or remote service otherwise not responding"); - } - return result; - } - - /** - * Requests URLs returned by {@link #getIpAddressWebsites()} until one returns an IP address or all URLs have been tried. - * The address is assumed to be the external IP address of localhost. - * @param blockFor The maximum duration to wait for the IP address to be resolved. - * An indefinite way if null. - * @return A string in IPv4 format, or null if no such address could be ascertained. - */ - private static String doLoad(Duration blockFor) { - // Check for a cached external IP address - final String resolvedIp = localExternalIp; - if (resolvedIp != null) { - return resolvedIp; - } - - // Check for an ongoing attempt to load an external IP address - final boolean startAttemptToLoadIp; - final CountDownLatch attemptToRetrieveLocalExternalIp; - synchronized (mutex) { - if (retrievingLocalExternalIp == null) { - retrievingLocalExternalIp = new CountDownLatch(1); - startAttemptToLoadIp = true; - } - else { - startAttemptToLoadIp = false; - } - attemptToRetrieveLocalExternalIp = retrievingLocalExternalIp; - } - - // Attempt to load the external IP address in private thread, otherwise blocks for 30s+ on dodgy network! - // (we can skip it if someone else is doing it, we have synch lock so we'll get notified) - if (startAttemptToLoadIp) { - final List<String> candidateUrls = getIpAddressWebsites(); - if (candidateUrls.isEmpty()) { - LOG.debug("No candidate URLs to use to determine external IP of localhost"); - return null; - } - - new Thread() { - public void run() { - for (String url : candidateUrls) { - try { - LOG.debug("Looking up external IP of this host from {} in private thread {}", url, Thread.currentThread()); - final String loadedIp = new IpLoader(url).call(); - localExternalIp = loadedIp; - LOG.debug("Finished looking up external IP of this host from {} in private thread, result {}", url, loadedIp); - break; - } catch (Throwable t) { - LOG.debug("Unable to look up external IP of this host from {}, probably offline {})", url, t); - } - } - - attemptToRetrieveLocalExternalIp.countDown(); - - synchronized (mutex) { - retrievingLocalExternalIp = null; - } - } - }.start(); - } - - try { - if (blockFor!=null) { - Durations.await(attemptToRetrieveLocalExternalIp, blockFor); - } else { - attemptToRetrieveLocalExternalIp.await(); - } - } catch (InterruptedException e) { - throw Exceptions.propagate(e); - } - - return localExternalIp; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/MaxMind2HostGeoLookup.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/MaxMind2HostGeoLookup.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/MaxMind2HostGeoLookup.java deleted file mode 100644 index 1880441..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/MaxMind2HostGeoLookup.java +++ /dev/null @@ -1,114 +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.geo; - -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.net.MalformedURLException; - -import org.apache.brooklyn.util.internal.BrooklynSystemProperties; -import org.apache.brooklyn.util.net.Networking; -import org.apache.brooklyn.util.text.Strings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Throwables; -import com.google.common.collect.Lists; -import com.maxmind.geoip2.DatabaseReader; -import com.maxmind.geoip2.model.CityResponse; -import com.maxmind.geoip2.record.Subdivision; - -public class MaxMind2HostGeoLookup implements HostGeoLookup { - - public static final Logger log = LoggerFactory.getLogger(MaxMind2HostGeoLookup.class); - - static final String MAXMIND_DB_URL = "http://dev.maxmind.com/geoip/geoip2/geolite2/#Downloads"; - // TODO this should be configurable from system property or brooklyn.properties - // TODO and should use properties BrooklynServerConfig.MGMT_BASE_DIR (but hard to get mgmt properties here!) - static final String MAXMIND_DB_PATH = System.getProperty("user.home")+"/"+".brooklyn/"+"GeoLite2-City.mmdb"; - - static boolean lookupFailed = false; - static DatabaseReader databaseReader = null; - - public static synchronized DatabaseReader getDatabaseReader() { - if (databaseReader!=null) return databaseReader; - try { - File f = new File(MAXMIND_DB_PATH); - databaseReader = new DatabaseReader.Builder(f).build(); - } catch (IOException e) { - lookupFailed = true; - log.debug("MaxMind geo lookup unavailable; either download and unpack the latest "+ - "binary from "+MAXMIND_DB_URL+" into "+MAXMIND_DB_PATH+", "+ - "or specify a different HostGeoLookup implementation with the key "+ - BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL.getPropertyName()+" (error trying to read: "+e+")"); - } - return databaseReader; - } - - public HostGeoInfo getHostGeoInfo(InetAddress address) throws MalformedURLException, IOException { - if (lookupFailed) return null; - - DatabaseReader ll = getDatabaseReader(); - if (ll==null) return null; - - InetAddress extAddress = address; - if (Networking.isPrivateSubnet(extAddress)) extAddress = InetAddress.getByName(LocalhostExternalIpLoader.getLocalhostIpQuicklyOrDefault()); - - try { - CityResponse l = ll.city(extAddress); - if (l==null) { - if (log.isDebugEnabled()) log.debug("Geo info failed to find location for address {}, using {}", extAddress, ll); - return null; - } - - StringBuilder name = new StringBuilder(); - - if (l.getCity()!=null && l.getCity().getName()!=null) name.append(l.getCity().getName()); - - if (l.getSubdivisions()!=null) { - for (Subdivision subd: Lists.reverse(l.getSubdivisions())) { - if (name.length()>0) name.append(", "); - // prefer e.g. USA state codes over state names - if (!Strings.isBlank(subd.getIsoCode())) - name.append(subd.getIsoCode()); - else - name.append(subd.getName()); - } - } - - if (l.getCountry()!=null) { - if (name.length()==0) { - name.append(l.getCountry().getName()); - } else { - name.append(" ("); name.append(l.getCountry().getIsoCode()); name.append(")"); - } - } - - - HostGeoInfo geo = new HostGeoInfo(address.getHostName(), name.toString(), l.getLocation().getLatitude(), l.getLocation().getLongitude()); - log.debug("Geo info lookup (MaxMind DB) for "+address+" returned: "+geo); - return geo; - } catch (Exception e) { - if (log.isDebugEnabled()) - log.debug("Geo info lookup failed: "+e); - throw Throwables.propagate(e); - } - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/UtraceHostGeoLookup.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/UtraceHostGeoLookup.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/UtraceHostGeoLookup.java deleted file mode 100644 index 5026ac4..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/geo/UtraceHostGeoLookup.java +++ /dev/null @@ -1,209 +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.geo; - -import groovy.util.Node; -import groovy.util.NodeList; -import groovy.util.XmlParser; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.util.concurrent.atomic.AtomicReference; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.javalang.JavaClassNames; -import org.apache.brooklyn.util.net.Networking; -import org.apache.brooklyn.util.time.Duration; -import org.apache.brooklyn.util.time.Durations; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Throwables; - -public class UtraceHostGeoLookup implements HostGeoLookup { - - - /* - * -http://xml.utrace.de/?query=88.198.156.18 -(IP address or hostname) - -The XML result is as follows: - -<?xml version="1.0" encoding="iso-8869-1"?> -<results> -<result> -<ip>88.198.156.18</ip> -<host>utrace.de</host> -<isp>Hetzner Online AG</isp> -<org>Pagedesign GmbH</org> -<region>Hamburg</region> -<countrycode>DE</countrycode> -<latitude>53.5499992371</latitude> -<longitude>10</longitude> -<queries>10</queries> -</result> -</results> - -Note the queries count field -- you are permitted 100 per day. -Beyond this you get blacklisted and requests may time out, or return none. -(This may last for several days once blacklisting, not sure how long.) - */ - - /** after failures, subsequent retries within this time interval are blocked */ - private static final Duration RETRY_INTERVAL = Duration.FIVE_MINUTES; - /** requests taking longer than this period are deemed to have timed out and failed; - * set reasonably low so that if we are blacklisted for making too many requests, - * the call to get geo info does not take very long */ - private static final Duration REQUEST_TIMEOUT = Duration.seconds(3); - - public static final Logger log = LoggerFactory.getLogger(UtraceHostGeoLookup.class); - - public String getLookupUrlForPublicIp(String ip) { - return "http://xml.utrace.de/?query="+ip.trim(); - } - - /** - * @deprecated since 0.7.0. Use {@link LocalhostExternalIpLoader} instead. - */ - @Deprecated - public static String getLocalhostExternalIp() { - return LocalhostExternalIpLoader.getLocalhostIpWithin(Duration.seconds(2)); - } - - /** - * @deprecated since 0.7.0. Use {@link LocalhostExternalIpLoader} instead. - */ - @Deprecated - public static String getLocalhostExternalIpImpl() { - return LocalhostExternalIpLoader.getLocalhostIpWithin(Duration.seconds(2)); - } - - public String getLookupUrlForLocalhost() { - return getLookupUrlForPublicIp(LocalhostExternalIpLoader.getLocalhostIpQuicklyOrDefault()); - } - - /** returns URL to get properties for the given address (assuming localhost if address is on a subnet) */ - public String getLookupUrlFor(InetAddress address) { - if (Networking.isPrivateSubnet(address)) return getLookupUrlForLocalhost(); - return getLookupUrlForPublicIp(address.getHostAddress()); - } - - private static boolean LOGGED_GEO_LOOKUP_UNAVAILABLE = false; - private static long LAST_FAILURE_UTC = -1; - - /** does the {@link #retrieveHostGeoInfo(InetAddress)}, but in the background with a default timeout */ - public HostGeoInfo getHostGeoInfo(InetAddress address) throws MalformedURLException, IOException { - if (Duration.sinceUtc(LAST_FAILURE_UTC).compareTo(RETRY_INTERVAL) < 0) { - // wait at least 60s since a failure - return null; - } - return getHostGeoInfo(address, REQUEST_TIMEOUT); - } - - /** does a {@link #retrieveHostGeoInfo(InetAddress)} with a timeout (returning null, interrupting, and setting failure time) */ - public HostGeoInfo getHostGeoInfo(final InetAddress address, Duration timeout) throws MalformedURLException, IOException { - final AtomicReference<HostGeoInfo> result = new AtomicReference<HostGeoInfo>(); - Thread lt = new Thread() { - public void run() { - try { - result.set(retrieveHostGeoInfo(address)); - } catch (Exception e) { - log.warn("Error computing geo info for "+address+"; internet issues or too many requests to (free) servers for "+JavaClassNames.simpleClassName(UtraceHostGeoLookup.this)+": "+e); - log.debug("Detail of host geo error: "+e, e); - } - } - }; - lt.start(); - - try { - Durations.join(lt, timeout); - } catch (InterruptedException e) { - throw Exceptions.propagate(e); - } - - if (lt.isAlive()) { - // interrupt and set the failure time so that subsequent attempts do not face this timeout - lt.interrupt(); - LAST_FAILURE_UTC = System.currentTimeMillis(); - log.debug("Geo info lookup for "+address+" timed out after "+timeout); - } - - return result.get(); - } - - public HostGeoInfo retrieveHostGeoInfo(InetAddress address) throws MalformedURLException, IOException { - String url = getLookupUrlFor(address); - if (log.isDebugEnabled()) - log.debug("Geo info lookup for "+address+" at "+url); - Node xml; - try { - xml = new XmlParser().parse(getLookupUrlFor(address)); - } catch (Exception e) { - LAST_FAILURE_UTC = System.currentTimeMillis(); - if (log.isDebugEnabled()) - log.debug("Geo info lookup for "+address+" failed: "+e); - if (!LOGGED_GEO_LOOKUP_UNAVAILABLE) { - LOGGED_GEO_LOOKUP_UNAVAILABLE = true; - log.info("Geo info lookup unavailable (for "+address+"; cause "+e+")"); - } - return null; - } - try { - String org = getXmlResultsField(xml, "org").trim(); - if (org.isEmpty()) org = getXmlResultsField(xml, "isp").trim(); - String region = getXmlResultsField(xml, "region").trim(); - if (!org.isEmpty()) { - if (!region.isEmpty()) region = org+", "+region; - else region = org; - } - if (region.isEmpty()) region = getXmlResultsField(xml, "isp").trim(); - if (region.isEmpty()) region = address.toString(); - HostGeoInfo geo = new HostGeoInfo(address.getHostName(), - region+ - " ("+getXmlResultsField(xml, "countrycode")+")", - Double.parseDouble(""+getXmlResultsField(xml, "latitude")), - Double.parseDouble(""+getXmlResultsField(xml, "longitude"))); - log.info("Geo info lookup for "+address+" returned: "+geo); - return geo; - } catch (Exception e) { - if (log.isDebugEnabled()) - log.debug("Geo info lookup failed, for "+address+" at "+url+", due to "+e+"; response is "+xml); - throw Throwables.propagate(e); - } - } - - @Nullable - private static Node getFirstChild(Node xml, String field) { - if (xml==null) return null; - NodeList nl = (NodeList)xml.get(field); - if (nl==null || nl.isEmpty()) return null; - return (Node)nl.get(0); - } - @Nonnull - private static String getXmlResultsField(Node xml, String field) { - Node f1 = getFirstChild(getFirstChild(xml, "result"), field); - if (f1==null) return ""; - return f1.text(); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationDynamicType.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationDynamicType.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationDynamicType.java deleted file mode 100644 index 59f0d34..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationDynamicType.java +++ /dev/null @@ -1,40 +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.internal; - -import org.apache.brooklyn.core.location.AbstractLocation; -import org.apache.brooklyn.core.objs.BrooklynDynamicType; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.location.LocationType; - -public class LocationDynamicType extends BrooklynDynamicType<Location, AbstractLocation> { - - public LocationDynamicType(AbstractLocation location) { - super(location); - } - - public LocationType getSnapshot() { - return (LocationType) super.getSnapshot(); - } - - @Override - protected LocationTypeSnapshot newSnapshot() { - return new LocationTypeSnapshot(name, value(configKeys)); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationInternal.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationInternal.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationInternal.java deleted file mode 100644 index 5c83f2d..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationInternal.java +++ /dev/null @@ -1,96 +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.internal; - -import java.util.Map; - -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.rebind.RebindSupport; -import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento; -import org.apache.brooklyn.config.ConfigInheritance; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.objs.BrooklynObjectInternal; -import org.apache.brooklyn.util.core.config.ConfigBag; - -import com.google.common.annotations.Beta; - -/** - * Information about locations private to Brooklyn. - */ -public interface LocationInternal extends BrooklynObjectInternal, Location { - - @Beta - public static final ConfigKey<String> ORIGINAL_SPEC = ConfigKeys.newStringConfigKey("spec.original", "The original spec used to instantiate a location"); - @Beta - public static final ConfigKey<String> FINAL_SPEC = ConfigKeys.newStringConfigKey("spec.final", "The actual spec (in a chain) which instantiates a location"); - @Beta - public static final ConfigKey<String> NAMED_SPEC_NAME = ConfigKeys.newStringConfigKey("spec.named.name", "The name on the (first) named spec in a chain"); - - /** - * Registers the given extension for the given type. If an extension already existed for - * this type, then this will override it. - * - * @throws NullPointerException if extensionType or extension are null - * @throws IllegalArgumentException if extension does not implement extensionType - */ - <T> void addExtension(Class<T> extensionType, T extension); - - /** - * Get a record of the metadata of this location. - * <p/> - * <p>Metadata records are used to record an audit trail of events relating to location usage - * (for billing purposes, for example). Implementations (and subclasses) should override this - * method to return information useful for this purpose.</p> - * - * @return - */ - public Map<String, String> toMetadataRecord(); - - /** - * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getLocalBag()} - */ - @Deprecated - ConfigBag getLocalConfigBag(); - - /** - * Returns all config, including that inherited from parents. - * - * This method does not respect {@link ConfigInheritance} and so usage is discouraged. - * - * @deprecated since 0.7.0; use {@link #config()}, such as {@code ((LocationInternal)location).config().getBag()} - */ - @Deprecated - ConfigBag getAllConfigBag(); - - /** - * Users are strongly discouraged from calling or overriding this method. - * It is for internal calls only, relating to persisting/rebinding entities. - * This method may change (or be removed) in a future release without notice. - */ - @Override - @Beta - RebindSupport<LocationMemento> getRebindSupport(); - - @Override - RelationSupportInternal<Location> relations(); - - ManagementContext getManagementContext(); -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationTypeSnapshot.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationTypeSnapshot.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationTypeSnapshot.java deleted file mode 100644 index 1c45da2..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/location/internal/LocationTypeSnapshot.java +++ /dev/null @@ -1,40 +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.internal; - -import java.util.Map; - -import org.apache.brooklyn.api.sensor.EnricherType; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.objs.BrooklynTypeSnapshot; - -public class LocationTypeSnapshot extends BrooklynTypeSnapshot implements EnricherType { - - private static final long serialVersionUID = 9150132836104748237L; - - LocationTypeSnapshot(String name, Map<String, ConfigKey<?>> configKeys) { - super(name, configKeys); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - return (obj instanceof LocationTypeSnapshot) && super.equals(obj); - } -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTags.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTags.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTags.java deleted file mode 100644 index 0ddc79a..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTags.java +++ /dev/null @@ -1,138 +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.mgmt; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.apache.brooklyn.util.collections.MutableList; -import org.codehaus.jackson.annotate.JsonIgnore; -import org.codehaus.jackson.annotate.JsonProperty; - -import com.google.common.annotations.Beta; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.collect.Lists; - -/** @since 0.7.0 some strongly typed tags for reference; note these may migrate elsewhere! */ -@Beta -public class BrooklynTags { - - public static final String YAML_SPEC_KIND = "yaml_spec"; - public static final String NOTES_KIND = "notes"; - - public static class NamedStringTag implements Serializable { - private static final long serialVersionUID = 7932098757009051348L; - @JsonProperty final String kind; - @JsonProperty final String contents; - public NamedStringTag(@JsonProperty("kind") String kind, @JsonProperty("contents") String contents) { - this.kind = kind; - this.contents = contents; - } - @Override - public String toString() { - return kind+"["+contents+"]"; - } - - public String getKind() { - return kind; - } - public String getContents() { - return contents; - } - } - - public static class ListTag<T> { - @JsonIgnore - final List<T> list; - - public ListTag(List<T> list) { - this.list = list; - } - - public List<T> getList() { - return list; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ListTag<?> that = (ListTag<?>) o; - return list == null ? that.list == null : list.equals(that.list); - } - - @Override - public int hashCode() { - return Objects.hashCode(list); - } - } - - public static class TraitsTag extends ListTag<String> { - public TraitsTag(List<Class<?>> interfaces) { - // The transformed list is a view, meaning that it references - // the instances list. This means that it will serialize - // the list of classes along with the anonymous function which - // is not what we want. Force eager evaluation instead, using - // a simple list, supported by {@link CatalogXmlSerializer}. - super(new ArrayList<String>( - Lists.transform(interfaces, new Function<Class<?>, String>() { - @Override public String apply(Class<?> input) { - return input.getName(); - } - }))); - } - - @JsonProperty("traits") - public List<String> getTraits() { - return super.list; - } - } - - public static NamedStringTag newYamlSpecTag(String contents) { - return new NamedStringTag(YAML_SPEC_KIND, contents); - } - - public static NamedStringTag newNotesTag(String contents) { - return new NamedStringTag(NOTES_KIND, contents); - } - - public static TraitsTag newTraitsTag(List<Class<?>> interfaces) { - return new TraitsTag(interfaces); - } - - public static NamedStringTag findFirst(String kind, Iterable<Object> tags) { - for (Object object: tags) { - if (object instanceof NamedStringTag && kind.equals(((NamedStringTag)object).kind)) - return (NamedStringTag) object; - } - return null; - } - - public static List<NamedStringTag> findAll(String kind, Iterable<Object> tags) { - List<NamedStringTag> result = MutableList.of(); - for (Object object: tags) { - if (object instanceof NamedStringTag && kind.equals(((NamedStringTag)object).kind)) - result.add( (NamedStringTag) object ); - } - return result; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTaskTags.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTaskTags.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTaskTags.java deleted file mode 100644 index 1fba49d..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTaskTags.java +++ /dev/null @@ -1,455 +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.mgmt; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.ByteArrayOutputStream; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -import org.apache.brooklyn.api.effector.Effector; -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.mgmt.ExecutionManager; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.api.mgmt.entitlement.EntitlementContext; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.core.task.TaskTags; -import org.apache.brooklyn.util.core.task.Tasks; -import org.apache.brooklyn.util.guava.Maybe; -import org.apache.brooklyn.util.javalang.MemoryUsageTracker; -import org.apache.brooklyn.util.stream.Streams; -import org.apache.brooklyn.util.text.StringEscapes.BashStringEscapes; -import org.apache.brooklyn.util.text.Strings; -import org.codehaus.jackson.annotate.JsonProperty; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.Beta; -import com.google.common.base.Functions; -import com.google.common.base.Objects; -import com.google.common.base.Preconditions; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableSet; - -/** Provides utilities for making Tasks easier to work with in Brooklyn. - * Main thing at present is to supply (and find) wrapped entities for tasks to understand the - * relationship of the entity to the task. - * TODO Longer term it would be better to remove 'tags' on Tasks and use a strongly typed context object. - * (Tags there are used mainly for determining who called it (caller), what they called it on (target entity), - * and what type of task it is (effector, schedule/sensor, etc).) - */ -public class BrooklynTaskTags extends TaskTags { - - private static final Logger log = LoggerFactory.getLogger(BrooklynTaskTags.WrappedEntity.class); - - /** Tag for tasks which are running on behalf of the management server, rather than any entity */ - public static final String BROOKLYN_SERVER_TASK_TAG = "BROOKLYN-SERVER"; - /** Tag for a task which represents an effector */ - public static final String EFFECTOR_TAG = "EFFECTOR"; - /** Tag for a task which *is* interesting, in contrast to {@link #TRANSIENT_TASK_TAG} */ - public static final String NON_TRANSIENT_TASK_TAG = "NON-TRANSIENT"; - /** indicates a task is transient, roughly that is to say it is uninteresting -- - * specifically this means it can be GC'd as soon as it is completed, - * and that it need not appear in some task lists; - * often used for framework lifecycle events and sensor polling */ - public static final String TRANSIENT_TASK_TAG = "TRANSIENT"; - - // ------------- entity tags ------------------------- - - public static class WrappedEntity { - public final String wrappingType; - public final Entity entity; - protected WrappedEntity(String wrappingType, Entity entity) { - Preconditions.checkNotNull(wrappingType); - Preconditions.checkNotNull(entity); - this.wrappingType = wrappingType; - this.entity = entity; - } - @Override - public String toString() { - return "Wrapped["+wrappingType+":"+entity+"]"; - } - @Override - public int hashCode() { - return Objects.hashCode(entity, wrappingType); - } - @Override - public boolean equals(Object obj) { - if (this==obj) return true; - if (!(obj instanceof WrappedEntity)) return false; - return - Objects.equal(entity, ((WrappedEntity)obj).entity) && - Objects.equal(wrappingType, ((WrappedEntity)obj).wrappingType); - } - } - - public static final String CONTEXT_ENTITY = "contextEntity"; - public static final String CALLER_ENTITY = "callerEntity"; - public static final String TARGET_ENTITY = "targetEntity"; - - public static WrappedEntity tagForContextEntity(Entity entity) { - return new WrappedEntity(CONTEXT_ENTITY, entity); - } - - public static WrappedEntity tagForCallerEntity(Entity entity) { - return new WrappedEntity(CALLER_ENTITY, entity); - } - - public static WrappedEntity tagForTargetEntity(Entity entity) { - return new WrappedEntity(TARGET_ENTITY, entity); - } - - public static Entity getWrappedEntityOfType(Task<?> t, String wrappingType) { - if (t==null) return null; - return getWrappedEntityOfType(t.getTags(), wrappingType); - } - public static Entity getWrappedEntityOfType(Collection<?> tags, String wrappingType) { - for (Object x: tags) - if ((x instanceof WrappedEntity) && ((WrappedEntity)x).wrappingType.equals(wrappingType)) - return ((WrappedEntity)x).entity; - return null; - } - - public static Entity getContextEntity(Task<?> task) { - return getWrappedEntityOfType(task, CONTEXT_ENTITY); - } - - public static Entity getTargetOrContextEntity(Task<?> t) { - if (t==null) return null; - Entity result = getWrappedEntityOfType(t, CONTEXT_ENTITY); - if (result!=null) return result; - result = getWrappedEntityOfType(t, TARGET_ENTITY); - if (result!=null) { - log.warn("Context entity found by looking at target entity tag, not context entity"); - return result; - } - - result = Tasks.tag(t, Entity.class, false); - if (result!=null) { - log.warn("Context entity found by looking at 'Entity' tag, not wrapped entity"); - } - return result; - } - - public static Set<Task<?>> getTasksInEntityContext(ExecutionManager em, Entity e) { - return em.getTasksWithTag(tagForContextEntity(e)); - } - - public static ManagementContext getManagementContext(Task<?> task) { - for (Object tag : task.getTags()) - if ((tag instanceof ManagementContext)) - return (ManagementContext) tag; - return null; - } - - // ------------- stream tags ------------------------- - - public static class WrappedStream { - public final String streamType; - public final Supplier<String> streamContents; - public final Supplier<Integer> streamSize; - protected WrappedStream(String streamType, Supplier<String> streamContents, Supplier<Integer> streamSize) { - Preconditions.checkNotNull(streamType); - Preconditions.checkNotNull(streamContents); - this.streamType = streamType; - this.streamContents = streamContents; - this.streamSize = streamSize != null ? streamSize : Suppliers.<Integer>ofInstance(streamContents.get().length()); - } - protected WrappedStream(String streamType, ByteArrayOutputStream stream) { - Preconditions.checkNotNull(streamType); - Preconditions.checkNotNull(stream); - this.streamType = streamType; - this.streamContents = Strings.toStringSupplier(stream); - this.streamSize = Streams.sizeSupplier(stream); - } - // fix for https://github.com/FasterXML/jackson-databind/issues/543 (which also applies to codehaus jackson) - @JsonProperty - public Integer getStreamSize() { - return streamSize.get(); - } - // there is a stream api so don't return everything unless explicitly requested! - @JsonProperty("streamContents") - public String getStreamContentsAbbreviated() { - return Strings.maxlenWithEllipsis(streamContents.get(), 80); - } - @Override - public String toString() { - return "Stream["+streamType+"/"+Strings.makeSizeString(streamSize.get())+"]"; - } - @Override - public int hashCode() { - return Objects.hashCode(streamContents, streamType); - } - @Override - public boolean equals(Object obj) { - if (!(obj instanceof WrappedStream)) return false; - return - Objects.equal(streamContents, ((WrappedStream)obj).streamContents) && - Objects.equal(streamType, ((WrappedStream)obj).streamType); - } - } - - public static final String STREAM_STDIN = "stdin"; - public static final String STREAM_STDOUT = "stdout"; - public static final String STREAM_STDERR = "stderr"; - /** not a stream, but inserted with the same mechanism */ - public static final String STREAM_ENV = "env"; - - private static final Maybe<ByteArrayOutputStream> STREAM_GARBAGE_COLLECTED_MAYBE = Maybe.of(Streams.byteArrayOfString("<contents-garbage-collected>")); - - /** creates a tag suitable for marking a stream available on a task */ - public static WrappedStream tagForStream(String streamType, ByteArrayOutputStream stream) { - return new WrappedStream(streamType, stream); - } - /** creates a tag suitable for marking a stream available on a task, but which might be GC'd */ - public static WrappedStream tagForStreamSoft(String streamType, ByteArrayOutputStream stream) { - MemoryUsageTracker.SOFT_REFERENCES.track(stream, stream.size()); - Maybe<ByteArrayOutputStream> weakStream = Maybe.softThen(stream, STREAM_GARBAGE_COLLECTED_MAYBE); - return new WrappedStream(streamType, - Suppliers.compose(Functions.toStringFunction(), weakStream), - Suppliers.compose(Streams.sizeFunction(), weakStream)); - } - - /** creates a tag suitable for marking a stream available on a task */ - public static WrappedStream tagForStream(String streamType, Supplier<String> contents, Supplier<Integer> size) { - return new WrappedStream(streamType, contents, size); - } - - /** creates a tag suitable for attaching a snapshot of an environment var map as a "stream" on a task; - * mainly for use with STREAM_ENV */ - public static WrappedStream tagForEnvStream(String streamEnv, Map<?, ?> env) { - StringBuilder sb = new StringBuilder(); - for (Map.Entry<?,?> kv: env.entrySet()) { - Object val = kv.getValue(); - sb.append(kv.getKey()+"=" + - (val!=null ? BashStringEscapes.wrapBash(val.toString()) : "") + "\n"); - } - return BrooklynTaskTags.tagForStream(BrooklynTaskTags.STREAM_ENV, Streams.byteArrayOfString(sb.toString())); - } - - /** returns the set of tags indicating the streams available on a task */ - public static Set<WrappedStream> streams(Task<?> task) { - Set<WrappedStream> result = new LinkedHashSet<BrooklynTaskTags.WrappedStream>(); - for (Object tag: task.getTags()) { - if (tag instanceof WrappedStream) { - result.add((WrappedStream)tag); - } - } - return ImmutableSet.copyOf(result); - } - - /** returns the tag for the indicated stream, or null */ - public static WrappedStream stream(Task<?> task, String streamType) { - if (task==null) return null; - for (Object tag: task.getTags()) - if ((tag instanceof WrappedStream) && ((WrappedStream)tag).streamType.equals(streamType)) - return (WrappedStream)tag; - return null; - } - - // ------ misc - - public static void setInessential(Task<?> task) { addTagDynamically(task, INESSENTIAL_TASK); } - public static void setTransient(Task<?> task) { addTagDynamically(task, TRANSIENT_TASK_TAG); } - public static boolean isTransient(Task<?> task) { - if (hasTag(task, TRANSIENT_TASK_TAG)) return true; - if (hasTag(task, NON_TRANSIENT_TASK_TAG)) return false; - if (task.getSubmittedByTask()!=null) return isTransient(task.getSubmittedByTask()); - return false; - } - public static boolean isSubTask(Task<?> task) { return hasTag(task, SUB_TASK_TAG); } - public static boolean isEffectorTask(Task<?> task) { return hasTag(task, EFFECTOR_TAG); } - - // ------ effector tags - - public static class EffectorCallTag { - protected final String entityId; - protected final String effectorName; - protected transient ConfigBag parameters; - protected EffectorCallTag(String entityId, String effectorName, ConfigBag parameters) { - this.entityId = checkNotNull(entityId, "entityId"); - this.effectorName = checkNotNull(effectorName, "effectorName"); - this.parameters = parameters; - } - public String toString() { - return EFFECTOR_TAG+"@"+entityId+":"+effectorName; - } - @Override - public int hashCode() { - return Objects.hashCode(entityId, effectorName); - } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof EffectorCallTag)) return false; - EffectorCallTag other = (EffectorCallTag) obj; - return - Objects.equal(entityId, other.entityId) && - Objects.equal(effectorName, other.effectorName); - } - public String getEntityId() { - return entityId; - } - public String getEffectorName() { - return effectorName; - } - public ConfigBag getParameters() { - return parameters; - } - public void setParameters(ConfigBag parameters) { - this.parameters = parameters; - } - } - - public static EffectorCallTag tagForEffectorCall(Entity entity, String effectorName, ConfigBag parameters) { - return new EffectorCallTag(entity.getId(), effectorName, parameters); - } - - /** - * checks if the given task is part of the given effector call on the given entity; - * @param task the task to check (false if null) - * @param entity the entity where this effector task should be running, or any entity if null - * @param effector the effector (matching name) where this task should be running, or any effector if null - * @param allowNestedEffectorCalls whether to match ancestor effector calls, e.g. if eff1 calls eff2, - * and we are checking eff2, whether to match eff1 - * @return whether the given task is part of the given effector - */ - public static boolean isInEffectorTask(Task<?> task, @Nullable Entity entity, @Nullable Effector<?> effector, boolean allowNestedEffectorCalls) { - Task<?> t = task; - while (t!=null) { - Set<Object> tags = t.getTags(); - if (tags.contains(EFFECTOR_TAG)) { - for (Object tag: tags) { - if (tag instanceof EffectorCallTag) { - EffectorCallTag et = (EffectorCallTag)tag; - if (entity!=null && !et.getEntityId().equals(entity.getId())) - continue; - if (effector!=null && !et.getEffectorName().equals(effector.getName())) - continue; - return true; - } - } - if (!allowNestedEffectorCalls) return false; - } - t = t.getSubmittedByTask(); - } - return false; - } - - /** - * finds the task up the {@code child} hierarchy handling the {@code effector} call, - * returns null if one doesn't exist. - */ - @Beta - public static Task<?> getClosestEffectorTask(Task<?> child, Effector<?> effector) { - Task<?> t = child; - while (t != null) { - Set<Object> tags = t.getTags(); - if (tags.contains(EFFECTOR_TAG)) { - for (Object tag: tags) { - if (tag instanceof EffectorCallTag) { - EffectorCallTag et = (EffectorCallTag) tag; - if (effector != null && !et.getEffectorName().equals(effector.getName())) - continue; - return t; - } - } - } - t = t.getSubmittedByTask(); - } - return null; - } - - /** finds the first {@link EffectorCallTag} tag on this tag, or optionally on submitters, or null */ - public static EffectorCallTag getEffectorCallTag(Task<?> task, boolean recurse) { - Task<?> t = task; - while (t!=null) { - for (Object tag: t.getTags()) { - if (tag instanceof EffectorCallTag) - return (EffectorCallTag)tag; - } - if (!recurse) - return null; - t = t.getSubmittedByTask(); - } - return null; - } - - /** finds the first {@link EffectorCallTag} tag on this tag or a submitter, and returns the effector name */ - public static String getEffectorName(Task<?> task) { - EffectorCallTag result = getEffectorCallTag(task, true); - return (result == null) ? null : result.getEffectorName(); - } - - public static ConfigBag getEffectorParameters(Task<?> task) { - EffectorCallTag result = getEffectorCallTag(task, true); - return (result == null) ? null : result.getParameters(); - } - - public static ConfigBag getCurrentEffectorParameters() { - return getEffectorParameters(Tasks.current()); - } - - public static void setEffectorParameters(Task<?> task, ConfigBag parameters) { - EffectorCallTag result = getEffectorCallTag(task, true); - if (result == null) { - throw new IllegalStateException("No EffectorCallTag found, is the task an effector? Task: " + task); - } - result.setParameters(parameters); - } - // ---------------- entitlement tags ---------------- - - public static class EntitlementTag { - private EntitlementContext entitlementContext; - } - - public static EntitlementContext getEntitlement(Task<?> task) { - if (task==null) return null; - return getEntitlement(task.getTags()); - } - - public static EntitlementContext getEntitlement(Collection<?> tags) { - if (tags==null) return null; - for (Object tag: tags) { - if (tag instanceof EntitlementTag) { - return ((EntitlementTag)tag).entitlementContext; - } - } - return null; - } - - public static EntitlementContext getEntitlement(EntitlementTag tag) { - if (tag==null) return null; - return tag.entitlementContext; - } - - public static EntitlementTag tagForEntitlement(EntitlementContext context) { - EntitlementTag tag = new EntitlementTag(); - tag.entitlementContext = context; - return tag; - } - -} http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/d03f254b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTasks.java ---------------------------------------------------------------------- diff --git a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTasks.java b/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTasks.java deleted file mode 100644 index e38c34f..0000000 --- a/brooklyn-server/core/src/main/java/org/apache/brooklyn/core/mgmt/BrooklynTasks.java +++ /dev/null @@ -1,25 +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.mgmt; - - -/** @deprecated since 0.7.0 use {@link BrooklynTaskTags} */ -@Deprecated -public class BrooklynTasks extends BrooklynTaskTags { -}
