Return-Path: X-Original-To: apmail-brooklyn-commits-archive@minotaur.apache.org Delivered-To: apmail-brooklyn-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 9351D183E0 for ; Wed, 19 Aug 2015 11:10:24 +0000 (UTC) Received: (qmail 97277 invoked by uid 500); 19 Aug 2015 11:10:24 -0000 Delivered-To: apmail-brooklyn-commits-archive@brooklyn.apache.org Received: (qmail 97247 invoked by uid 500); 19 Aug 2015 11:10:24 -0000 Mailing-List: contact commits-help@brooklyn.incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@brooklyn.incubator.apache.org Delivered-To: mailing list commits@brooklyn.incubator.apache.org Received: (qmail 97238 invoked by uid 99); 19 Aug 2015 11:10:24 -0000 Received: from Unknown (HELO spamd3-us-west.apache.org) (209.188.14.142) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 19 Aug 2015 11:10:24 +0000 Received: from localhost (localhost [127.0.0.1]) by spamd3-us-west.apache.org (ASF Mail Server at spamd3-us-west.apache.org) with ESMTP id E1283182108 for ; Wed, 19 Aug 2015 11:10:23 +0000 (UTC) X-Virus-Scanned: Debian amavisd-new at spamd3-us-west.apache.org X-Spam-Flag: NO X-Spam-Score: 1.795 X-Spam-Level: * X-Spam-Status: No, score=1.795 tagged_above=-999 required=6.31 tests=[KAM_ASCII_DIVIDERS=0.8, KAM_LAZY_DOMAIN_SECURITY=1, RP_MATCHES_RCVD=-0.006, URIBL_BLOCKED=0.001] autolearn=disabled Received: from mx1-eu-west.apache.org ([10.40.0.8]) by localhost (spamd3-us-west.apache.org [10.40.0.10]) (amavisd-new, port 10024) with ESMTP id L4hXpxbzUpvY for ; Wed, 19 Aug 2015 11:10:10 +0000 (UTC) Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by mx1-eu-west.apache.org (ASF Mail Server at mx1-eu-west.apache.org) with SMTP id 1B8243683C for ; Wed, 19 Aug 2015 11:09:26 +0000 (UTC) Received: (qmail 88790 invoked by uid 99); 19 Aug 2015 11:09:21 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Wed, 19 Aug 2015 11:09:21 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 1C879E095F; Wed, 19 Aug 2015 11:09:21 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: heneveld@apache.org To: commits@brooklyn.incubator.apache.org Date: Wed, 19 Aug 2015 11:10:20 -0000 Message-Id: <129b53f37192404a94c9326a877aa9f0@git.apache.org> In-Reply-To: <2e877560197c4bf1beceabf8195151bb@git.apache.org> References: <2e877560197c4bf1beceabf8195151bb@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [62/72] [abbrv] incubator-brooklyn git commit: BROOKLYN-162 - jclouds last few package prefixes needed, and tidy in core and elsewhere related (or observed in the process) http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java b/core/src/main/java/org/apache/brooklyn/location/basic/AggregatingMachineProvisioningLocation.java deleted file mode 100644 index 2898ea8..0000000 --- a/core/src/main/java/org/apache/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 org.apache.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 org.apache.brooklyn.api.location.MachineLocation; -import org.apache.brooklyn.api.location.MachineProvisioningLocation; -import org.apache.brooklyn.api.location.NoMachinesAvailableException; -import org.apache.brooklyn.util.core.flags.SetFromFlag; -import org.apache.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 extends AbstractLocation - implements MachineProvisioningLocation, Closeable { - - private Object lock; - - @SetFromFlag - protected List> provisioners; - - @SetFromFlag - protected Map> 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.>newArrayList(); - inUse = Maps.>newLinkedHashMap(); - } - return super.configure(properties); - } - - @Override - public AggregatingMachineProvisioningLocation 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.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 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 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 getProvisioningFlags(Collection tags) { - return Maps.newLinkedHashMap(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicHardwareDetails.java deleted file mode 100644 index 4393884..0000000 --- a/core/src/main/java/org/apache/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 org.apache.brooklyn.location.basic; - -import javax.annotation.concurrent.Immutable; - -import com.google.common.base.Objects; - -import org.apache.brooklyn.api.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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationDefinition.java deleted file mode 100644 index cae2986..0000000 --- a/core/src/main/java/org/apache/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 org.apache.brooklyn.location.basic; - -import java.util.Map; - -import org.apache.brooklyn.api.location.LocationDefinition; -import org.apache.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 config; - - public BasicLocationDefinition(String name, String spec, Map config) { - this(Identifiers.makeRandomId(8), name, spec, config); - } - - public BasicLocationDefinition(String id, String name, String spec, Map config) { - this.id = Preconditions.checkNotNull(id); - this.name = name; - this.spec = Preconditions.checkNotNull(spec); - this.config = config==null ? ImmutableMap.of() : ImmutableMap.copyOf(config); - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } - - public String getSpec() { - return spec; - } - - @Override - public Map 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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java deleted file mode 100644 index 7f08e04..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicLocationRegistry.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.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.location.Location; -import org.apache.brooklyn.api.location.LocationDefinition; -import org.apache.brooklyn.api.location.LocationRegistry; -import org.apache.brooklyn.api.location.LocationResolver; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.config.ConfigMap; -import org.apache.brooklyn.core.catalog.CatalogPredicates; -import org.apache.brooklyn.core.config.ConfigPredicates; -import org.apache.brooklyn.core.config.ConfigUtils; -import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.exceptions.Exceptions; -import org.apache.brooklyn.util.guava.Maybe; -import org.apache.brooklyn.util.guava.Maybe.Absent; -import org.apache.brooklyn.util.javalang.JavaClassNames; -import org.apache.brooklyn.util.text.Identifiers; -import org.apache.brooklyn.util.text.WildcardGlobs; -import org.apache.brooklyn.util.text.StringEscapes.JavaStringEscapes; -import org.apache.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. - *

- * 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. - *

- * 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)}. - *

