You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by ha...@apache.org on 2015/08/14 05:43:10 UTC
[41/54] incubator-brooklyn git commit: [BROOKLYN-162] Renaming
package brooklyn.location
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/AbstractLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/AbstractLocationResolver.java b/core/src/main/java/brooklyn/location/basic/AbstractLocationResolver.java
deleted file mode 100644
index f2799df..0000000
--- a/core/src/main/java/brooklyn/location/basic/AbstractLocationResolver.java
+++ /dev/null
@@ -1,189 +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 com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.brooklyn.api.management.ManagementContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.location.Location;
-import brooklyn.location.LocationRegistry;
-import brooklyn.location.LocationResolver;
-import brooklyn.location.LocationSpec;
-import brooklyn.location.basic.AbstractLocationResolver.SpecParser.ParsedSpec;
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.config.ConfigBag;
-import brooklyn.util.text.KeyValueParser;
-
-import com.google.common.collect.ImmutableList;
-
-/**
- * Examples of valid specs:
- * <ul>
- * <li>byon(hosts=myhost)
- * <li>byon(hosts=myhost,myhost2)
- * <li>byon(hosts="myhost, myhost2")
- * <li>byon(hosts=myhost,myhost2, name=abc)
- * <li>byon(hosts="myhost, myhost2", name="my location name")
- * </ul>
- *
- * @author aled
- */
-@SuppressWarnings({"unchecked","rawtypes"})
-public abstract class AbstractLocationResolver implements LocationResolver {
-
- public static final Logger log = LoggerFactory.getLogger(AbstractLocationResolver.class);
-
- protected volatile ManagementContext managementContext;
-
- protected volatile SpecParser specParser;
-
- protected abstract Class<? extends Location> getLocationType();
-
- protected abstract SpecParser getSpecParser();
-
- @Override
- public void init(ManagementContext managementContext) {
- this.managementContext = checkNotNull(managementContext, "managementContext");
- this.specParser = getSpecParser();
- }
-
- @Override
- public boolean accepts(String spec, LocationRegistry registry) {
- return BasicLocationRegistry.isResolverPrefixForSpec(this, spec, true);
- }
-
- @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());
-
- if (registry != null) {
- LocationPropertiesFromBrooklynProperties.setLocalTempDir(globalProperties, config);
- }
-
- return managementContext.getLocationManager().createLocation(LocationSpec.create(getLocationType())
- .configure(config.getAllConfig())
- .configure(LocationConfigUtils.finalAndOriginalSpecs(spec, locationFlags, globalProperties, namedLocation)));
- }
-
- protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, brooklyn.location.LocationRegistry registry) {
- Map globalProperties = registry.getProperties();
- ParsedSpec parsedSpec = specParser.parse(spec);
- String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());
-
- // prefer args map over location flags
- Map<String, Object> filteredProperties = getFilteredLocationProperties(getPrefix(), namedLocation, globalProperties);
- ConfigBag flags = ConfigBag.newInstance(parsedSpec.argsMap).putIfAbsent(locationFlags).putIfAbsent(filteredProperties);
-
- return flags;
- }
-
- protected Map<String, Object> getFilteredLocationProperties(String provider, String namedLocation, Map<String, ?> globalProperties) {
- return new LocationPropertiesFromBrooklynProperties().getLocationProperties(getPrefix(), namedLocation, globalProperties);
- }
-
- /**
- * Parses a spec, by default of the general form "prefix:parts1:part2(arg1=val1,arg2=val2)"
- */
- protected static class SpecParser {
-
- protected static class ParsedSpec {
- public final String spec;
- public final List<String> partsList;
- public final Map<String,String> argsMap;
-
- ParsedSpec(String spec, List<String> partsList, Map<String,String> argsMap) {
- this.spec = spec;
- this.partsList = ImmutableList.copyOf(partsList);
- this.argsMap = Collections.unmodifiableMap(MutableMap.copyOf(argsMap));
- }
- }
-
- protected final String prefix;
- protected final Pattern pattern;
- private String exampleUsage;
-
- public SpecParser(String prefix) {
- this.prefix = prefix;
- pattern = Pattern.compile("("+prefix+"|"+prefix.toLowerCase()+"|"+prefix.toUpperCase()+")" + "(:)?" + "(\\((.*)\\))?$");
- }
-
- public SpecParser(String prefix, Pattern pattern) {
- this.prefix = prefix;
- this.pattern = pattern;
- }
-
- public SpecParser setExampleUsage(String exampleUsage) {
- this.exampleUsage = exampleUsage;
- return this;
- }
-
- protected String getUsage(String spec) {
- if (exampleUsage == null) {
- return "Spec should be in the form "+pattern;
- } else {
- return "for example, "+exampleUsage;
- }
- }
-
- protected void checkParsedSpec(ParsedSpec parsedSpec) {
- // If someone tries "byon:(),byon:()" as a single spec, we get weird key-values!
- for (String key : parsedSpec.argsMap.keySet()) {
- if (key.contains(":") || key.contains("{") || key.contains("}") || key.contains("(") || key.contains(")")) {
- throw new IllegalArgumentException("Invalid byon spec: "+parsedSpec.spec+" (key="+key+")");
- }
- }
- String name = parsedSpec.argsMap.get("name");
- if (parsedSpec.argsMap.containsKey("name") && (name == null || name.isEmpty())) {
- throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if name supplied then value must be non-empty");
- }
- String displayName = parsedSpec.argsMap.get("displayName");
- if (parsedSpec.argsMap.containsKey("displayName") && (displayName == null || displayName.isEmpty())) {
- throw new IllegalArgumentException("Invalid location '"+parsedSpec.spec+"'; if displayName supplied then value must be non-empty");
- }
- }
-
- public ParsedSpec parse(String spec) {
- Matcher matcher = pattern.matcher(spec);
- if (!matcher.matches()) {
- throw new IllegalArgumentException("Invalid location '"+spec+"'; "+getUsage(spec));
- }
-
- String argsPart = matcher.group(3);
- if (argsPart != null && argsPart.startsWith("(") && argsPart.endsWith(")")) {
- // TODO Hacky; hosts("1.1.1.1") returns argsPart=("1.1.1.1")
- argsPart = argsPart.substring(1, argsPart.length()-1);
- }
- Map<String, String> argsMap = KeyValueParser.parseMap(argsPart);
- ParsedSpec result = new ParsedSpec(spec, ImmutableList.<String>of(), argsMap);
- checkParsedSpec(result);
- return result;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java b/core/src/main/java/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
deleted file mode 100644
index a644459..0000000
--- a/core/src/main/java/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java
+++ /dev/null
@@ -1,139 +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 com.google.common.base.Preconditions.checkState;
-
-import java.io.Closeable;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import brooklyn.location.MachineLocation;
-import brooklyn.location.MachineProvisioningLocation;
-import brooklyn.location.NoMachinesAvailableException;
-import brooklyn.util.flags.SetFromFlag;
-import brooklyn.util.stream.Streams;
-
-import com.google.common.base.Objects;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-/**
- * Takes a list of other provisioners, and round-robins across them when obtaining a machine.
- */
-public class AggregatingMachineProvisioningLocation<T extends MachineLocation> extends AbstractLocation
- implements MachineProvisioningLocation<T>, Closeable {
-
- private Object lock;
-
- @SetFromFlag
- protected List<MachineProvisioningLocation<T>> provisioners;
-
- @SetFromFlag
- protected Map<T, MachineProvisioningLocation<T>> inUse;
-
- protected final AtomicInteger obtainCounter = new AtomicInteger();
-
- public AggregatingMachineProvisioningLocation() {
- this(Maps.newLinkedHashMap());
- }
-
- public AggregatingMachineProvisioningLocation(Map properties) {
- super(properties);
-
- if (isLegacyConstruction()) {
- init();
- }
- }
-
- @Override
- public void init() {
- super.init();
- }
-
- @Override
- public String toVerboseString() {
- return Objects.toStringHelper(this).omitNullValues()
- .add("id", getId()).add("name", getDisplayName())
- .add("provisioners", provisioners)
- .toString();
- }
-
- @Override
- public AbstractLocation configure(Map<?,?> properties) {
- if (lock == null) {
- lock = new Object();
- provisioners = Lists.<MachineProvisioningLocation<T>>newArrayList();
- inUse = Maps.<T, MachineProvisioningLocation<T>>newLinkedHashMap();
- }
- return super.configure(properties);
- }
-
- @Override
- public AggregatingMachineProvisioningLocation<T> newSubLocation(Map<?,?> newFlags) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void close() {
- for (MachineProvisioningLocation<?> provisioner : provisioners) {
- if (provisioner instanceof Closeable) {
- Streams.closeQuietly((Closeable)provisioner);
- }
- }
- }
-
- public T obtain() throws NoMachinesAvailableException {
- return obtain(Maps.<String,Object>newLinkedHashMap());
- }
-
- @Override
- public T obtain(Map<?,?> flags) throws NoMachinesAvailableException {
- checkState(provisioners.size() > 0, "no provisioners!");
- int index = obtainCounter.getAndIncrement();
- for (int i = 0; i < provisioners.size(); i++) {
- MachineProvisioningLocation<T> provisioner = provisioners.get(index++ % provisioners.size());
- try {
- T machine = provisioner.obtain(flags);
- inUse.put(machine, provisioner);
- return machine;
- } catch (NoMachinesAvailableException e) {
- // move on; try next
- }
- }
- throw new NoMachinesAvailableException("No machines available in "+toString());
- }
-
- @Override
- public void release(T machine) {
- MachineProvisioningLocation<T> provisioner = inUse.remove(machine);
- if (provisioner != null) {
- provisioner.release(machine);
- } else {
- throw new IllegalStateException("Request to release machine "+machine+", but this machine is not currently allocated");
- }
- }
-
- @Override
- public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
- return Maps.<String,Object>newLinkedHashMap();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicHardwareDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicHardwareDetails.java b/core/src/main/java/brooklyn/location/basic/BasicHardwareDetails.java
deleted file mode 100644
index eac4a2b..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicHardwareDetails.java
+++ /dev/null
@@ -1,56 +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 javax.annotation.concurrent.Immutable;
-
-import com.google.common.base.Objects;
-
-import brooklyn.location.HardwareDetails;
-
-@Immutable
-public class BasicHardwareDetails implements HardwareDetails {
-
- private final Integer cpuCount;
- private final Integer ram;
-
- public BasicHardwareDetails(Integer cpuCount, Integer ram) {
- this.cpuCount = cpuCount;
- this.ram = ram;
- }
-
- @Override
- public Integer getCpuCount() {
- return cpuCount;
- }
-
- @Override
- public Integer getRam() {
- return ram;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(HardwareDetails.class)
- .omitNullValues()
- .add("cpuCount", cpuCount)
- .add("ram", ram)
- .toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicLocationDefinition.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicLocationDefinition.java b/core/src/main/java/brooklyn/location/basic/BasicLocationDefinition.java
deleted file mode 100644
index 2604c18..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicLocationDefinition.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 brooklyn.location.basic;
-
-import java.util.Map;
-
-import brooklyn.location.LocationDefinition;
-import brooklyn.util.text.Identifiers;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableMap;
-
-public class BasicLocationDefinition implements LocationDefinition {
-
- private final String id;
- private final String name;
- private final String spec;
- private final Map<String,Object> config;
-
- public BasicLocationDefinition(String name, String spec, Map<String,? extends Object> config) {
- this(Identifiers.makeRandomId(8), name, spec, config);
- }
-
- public BasicLocationDefinition(String id, String name, String spec, Map<String,? extends Object> config) {
- this.id = Preconditions.checkNotNull(id);
- this.name = name;
- this.spec = Preconditions.checkNotNull(spec);
- this.config = config==null ? ImmutableMap.<String, Object>of() : ImmutableMap.<String, Object>copyOf(config);
- }
-
- public String getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-
- public String getSpec() {
- return spec;
- }
-
- @Override
- public Map<String, Object> getConfig() {
- return config;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this==o) return true;
- if ((o instanceof LocationDefinition) && id.equals(((LocationDefinition)o).getId())) return true;
- return false;
- }
-
- @Override
- public int hashCode() {
- return id.hashCode();
- }
-
- @Override
- public String toString() {
- return "LocationDefinition{" +
- "id='" + getId() + '\'' +
- ", name='" + getName() + '\'' +
- ", spec='" + getSpec() + '\'' +
- ", config=" + getConfig() +
- '}';
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicLocationRegistry.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicLocationRegistry.java b/core/src/main/java/brooklyn/location/basic/BasicLocationRegistry.java
deleted file mode 100644
index c0169d6..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicLocationRegistry.java
+++ /dev/null
@@ -1,481 +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 com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.ServiceLoader;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.BrooklynCatalog;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.management.ManagementContext;
-
-import brooklyn.catalog.CatalogPredicates;
-import brooklyn.config.ConfigMap;
-import brooklyn.config.ConfigPredicates;
-import brooklyn.config.ConfigUtils;
-import brooklyn.location.Location;
-import brooklyn.location.LocationDefinition;
-import brooklyn.location.LocationRegistry;
-import brooklyn.location.LocationResolver;
-import brooklyn.location.LocationResolver.EnableableLocationResolver;
-import brooklyn.location.LocationSpec;
-import brooklyn.management.internal.LocalLocationManager;
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.config.ConfigBag;
-import brooklyn.util.exceptions.Exceptions;
-import brooklyn.util.guava.Maybe;
-import brooklyn.util.guava.Maybe.Absent;
-import brooklyn.util.javalang.JavaClassNames;
-import brooklyn.util.text.Identifiers;
-import brooklyn.util.text.StringEscapes.JavaStringEscapes;
-import brooklyn.util.text.WildcardGlobs;
-import brooklyn.util.text.WildcardGlobs.PhraseTreatment;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Suppliers;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
-
-/**
- * See {@link LocationRegistry} for general description.
- * <p>
- * TODO The relationship between the catalog and the location registry is a bit messy.
- * For all existing code, the location registry is the definitive way to resolve
- * locations.
- * <p>
- * Any location item added to the catalog must therefore be registered here.
- * Whenever an item is added to the catalog, it will automatically call
- * {@link #updateDefinedLocation(CatalogItem)}. Similarly, when a location
- * is deleted from the catalog it will call {@link #removeDefinedLocation(CatalogItem)}.
- * <p>
- * However, the location item in the catalog has an unparsed blob of YAML, which contains
- * important things like the type and the config of the location. This is only parsed when
- * {@link BrooklynCatalog#createSpec(CatalogItem)} is called. We therefore jump through
- * some hoops to wire together the catalog and the registry.
- * <p>
- * To add a location to the catalog, and then to resolve a location that is in the catalog,
- * it goes through the following steps:
- *
- * <ol>
- * <li>Call {@link BrooklynCatalog#addItems(String)}
- * <ol>
- * <li>This automatically calls {@link #updateDefinedLocation(CatalogItem)}
- * <li>A LocationDefinition is creating, using as its id the {@link CatalogItem#getSymbolicName()}.
- * The definition's spec is {@code brooklyn.catalog:<symbolicName>:<version>},
- * </ol>
- * <li>A blueprint can reference the catalog item using its symbolic name,
- * such as the YAML {@code location: my-new-location}.
- * (this feels similar to the "named locations").
- * <ol>
- * <li>This automatically calls {@link #resolve(String)}.
- * <li>The LocationDefinition is found by lookig up this name.
- * <li>The {@link LocationDefiniton.getSpec()} is retrieved; the right {@link LocationResolver} is
- * found for it.
- * <li>This uses the {@link CatalogLocationResolver}, because the spec starts with {@code brooklyn.catalog:}.
- * <li>This resolver extracts from the spec the <symobolicName>:<version>, and looks up the
- * catalog item using {@link BrooklynCatalog#getCatalogItem(String, String)}.
- * <li>It then creates a {@link LocationSpec} by calling {@link BrooklynCatalog#createSpec(CatalogItem)}.
- * <ol>
- * <li>This first tries to use the type (that is in the YAML) as a simple Java class.
- * <li>If that fails, it will resolve the type using {@link #resolve(String, Boolean, Map)}, which
- * returns an actual location object.
- * <li>It extracts from that location object the appropriate metadata to create a {@link LocationSpec},
- * returns the spec and discards the location object.
- * </ol>
- * <li>The resolver creates the {@link Location} from the {@link LocationSpec}
- * </ol>
- * </ol>
- *
- * There is no concept of a location version in this registry. The version
- * in the catalog is generally ignored.
- */
-@SuppressWarnings({"rawtypes","unchecked"})
-public class BasicLocationRegistry implements LocationRegistry {
-
- // TODO save / serialize
- // (we persist live locations, ie those in the LocationManager, but not "catalog" locations, ie those in this Registry)
-
- public static final Logger log = LoggerFactory.getLogger(BasicLocationRegistry.class);
-
- /**
- * Splits a comma-separated list of locations (names or specs) into an explicit list.
- * The splitting is very careful to handle commas embedded within specs, to split correctly.
- */
- public static List<String> expandCommaSeparateLocations(String locations) {
- return WildcardGlobs.getGlobsAfterBraceExpansion("{"+locations+"}", false, PhraseTreatment.INTERIOR_NOT_EXPANDABLE, PhraseTreatment.INTERIOR_NOT_EXPANDABLE);
- // don't do this, it tries to expand commas inside parentheses which is not good!
-// QuotedStringTokenizer.builder().addDelimiterChars(",").buildList((String)id);
- }
-
- private final ManagementContext mgmt;
- /** map of defined locations by their ID */
- private final Map<String,LocationDefinition> definedLocations = new LinkedHashMap<String, LocationDefinition>();
-
- protected final Map<String,LocationResolver> resolvers = new LinkedHashMap<String, LocationResolver>();
-
- private final Set<String> specsWarnedOnException = Sets.newConcurrentHashSet();
-
- public BasicLocationRegistry(ManagementContext mgmt) {
- this.mgmt = checkNotNull(mgmt, "mgmt");
- findServices();
- updateDefinedLocations();
- }
-
- protected void findServices() {
- ServiceLoader<LocationResolver> loader = ServiceLoader.load(LocationResolver.class, mgmt.getCatalogClassLoader());
- for (LocationResolver r: loader) {
- registerResolver(r);
- }
- if (log.isDebugEnabled()) log.debug("Location resolvers are: "+resolvers);
- if (resolvers.isEmpty()) log.warn("No location resolvers detected: is src/main/resources correctly included?");
- }
-
- /** Registers the given resolver, invoking {@link LocationResolver#init(ManagementContext)} on the argument
- * and returning true, unless the argument indicates false for {@link EnableableLocationResolver#isEnabled()} */
- public boolean registerResolver(LocationResolver r) {
- r.init(mgmt);
- if (r instanceof EnableableLocationResolver) {
- if (!((EnableableLocationResolver)r).isEnabled()) {
- return false;
- }
- }
- resolvers.put(r.getPrefix(), r);
- return true;
- }
-
- @Override
- public Map<String,LocationDefinition> getDefinedLocations() {
- synchronized (definedLocations) {
- return ImmutableMap.<String,LocationDefinition>copyOf(definedLocations);
- }
- }
-
- @Override
- public LocationDefinition getDefinedLocationById(String id) {
- return definedLocations.get(id);
- }
-
- @Override
- public LocationDefinition getDefinedLocationByName(String name) {
- synchronized (definedLocations) {
- for (LocationDefinition l: definedLocations.values()) {
- if (l.getName().equals(name)) return l;
- }
- return null;
- }
- }
-
- @Override
- public void updateDefinedLocation(LocationDefinition l) {
- synchronized (definedLocations) {
- definedLocations.put(l.getId(), l);
- }
- }
-
- /**
- * Converts the given item from the catalog into a LocationDefinition, and adds it
- * to the registry (overwriting anything already registered with the id
- * {@link CatalogItem#getCatalogItemId()}.
- */
- public void updateDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
- String id = item.getCatalogItemId();
- String symbolicName = item.getSymbolicName();
- String spec = CatalogLocationResolver.NAME + ":" + id;
- Map<String, Object> config = ImmutableMap.<String, Object>of();
- BasicLocationDefinition locDefinition = new BasicLocationDefinition(symbolicName, symbolicName, spec, config);
-
- updateDefinedLocation(locDefinition);
- }
-
- public void removeDefinedLocation(CatalogItem<Location, LocationSpec<?>> item) {
- removeDefinedLocation(item.getSymbolicName());
- }
-
- @Override
- public void removeDefinedLocation(String id) {
- LocationDefinition removed;
- synchronized (definedLocations) {
- removed = definedLocations.remove(id);
- }
- if (removed == null && log.isDebugEnabled()) {
- log.debug("{} was asked to remove location with id {} but no such location was registered", this, id);
- }
- }
-
- public void updateDefinedLocations() {
- synchronized (definedLocations) {
- // first read all properties starting brooklyn.location.named.xxx
- // (would be nice to move to a better way, e.g. yaml, then deprecate this approach, but first
- // we need ability/format for persisting named locations, and better support for adding+saving via REST/GUI)
- int count = 0;
- String NAMED_LOCATION_PREFIX = "brooklyn.location.named.";
- ConfigMap namedLocationProps = mgmt.getConfig().submap(ConfigPredicates.startingWith(NAMED_LOCATION_PREFIX));
- for (String k: namedLocationProps.asMapWithStringKeys().keySet()) {
- String name = k.substring(NAMED_LOCATION_PREFIX.length());
- // If has a dot, then is a sub-property of a named location (e.g. brooklyn.location.named.prod1.user=bob)
- if (!name.contains(".")) {
- // this is a new named location
- String spec = (String) namedLocationProps.asMapWithStringKeys().get(k);
- // make up an ID
- String id = Identifiers.makeRandomId(8);
- Map<String, Object> config = ConfigUtils.filterForPrefixAndStrip(namedLocationProps.asMapWithStringKeys(), k+".");
- definedLocations.put(id, new BasicLocationDefinition(id, name, spec, config));
- count++;
- }
- }
- if (log.isDebugEnabled())
- log.debug("Found "+count+" defined locations from properties (*.named.* syntax): "+definedLocations.values());
- if (getDefinedLocationByName("localhost")==null && !BasicOsDetails.Factory.newLocalhostInstance().isWindows()
- && LocationConfigUtils.isEnabled(mgmt, "brooklyn.location.localhost")) {
- log.debug("Adding a defined location for localhost");
- // add 'localhost' *first*
- ImmutableMap<String, LocationDefinition> oldDefined = ImmutableMap.copyOf(definedLocations);
- definedLocations.clear();
- String id = Identifiers.makeRandomId(8);
- definedLocations.put(id, localhost(id));
- definedLocations.putAll(oldDefined);
- }
-
- for (CatalogItem<Location, LocationSpec<?>> item : mgmt.getCatalog().getCatalogItems(CatalogPredicates.IS_LOCATION)) {
- updateDefinedLocation(item);
- count++;
- }
- }
- }
-
- @VisibleForTesting
- void disablePersistence() {
- // persistence isn't enabled yet anyway (have to manually save things,
- // defining the format and file etc)
- }
-
- protected static BasicLocationDefinition localhost(String id) {
- return new BasicLocationDefinition(id, "localhost", "localhost", null);
- }
-
- /** to catch circular references */
- protected ThreadLocal<Set<String>> specsSeen = new ThreadLocal<Set<String>>();
-
- @Override @Deprecated
- public boolean canMaybeResolve(String spec) {
- return getSpecResolver(spec) != null;
- }
-
- @Override
- public final Location resolve(String spec) {
- return resolve(spec, true, null).get();
- }
-
- @Override @Deprecated
- public final Location resolveIfPossible(String spec) {
- if (!canMaybeResolve(spec)) return null;
- return resolve(spec, null, null).orNull();
- }
-
- @Deprecated /** since 0.7.0 not used */
- public final Maybe<Location> resolve(String spec, boolean manage) {
- return resolve(spec, manage, null);
- }
-
- public Maybe<Location> resolve(String spec, Boolean manage, Map locationFlags) {
- try {
- locationFlags = MutableMap.copyOf(locationFlags);
- if (manage!=null) {
- locationFlags.put(LocalLocationManager.CREATE_UNMANAGED, !manage);
- }
-
- Set<String> seenSoFar = specsSeen.get();
- if (seenSoFar==null) {
- seenSoFar = new LinkedHashSet<String>();
- specsSeen.set(seenSoFar);
- }
- if (seenSoFar.contains(spec))
- return Maybe.absent(Suppliers.ofInstance(new IllegalStateException("Circular reference in definition of location '"+spec+"' ("+seenSoFar+")")));
- seenSoFar.add(spec);
-
- LocationResolver resolver = getSpecResolver(spec);
-
- if (resolver != null) {
- try {
- return Maybe.of(resolver.newLocationFromString(locationFlags, spec, this));
- } catch (RuntimeException e) {
- return Maybe.absent(Suppliers.ofInstance(e));
- }
- }
-
- // problem: but let's ensure that classpath is sane to give better errors in common IDE bogus case;
- // and avoid repeated logging
- String errmsg;
- if (spec == null || specsWarnedOnException.add(spec)) {
- if (resolvers.get("id")==null || resolvers.get("named")==null) {
- log.error("Standard location resolvers not installed, location resolution will fail shortly. "
- + "This usually indicates a classpath problem, such as when running from an IDE which "
- + "has not properly copied META-INF/services from src/main/resources. "
- + "Known resolvers are: "+resolvers.keySet());
- errmsg = "Unresolvable location '"+spec+"': "
- + "Problem detected with location resolver configuration; "
- + resolvers.keySet()+" are the only available location resolvers. "
- + "More information can be found in the logs.";
- } else {
- log.debug("Location resolution failed for '"+spec+"' (if this is being loaded it will fail shortly): known resolvers are: "+resolvers.keySet());
- errmsg = "Unknown location '"+spec+"': "
- + "either this location is not recognised or there is a problem with location resolver configuration.";
- }
- } else {
- // For helpful log message construction: assumes classpath will not suddenly become wrong; might happen with OSGi though!
- if (log.isDebugEnabled()) log.debug("Location resolution failed again for '"+spec+"' (throwing)");
- errmsg = "Unknown location '"+spec+"': "
- + "either this location is not recognised or there is a problem with location resolver configuration.";
- }
-
- return Maybe.absent(Suppliers.ofInstance(new NoSuchElementException(errmsg)));
-
- } finally {
- specsSeen.remove();
- }
- }
-
- @Override
- public final Location resolve(String spec, Map locationFlags) {
- return resolve(spec, null, locationFlags).get();
- }
-
- protected LocationResolver getSpecResolver(String spec) {
- int colonIndex = spec.indexOf(':');
- int bracketIndex = spec.indexOf("(");
- int dividerIndex = (colonIndex < 0) ? bracketIndex : (bracketIndex < 0 ? colonIndex : Math.min(bracketIndex, colonIndex));
- String prefix = dividerIndex >= 0 ? spec.substring(0, dividerIndex) : spec;
- LocationResolver resolver = resolvers.get(prefix);
-
- if (resolver == null)
- resolver = getSpecDefaultResolver(spec);
-
- return resolver;
- }
-
- protected LocationResolver getSpecDefaultResolver(String spec) {
- return getSpecFirstResolver(spec, "id", "named", "jclouds");
- }
- protected LocationResolver getSpecFirstResolver(String spec, String ...resolversToCheck) {
- for (String resolverId: resolversToCheck) {
- LocationResolver resolver = resolvers.get(resolverId);
- if (resolver!=null && resolver.accepts(spec, this))
- return resolver;
- }
- return null;
- }
-
- /** providers default impl for RegistryLocationResolver.accepts */
- public static boolean isResolverPrefixForSpec(LocationResolver resolver, String spec, boolean argumentRequired) {
- if (spec==null) return false;
- if (spec.startsWith(resolver.getPrefix()+":")) return true;
- if (!argumentRequired && spec.equals(resolver.getPrefix())) return true;
- return false;
- }
-
- @Override
- public List<Location> resolve(Iterable<?> spec) {
- List<Location> result = new ArrayList<Location>();
- for (Object id : spec) {
- if (id instanceof String) {
- result.add(resolve((String) id));
- } else if (id instanceof Location) {
- result.add((Location) id);
- } else {
- if (id instanceof Iterable)
- throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; collections of collections not allowed");
- throw new IllegalArgumentException("Cannot resolve '"+id+"' to a location; unsupported type "+
- (id == null ? "null" : id.getClass().getName()));
- }
- }
- return result;
- }
-
- public List<Location> resolveList(Object l) {
- if (l==null) l = Collections.emptyList();
- if (l instanceof String) l = JavaStringEscapes.unwrapJsonishListIfPossible((String)l);
- if (l instanceof Iterable) return resolve((Iterable<?>)l);
- throw new IllegalArgumentException("Location list must be supplied as a collection or a string, not "+
- JavaClassNames.simpleClassName(l)+"/"+l);
- }
-
- @Override
- public Location resolve(LocationDefinition ld) {
- return resolve(ld, null, null).get();
- }
-
- @Override @Deprecated
- public Location resolveForPeeking(LocationDefinition ld) {
- // TODO should clean up how locations are stored, figuring out whether they are shared or not;
- // or maybe better, the API calls to this might just want to get the LocationSpec objects back
-
- // for now we use a 'CREATE_UNMANGED' flag to prevent management (leaks and logging)
- return resolve(ld, ConfigBag.newInstance().configure(LocalLocationManager.CREATE_UNMANAGED, true).getAllConfig());
- }
-
- @Override @Deprecated
- public Location resolve(LocationDefinition ld, Map<?,?> flags) {
- return resolveLocationDefinition(ld, flags, null);
- }
-
- /** @deprecated since 0.7.0 not used (and optionalName was ignored anyway) */
- @Deprecated
- public Location resolveLocationDefinition(LocationDefinition ld, Map locationFlags, String optionalName) {
- return resolve(ld, null, locationFlags).get();
- }
-
- public Maybe<Location> resolve(LocationDefinition ld, Boolean manage, Map locationFlags) {
- ConfigBag newLocationFlags = ConfigBag.newInstance(ld.getConfig())
- .putAll(locationFlags)
- .putIfAbsentAndNotNull(LocationInternal.NAMED_SPEC_NAME, ld.getName())
- .putIfAbsentAndNotNull(LocationInternal.ORIGINAL_SPEC, ld.getName());
- Maybe<Location> result = resolve(ld.getSpec(), manage, newLocationFlags.getAllConfigRaw());
- if (result.isPresent())
- return result;
- throw new IllegalStateException("Cannot instantiate location '"+ld+"' pointing at "+ld.getSpec()+": "+
- Exceptions.collapseText( ((Absent<?>)result).getException() ));
- }
-
- @Override
- public Map getProperties() {
- return mgmt.getConfig().asMapWithStringKeys();
- }
-
- @VisibleForTesting
- public static void setupLocationRegistryForTesting(ManagementContext mgmt) {
- // ensure localhost is added (even on windows)
- LocationDefinition l = mgmt.getLocationRegistry().getDefinedLocationByName("localhost");
- if (l==null) mgmt.getLocationRegistry().updateDefinedLocation(
- BasicLocationRegistry.localhost(Identifiers.makeRandomId(8)) );
-
- ((BasicLocationRegistry)mgmt.getLocationRegistry()).disablePersistence();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicMachineDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicMachineDetails.java b/core/src/main/java/brooklyn/location/basic/BasicMachineDetails.java
deleted file mode 100644
index 543db37..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicMachineDetails.java
+++ /dev/null
@@ -1,181 +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 com.google.common.base.Preconditions.checkNotNull;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-
-import javax.annotation.Nonnull;
-import javax.annotation.concurrent.Immutable;
-
-import org.apache.brooklyn.api.management.Task;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.location.HardwareDetails;
-import brooklyn.location.MachineDetails;
-import brooklyn.location.OsDetails;
-import brooklyn.util.ResourceUtils;
-import brooklyn.util.stream.Streams;
-import brooklyn.util.task.DynamicTasks;
-import brooklyn.util.task.TaskTags;
-import brooklyn.util.task.ssh.internal.PlainSshExecTaskFactory;
-import brooklyn.util.task.system.ProcessTaskWrapper;
-
-import com.google.common.base.CharMatcher;
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Objects;
-import com.google.common.base.Splitter;
-import com.google.common.base.Throwables;
-import com.google.common.collect.Maps;
-import com.google.common.io.CharStreams;
-
-@Immutable
-public class BasicMachineDetails implements MachineDetails {
-
- public static final Logger LOG = LoggerFactory.getLogger(BasicMachineDetails.class);
-
- private final HardwareDetails hardwareDetails;
- private final OsDetails osDetails;
-
- public BasicMachineDetails(HardwareDetails hardwareDetails, OsDetails osDetails) {
- this.hardwareDetails = checkNotNull(hardwareDetails, "hardwareDetails");
- this.osDetails = checkNotNull(osDetails, "osDetails");
- }
-
- @Nonnull
- @Override
- public HardwareDetails getHardwareDetails() {
- return hardwareDetails;
- }
-
- @Nonnull
- @Override
- public OsDetails getOsDetails() {
- return osDetails;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(MachineDetails.class)
- .add("os", osDetails)
- .add("hardware", hardwareDetails)
- .toString();
- }
-
- /**
- * Creates a MachineDetails for the given location by SSHing to the machine and
- * running a Bash script to gather data. Should only be called from within a
- * task context. If this might not be the case then use {@link
- * #taskForSshMachineLocation(SshMachineLocation)} instead.
- */
- static BasicMachineDetails forSshMachineLocation(SshMachineLocation location) {
- return TaskTags.markInessential(DynamicTasks.queueIfPossible(taskForSshMachineLocation(location))
- .orSubmitAsync()
- .asTask())
- .getUnchecked();
- }
-
- /**
- * @return A task that gathers machine details by SSHing to the machine and running
- * a Bash script to gather data.
- */
- static Task<BasicMachineDetails> taskForSshMachineLocation(SshMachineLocation location) {
- BufferedReader reader = new BufferedReader(Streams.reader(
- new ResourceUtils(BasicMachineDetails.class).getResourceFromUrl(
- "classpath://brooklyn/location/basic/os-details.sh")));
- List<String> script;
- try {
- script = CharStreams.readLines(reader);
- } catch (IOException e) {
- LOG.error("Error reading os-details script", e);
- throw Throwables.propagate(e);
- } finally {
- try {
- reader.close();
- } catch (IOException e) {
- // Not rethrowing e because it might obscure an exception caught by the first catch
- LOG.error("Error closing os-details script reader", e);
- }
- }
- Task<BasicMachineDetails> task = new PlainSshExecTaskFactory<String>(location, script)
- .summary("Getting machine details for: " + location)
- .requiringZeroAndReturningStdout()
- .returning(taskToMachineDetailsFunction(location))
- .newTask()
- .asTask();
-
- return task;
- }
-
- private static Function<ProcessTaskWrapper<?>, BasicMachineDetails> taskToMachineDetailsFunction(final SshMachineLocation location) {
- return new Function<ProcessTaskWrapper<?>, BasicMachineDetails>() {
- @Override
- public BasicMachineDetails apply(ProcessTaskWrapper<?> input) {
- if (input.getExitCode() != 0) {
- LOG.warn("Non-zero exit code when fetching machine details for {}; guessing anonymous linux", location);
- return new BasicMachineDetails(new BasicHardwareDetails(null, null),
- BasicOsDetails.Factory.ANONYMOUS_LINUX);
- }
-
- String stdout = input.getStdout();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Found following details at {}: {}", location, stdout);
- }
-
- Map<String,String> details = Maps.newHashMap(Splitter.on(CharMatcher.anyOf("\r\n"))
- .omitEmptyStrings()
- .withKeyValueSeparator(":")
- .split(stdout));
-
- String name = details.remove("name");
- String version = details.remove("version");
- String architecture = details.remove("architecture");
- Integer ram = intOrNull(details, "ram");
- Integer cpuCount = intOrNull(details, "cpus");
- if (!details.isEmpty()) {
- LOG.debug("Unused keys from os-details script: " + Joiner.on(", ").join(details.keySet()));
- }
-
- OsDetails osDetails = new BasicOsDetails(name, architecture, version);
- HardwareDetails hardwareDetails = new BasicHardwareDetails(cpuCount, ram);
- BasicMachineDetails machineDetails = new BasicMachineDetails(hardwareDetails, osDetails);
-
- if (LOG.isDebugEnabled())
- LOG.debug("Machine details for {}: {}", location, machineDetails);
-
- return machineDetails;
- }
-
- private Integer intOrNull(Map<String, String> details, String key) {
- try {
- return Integer.valueOf(details.remove(key));
- } catch (NumberFormatException e) {
- return null;
- }
- }
- };
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicMachineMetadata.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicMachineMetadata.java b/core/src/main/java/brooklyn/location/basic/BasicMachineMetadata.java
deleted file mode 100644
index 6808312..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicMachineMetadata.java
+++ /dev/null
@@ -1,84 +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 brooklyn.location.MachineManagementMixins.MachineMetadata;
-
-import com.google.common.base.Objects;
-
-public class BasicMachineMetadata implements MachineMetadata {
-
- final String id, name, primaryIp;
- final Boolean isRunning;
- final Object originalMetadata;
-
- public BasicMachineMetadata(String id, String name, String primaryIp, Boolean isRunning, Object originalMetadata) {
- super();
- this.id = id;
- this.name = name;
- this.primaryIp = primaryIp;
- this.isRunning = isRunning;
- this.originalMetadata = originalMetadata;
- }
-
- public String getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-
- public String getPrimaryIp() {
- return primaryIp;
- }
-
- public Boolean isRunning() {
- return isRunning;
- }
-
- public Object getOriginalMetadata() {
- return originalMetadata;
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(id, isRunning, name, originalMetadata, primaryIp);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- BasicMachineMetadata other = (BasicMachineMetadata) obj;
- if (!Objects.equal(id, other.id)) return false;
- if (!Objects.equal(name, other.name)) return false;
- if (!Objects.equal(primaryIp, other.primaryIp)) return false;
- if (!Objects.equal(isRunning, other.isRunning)) return false;
- if (!Objects.equal(originalMetadata, other.originalMetadata)) return false;
- return true;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(this).add("id", id).add("name", name).add("originalMetadata", originalMetadata).toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/BasicOsDetails.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/BasicOsDetails.java b/core/src/main/java/brooklyn/location/basic/BasicOsDetails.java
deleted file mode 100644
index a9eba56..0000000
--- a/core/src/main/java/brooklyn/location/basic/BasicOsDetails.java
+++ /dev/null
@@ -1,122 +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 java.util.regex.Pattern;
-import javax.annotation.Nullable;
-import javax.annotation.concurrent.Immutable;
-
-import com.google.common.base.Objects;
-
-import brooklyn.location.OsDetails;
-
-@Immutable
-public class BasicOsDetails implements OsDetails {
-
- final String name, arch, version;
- final boolean is64bit;
- // (?i) forces matches to be case insensitive
- public static final String UNIX_OS_NAME_PATTERNS = "(?i).*linux.*|centos|debian|fedora|gentoo|rhel|slackware|solaris|suse|ubuntu|coreos";
-
- /** Sets is64Bit according to value of arch parameter. */
- public BasicOsDetails(String name, String arch, String version) {
- this(name, arch, version, arch != null && arch.contains("64"));
- }
-
- public BasicOsDetails(String name, String arch, String version, boolean is64Bit) {
- this.name = name; this.arch = arch; this.version = version; this.is64bit = is64Bit;
- }
-
- // TODO: Should be replaced with an enum like Jclouds' OsFamily and isX methods should
- // switch against known cases
- @Nullable
- @Override
- public String getName() {
- return name;
- }
-
- @Nullable
- @Override
- public String getArch() {
- return arch;
- }
-
- @Nullable
- @Override
- public String getVersion() {
- return version;
- }
-
- @Override
- public boolean isWindows() {
- //TODO confirm
- return getName()!=null && getName().toLowerCase().contains("microsoft");
- }
-
- @Override
- public boolean isLinux() {
- return getName() != null && Pattern.matches(UNIX_OS_NAME_PATTERNS, getName());
- }
-
- @Override
- public boolean isMac() {
- return getName()!=null && getName().equals(OsNames.MAC_OS_X);
- }
-
- @Override
- public boolean is64bit() {
- return is64bit;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(OsDetails.class)
- .omitNullValues()
- .add("name", name)
- .add("version", version)
- .add("arch", arch)
- .toString();
- }
-
- public static class OsNames {
- public static final String MAC_OS_X = "Mac OS X";
- }
-
- public static class OsArchs {
- public static final String X_86_64 = "x86_64";
-// public static final String X_86 = "x86";
-// // is this standard? or do we ever need the above?
- public static final String I386 = "i386";
- }
-
- public static class OsVersions {
- public static final String MAC_10_8 = "10.8";
- public static final String MAC_10_9 = "10.9";
- }
-
- public static class Factory {
- public static OsDetails newLocalhostInstance() {
- return new BasicOsDetails(System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"));
- }
-
- public static final OsDetails ANONYMOUS_LINUX = new BasicOsDetails("linux", OsArchs.I386, "unknown");
- public static final OsDetails ANONYMOUS_LINUX_64 = new BasicOsDetails("linux", OsArchs.X_86_64, "unknown");
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/ByonLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/ByonLocationResolver.java b/core/src/main/java/brooklyn/location/basic/ByonLocationResolver.java
deleted file mode 100644
index 7838e24..0000000
--- a/core/src/main/java/brooklyn/location/basic/ByonLocationResolver.java
+++ /dev/null
@@ -1,250 +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 com.google.common.base.Preconditions.checkArgument;
-
-import java.net.InetAddress;
-import java.util.List;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.net.HostAndPort;
-
-import brooklyn.config.ConfigKey;
-import brooklyn.entity.basic.ConfigKeys;
-import brooklyn.entity.basic.Sanitizer;
-import brooklyn.location.Location;
-import brooklyn.location.LocationSpec;
-import brooklyn.location.MachineLocation;
-import brooklyn.management.internal.LocalLocationManager;
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.config.ConfigBag;
-import brooklyn.util.flags.TypeCoercions;
-import brooklyn.util.net.UserAndHostAndPort;
-import brooklyn.util.text.WildcardGlobs;
-import brooklyn.util.text.WildcardGlobs.PhraseTreatment;
-
-/**
- * Examples of valid specs:
- * <ul>
- * <li>byon:(hosts=myhost)
- * <li>byon:(hosts=myhost,myhost2)
- * <li>byon:(hosts="myhost, myhost2")
- * <li>byon:(hosts=myhost,myhost2, name=abc)
- * <li>byon:(hosts="myhost, myhost2", name="my location name")
- * </ul>
- *
- * @author aled
- */
-@SuppressWarnings({"rawtypes"})
-public class ByonLocationResolver extends AbstractLocationResolver {
-
- public static final Logger log = LoggerFactory.getLogger(ByonLocationResolver.class);
-
- public static final String BYON = "byon";
-
- public static final ConfigKey<String> OS_FAMILY = ConfigKeys.newStringConfigKey("osfamily", "OS Family of the machine, either windows or linux", "linux");
-
- public static final Map<String, Class<? extends MachineLocation>> OS_TO_MACHINE_LOCATION_TYPE = ImmutableMap.<String, Class<? extends MachineLocation>>of(
- "windows", WinRmMachineLocation.class,
- "linux", SshMachineLocation.class);
-
- @Override
- public String getPrefix() {
- return BYON;
- }
-
- @Override
- protected Class<? extends Location> getLocationType() {
- return FixedListMachineProvisioningLocation.class;
- }
-
- @Override
- protected SpecParser getSpecParser() {
- return new AbstractLocationResolver.SpecParser(getPrefix()).setExampleUsage("\"byon(hosts='addr1,addr2')\"");
- }
-
- @Override
- protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, brooklyn.location.LocationRegistry registry) {
- ConfigBag config = super.extractConfig(locationFlags, spec, registry);
-
- Object hosts = config.getStringKey("hosts");
- config.remove("hosts");
- String user = (String) config.getStringKey("user");
- Integer port = (Integer) TypeCoercions.coerce(config.getStringKey("port"), Integer.class);
- Class<? extends MachineLocation> locationClass = OS_TO_MACHINE_LOCATION_TYPE.get(config.get(OS_FAMILY));
-
- MutableMap<String, Object> defaultProps = MutableMap.of();
- defaultProps.addIfNotNull("user", user);
- defaultProps.addIfNotNull("port", port);
-
- List<String> hostAddresses;
-
- if (hosts instanceof String) {
- if (((String) hosts).isEmpty()) {
- hostAddresses = ImmutableList.of();
- } else {
- hostAddresses = WildcardGlobs.getGlobsAfterBraceExpansion("{"+hosts+"}",
- true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR);
- }
- } else if (hosts instanceof Iterable) {
- hostAddresses = ImmutableList.copyOf((Iterable<String>)hosts);
- } else {
- throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
- }
- if (hostAddresses.isEmpty()) {
- throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
- }
-
- List<MachineLocation> machines = Lists.newArrayList();
- for (Object host : hostAddresses) {
- LocationSpec<? extends MachineLocation> machineSpec;
- if (host instanceof String) {
- machineSpec = parseMachine((String)host, locationClass, defaultProps, spec);
- } else if (host instanceof Map) {
- machineSpec = parseMachine((Map<String, ?>)host, locationClass, defaultProps, spec);
- } else {
- throw new IllegalArgumentException("Expected machine to be String or Map, but was "+host.getClass().getName()+" ("+host+")");
- }
- machineSpec.configureIfNotNull(LocalLocationManager.CREATE_UNMANAGED, config.get(LocalLocationManager.CREATE_UNMANAGED));
- MachineLocation machine = managementContext.getLocationManager().createLocation(machineSpec);
- machines.add(machine);
- }
-
- config.putStringKey("machines", machines);
-
- return config;
- }
-
- protected LocationSpec<? extends MachineLocation> parseMachine(Map<String, ?> vals, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
- Map<String, Object> valSanitized = Sanitizer.sanitize(vals);
- Map<String, Object> machineConfig = MutableMap.copyOf(vals);
-
- String osfamily = (String) machineConfig.remove(OS_FAMILY.getName());
- String ssh = (String) machineConfig.remove("ssh");
- String winrm = (String) machineConfig.remove("winrm");
- Map<Integer, String> tcpPortMappings = (Map<Integer, String>) machineConfig.get("tcpPortMappings");
-
- checkArgument(ssh != null ^ winrm != null, "Must specify exactly one of 'ssh' or 'winrm' for machine: %s", valSanitized);
-
- UserAndHostAndPort userAndHostAndPort;
- String host;
- int port;
- if (ssh != null) {
- userAndHostAndPort = parseUserAndHostAndPort((String)ssh, 22);
- } else {
- userAndHostAndPort = parseUserAndHostAndPort((String)winrm, 5985);
- }
-
- // If there is a tcpPortMapping defined for the connection-port, then use that for ssh/winrm machine
- port = userAndHostAndPort.getHostAndPort().getPort();
- if (tcpPortMappings != null && tcpPortMappings.containsKey(port)) {
- String override = tcpPortMappings.get(port);
- HostAndPort hostAndPortOverride = HostAndPort.fromString(override);
- if (!hostAndPortOverride.hasPort()) {
- throw new IllegalArgumentException("Invalid portMapping ('"+override+"') for port "+port+" in "+specForErrMsg);
- }
- port = hostAndPortOverride.getPort();
- host = hostAndPortOverride.getHostText().trim();
- } else {
- host = userAndHostAndPort.getHostAndPort().getHostText().trim();
- }
-
- machineConfig.put("address", host);
- try {
- InetAddress.getByName(host);
- } catch (Exception e) {
- throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
- }
-
- if (userAndHostAndPort.getUser() != null) {
- checkArgument(!vals.containsKey("user"), "Must not specify user twice for machine: %s", valSanitized);
- machineConfig.put("user", userAndHostAndPort.getUser());
- }
- if (userAndHostAndPort.getHostAndPort().hasPort()) {
- checkArgument(!vals.containsKey("port"), "Must not specify port twice for machine: %s", valSanitized);
- machineConfig.put("port", port);
- }
- for (Map.Entry<String, ?> entry : defaults.entrySet()) {
- if (!machineConfig.containsKey(entry.getKey())) {
- machineConfig.put(entry.getKey(), entry.getValue());
- }
- }
-
- Class<? extends MachineLocation> locationClassHere = locationClass;
- if (osfamily != null) {
- locationClassHere = OS_TO_MACHINE_LOCATION_TYPE.get(osfamily);
- }
-
- return LocationSpec.create(locationClassHere).configure(machineConfig);
- }
-
- protected LocationSpec<? extends MachineLocation> parseMachine(String val, Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
- Map<String, Object> machineConfig = Maps.newLinkedHashMap();
-
- UserAndHostAndPort userAndHostAndPort = parseUserAndHostAndPort(val);
-
- String host = userAndHostAndPort.getHostAndPort().getHostText().trim();
- machineConfig.put("address", host);
- try {
- InetAddress.getByName(host.trim());
- } catch (Exception e) {
- throw new IllegalArgumentException("Invalid host '"+host+"' specified in '"+specForErrMsg+"': "+e);
- }
-
- if (userAndHostAndPort.getUser() != null) {
- machineConfig.put("user", userAndHostAndPort.getUser());
- }
- if (userAndHostAndPort.getHostAndPort().hasPort()) {
- machineConfig.put("port", userAndHostAndPort.getHostAndPort().getPort());
- }
- for (Map.Entry<String, ?> entry : defaults.entrySet()) {
- if (!machineConfig.containsKey(entry.getKey())) {
- machineConfig.put(entry.getKey(), entry.getValue());
- }
- }
-
- return LocationSpec.create(locationClass).configure(machineConfig);
- }
-
- private UserAndHostAndPort parseUserAndHostAndPort(String val) {
- String userPart = null;
- String hostPart = val;
- if (val.contains("@")) {
- userPart = val.substring(0, val.indexOf("@"));
- hostPart = val.substring(val.indexOf("@")+1);
- }
- return UserAndHostAndPort.fromParts(userPart, HostAndPort.fromString(hostPart));
- }
-
- private UserAndHostAndPort parseUserAndHostAndPort(String val, int defaultPort) {
- UserAndHostAndPort result = parseUserAndHostAndPort(val);
- if (!result.getHostAndPort().hasPort()) {
- result = UserAndHostAndPort.fromParts(result.getUser(), result.getHostAndPort().getHostText(), defaultPort);
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/CatalogLocationResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/CatalogLocationResolver.java b/core/src/main/java/brooklyn/location/basic/CatalogLocationResolver.java
deleted file mode 100644
index a036c85..0000000
--- a/core/src/main/java/brooklyn/location/basic/CatalogLocationResolver.java
+++ /dev/null
@@ -1,80 +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 com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.brooklyn.api.catalog.CatalogItem;
-import org.apache.brooklyn.api.management.ManagementContext;
-
-import brooklyn.catalog.internal.CatalogUtils;
-import brooklyn.location.Location;
-import brooklyn.location.LocationRegistry;
-import brooklyn.location.LocationResolver;
-import brooklyn.location.LocationSpec;
-
-/**
- * Given a location spec in the form {@code brooklyn.catalog:<symbolicName>:<version>},
- * looks up the catalog to get its definition and creates such a location.
- */
-public class CatalogLocationResolver implements LocationResolver {
-
- @SuppressWarnings("unused")
- private static final Logger log = LoggerFactory.getLogger(CatalogLocationResolver.class);
-
- public static final String NAME = "brooklyn.catalog";
-
- private ManagementContext managementContext;
-
- @Override
- public void init(ManagementContext managementContext) {
- this.managementContext = checkNotNull(managementContext, "managementContext");
- }
-
- @Override
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public Location newLocationFromString(Map locationFlags, String spec, brooklyn.location.LocationRegistry registry) {
- String id = spec.substring(NAME.length()+1);
- CatalogItem<?, ?> item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id);
- LocationSpec<?> origLocSpec = managementContext.getCatalog().createSpec((CatalogItem<Location, LocationSpec<?>>)item);
- LocationSpec<?> locSpec = LocationSpec.create(origLocSpec)
- .configure(locationFlags);
- return managementContext.getLocationManager().createLocation(locSpec);
- }
-
- @Override
- public String getPrefix() {
- return NAME;
- }
-
- /**
- * accepts anything that looks like it will be a YAML catalog item (e.g. starting "brooklyn.locations")
- */
- @Override
- public boolean accepts(String spec, LocationRegistry registry) {
- if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
- if (registry.getDefinedLocationByName(spec)!=null) return true;
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/DefinedLocationByIdResolver.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/DefinedLocationByIdResolver.java b/core/src/main/java/brooklyn/location/basic/DefinedLocationByIdResolver.java
deleted file mode 100644
index 62aaf66..0000000
--- a/core/src/main/java/brooklyn/location/basic/DefinedLocationByIdResolver.java
+++ /dev/null
@@ -1,75 +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 com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.Map;
-
-import org.apache.brooklyn.api.management.ManagementContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import brooklyn.location.Location;
-import brooklyn.location.LocationDefinition;
-import brooklyn.location.LocationRegistry;
-import brooklyn.location.LocationResolver;
-
-/**
- * looks up based on ID in DefinedLocations map
- */
-public class DefinedLocationByIdResolver implements LocationResolver {
-
- public static final Logger log = LoggerFactory.getLogger(DefinedLocationByIdResolver.class);
-
- public static final String ID = "id";
-
- private volatile ManagementContext managementContext;
-
- @Override
- public void init(ManagementContext managementContext) {
- this.managementContext = checkNotNull(managementContext, "managementContext");
- }
-
- @SuppressWarnings({ "rawtypes" })
- @Override
- public Location newLocationFromString(Map locationFlags, String spec, brooklyn.location.LocationRegistry registry) {
- String id = spec;
- if (spec.toLowerCase().startsWith(ID+":")) {
- id = spec.substring( (ID+":").length() );
- }
- LocationDefinition ld = registry.getDefinedLocationById(id);
- ld.getSpec();
- return ((BasicLocationRegistry)registry).resolveLocationDefinition(ld, locationFlags, null);
- }
-
- @Override
- public String getPrefix() {
- return ID;
- }
-
- /** accepts anything starting id:xxx or just xxx where xxx is a defined location ID */
- @Override
- public boolean accepts(String spec, LocationRegistry registry) {
- if (BasicLocationRegistry.isResolverPrefixForSpec(this, spec, false)) return true;
- if (registry.getDefinedLocationById(spec)!=null) return true;
- return false;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/e2c57058/core/src/main/java/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java b/core/src/main/java/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
deleted file mode 100644
index a426b6e..0000000
--- a/core/src/main/java/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java
+++ /dev/null
@@ -1,67 +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 java.util.Map;
-
-import org.slf4j.Logger;
-
-import brooklyn.config.ConfigKey;
-
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.ImmutableMap;
-
-/**
-* @deprecated since 0.6; for use only in converting deprecated flags; will be deleted in future version.
-*/
-public class DeprecatedKeysMappingBuilder {
- private final ImmutableMap.Builder<String,String> builder = new ImmutableMap.Builder<String,String>();
- private final Logger logger;
-
- public DeprecatedKeysMappingBuilder(Logger logger) {
- this.logger = logger;
- }
-
- public DeprecatedKeysMappingBuilder camelToHyphen(ConfigKey<?> key) {
- return camelToHyphen(key.getName());
- }
-
- public DeprecatedKeysMappingBuilder camelToHyphen(String key) {
- String hyphen = toHyphen(key);
- if (key.equals(hyphen)) {
- logger.warn("Invalid attempt to convert camel-case key {} to deprecated hyphen-case: both the same", hyphen);
- } else {
- builder.put(hyphen, key);
- }
- return this;
- }
-
- public DeprecatedKeysMappingBuilder putAll(Map<String,String> vals) {
- builder.putAll(vals);
- return this;
- }
-
- public Map<String,String> build() {
- return builder.build();
- }
-
- private String toHyphen(String word) {
- return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, word);
- }
-}