http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortForwardManager.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortForwardManager.java b/core/src/main/java/brooklyn/location/access/PortForwardManager.java deleted file mode 100644 index 71c3974..0000000 --- a/core/src/main/java/brooklyn/location/access/PortForwardManager.java +++ /dev/null @@ -1,327 +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 brooklyn.location.access; - -import brooklyn.config.ConfigKey; -import brooklyn.entity.basic.ConfigKeys; -import brooklyn.location.Location; -import com.google.common.annotations.Beta; -import com.google.common.base.Objects; -import com.google.common.base.Predicate; -import com.google.common.net.HostAndPort; - -import java.util.Collection; - -/** - * Acts as a registry for existing port mappings (e.g. the public endpoints for accessing specific - * ports on private VMs). This could be using DNAT, or iptables port-forwarding, or Docker port-mapping - * via the host, or any other port mapping approach. - * - * Also controls the allocation of ports via {@link #acquirePublicPort(String)} - * (e.g. for port-mapping with DNAT, then which port to use for the public side). - * - * Implementations typically will not know anything about what the firewall/IP actually is, they just - * handle a unique identifier for it. - * - * To use, see {@link PortForwardManagerLocationResolver}, with code such as - * {@code managementContext.getLocationRegistry().resolve("portForwardManager(scope=global)")}. - * - * @see PortForwardManagerImpl for implementation notes and considerations. - */ -@Beta -public interface PortForwardManager extends Location { - - @Beta - class AssociationMetadata { - private final String publicIpId; - private final HostAndPort publicEndpoint; - private final Location location; - private final int privatePort; - - /** - * Users are discouraged from calling this constructor; the signature may change in future releases. - * Instead, instances will be created automatically by Brooklyn to be passed to the - * {@link AssociationListener#onAssociationCreated(AssociationMetadata)} method. - */ - public AssociationMetadata(String publicIpId, HostAndPort publicEndpoint, Location location, int privatePort) { - this.publicIpId = publicIpId; - this.publicEndpoint = publicEndpoint; - this.location = location; - this.privatePort = privatePort; - } - - public String getPublicIpId() { - return publicIpId; - } - - public HostAndPort getPublicEndpoint() { - return publicEndpoint; - } - - public Location getLocation() { - return location; - } - - public int getPrivatePort() { - return privatePort; - } - - public String toString() { - return Objects.toStringHelper(this) - .add("publicIpId", publicIpId) - .add("publicEndpoint", publicEndpoint) - .add("location", location) - .add("privatePort", privatePort) - .toString(); - } - } - - @Beta - interface AssociationListener { - void onAssociationCreated(AssociationMetadata metadata); - void onAssociationDeleted(AssociationMetadata metadata); - } - - /** - * The intention is that there is one PortForwardManager instance per "scope". If you - * use global, then it will be a shared instance (for that management context). If you - * pass in your own name (e.g. "docker-fjie3") then it will shared with just any other - * places that use that same location spec (e.g. {@code portForwardManager(scope=docker-fjie3)}). - */ - // TODO Note: using name "scope" rather than "brooklyn.portForwardManager.scope" so that location spec - // "portForwardManager(scope=global)" works, rather than having to do - // portForwardManager(brooklyn.portForwardManager.scope=global). - // The config being read by the PortForwardManagerLocationResolver doesn't respect @SetFromFlag("scope"). - public static final ConfigKey<String> SCOPE = ConfigKeys.newStringConfigKey( - "scope", - "The scope that this applies to, defaulting to global", - "global"); - - @Beta - public static final ConfigKey<Integer> PORT_FORWARD_MANAGER_STARTING_PORT = ConfigKeys.newIntegerConfigKey( - "brooklyn.portForwardManager.startingPort", - "The starting port for assigning port numbers, such as for DNAT", - 11000); - - public String getScope(); - - /** - * Reserves a unique public port on the given publicIpId. - * <p> - * Often followed by {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - * to enable {@link #lookup(String, int)} or {@link #lookup(Location, int)} respectively. - */ - public int acquirePublicPort(String publicIpId); - - /** - * Records a location and private port against a public endpoint (ip and port), - * to support {@link #lookup(Location, int)}. - * <p> - * Superfluous if {@link #acquirePublicPort(String, Location, int)} was used, - * but strongly recommended if {@link #acquirePublicPortExplicit(String, int)} was used - * e.g. if the location is not known ahead of time. - */ - public void associate(String publicIpId, HostAndPort publicEndpoint, Location l, int privatePort); - - /** - * Records a mapping for publicIpId:privatePort to a public endpoint, such that it can - * subsequently be looked up using {@link #lookup(String, int)}. - */ - public void associate(String publicIpId, HostAndPort publicEndpoint, int privatePort); - - /** - * Registers a listener, which will be notified each time a new port mapping is associated. See {@link #associate(String, HostAndPort, int)} - * and {@link #associate(String, HostAndPort, Location, int)}. - */ - @Beta - public void addAssociationListener(AssociationListener listener, Predicate<? super AssociationMetadata> filter); - - @Beta - public void removeAssociationListener(AssociationListener listener); - - /** - * Returns the public ip hostname and public port for use contacting the given endpoint. - * <p> - * Will return null if: - * <ul> - * <li>No publicPort is associated with this location and private port. - * <li>No publicIpId is associated with this location and private port. - * <li>No publicIpHostname is recorded against the associated publicIpId. - * </ul> - * Conceivably this may have to be access-location specific. - * - * @see #recordPublicIpHostname(String, String) - */ - public HostAndPort lookup(Location l, int privatePort); - - /** - * Returns the public endpoint (host and port) for use contacting the given endpoint. - * - * Expects a previous call to {@link #associate(String, HostAndPort, int)}, to register - * the endpoint. - * - * Will return null if there has not been a public endpoint associated with this pairing. - */ - public HostAndPort lookup(String publicIpId, int privatePort); - - /** - * Clears the given port mapping, returning true if there was a match. - */ - public boolean forgetPortMapping(String publicIpId, int publicPort); - - /** - * Clears the port mappings associated with the given location, returning true if there were any matches. - */ - public boolean forgetPortMappings(Location location); - - /** - * Clears the port mappings associated with the given publicIpId, returning true if there were any matches. - */ - public boolean forgetPortMappings(String publicIpId); - - public String toVerboseString(); - - - /////////////////////////////////////////////////////////////////////////////////// - // Deprecated - /////////////////////////////////////////////////////////////////////////////////// - - /** - * Reserves a unique public port for the purpose of forwarding to the given target, - * associated with a given location for subsequent lookup purpose. - * <p> - * If already allocated, returns the previously allocated. - * - * @deprecated since 0.7.0; use {@link #acquirePublicPort(String)}, and then use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Deprecated - public int acquirePublicPort(String publicIpId, Location l, int privatePort); - - /** - * Returns old mapping if it existed, null if it is new. - * - * @deprecated since 0.7.0; use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Deprecated - public PortMapping acquirePublicPortExplicit(String publicIpId, int port); - - /** - * Records a location and private port against a publicIp and public port, - * to support {@link #lookup(Location, int)}. - * <p> - * Superfluous if {@link #acquirePublicPort(String, Location, int)} was used, - * but strongly recommended if {@link #acquirePublicPortExplicit(String, int)} was used - * e.g. if the location is not known ahead of time. - * - * @deprecated Use {@link #associate(String, HostAndPort, Location, int)} - */ - @Deprecated - public void associate(String publicIpId, int publicPort, Location l, int privatePort); - - /** - * Records a public hostname or address to be associated with the given publicIpId for lookup purposes. - * <p> - * Conceivably this may have to be access-location specific. - * - * @deprecated Use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Deprecated - public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress); - - /** - * Returns a recorded public hostname or address. - * - * @deprecated Use {@link #lookup(String, int)} or {@link #lookup(Location, int)} - */ - @Deprecated - public String getPublicIpHostname(String publicIpId); - - /** - * Clears a previous call to {@link #recordPublicIpHostname(String, String)}. - * - * @deprecated Use {@link #forgetPortMapping(String, int)} or {@link #forgetPortMappings(Location)} - */ - @Deprecated - public boolean forgetPublicIpHostname(String publicIpId); - - /** - * Returns true if this implementation is a client which is immutable/safe for serialization - * i.e. it delegates to something on an entity or location elsewhere. - * - * @deprecated since 0.7.0; no need to separate client-proxy from impl - */ - @Deprecated - public boolean isClient(); - - - /////////////////////////////////////////////////////////////////////////////////// - // Deprecated; just internal - /////////////////////////////////////////////////////////////////////////////////// - - /** - * Returns the port mapping for a given publicIpId and public port. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public PortMapping getPortMappingWithPublicSide(String publicIpId, int publicPort); - - /** - * Returns the subset of port mappings associated with a given public IP ID. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public Collection<PortMapping> getPortMappingWithPublicIpId(String publicIpId); - - /** - * @see {@link #forgetPortMapping(String, int)} and {@link #forgetPortMappings(Location)} - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public boolean forgetPortMapping(PortMapping m); - - /** - * Returns the public host and port for use accessing the given mapping. - * <p> - * Conceivably this may have to be access-location specific. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public HostAndPort getPublicHostAndPort(PortMapping m); - - /** - * Returns the subset of port mappings associated with a given location. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public Collection<PortMapping> getLocationPublicIpIds(Location l); - - /** - * Returns the mapping to a given private port, or null if none. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Deprecated - public PortMapping getPortMappingWithPrivateSide(Location l, int privatePort); - -}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortForwardManagerAuthority.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortForwardManagerAuthority.java b/core/src/main/java/brooklyn/location/access/PortForwardManagerAuthority.java deleted file mode 100644 index 796328d..0000000 --- a/core/src/main/java/brooklyn/location/access/PortForwardManagerAuthority.java +++ /dev/null @@ -1,47 +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 brooklyn.location.access; - - -import org.apache.brooklyn.api.entity.Entity; - -import brooklyn.entity.basic.EntityInternal; - -/** - * @deprecated since 0.7.0; use {@link PortForwardManagerImpl} - */ -@Deprecated -public class PortForwardManagerAuthority extends PortForwardManagerImpl { - private Entity owningEntity; - - public PortForwardManagerAuthority() { - } - - public PortForwardManagerAuthority(Entity owningEntity) { - this.owningEntity = owningEntity; - } - - protected void onChanged() { - if (owningEntity != null) { - ((EntityInternal) owningEntity).requestPersist(); - } else { - super.onChanged(); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortForwardManagerClient.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortForwardManagerClient.java b/core/src/main/java/brooklyn/location/access/PortForwardManagerClient.java deleted file mode 100644 index 5013711..0000000 --- a/core/src/main/java/brooklyn/location/access/PortForwardManagerClient.java +++ /dev/null @@ -1,406 +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 brooklyn.location.access; - -import java.util.Collection; -import java.util.Map; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.event.AttributeSensor; - -import brooklyn.config.ConfigKey; -import brooklyn.config.ConfigKey.HasConfigKey; -import brooklyn.location.Location; -import brooklyn.util.exceptions.Exceptions; - -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.net.HostAndPort; - -/** - * @deprecated since 0.7.0; just use the {@link PortForwardManager}, or a direct reference to its impl {@link PortForwardManagerImpl} - */ -@Deprecated -public class PortForwardManagerClient implements PortForwardManager { - - private static final long serialVersionUID = -295204304305332895L; - - protected final Supplier<PortForwardManager> delegateSupplier; - private transient volatile PortForwardManager _delegate; - - protected PortForwardManagerClient(Supplier<PortForwardManager> supplier) { - this.delegateSupplier = supplier; - } - - /** creates an instance given a supplier; - * the supplier should be brooklyn-persistable, that is to say - * references should be in terms of entities/locations - * which can retrieve an authoritative source even under cloning */ - public static PortForwardManager fromSupplier(Supplier<PortForwardManager> supplier) { - return new PortForwardManagerClient(supplier); - } - - /** creates an instance given an entity and an interface method it implements to retrieve the PortForwardManager */ - public static PortForwardManager fromMethodOnEntity(final Entity entity, final String getterMethodOnEntity) { - Preconditions.checkNotNull(entity); - Preconditions.checkNotNull(getterMethodOnEntity); - return new PortForwardManagerClient(new Supplier<PortForwardManager>() { - @Override - public PortForwardManager get() { - PortForwardManager result; - try { - result = (PortForwardManager) entity.getClass().getMethod(getterMethodOnEntity).invoke(entity); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - throw new IllegalStateException("Cannot invoke "+getterMethodOnEntity+" on "+entity+" ("+entity.getClass()+"): "+e, e); - } - if (result==null) - throw new IllegalStateException("No PortForwardManager available via "+getterMethodOnEntity+" on "+entity+" (returned null)"); - return result; - } - }); - } - - /** creates an instance given an entity and {@link AttributeSensor} to retrieve the PortForwardManager */ - public static PortForwardManager fromAttributeOnEntity(final Entity entity, final AttributeSensor<PortForwardManager> attributeOnEntity) { - Preconditions.checkNotNull(entity); - Preconditions.checkNotNull(attributeOnEntity); - return new PortForwardManagerClient(new Supplier<PortForwardManager>() { - @Override - public PortForwardManager get() { - PortForwardManager result = entity.getAttribute(attributeOnEntity); - if (result==null) - throw new IllegalStateException("No PortForwardManager available via "+attributeOnEntity+" on "+entity+" (returned null)"); - return result; - } - }); - } - - protected PortForwardManager getDelegate() { - if (_delegate==null) { - _delegate = delegateSupplier.get(); - } - return _delegate; - } - - @Override - public int acquirePublicPort(String publicIpId) { - return getDelegate().acquirePublicPort(publicIpId); - } - - @Override - public void associate(String publicIpId, HostAndPort publicEndpoint, Location l, int privatePort) { - getDelegate().associate(publicIpId, publicEndpoint, l, privatePort); - } - - @Override - public void associate(String publicIpId, HostAndPort publicEndpoint, int privatePort) { - getDelegate().associate(publicIpId, publicEndpoint, privatePort); - } - - @Override - public HostAndPort lookup(Location l, int privatePort) { - return getDelegate().lookup(l, privatePort); - } - - @Override - public HostAndPort lookup(String publicIpId, int privatePort) { - return getDelegate().lookup(publicIpId, privatePort); - } - - @Override - public boolean forgetPortMapping(String publicIpId, int publicPort) { - return getDelegate().forgetPortMapping(publicIpId, publicPort); - } - - @Override - public boolean forgetPortMappings(Location location) { - return getDelegate().forgetPortMappings(location); - } - - @Override - public boolean forgetPortMappings(String publicIpId) { - return getDelegate().forgetPortMappings(publicIpId); - } - - @Override - public String getId() { - return getDelegate().getId(); - } - - @Override - public String getScope() { - return getDelegate().getScope(); - } - - @Override - public void addAssociationListener(AssociationListener listener, Predicate<? super AssociationMetadata> filter) { - getDelegate().addAssociationListener(listener, filter); - } - - @Override - public void removeAssociationListener(AssociationListener listener) { - getDelegate().removeAssociationListener(listener); - } - - @Override - public String toVerboseString() { - return getClass().getName()+"[wrapping="+getDelegate().toVerboseString()+"]"; - } - - /////////////////////////////////////////////////////////////////////////////////// - // Deprecated - /////////////////////////////////////////////////////////////////////////////////// - - /** - * Reserves a unique public port for the purpose of forwarding to the given target, - * associated with a given location for subsequent lookup purpose. - * <p> - * If already allocated, returns the previously allocated. - * - * @deprecated since 0.7.0; use {@link #acquirePublicPort(String)}, and then use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Override - @Deprecated - public int acquirePublicPort(String publicIpId, Location l, int privatePort) { - return getDelegate().acquirePublicPort(publicIpId, l, privatePort); - } - - /** - * Returns old mapping if it existed, null if it is new. - * - * @deprecated since 0.7.0; use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Override - @Deprecated - public PortMapping acquirePublicPortExplicit(String publicIpId, int publicPort) { - return getDelegate().acquirePublicPortExplicit(publicIpId, publicPort); - } - - /** - * Records a location and private port against a publicIp and public port, - * to support {@link #lookup(Location, int)}. - * <p> - * Superfluous if {@link #acquirePublicPort(String, Location, int)} was used, - * but strongly recommended if {@link #acquirePublicPortExplicit(String, int)} was used - * e.g. if the location is not known ahead of time. - * - * @deprecated Use {@link #associate(String, HostAndPort, Location, int)} - */ - @Override - @Deprecated - public void associate(String publicIpId, int publicPort, Location l, int privatePort) { - getDelegate().associate(publicIpId, publicPort, l, privatePort); - } - - /** - * Records a public hostname or address to be associated with the given publicIpId for lookup purposes. - * <p> - * Conceivably this may have to be access-location specific. - * - * @deprecated Use {@link #associate(String, HostAndPort, int)} or {@link #associate(String, HostAndPort, Location, int)} - */ - @Override - @Deprecated - public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { - getDelegate().recordPublicIpHostname(publicIpId, hostnameOrPublicIpAddress); - } - - /** - * Returns a recorded public hostname or address. - * - * @deprecated Use {@link #lookup(String, int)} or {@link #lookup(Location, int)} - */ - @Override - @Deprecated - public String getPublicIpHostname(String publicIpId) { - return getDelegate().getPublicIpHostname(publicIpId); - } - - /** - * Clears a previous call to {@link #recordPublicIpHostname(String, String)}. - * - * @deprecated Use {@link #forgetPortMapping(String, int)} or {@link #forgetPortMapping(Location, int)} - */ - @Override - @Deprecated - public boolean forgetPublicIpHostname(String publicIpId) { - return getDelegate().forgetPublicIpHostname(publicIpId); - } - - @Override - @Deprecated - public boolean isClient() { - return true; - } - - - /////////////////////////////////////////////////////////////////////////////////// - // Deprecated; just internal - /////////////////////////////////////////////////////////////////////////////////// - - /** - * Returns the port mapping for a given publicIpId and public port. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public PortMapping getPortMappingWithPublicSide(String publicIpId, int publicPort) { - return getDelegate().getPortMappingWithPublicSide(publicIpId, publicPort); - } - - /** - * Returns the subset of port mappings associated with a given public IP ID. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public Collection<PortMapping> getPortMappingWithPublicIpId(String publicIpId) { - return getDelegate().getPortMappingWithPublicIpId(publicIpId); - } - - /** - * @see #forgetPortMapping(String, int) - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public boolean forgetPortMapping(PortMapping m) { - return getDelegate().forgetPortMapping(m); - } - - /** - * Returns the public host and port for use accessing the given mapping. - * <p> - * Conceivably this may have to be access-location specific. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public HostAndPort getPublicHostAndPort(PortMapping m) { - return getDelegate().getPublicHostAndPort(m); - } - - /** - * Returns the subset of port mappings associated with a given location. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public Collection<PortMapping> getLocationPublicIpIds(Location l) { - return getDelegate().getLocationPublicIpIds(l); - } - - /** - * Returns the mapping to a given private port, or null if none. - * - * @deprecated since 0.7.0; this method will be internal only - */ - @Override - @Deprecated - public PortMapping getPortMappingWithPrivateSide(Location l, int privatePort) { - return getDelegate().getPortMappingWithPrivateSide(l, privatePort); - } - - @Override - public String toString() { - return getClass().getName()+"[id="+getId()+"]"; - } - - @Override - public String getDisplayName() { - return getDelegate().getDisplayName(); - } - - @Override - public Location getParent() { - return getDelegate().getParent(); - } - - @Override - public Collection<Location> getChildren() { - return getDelegate().getChildren(); - } - - @Override - public void setParent(Location newParent) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsLocation(Location potentialDescendent) { - return getDelegate().containsLocation(potentialDescendent); - } - - @Override - public <T> T getConfig(ConfigKey<T> key) { - return getDelegate().getConfig(key); - } - - @Override - public <T> T getConfig(HasConfigKey<T> key) { - return getDelegate().getConfig(key); - } - - @Override - public boolean hasConfig(ConfigKey<?> key, boolean includeInherited) { - return getDelegate().hasConfig(key, includeInherited); - } - - @Override - public Map<String, Object> getAllConfig(boolean includeInherited) { - return getDelegate().getAllConfig(includeInherited); - } - - @Override - public boolean hasExtension(Class<?> extensionType) { - return getDelegate().hasExtension(extensionType); - } - - @Override - public <T> T getExtension(Class<T> extensionType) { - return getDelegate().getExtension(extensionType); - } - - @Override - public String getCatalogItemId() { - return getDelegate().getCatalogItemId(); - } - - @Override - public TagSupport tags() { - return getDelegate().tags(); - } - - @Override - public <T> T setConfig(ConfigKey<T> key, T val) { - return getDelegate().setConfig(key, val); - } - - @Override - public ConfigurationSupport config() { - return getDelegate().config(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortForwardManagerImpl.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortForwardManagerImpl.java b/core/src/main/java/brooklyn/location/access/PortForwardManagerImpl.java deleted file mode 100644 index 75de91f..0000000 --- a/core/src/main/java/brooklyn/location/access/PortForwardManagerImpl.java +++ /dev/null @@ -1,506 +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 brooklyn.location.access; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.brooklyn.api.entity.rebind.RebindContext; -import org.apache.brooklyn.api.entity.rebind.RebindSupport; -import org.apache.brooklyn.mementos.LocationMemento; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.entity.rebind.BasicLocationRebindSupport; -import brooklyn.location.Location; -import brooklyn.location.basic.AbstractLocation; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.exceptions.Exceptions; - -import com.google.common.base.Objects.ToStringHelper; -import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.net.HostAndPort; - -/** - * - * @author aled - * - * TODO This implementation is not efficient, and currently has a cap of about 50000 rules. - * Need to improve the efficiency and scale. - * A quick win could be to use a different portReserved counter for each publicIpId, - * when calling acquirePublicPort? - * - * TODO Callers need to be more careful in acquirePublicPort for which ports are actually in use. - * If multiple apps sharing the same public-ip (e.g. in the same vcloud-director vOrg) then they - * must not allocate the same public port (e.g. ensure they share the same PortForwardManager - * by using the same scope in - * {@code managementContext.getLocationRegistry().resolve("portForwardManager(scope=global)")}. - * However, this still doesn't check if the port is *actually* available. For example, if a - * different Brooklyn instance is also deploying there then we can get port conflicts, or if - * some ports in that range are already in use (e.g. due to earlier dev/test runs) then this - * will not be respected. Callers should probably figure out the port number themselves, but - * that also leads to concurrency issues. - * - * TODO The publicIpId means different things to different callers: - * <ul> - * <li> In acquirePublicPort() it is (often?) an identifier of the actual public ip. - * <li> In later calls to associate(), it is (often?) an identifier for the target machine - * such as the jcloudsMachine.getJcloudsId(). - * </ul> - */ -@SuppressWarnings("serial") -public class PortForwardManagerImpl extends AbstractLocation implements PortForwardManager { - - private static final Logger log = LoggerFactory.getLogger(PortForwardManagerImpl.class); - - protected final Map<String,PortMapping> mappings = new LinkedHashMap<String,PortMapping>(); - - private final Map<AssociationListener, Predicate<? super AssociationMetadata>> associationListeners = new ConcurrentHashMap<AssociationListener, Predicate<? super AssociationMetadata>>(); - - @Deprecated - protected final Map<String,String> publicIpIdToHostname = new LinkedHashMap<String,String>(); - - // horrible hack -- see javadoc above - private final AtomicInteger portReserved = new AtomicInteger(11000); - - private final Object mutex = new Object(); - - public PortForwardManagerImpl() { - super(); - if (isLegacyConstruction()) { - log.warn("Deprecated construction of "+PortForwardManagerImpl.class.getName()+"; instead use location resolver"); - } - } - - @Override - public void init() { - super.init(); - Integer portStartingPoint; - Object rawPort = getAllConfigBag().getStringKey(PORT_FORWARD_MANAGER_STARTING_PORT.getName()); - if (rawPort != null) { - portStartingPoint = getConfig(PORT_FORWARD_MANAGER_STARTING_PORT); - } else { - portStartingPoint = getManagementContext().getConfig().getConfig(PORT_FORWARD_MANAGER_STARTING_PORT); - } - portReserved.set(portStartingPoint); - log.debug(this+" set initial port to "+portStartingPoint); - } - - // TODO Need to use attributes for these so they are persisted (once a location is an entity), - // rather than this deprecated approach of custom fields. - @Override - public RebindSupport<LocationMemento> getRebindSupport() { - return new BasicLocationRebindSupport(this) { - @Override public LocationMemento getMemento() { - Map<String, PortMapping> mappingsCopy; - Map<String,String> publicIpIdToHostnameCopy; - synchronized (mutex) { - mappingsCopy = MutableMap.copyOf(mappings); - publicIpIdToHostnameCopy = MutableMap.copyOf(publicIpIdToHostname); - } - return getMementoWithProperties(MutableMap.<String,Object>of( - "mappings", mappingsCopy, - "portReserved", portReserved.get(), - "publicIpIdToHostname", publicIpIdToHostnameCopy)); - } - @Override - protected void doReconstruct(RebindContext rebindContext, LocationMemento memento) { - super.doReconstruct(rebindContext, memento); - mappings.putAll( Preconditions.checkNotNull((Map<String, PortMapping>) memento.getCustomField("mappings"), "mappings was not serialized correctly")); - portReserved.set( (Integer)memento.getCustomField("portReserved")); - publicIpIdToHostname.putAll( Preconditions.checkNotNull((Map<String, String>)memento.getCustomField("publicIpIdToHostname"), "publicIpIdToHostname was not serialized correctly") ); - } - }; - } - - @Override - public int acquirePublicPort(String publicIpId) { - int port; - synchronized (mutex) { - // far too simple -- see javadoc above - port = getNextPort(); - - // TODO When delete deprecated code, stop registering PortMapping until associate() is called - PortMapping mapping = new PortMapping(publicIpId, port, null, -1); - log.debug(this+" allocating public port "+port+" on "+publicIpId+" (no association info yet)"); - - mappings.put(makeKey(publicIpId, port), mapping); - } - onChanged(); - return port; - } - - protected int getNextPort() { - // far too simple -- see javadoc above - return portReserved.getAndIncrement(); - } - - @Override - public void associate(String publicIpId, HostAndPort publicEndpoint, Location l, int privatePort) { - associateImpl(publicIpId, publicEndpoint, l, privatePort); - emitAssociationCreatedEvent(publicIpId, publicEndpoint, l, privatePort); - } - - @Override - public void associate(String publicIpId, HostAndPort publicEndpoint, int privatePort) { - associateImpl(publicIpId, publicEndpoint, null, privatePort); - emitAssociationCreatedEvent(publicIpId, publicEndpoint, null, privatePort); - } - - protected void associateImpl(String publicIpId, HostAndPort publicEndpoint, Location l, int privatePort) { - synchronized (mutex) { - String publicIp = publicEndpoint.getHostText(); - int publicPort = publicEndpoint.getPort(); - recordPublicIpHostname(publicIpId, publicIp); - PortMapping mapping = new PortMapping(publicIpId, publicEndpoint, l, privatePort); - PortMapping oldMapping = getPortMappingWithPublicSide(publicIpId, publicPort); - log.debug(this+" associating public "+publicEndpoint+" on "+publicIpId+" with private port "+privatePort+" at "+l+" ("+mapping+")" - +(oldMapping == null ? "" : " (overwriting "+oldMapping+" )")); - mappings.put(makeKey(publicIpId, publicPort), mapping); - } - onChanged(); - } - - private void emitAssociationCreatedEvent(String publicIpId, HostAndPort publicEndpoint, Location location, int privatePort) { - AssociationMetadata metadata = new AssociationMetadata(publicIpId, publicEndpoint, location, privatePort); - for (Map.Entry<AssociationListener, Predicate<? super AssociationMetadata>> entry : associationListeners.entrySet()) { - if (entry.getValue().apply(metadata)) { - try { - entry.getKey().onAssociationCreated(metadata); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - log.warn("Exception thrown when emitting association creation event " + metadata, e); - } - } - } - } - - @Override - public HostAndPort lookup(Location l, int privatePort) { - synchronized (mutex) { - for (PortMapping m: mappings.values()) { - if (l.equals(m.target) && privatePort == m.privatePort) - return getPublicHostAndPort(m); - } - } - return null; - } - - @Override - public HostAndPort lookup(String publicIpId, int privatePort) { - synchronized (mutex) { - for (PortMapping m: mappings.values()) { - if (publicIpId.equals(m.publicIpId) && privatePort==m.privatePort) - return getPublicHostAndPort(m); - } - } - return null; - } - - @Override - public boolean forgetPortMapping(String publicIpId, int publicPort) { - PortMapping old; - synchronized (mutex) { - old = mappings.remove(makeKey(publicIpId, publicPort)); - if (old != null) { - emitAssociationDeletedEvent(associationMetadataFromPortMapping(old)); - } - log.debug("cleared port mapping for "+publicIpId+":"+publicPort+" - "+old); - } - if (old != null) onChanged(); - return (old != null); - } - - @Override - public boolean forgetPortMappings(Location l) { - List<PortMapping> result = Lists.newArrayList(); - synchronized (mutex) { - for (Iterator<PortMapping> iter = mappings.values().iterator(); iter.hasNext();) { - PortMapping m = iter.next(); - if (l.equals(m.target)) { - iter.remove(); - result.add(m); - emitAssociationDeletedEvent(associationMetadataFromPortMapping(m)); - } - } - } - if (log.isDebugEnabled()) log.debug("cleared all port mappings for "+l+" - "+result); - if (!result.isEmpty()) { - onChanged(); - } - return !result.isEmpty(); - } - - @Override - public boolean forgetPortMappings(String publicIpId) { - List<PortMapping> result = Lists.newArrayList(); - synchronized (mutex) { - for (Iterator<PortMapping> iter = mappings.values().iterator(); iter.hasNext();) { - PortMapping m = iter.next(); - if (publicIpId.equals(m.publicIpId)) { - iter.remove(); - result.add(m); - emitAssociationDeletedEvent(associationMetadataFromPortMapping(m)); - } - } - } - if (log.isDebugEnabled()) log.debug("cleared all port mappings for "+publicIpId+" - "+result); - if (!result.isEmpty()) { - onChanged(); - } - return !result.isEmpty(); - } - - private void emitAssociationDeletedEvent(AssociationMetadata metadata) { - for (Map.Entry<AssociationListener, Predicate<? super AssociationMetadata>> entry : associationListeners.entrySet()) { - if (entry.getValue().apply(metadata)) { - try { - entry.getKey().onAssociationDeleted(metadata); - } catch (Exception e) { - Exceptions.propagateIfFatal(e); - log.warn("Exception thrown when emitting association creation event " + metadata, e); - } - } - } - } - - @Override - protected ToStringHelper string() { - int size; - synchronized (mutex) { - size = mappings.size(); - } - return super.string().add("scope", getScope()).add("mappingsSize", size); - } - - @Override - public String toVerboseString() { - String mappingsStr; - synchronized (mutex) { - mappingsStr = mappings.toString(); - } - return string().add("mappings", mappingsStr).toString(); - } - - @Override - public String getScope() { - return checkNotNull(getConfig(SCOPE), "scope"); - } - - @Override - public boolean isClient() { - return false; - } - - @Override - public void addAssociationListener(AssociationListener listener, Predicate<? super AssociationMetadata> filter) { - associationListeners.put(listener, filter); - } - - @Override - public void removeAssociationListener(AssociationListener listener) { - associationListeners.remove(listener); - } - - protected String makeKey(String publicIpId, int publicPort) { - return publicIpId+":"+publicPort; - } - - private AssociationMetadata associationMetadataFromPortMapping(PortMapping portMapping) { - String publicIpId = portMapping.getPublicEndpoint().getHostText(); - HostAndPort publicEndpoint = portMapping.getPublicEndpoint(); - Location location = portMapping.getTarget(); - int privatePort = portMapping.getPrivatePort(); - return new AssociationMetadata(publicIpId, publicEndpoint, location, privatePort); - } - - /////////////////////////////////////////////////////////////////////////////////// - // Internal state, for generating memento - /////////////////////////////////////////////////////////////////////////////////// - - public List<PortMapping> getPortMappings() { - synchronized (mutex) { - return ImmutableList.copyOf(mappings.values()); - } - } - - public Map<String, Integer> getPortCounters() { - return ImmutableMap.of("global", portReserved.get()); - } - - - /////////////////////////////////////////////////////////////////////////////////// - // Deprecated - /////////////////////////////////////////////////////////////////////////////////// - - @Override - @Deprecated - public PortMapping acquirePublicPortExplicit(String publicIpId, int port) { - PortMapping mapping = new PortMapping(publicIpId, port, null, -1); - log.debug("assigning explicit public port "+port+" at "+publicIpId); - PortMapping result; - synchronized (mutex) { - result = mappings.put(makeKey(publicIpId, port), mapping); - } - onChanged(); - return result; - } - - @Override - @Deprecated - public boolean forgetPortMapping(PortMapping m) { - return forgetPortMapping(m.publicIpId, m.publicPort); - } - - @Override - @Deprecated - public void recordPublicIpHostname(String publicIpId, String hostnameOrPublicIpAddress) { - log.debug("recording public IP "+publicIpId+" associated with "+hostnameOrPublicIpAddress); - synchronized (mutex) { - String old = publicIpIdToHostname.put(publicIpId, hostnameOrPublicIpAddress); - if (old!=null && !old.equals(hostnameOrPublicIpAddress)) - log.warn("Changing hostname recorded against public IP "+publicIpId+"; from "+old+" to "+hostnameOrPublicIpAddress); - } - onChanged(); - } - - @Override - @Deprecated - public String getPublicIpHostname(String publicIpId) { - synchronized (mutex) { - return publicIpIdToHostname.get(publicIpId); - } - } - - @Override - @Deprecated - public boolean forgetPublicIpHostname(String publicIpId) { - log.debug("forgetting public IP "+publicIpId+" association"); - boolean result; - synchronized (mutex) { - result = (publicIpIdToHostname.remove(publicIpId) != null); - } - onChanged(); - return result; - } - - @Override - @Deprecated - public int acquirePublicPort(String publicIpId, Location l, int privatePort) { - int publicPort; - synchronized (mutex) { - PortMapping old = getPortMappingWithPrivateSide(l, privatePort); - // only works for 1 public IP ID per location (which is the norm) - if (old!=null && old.publicIpId.equals(publicIpId)) { - log.debug("request to acquire public port at "+publicIpId+" for "+l+":"+privatePort+", reusing old assignment "+old); - return old.getPublicPort(); - } - - publicPort = acquirePublicPort(publicIpId); - log.debug("request to acquire public port at "+publicIpId+" for "+l+":"+privatePort+", allocating "+publicPort); - associateImpl(publicIpId, publicPort, l, privatePort); - } - onChanged(); - return publicPort; - } - - @Override - @Deprecated - public void associate(String publicIpId, int publicPort, Location l, int privatePort) { - synchronized (mutex) { - associateImpl(publicIpId, publicPort, l, privatePort); - } - onChanged(); - } - - protected void associateImpl(String publicIpId, int publicPort, Location l, int privatePort) { - synchronized (mutex) { - PortMapping mapping = new PortMapping(publicIpId, publicPort, l, privatePort); - PortMapping oldMapping = getPortMappingWithPublicSide(publicIpId, publicPort); - log.debug("associating public port "+publicPort+" on "+publicIpId+" with private port "+privatePort+" at "+l+" ("+mapping+")" - +(oldMapping == null ? "" : " (overwriting "+oldMapping+" )")); - mappings.put(makeKey(publicIpId, publicPort), mapping); - } - } - - /////////////////////////////////////////////////////////////////////////////////// - // Internal only; make protected when deprecated interface method removed - /////////////////////////////////////////////////////////////////////////////////// - - @Override - public HostAndPort getPublicHostAndPort(PortMapping m) { - if (m.publicEndpoint == null) { - String hostname = getPublicIpHostname(m.publicIpId); - if (hostname==null) - throw new IllegalStateException("No public hostname associated with "+m.publicIpId+" (mapping "+m+")"); - return HostAndPort.fromParts(hostname, m.publicPort); - } else { - return m.publicEndpoint; - } - } - - @Override - public PortMapping getPortMappingWithPublicSide(String publicIpId, int publicPort) { - synchronized (mutex) { - return mappings.get(makeKey(publicIpId, publicPort)); - } - } - - @Override - public Collection<PortMapping> getPortMappingWithPublicIpId(String publicIpId) { - List<PortMapping> result = new ArrayList<PortMapping>(); - synchronized (mutex) { - for (PortMapping m: mappings.values()) - if (publicIpId.equals(m.publicIpId)) result.add(m); - } - return result; - } - - /** returns the subset of port mappings associated with a given location */ - @Override - public Collection<PortMapping> getLocationPublicIpIds(Location l) { - List<PortMapping> result = new ArrayList<PortMapping>(); - synchronized (mutex) { - for (PortMapping m: mappings.values()) - if (l.equals(m.getTarget())) result.add(m); - } - return result; - } - - @Override - public PortMapping getPortMappingWithPrivateSide(Location l, int privatePort) { - synchronized (mutex) { - for (PortMapping m: mappings.values()) - if (l.equals(m.getTarget()) && privatePort==m.privatePort) return m; - } - return null; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortForwardManagerLocationResolver.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortForwardManagerLocationResolver.java b/core/src/main/java/brooklyn/location/access/PortForwardManagerLocationResolver.java deleted file mode 100644 index e56d1c0..0000000 --- a/core/src/main/java/brooklyn/location/access/PortForwardManagerLocationResolver.java +++ /dev/null @@ -1,89 +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 brooklyn.location.access; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.location.Location; -import brooklyn.location.LocationSpec; -import brooklyn.location.basic.AbstractLocationResolver; -import brooklyn.location.basic.LocationConfigUtils; -import brooklyn.location.basic.LocationInternal; -import brooklyn.location.basic.LocationPredicates; -import brooklyn.util.config.ConfigBag; - -import com.google.common.base.Optional; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; - -public class PortForwardManagerLocationResolver extends AbstractLocationResolver { - - private static final Logger LOG = LoggerFactory.getLogger(PortForwardManagerLocationResolver.class); - - public static final String PREFIX = "portForwardManager"; - - @Override - public String getPrefix() { - return PREFIX; - } - - @Override - public Location newLocationFromString(Map locationFlags, String spec, brooklyn.location.LocationRegistry registry) { - ConfigBag config = extractConfig(locationFlags, spec, registry); - Map globalProperties = registry.getProperties(); - String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName()); - String scope = config.get(PortForwardManager.SCOPE); - - Optional<Location> result = Iterables.tryFind(managementContext.getLocationManager().getLocations(), - Predicates.and( - Predicates.instanceOf(PortForwardManager.class), - LocationPredicates.configEqualTo(PortForwardManager.SCOPE, scope))); - - if (result.isPresent()) { - return result.get(); - } else { - PortForwardManager loc = managementContext.getLocationManager().createLocation(LocationSpec.create(PortForwardManagerImpl.class) - .configure(config.getAllConfig()) - .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation))); - - if (LOG.isDebugEnabled()) LOG.debug("Created "+loc+" for scope "+scope); - return loc; - } - } - - @Override - protected Class<? extends Location> getLocationType() { - return PortForwardManager.class; - } - - @Override - protected SpecParser getSpecParser() { - return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"portForwardManager\" or \"portForwardManager(scope=global)\""); - } - - @Override - protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, brooklyn.location.LocationRegistry registry) { - ConfigBag config = super.extractConfig(locationFlags, spec, registry); - config.putAsStringKeyIfAbsent("name", "localhost"); - return config; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/access/PortMapping.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/access/PortMapping.java b/core/src/main/java/brooklyn/location/access/PortMapping.java deleted file mode 100644 index aaf0ca5..0000000 --- a/core/src/main/java/brooklyn/location/access/PortMapping.java +++ /dev/null @@ -1,101 +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 brooklyn.location.access; - -import static com.google.common.base.Preconditions.checkNotNull; - -import javax.annotation.Nullable; - -import brooklyn.location.Location; - -import com.google.common.annotations.Beta; -import com.google.common.base.Objects; -import com.google.common.net.HostAndPort; - -public class PortMapping { - - final String publicIpId; - final HostAndPort publicEndpoint; - final int publicPort; - - final Location target; - final int privatePort; - // TODO CIDR's ? - - public PortMapping(String publicIpId, HostAndPort publicEndpoint, Location target, int privatePort) { - this.publicIpId = checkNotNull(publicIpId, "publicIpId"); - this.publicEndpoint = checkNotNull(publicEndpoint, "publicEndpoint"); - this.publicPort = publicEndpoint.getPort(); - this.target = target; - this.privatePort = privatePort; - } - - public PortMapping(String publicIpId, int publicPort, Location target, int privatePort) { - this.publicIpId = checkNotNull(publicIpId, "publicIpId"); - this.publicEndpoint = null; - this.publicPort = publicPort; - this.target = target; - this.privatePort = privatePort; - } - - // In a release after 0.7.0, this will no longer be @Nullable - @Beta - @Nullable - public HostAndPort getPublicEndpoint() { - return publicEndpoint; - } - - public int getPublicPort() { - return publicPort; - } - - public Location getTarget() { - return target; - } - - public int getPrivatePort() { - return privatePort; - } - - @Override - public String toString() { - return Objects.toStringHelper(this) - .add("publicIpId", publicIpId+":"+publicPort) - .add("publicEndpoint", (publicEndpoint == null ? publicPort : publicEndpoint)) - .add("targetLocation", target) - .add("targetPort", privatePort) - .toString(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof PortMapping)) return false; - PortMapping opm = (PortMapping)obj; - return Objects.equal(publicIpId, opm.publicIpId) && - Objects.equal(publicPort, opm.publicPort) && - Objects.equal(target, opm.target) && - Objects.equal(privatePort, opm.privatePort); - } - - @Override - public int hashCode() { - return Objects.hashCode(publicIpId, publicPort, target, privatePort); - } - -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/AbstractLocation.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/brooklyn/location/basic/AbstractLocation.java b/core/src/main/java/brooklyn/location/basic/AbstractLocation.java deleted file mode 100644 index a5eb1cc..0000000 --- a/core/src/main/java/brooklyn/location/basic/AbstractLocation.java +++ /dev/null @@ -1,708 +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 brooklyn.location.basic; - -import static brooklyn.util.GroovyJavaMethods.elvis; -import static brooklyn.util.JavaGroovyEquivalents.groovyTruth; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.Closeable; -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.brooklyn.api.entity.rebind.RebindSupport; -import org.apache.brooklyn.api.entity.trait.Configurable; -import org.apache.brooklyn.api.management.Task; -import org.apache.brooklyn.mementos.LocationMemento; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import brooklyn.basic.AbstractBrooklynObject; -import brooklyn.config.ConfigInheritance; -import brooklyn.config.ConfigKey; -import brooklyn.config.ConfigKey.HasConfigKey; -import brooklyn.entity.basic.ConfigKeys; -import brooklyn.entity.rebind.BasicLocationRebindSupport; -import brooklyn.event.basic.BasicConfigKey; -import brooklyn.internal.BrooklynFeatureEnablement; -import brooklyn.internal.storage.BrooklynStorage; -import brooklyn.internal.storage.Reference; -import brooklyn.internal.storage.impl.BasicReference; -import brooklyn.location.Location; -import brooklyn.location.LocationSpec; -import brooklyn.location.geo.HasHostGeoInfo; -import brooklyn.location.geo.HostGeoInfo; -import brooklyn.management.internal.LocalLocationManager; -import brooklyn.management.internal.ManagementContextInternal; -import brooklyn.util.collections.SetFromLiveMap; -import brooklyn.util.config.ConfigBag; -import brooklyn.util.flags.FlagUtils; -import brooklyn.util.flags.TypeCoercions; -import brooklyn.util.guava.Maybe; -import brooklyn.util.stream.Streams; - -import com.google.common.base.Objects; -import com.google.common.base.Objects.ToStringHelper; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.common.reflect.TypeToken; - -/** - * A basic implementation of the {@link Location} interface. - * - * This provides an implementation which works according to the requirements of - * the interface documentation, and is ready to be extended to make more specialized locations. - * - * Override {@link #configure(Map)} to add special initialization logic. - */ -public abstract class AbstractLocation extends AbstractBrooklynObject implements LocationInternal, HasHostGeoInfo, Configurable { - - private static final long serialVersionUID = -7495805474138619830L; - - /** @deprecated since 0.7.0 shouldn't be public */ - @Deprecated - public static final Logger LOG = LoggerFactory.getLogger(AbstractLocation.class); - - public static final ConfigKey<Location> PARENT_LOCATION = new BasicConfigKey<Location>(Location.class, "parentLocation"); - - public static final ConfigKey<Boolean> TEMPORARY_LOCATION = ConfigKeys.newBooleanConfigKey("temporaryLocation", - "Indicates that the location is a temporary location that has been created to test connectivity, and that" + - "the location's events should not be recorded by usage listeners", false); - - private final AtomicBoolean configured = new AtomicBoolean(); - - private Reference<Long> creationTimeUtc = new BasicReference<Long>(System.currentTimeMillis()); - - // _not_ set from flag; configured explicitly in configure, because we also need to update the parent's list of children - private Reference<Location> parent = new BasicReference<Location>(); - - // NB: all accesses should be synchronized - private Set<Location> children = Sets.newLinkedHashSet(); - - private Reference<String> name = new BasicReference<String>(); - private boolean displayNameAutoGenerated = true; - - private Reference<HostGeoInfo> hostGeoInfo = new BasicReference<HostGeoInfo>(); - - private BasicConfigurationSupport config = new BasicConfigurationSupport(); - - private ConfigBag configBag = new ConfigBag(); - - private volatile boolean managed; - - private boolean inConstruction; - - private Reference<Map<Class<?>, Object>> extensions = new BasicReference<Map<Class<?>, Object>>(Maps.<Class<?>, Object>newConcurrentMap()); - - private final LocationDynamicType locationType; - - /** - * Construct a new instance of an AbstractLocation. - */ - public AbstractLocation() { - this(Maps.newLinkedHashMap()); - } - - /** - * Construct a new instance of an AbstractLocation. - * - * The properties map recognizes the following keys: - * <ul> - * <li>name - a name for the location - * <li>parentLocation - the parent {@link Location} - * </ul> - * - * Other common properties (retrieved via get/findLocationProperty) include: - * <ul> - * <li>latitude - * <li>longitude - * <li>displayName - * <li>iso3166 - list of iso3166-2 code strings - * <li>timeZone - * <li>abbreviatedName - * </ul> - */ - public AbstractLocation(Map<?,?> properties) { - super(properties); - inConstruction = true; - - // When one calls getConfig(key), we want to use the default value specified on *this* location - // if it overrides the default config, by using the type object - locationType = new LocationDynamicType(this); - - if (isLegacyConstruction()) { - AbstractBrooklynObject checkWeGetThis = configure(properties); - assert this.equals(checkWeGetThis) : this+" configure method does not return itself; returns "+checkWeGetThis+" instead of "+this; - - boolean deferConstructionChecks = (properties.containsKey("deferConstructionChecks") && TypeCoercions.coerce(properties.get("deferConstructionChecks"), Boolean.class)); - if (!deferConstructionChecks) { - FlagUtils.checkRequiredFields(this); - } - } - - inConstruction = false; - } - - protected void assertNotYetManaged() { - if (!inConstruction && Locations.isManaged(this)) { - LOG.warn("Configuration being made to {} after deployment; may not be supported in future versions", this); - } - //throw new IllegalStateException("Cannot set configuration "+key+" on active location "+this) - } - - public void setManagementContext(ManagementContextInternal managementContext) { - super.setManagementContext(managementContext); - if (displayNameAutoGenerated && getId() != null) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4))); - - if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_USE_BROOKLYN_LIVE_OBJECTS_DATAGRID_STORAGE)) { - Location oldParent = parent.get(); - Set<Location> oldChildren = children; - Map<String, Object> oldConfig = configBag.getAllConfig(); - Long oldCreationTimeUtc = creationTimeUtc.get(); - String oldDisplayName = name.get(); - HostGeoInfo oldHostGeoInfo = hostGeoInfo.get(); - - parent = managementContext.getStorage().getReference(getId()+"-parent"); - children = SetFromLiveMap.create(managementContext.getStorage().<Location,Boolean>getMap(getId()+"-children")); - creationTimeUtc = managementContext.getStorage().getReference(getId()+"-creationTime"); - hostGeoInfo = managementContext.getStorage().getReference(getId()+"-hostGeoInfo"); - name = managementContext.getStorage().getReference(getId()+"-displayName"); - - // Only override stored defaults if we have actual values. We might be in setManagementContext - // because we are reconstituting an existing entity in a new brooklyn management-node (in which - // case believe what is already in the storage), or we might be in the middle of creating a new - // entity. Normally for a new entity (using EntitySpec creation approach), this will get called - // before setting the parent etc. However, for backwards compatibility we still support some - // things calling the entity's constructor directly. - if (oldParent != null) parent.set(oldParent); - if (oldChildren.size() > 0) children.addAll(oldChildren); - if (creationTimeUtc.isNull()) creationTimeUtc.set(oldCreationTimeUtc); - if (hostGeoInfo.isNull()) hostGeoInfo.set(oldHostGeoInfo); - if (name.isNull()) { - name.set(oldDisplayName); - } else { - displayNameAutoGenerated = false; - } - - configBag = ConfigBag.newLiveInstance(managementContext.getStorage().<String,Object>getMap(getId()+"-config")); - if (oldConfig.size() > 0) { - configBag.putAll(oldConfig); - } - } - } - - /** - * @deprecated since 0.7.0; only used for legacy brooklyn types where constructor is called directly; - * see overridden method for more info - */ - @SuppressWarnings("serial") - @Override - @Deprecated - public AbstractLocation configure(Map<?,?> properties) { - assertNotYetManaged(); - - boolean firstTime = !configured.getAndSet(true); - - configBag.putAll(properties); - - if (properties.containsKey(PARENT_LOCATION.getName())) { - // need to ensure parent's list of children is also updated - setParent(configBag.get(PARENT_LOCATION)); - - // don't include parentLocation in configBag, as breaks rebind - configBag.remove(PARENT_LOCATION); - } - - // NB: flag-setting done here must also be done in BasicLocationRebindSupport - FlagUtils.setFieldsFromFlagsWithBag(this, properties, configBag, firstTime); - FlagUtils.setAllConfigKeys(this, configBag, false); - - if (properties.containsKey("displayName")) { - name.set((String) removeIfPossible(properties, "displayName")); - displayNameAutoGenerated = false; - } else if (properties.containsKey("name")) { - name.set((String) removeIfPossible(properties, "name")); - displayNameAutoGenerated = false; - } else if (isLegacyConstruction()) { - name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4))); - displayNameAutoGenerated = true; - } - - // TODO Explicitly dealing with iso3166 here because want custom splitter rule comma-separated string. - // Is there a better way to do it (e.g. more similar to latitude, where configKey+TypeCoercion is enough)? - if (groovyTruth(properties.get("iso3166"))) { - Object rawCodes = removeIfPossible(properties, "iso3166"); - Set<String> codes; - if (rawCodes instanceof CharSequence) { - codes = ImmutableSet.copyOf(Splitter.on(",").trimResults().split((CharSequence)rawCodes)); - } else { - codes = TypeCoercions.coerce(rawCodes, new TypeToken<Set<String>>() {}); - } - configBag.put(LocationConfigKeys.ISO_3166, codes); - } - - return this; - } - - // TODO ensure no callers rely on 'remove' semantics, and don't remove; - // or perhaps better use a config bag so we know what is used v unused - private static Object removeIfPossible(Map<?,?> map, Object key) { - try { - return map.remove(key); - } catch (Exception e) { - return map.get(key); - } - } - - public boolean isManaged() { - return getManagementContext() != null && managed; - } - - public void onManagementStarted() { - if (displayNameAutoGenerated) name.set(getClass().getSimpleName()+":"+getId().substring(0, Math.min(getId().length(),4))); - this.managed = true; - } - - public void onManagementStopped() { - this.managed = false; - if (getManagementContext().isRunning()) { - BrooklynStorage storage = ((ManagementContextInternal)getManagementContext()).getStorage(); - storage.remove(getId()+"-parent"); - storage.remove(getId()+"-children"); - storage.remove(getId()+"-creationTime"); - storage.remove(getId()+"-hostGeoInfo"); - storage.remove(getId()+"-displayName"); - storage.remove(getId()+"-config"); - } - } - - @Override - public String getDisplayName() { - return name.get(); - } - - protected boolean isDisplayNameAutoGenerated() { - return displayNameAutoGenerated; - } - - @Override - public Location getParent() { - return parent.get(); - } - - @Override - public Collection<Location> getChildren() { - synchronized (children) { - return ImmutableList.copyOf(children); - } - } - - @Override - public void setParent(Location newParent) { - setParent(newParent, true); - } - - public void setParent(Location newParent, boolean updateChildListParents) { - if (newParent == this) { - throw new IllegalArgumentException("Location cannot be its own parent: "+this); - } - if (newParent == parent.get()) { - return; // no-op; already have desired parent - } - - if (parent.get() != null) { - Location oldParent = parent.get(); - parent.set(null); - if (updateChildListParents) - ((AbstractLocation)oldParent).removeChild(this); - } - // TODO Should we support a location changing parent? The resulting unmanage/manage might cause problems. - // The code above suggests we do, but maybe we should warn or throw error, or at least test it! - - parent.set(newParent); - if (newParent != null) { - if (updateChildListParents) - ((AbstractLocation)newParent).addChild(this); - } - - onChanged(); - } - - @Override - public ConfigurationSupportInternal config() { - return config ; - } - - private class BasicConfigurationSupport implements ConfigurationSupportInternal { - - @Override - public <T> T get(ConfigKey<T> key) { - if (hasConfig(key, false)) return getLocalBag().get(key); - if (getParent() != null && isInherited(key)) { - return getParent().getConfig(key); - } - - // In case this entity class has overridden the given key (e.g. to set default), then retrieve this entity's key - // TODO when locations become entities, the duplication of this compared to EntityConfigMap.getConfig will disappear. - @SuppressWarnings("unchecked") - ConfigKey<T> ownKey = (ConfigKey<T>) elvis(locationType.getConfigKey(key.getName()), key); - - return ownKey.getDefaultValue(); - } - - @Override - public <T> T get(HasConfigKey<T> key) { - return get(key.getConfigKey()); - } - - @Override - public <T> T set(ConfigKey<T> key, T val) { - T result = configBag.put(key, val); - onChanged(); - return result; - } - - @Override - public <T> T set(HasConfigKey<T> key, T val) { - return set(key.getConfigKey(), val); - } - - @Override - public <T> T set(ConfigKey<T> key, Task<T> val) { - // TODO Support for locations - throw new UnsupportedOperationException(); - } - - @Override - public <T> T set(HasConfigKey<T> key, Task<T> val) { - // TODO Support for locations - throw new UnsupportedOperationException(); - } - - @Override - public ConfigBag getBag() { - ConfigBag result = ConfigBag.newInstanceExtending(configBag, ImmutableMap.of()); - Location p = getParent(); - if (p!=null) result.putIfAbsent(((LocationInternal)p).config().getBag()); - return result; - } - - @Override - public ConfigBag getLocalBag() { - return configBag; - } - - @Override - public Maybe<Object> getRaw(ConfigKey<?> key) { - if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName())); - if (getParent() != null && isInherited(key)) return ((LocationInternal)getParent()).config().getRaw(key); - return Maybe.absent(); - } - - @Override - public Maybe<Object> getRaw(HasConfigKey<?> key) { - return getRaw(key.getConfigKey()); - } - - @Override - public Maybe<Object> getLocalRaw(ConfigKey<?> key) { - if (hasConfig(key, false)) return Maybe.of(getLocalBag().getStringKey(key.getName())); - return Maybe.absent(); - } - - @Override - public Maybe<Object> getLocalRaw(HasConfigKey<?> key) { - return getLocalRaw(key.getConfigKey()); - } - - @Override - public void addToLocalBag(Map<String, ?> vals) { - configBag.putAll(vals); - } - - @Override - public void removeFromLocalBag(String key) { - configBag.remove(key); - } - - @Override - public void refreshInheritedConfig() { - // no-op for location - } - - @Override - public void refreshInheritedConfigOfChildren() { - // no-op for location - } - - private boolean hasConfig(ConfigKey<?> key, boolean includeInherited) { - if (includeInherited && isInherited(key)) { - return getBag().containsKey(key); - } else { - return getLocalBag().containsKey(key); - } - } - - private boolean isInherited(ConfigKey<?> key) { - ConfigInheritance inheritance = key.getInheritance(); - if (inheritance==null) inheritance = getDefaultInheritance(); - return inheritance.isInherited(key, getParent(), AbstractLocation.this); - } - - private ConfigInheritance getDefaultInheritance() { - return ConfigInheritance.ALWAYS; - } - } - - @Override - public <T> T getConfig(HasConfigKey<T> key) { - return config().get(key); - } - - @Override - public <T> T getConfig(ConfigKey<T> key) { - return config().get(key); - } - - @Override - @Deprecated - public boolean hasConfig(ConfigKey<?> key, boolean includeInherited) { - return config.hasConfig(key, includeInherited); - } - - @Override - @Deprecated - public Map<String,Object> getAllConfig(boolean includeInherited) { - // TODO Have no information about what to include/exclude inheritance wise. - // however few things use getAllConfigBag() - ConfigBag bag = (includeInherited ? config().getBag() : config().getLocalBag()); - return bag.getAllConfig(); - } - - @Override - @Deprecated - public ConfigBag getAllConfigBag() { - // TODO see comments in EntityConfigMap and on interface methods. - // here ConfigBag is used exclusively so - // we have no information about what to include/exclude inheritance wise. - // however few things use getAllConfigBag() - return config().getBag(); - } - - @Override - public ConfigBag getLocalConfigBag() { - return config().getLocalBag(); - } - - /** - * @deprecated since 0.7; use {@link #getLocalConfigBag()} - * @since 0.6 - */ - @Deprecated - public ConfigBag getRawLocalConfigBag() { - return config().getLocalBag(); - } - - @Override - @Deprecated - public <T> T setConfig(ConfigKey<T> key, T value) { - return config().set(key, value); - } - - /** - * @since 0.6.0 (?) - use getDisplayName - * @deprecated since 0.7.0; use {@link #getDisplayName()} - */ - @Deprecated - public void setName(String newName) { - setDisplayName(newName); - } - - public void setDisplayName(String newName) { - name.set(newName); - displayNameAutoGenerated = false; - onChanged(); - } - - @Override - public boolean equals(Object o) { - if (! (o instanceof Location)) { - return false; - } - - Location l = (Location) o; - return getId().equals(l.getId()); - } - - @Override - public int hashCode() { - return getId().hashCode(); - } - - @Override - public boolean containsLocation(Location potentialDescendent) { - Location loc = potentialDescendent; - while (loc != null) { - if (this == loc) return true; - loc = loc.getParent(); - } - return false; - } - - protected <T extends Location> T addChild(LocationSpec<T> spec) { - T child = getManagementContext().getLocationManager().createLocation(spec); - addChild(child); - return child; - } - - @SuppressWarnings("deprecation") - public void addChild(Location child) { - // Previously, setParent delegated to addChildLocation and we sometimes ended up with - // duplicate entries here. Instead this now uses a similar scheme to - // AbstractLocation.setParent/addChild (with any weaknesses for distribution that such a - // scheme might have...). - // - // We continue to use a list to allow identical-looking locations, but they must be different - // instances. - - synchronized (children) { - for (Location contender : children) { - if (contender == child) { - // don't re-add; no-op - return; - } - } - - children.add(child); - } - - if (isManaged()) { - if (!getManagementContext().getLocationManager().isManaged(child)) { - Locations.manage(child, getManagementContext()); - } - } else if (getManagementContext() != null) { - if (((LocalLocationManager)getManagementContext().getLocationManager()).getLocationEvenIfPreManaged(child.getId()) == null) { - ((ManagementContextInternal)getManagementContext()).prePreManage(child); - } - } - - children.add(child); - child.setParent(this); - - onChanged(); - } - - public boolean removeChild(Location child) { - boolean removed; - synchronized (children) { - removed = children.remove(child); - } - if (removed) { - if (child instanceof Closeable) { - Streams.closeQuietly((Closeable)child); - } - child.setParent(null); - - if (isManaged()) { - getManagementContext().getLocationManager().unmanage(child); - } - } - onChanged(); - return removed; - } - - protected void onChanged() { - // currently changes simply trigger re-persistence; there is no intermediate listener as we do for EntityChangeListener - if (isManaged()) { - getManagementContext().getRebindManager().getChangeListener().onChanged(this); - } - } - - /** Default String representation is simplified name of class, together with selected fields. */ - @Override - public String toString() { - return string().toString(); - } - - @Override - public String toVerboseString() { - return toString(); - } - - /** override this, adding to the returned value, to supply additional fields to include in the toString */ - protected ToStringHelper string() { - return Objects.toStringHelper(getClass()).add("id", getId()).add("name", name); - } - - @Override - public HostGeoInfo getHostGeoInfo() { return hostGeoInfo.get(); } - - public void setHostGeoInfo(HostGeoInfo hostGeoInfo) { - if (hostGeoInfo!=null) { - this.hostGeoInfo.set(hostGeoInfo); - setConfig(LocationConfigKeys.LATITUDE, hostGeoInfo.latitude); - setConfig(LocationConfigKeys.LONGITUDE, hostGeoInfo.longitude); - } - } - - @Override - public RebindSupport<LocationMemento> getRebindSupport() { - return new BasicLocationRebindSupport(this); - } - - @Override - public boolean hasExtension(Class<?> extensionType) { - return extensions.get().containsKey(checkNotNull(extensionType, "extensionType")); - } - - @Override - @SuppressWarnings("unchecked") - public <T> T getExtension(Class<T> extensionType) { - Object extension = extensions.get().get(checkNotNull(extensionType, "extensionType")); - if (extension == null) { - throw new IllegalArgumentException("No extension of type "+extensionType+" registered for location "+this); - } - return (T) extension; - } - - @Override - public <T> void addExtension(Class<T> extensionType, T extension) { - checkNotNull(extensionType, "extensionType"); - checkNotNull(extension, "extension"); - checkArgument(extensionType.isInstance(extension), "extension %s does not implement %s", extension, extensionType); - extensions.get().put(extensionType, extension); - } - - @Override - public Map<String, String> toMetadataRecord() { - ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); - if (getDisplayName() != null) builder.put("displayName", getDisplayName()); - if (getParent() != null && getParent().getDisplayName() != null) { - builder.put("parentDisplayName", getParent().getDisplayName()); - } - return builder.build(); - } -}