- * 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. - *

- * To add a location to the catalog, and then to resolve a location that is in the catalog, - * it goes through the following steps: - * - *

    - *
  1. Call {@link BrooklynCatalog#addItems(String)} - *
      - *
    1. This automatically calls {@link #updateDefinedLocation(CatalogItem)} - *
    2. A LocationDefinition is creating, using as its id the {@link CatalogItem#getSymbolicName()}. - * The definition's spec is {@code brooklyn.catalog::}, - *
    - *
  2. 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"). - *
      - *
    1. This automatically calls {@link #resolve(String)}. - *
    2. The LocationDefinition is found by lookig up this name. - *
    3. The {@link LocationDefiniton.getSpec()} is retrieved; the right {@link LocationResolver} is - * found for it. - *
    4. This uses the {@link CatalogLocationResolver}, because the spec starts with {@code brooklyn.catalog:}. - *
    5. This resolver extracts from the spec the :, and looks up the - * catalog item using {@link BrooklynCatalog#getCatalogItem(String, String)}. - *
    6. It then creates a {@link LocationSpec} by calling {@link BrooklynCatalog#createSpec(CatalogItem)}. - *
        - *
      1. This first tries to use the type (that is in the YAML) as a simple Java class. - *
      2. If that fails, it will resolve the type using {@link #resolve(String, Boolean, Map)}, which - * returns an actual location object. - *
      3. It extracts from that location object the appropriate metadata to create a {@link LocationSpec}, - * returns the spec and discards the location object. - *
      - *
    7. The resolver creates the {@link Location} from the {@link LocationSpec} - *
    - *
- * - * 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 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 definedLocations = new LinkedHashMap(); - - protected final Map resolvers = new LinkedHashMap(); - - private final Set specsWarnedOnException = Sets.newConcurrentHashSet(); - - public BasicLocationRegistry(ManagementContext mgmt) { - this.mgmt = checkNotNull(mgmt, "mgmt"); - findServices(); - updateDefinedLocations(); - } - - protected void findServices() { - ServiceLoader 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 LocationResolver.EnableableLocationResolver#isEnabled()} */ - public boolean registerResolver(LocationResolver r) { - r.init(mgmt); - if (r instanceof LocationResolver.EnableableLocationResolver) { - if (!((LocationResolver.EnableableLocationResolver)r).isEnabled()) { - return false; - } - } - resolvers.put(r.getPrefix(), r); - return true; - } - - @Override - public Map getDefinedLocations() { - synchronized (definedLocations) { - return ImmutableMap.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> item) { - String id = item.getCatalogItemId(); - String symbolicName = item.getSymbolicName(); - String spec = CatalogLocationResolver.NAME + ":" + id; - Map config = ImmutableMap.of(); - BasicLocationDefinition locDefinition = new BasicLocationDefinition(symbolicName, symbolicName, spec, config); - - updateDefinedLocation(locDefinition); - } - - public void removeDefinedLocation(CatalogItem> 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 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 oldDefined = ImmutableMap.copyOf(definedLocations); - definedLocations.clear(); - String id = Identifiers.makeRandomId(8); - definedLocations.put(id, localhost(id)); - definedLocations.putAll(oldDefined); - } - - for (CatalogItem> 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> specsSeen = new ThreadLocal>(); - - @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 resolve(String spec, boolean manage) { - return resolve(spec, manage, null); - } - - public Maybe resolve(String spec, Boolean manage, Map locationFlags) { - try { - locationFlags = MutableMap.copyOf(locationFlags); - if (manage!=null) { - locationFlags.put(LocalLocationManager.CREATE_UNMANAGED, !manage); - } - - Set seenSoFar = specsSeen.get(); - if (seenSoFar==null) { - seenSoFar = new LinkedHashSet(); - 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 resolve(Iterable spec) { - List result = new ArrayList(); - 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 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 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 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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java deleted file mode 100644 index e92deaf..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineDetails.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.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.location.HardwareDetails; -import org.apache.brooklyn.api.location.MachineDetails; -import org.apache.brooklyn.api.location.OsDetails; -import org.apache.brooklyn.api.mgmt.Task; -import org.apache.brooklyn.util.core.ResourceUtils; -import org.apache.brooklyn.util.core.task.DynamicTasks; -import org.apache.brooklyn.util.core.task.TaskTags; -import org.apache.brooklyn.util.core.task.ssh.internal.PlainSshExecTaskFactory; -import org.apache.brooklyn.util.core.task.system.ProcessTaskWrapper; -import org.apache.brooklyn.util.stream.Streams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -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 taskForSshMachineLocation(SshMachineLocation location) { - BufferedReader reader = new BufferedReader(Streams.reader( - new ResourceUtils(BasicMachineDetails.class).getResourceFromUrl( - "classpath://org/apache/brooklyn/location/basic/os-details.sh"))); - List 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 task = new PlainSshExecTaskFactory(location, script) - .summary("Getting machine details for: " + location) - .requiringZeroAndReturningStdout() - .returning(taskToMachineDetailsFunction(location)) - .newTask() - .asTask(); - - return task; - } - - private static Function, BasicMachineDetails> taskToMachineDetailsFunction(final SshMachineLocation location) { - return new Function, 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 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 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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicMachineMetadata.java deleted file mode 100644 index 95c8f0e..0000000 --- a/core/src/main/java/org/apache/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 org.apache.brooklyn.location.basic; - -import com.google.common.base.Objects; - -import org.apache.brooklyn.api.location.MachineManagementMixins; - -public class BasicMachineMetadata implements MachineManagementMixins.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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java b/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java deleted file mode 100644 index 7ab72c7..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/BasicOsDetails.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.location.basic; - -import java.util.regex.Pattern; - -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; - -import com.google.common.base.Objects; - -import org.apache.brooklyn.api.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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/ByonLocationResolver.java deleted file mode 100644 index 8a00cda..0000000 --- a/core/src/main/java/org/apache/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 org.apache.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.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.location.LocationRegistry; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.location.MachineLocation; -import org.apache.brooklyn.config.ConfigKey; -import org.apache.brooklyn.core.config.ConfigKeys; -import org.apache.brooklyn.core.config.Sanitizer; -import org.apache.brooklyn.core.mgmt.internal.LocalLocationManager; -import org.apache.brooklyn.util.collections.MutableMap; -import org.apache.brooklyn.util.core.config.ConfigBag; -import org.apache.brooklyn.util.core.flags.TypeCoercions; -import org.apache.brooklyn.util.net.UserAndHostAndPort; -import org.apache.brooklyn.util.text.WildcardGlobs; -import org.apache.brooklyn.util.text.WildcardGlobs.PhraseTreatment; -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; - -/** - * Examples of valid specs: - *
    - *
  • byon:(hosts=myhost) - *
  • byon:(hosts=myhost,myhost2) - *
  • byon:(hosts="myhost, myhost2") - *
  • byon:(hosts=myhost,myhost2, name=abc) - *
  • byon:(hosts="myhost, myhost2", name="my location name") - *
- * - * @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 OS_FAMILY = ConfigKeys.newStringConfigKey("osfamily", "OS Family of the machine, either windows or linux", "linux"); - - public static final Map> OS_TO_MACHINE_LOCATION_TYPE = ImmutableMap.>of( - "windows", WinRmMachineLocation.class, - "linux", SshMachineLocation.class); - - @Override - public String getPrefix() { - return BYON; - } - - @Override - protected Class 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, 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 locationClass = OS_TO_MACHINE_LOCATION_TYPE.get(config.get(OS_FAMILY)); - - MutableMap defaultProps = MutableMap.of(); - defaultProps.addIfNotNull("user", user); - defaultProps.addIfNotNull("port", port); - - List 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)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 machines = Lists.newArrayList(); - for (Object host : hostAddresses) { - LocationSpec machineSpec; - if (host instanceof String) { - machineSpec = parseMachine((String)host, locationClass, defaultProps, spec); - } else if (host instanceof Map) { - machineSpec = parseMachine((Map)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 parseMachine(Map vals, Class locationClass, Map defaults, String specForErrMsg) { - Map valSanitized = Sanitizer.sanitize(vals); - Map 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 tcpPortMappings = (Map) 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 entry : defaults.entrySet()) { - if (!machineConfig.containsKey(entry.getKey())) { - machineConfig.put(entry.getKey(), entry.getValue()); - } - } - - Class locationClassHere = locationClass; - if (osfamily != null) { - locationClassHere = OS_TO_MACHINE_LOCATION_TYPE.get(osfamily); - } - - return LocationSpec.create(locationClassHere).configure(machineConfig); - } - - protected LocationSpec parseMachine(String val, Class locationClass, Map defaults, String specForErrMsg) { - Map 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 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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java deleted file mode 100644 index 1b87398..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/CatalogLocationResolver.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.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.location.Location; -import org.apache.brooklyn.api.location.LocationRegistry; -import org.apache.brooklyn.api.location.LocationResolver; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.apache.brooklyn.core.catalog.internal.CatalogUtils; - -/** - * Given a location spec in the form {@code brooklyn.catalog::}, - * 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, LocationRegistry registry) { - String id = spec.substring(NAME.length()+1); - CatalogItem item = CatalogUtils.getCatalogItemOptionalVersion(managementContext, id); - LocationSpec origLocSpec = managementContext.getCatalog().createSpec((CatalogItem>)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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java b/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java deleted file mode 100644 index 3c4cec0..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/DefinedLocationByIdResolver.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.location.basic; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.location.LocationDefinition; -import org.apache.brooklyn.api.location.LocationRegistry; -import org.apache.brooklyn.api.location.LocationResolver; -import org.apache.brooklyn.api.mgmt.ManagementContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 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, 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/a1ad34d7/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java ---------------------------------------------------------------------- diff --git a/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java b/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java deleted file mode 100644 index a165086..0000000 --- a/core/src/main/java/org/apache/brooklyn/location/basic/DeprecatedKeysMappingBuilder.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.brooklyn.location.basic; - -import java.util.Map; - -import org.apache.brooklyn.config.ConfigKey; -import org.slf4j.Logger; - -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 builder = new ImmutableMap.Builder(); - 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 vals) { - builder.putAll(vals); - return this; - } - - public Map build() { - return builder.build(); - } - - private String toHyphen(String word) { - return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, word); - } -}