Merge branch 'master' of github.com:jclouds/jclouds

This commit is contained in:
Lili Nader 2010-10-27 12:34:41 -07:00
commit 9b28ed54ab
205 changed files with 5693 additions and 1889 deletions

View File

@ -49,7 +49,7 @@ import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
@ -270,7 +270,7 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties());
} }

View File

@ -36,7 +36,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -139,7 +139,7 @@ public class AtmosBlobRequestSignerTest extends RestClientTest<AtmosStorageAsync
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties());
} }

View File

@ -19,12 +19,16 @@
package org.jclouds.aws.config; package org.jclouds.aws.config;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.get;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static org.jclouds.aws.reference.AWSConstants.PROPERTY_REGIONS; import static org.jclouds.aws.reference.AWSConstants.PROPERTY_REGIONS;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -39,14 +43,13 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.http.annotation.ClientError; import org.jclouds.http.annotation.ClientError;
import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.Redirection;
import org.jclouds.http.annotation.ServerError; import org.jclouds.http.annotation.ServerError;
import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key; import com.google.inject.Key;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -61,8 +64,7 @@ import com.google.inject.name.Names;
@RequiresHttp @RequiresHttp
public class AWSRestClientModule<S, A> extends RestClientModule<S, A> { public class AWSRestClientModule<S, A> extends RestClientModule<S, A> {
public AWSRestClientModule(Class<S> syncClientType, Class<A> asyncClientType, public AWSRestClientModule(Class<S> syncClientType, Class<A> asyncClientType, Map<Class<?>, Class<?>> delegates) {
Map<Class<?>, Class<?>> delegates) {
super(syncClientType, asyncClientType, delegates); super(syncClientType, asyncClientType, delegates);
} }
@ -74,12 +76,13 @@ public class AWSRestClientModule<S, A> extends RestClientModule<S, A> {
@Singleton @Singleton
@Region @Region
protected Map<String, URI> provideRegions(Injector injector) { protected Map<String, URI> provideRegions(Injector injector) {
String regionString = injector.getInstance(Key.get(String.class, Names String regionString = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_REGIONS)));
.named(PROPERTY_REGIONS))); Map<String, URI> regions = newLinkedHashMap();
Map<String, URI> regions = Maps.newLinkedHashMap();
for (String region : Splitter.on(',').split(regionString)) { for (String region : Splitter.on(',').split(regionString)) {
regions.put(region, URI.create(injector.getInstance(Key.get(String.class, Names regions.put(
.named(Constants.PROPERTY_ENDPOINT + "." + region))))); region,
URI.create(injector.getInstance(Key.get(String.class,
Names.named(Constants.PROPERTY_ENDPOINT + "." + region)))));
} }
return regions; return regions;
} }
@ -94,33 +97,35 @@ public class AWSRestClientModule<S, A> extends RestClientModule<S, A> {
@Provides @Provides
@Singleton @Singleton
@Region @Region
protected String getDefaultRegion(@Provider final URI uri, @Region Map<String, URI> map) { protected String getDefaultRegion(@Provider final URI uri, @Region Map<String, URI> map, LoggerFactory logFactory) {
return Iterables.find(map.entrySet(), new Predicate<Entry<String, URI>>() { try {
return find(map.entrySet(), new Predicate<Entry<String, URI>>() {
@Override @Override
public boolean apply(Entry<String, URI> input) { public boolean apply(Entry<String, URI> input) {
return input.getValue().equals(uri); return input.getValue().equals(uri);
} }
}).getKey(); }).getKey();
} catch (NoSuchElementException e) {
String region = get(map.keySet(), 0);
logFactory.getLogger("jclouds.compute").warn(
"failed to find region for current endpoint %s in %s; choosing first: %s", uri, map, region);
return region;
}
} }
@Override @Override
protected void bindErrorHandlers() { protected void bindErrorHandlers() {
bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to( bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class);
ParseAWSErrorFromXmlContent.class); bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class);
bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to( bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class);
ParseAWSErrorFromXmlContent.class);
bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(
ParseAWSErrorFromXmlContent.class);
} }
@Override @Override
protected void bindRetryHandlers() { protected void bindRetryHandlers() {
bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to( bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to(AWSRedirectionRetryHandler.class);
AWSRedirectionRetryHandler.class); bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AWSClientErrorRetryHandler.class);
bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(
AWSClientErrorRetryHandler.class);
} }
} }

View File

@ -0,0 +1,79 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.aws.ec2.compute.config;
import org.jclouds.aws.ec2.compute.strategy.EC2DestroyNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2GetNodeMetadataStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2ListNodesStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RebootNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy;
import org.jclouds.compute.config.BindComputeStrategiesByClass;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
/**
* @author Adrian Cole
*/
public class EC2BindComputeStrategiesByClass extends BindComputeStrategiesByClass {
@Override
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EC2RunNodesAndAddToSetStrategy.class;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return null;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return EC2DestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return EC2GetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return EC2ListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return EC2RebootNodeStrategy.class;
}
}

View File

@ -0,0 +1,56 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.aws.ec2.compute.config;
import java.util.Set;
import org.jclouds.aws.ec2.compute.suppliers.EC2HardwareSupplier;
import org.jclouds.aws.ec2.compute.suppliers.EC2ImageSupplier;
import org.jclouds.aws.ec2.compute.suppliers.EC2LocationSupplier;
import org.jclouds.compute.config.BindComputeSuppliersByClass;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import com.google.common.base.Supplier;
/**
* @author Adrian Cole
*/
public class EC2BindComputeSuppliersByClass extends BindComputeSuppliersByClass {
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return EC2HardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return EC2ImageSupplier.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return org.jclouds.aws.suppliers.DefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return EC2LocationSupplier.class;
}
}

View File

@ -25,7 +25,6 @@ import static org.jclouds.compute.domain.OsFamily.CENTOS;
import static org.jclouds.compute.domain.OsFamily.UBUNTU; import static org.jclouds.compute.domain.OsFamily.UBUNTU;
import java.util.Map; import java.util.Map;
import java.util.Set;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -33,30 +32,14 @@ import javax.inject.Singleton;
import org.jclouds.aws.ec2.compute.EC2ComputeService; import org.jclouds.aws.ec2.compute.EC2ComputeService;
import org.jclouds.aws.ec2.compute.domain.RegionAndName; import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.compute.strategy.EC2DestroyLoadBalancerStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2DestroyLoadBalancerStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2DestroyNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2GetNodeMetadataStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2ListNodesStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2LoadBalanceNodesStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2LoadBalanceNodesStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RebootNodeStrategy;
import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy;
import org.jclouds.aws.ec2.compute.suppliers.EC2HardwareSupplier;
import org.jclouds.aws.ec2.compute.suppliers.EC2ImageSupplier;
import org.jclouds.aws.ec2.compute.suppliers.EC2LocationSupplier;
import org.jclouds.aws.ec2.compute.suppliers.RegionAndNameToImageSupplier; import org.jclouds.aws.ec2.compute.suppliers.RegionAndNameToImageSupplier;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyLoadBalancerStrategy; import org.jclouds.compute.strategy.DestroyLoadBalancerStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.LoadBalanceNodesStrategy; import org.jclouds.compute.strategy.LoadBalanceNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.domain.Location;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier; import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier;
@ -74,6 +57,8 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod
@Override @Override
protected void configure() { protected void configure() {
install(new EC2ComputeServiceDependenciesModule()); install(new EC2ComputeServiceDependenciesModule());
install(new EC2BindComputeStrategiesByClass());
install(new EC2BindComputeSuppliersByClass());
super.configure(); super.configure();
} }
@ -91,14 +76,14 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod
@Provides @Provides
@Singleton @Singleton
protected Supplier<Map<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache( protected Supplier<Map<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache(
@Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) { @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Map<RegionAndName, ? extends Image>>( return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Map<RegionAndName, ? extends Image>>(
authException, seconds, new Supplier<Map<RegionAndName, ? extends Image>>() { authException, seconds, new Supplier<Map<RegionAndName, ? extends Image>>() {
@Override @Override
public Map<RegionAndName, ? extends Image> get() { public Map<RegionAndName, ? extends Image> get() {
return supplier.get(); return supplier.get();
} }
}); });
} }
@Override @Override
@ -106,64 +91,4 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod
bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class); bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class);
bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class); bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class);
} }
@Override
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EC2RunNodesAndAddToSetStrategy.class;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return null;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return EC2DestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return EC2GetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return EC2HardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return EC2ImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return EC2ListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return EC2RebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return org.jclouds.aws.suppliers.DefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return EC2LocationSupplier.class;
}
} }

View File

@ -53,12 +53,12 @@ public class EC2DestroyNodeStrategy implements DestroyNodeStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata destroyNode(String id) {
String[] parts = parseHandle(id); String[] parts = parseHandle(id);
String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];
ec2Client.getInstanceServices().terminateInstancesInRegion(region, ec2Client.getInstanceServices().terminateInstancesInRegion(region,
instanceId); instanceId);
return getNode.execute(id); return getNode.getNode(id);
} }
} }

View File

@ -53,7 +53,7 @@ public class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata getNode(String id) {
String[] parts = parseHandle(id); String[] parts = parseHandle(id);
String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];

View File

@ -77,7 +77,7 @@ public class EC2ListNodesStrategy implements ListNodesStrategy {
} }
@Override @Override
public Set<? extends ComputeMetadata> list() { public Set<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all()); return listDetailsOnNodesMatching(NodePredicates.all());
} }

View File

@ -46,12 +46,12 @@ public class EC2RebootNodeStrategy implements RebootNodeStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata rebootNode(String id) {
String[] parts = parseHandle(id); String[] parts = parseHandle(id);
String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];
client.rebootInstancesInRegion(region, instanceId); client.rebootInstancesInRegion(region, instanceId);
return getNode.execute(id); return getNode.getNode(id);
} }
} }

View File

@ -39,7 +39,7 @@ import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -101,7 +101,7 @@ public class CloudWatchAsyncClientTest extends RestClientTest<CloudWatchAsyncCli
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("cloudwatch", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("cloudwatch", "identity", "credential", new Properties());
} }

View File

@ -0,0 +1,63 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.aws.config;
import static org.testng.Assert.assertEquals;
import java.net.URI;
import java.util.Map;
import org.jclouds.aws.ec2.EC2AsyncClient;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.logging.jdk.JDKLogger;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
/**
*
* @author Adrian Cole
*/
@Test(sequential = true, groups = { "unit" }, testName = "aws.AWSRestClientModuleTest")
public class AWSRestClientModuleTest {
@Test
public void testDefaultRegionWhenThereIsAMatch() {
AWSRestClientModule<EC2Client, EC2AsyncClient> module = new AWSRestClientModule<EC2Client, EC2AsyncClient>(
EC2Client.class, EC2AsyncClient.class);
URI currentEndpoint = URI.create("http://region1");
Map<String, URI> map = ImmutableMap.of("region1", currentEndpoint, "region2", URI.create("http://region2"));
assertEquals("region1", module.getDefaultRegion(currentEndpoint, map, new JDKLogger.JDKLoggerFactory()));
}
@Test
public void testDefaultRegionWhenThereIsNoMatch() {
AWSRestClientModule<EC2Client, EC2AsyncClient> module = new AWSRestClientModule<EC2Client, EC2AsyncClient>(
EC2Client.class, EC2AsyncClient.class);
URI currentEndpoint = URI.create("http://region3");
Map<String, URI> map = ImmutableMap.of("region1", currentEndpoint, "region2", URI.create("http://region2"));
assertEquals("region1", module.getDefaultRegion(currentEndpoint, map, new JDKLogger.JDKLoggerFactory()));
}
}

View File

@ -40,7 +40,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -102,7 +102,7 @@ public abstract class BaseEC2AsyncClientTest<T> extends RestClientTest<T> {
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("ec2", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("ec2", "identity", "credential", new Properties());
} }

View File

@ -38,7 +38,7 @@ import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -103,7 +103,7 @@ public class ELBAsyncClientTest extends RestClientTest<ELBAsyncClient> {
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("elb", "identity", "credential", return new RestContextFactory().createContextSpec("elb", "identity", "credential",
new Properties()); new Properties());
} }

View File

@ -29,7 +29,7 @@ import org.jclouds.aws.s3.filters.RequestAuthorizeSignature;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -65,7 +65,7 @@ public abstract class BaseS3AsyncClientTest extends RestClientTest<S3AsyncClient
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties());
} }

View File

@ -36,7 +36,7 @@ import org.jclouds.io.payloads.PhantomPayload;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -135,7 +135,7 @@ public class S3BlobRequestSignerTest extends RestClientTest<S3AsyncClient> {
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties());
} }

View File

@ -44,7 +44,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -170,7 +170,7 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("sqs", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("sqs", "identity", "credential", new Properties());
} }

View File

@ -37,12 +37,12 @@ import org.jclouds.aws.ec2.domain.Reservation;
import org.jclouds.aws.ec2.domain.RunningInstance; import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.aws.ec2.predicates.InstanceStateRunning; import org.jclouds.aws.ec2.predicates.InstanceStateRunning;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.scriptbuilder.ScriptBuilder; import org.jclouds.scriptbuilder.ScriptBuilder;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.ssh.jsch.predicates.InetSocketAddressConnect;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;

View File

@ -47,7 +47,7 @@ import org.jclouds.http.functions.ReturnTrueOn404;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -277,7 +277,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties());
} }
} }

View File

@ -35,7 +35,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -133,7 +133,7 @@ public class AzureBlobRequestSignerTest extends RestClientTest<AzureBlobAsyncCli
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties());
} }

View File

@ -42,7 +42,7 @@ import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -233,7 +233,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", new Properties());
} }

View File

@ -41,7 +41,6 @@ public abstract class BlobStoreContextBuilder<S, A> extends RestContextBuilder<S
public BlobStoreContextBuilder(Class<S> syncClientType, Class<A> asyncClientType, Properties properties) { public BlobStoreContextBuilder(Class<S> syncClientType, Class<A> asyncClientType, Properties properties) {
super(syncClientType, asyncClientType, properties); super(syncClientType, asyncClientType, properties);
} }
public BlobStoreContext buildBlobStoreContext() { public BlobStoreContext buildBlobStoreContext() {

View File

@ -27,7 +27,7 @@ import java.util.Properties;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import com.google.inject.Module; import com.google.inject.Module;
@ -124,18 +124,18 @@ public class BlobStoreContextFactory {
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec) * @see RestContextFactory#createContextBuilder(RestContextSpec)
*/ */
public <S, A> BlobStoreContext createContext(ContextSpec<S, A> contextSpec) { public <S, A> BlobStoreContext createContext(RestContextSpec<S, A> contextSpec) {
BlobStoreContextBuilder<?, ?> builder = BlobStoreContextBuilder.class.cast(createContextBuilder(contextSpec)); BlobStoreContextBuilder<?, ?> builder = BlobStoreContextBuilder.class.cast(createContextBuilder(contextSpec));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec, Properties) * @see RestContextFactory#createContextBuilder(RestContextSpec, Properties)
*/ */
public <S, A> BlobStoreContext createContext(ContextSpec<S, A> contextSpec, Properties overrides) { public <S, A> BlobStoreContext createContext(RestContextSpec<S, A> contextSpec, Properties overrides) {
BlobStoreContextBuilder<?, ?> builder = BlobStoreContextBuilder.class.cast(createContextBuilder(contextSpec, BlobStoreContextBuilder<?, ?> builder = BlobStoreContextBuilder.class.cast(createContextBuilder(contextSpec,
overrides)); overrides));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);

View File

@ -30,7 +30,7 @@ import org.jclouds.http.HttpRequest;
import org.jclouds.io.payloads.PhantomPayload; import org.jclouds.io.payloads.PhantomPayload;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -97,7 +97,7 @@ public class TransientBlobRequestSignerTest extends RestClientTest<TransientAsyn
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("transient", "identity", "credential", new Properties()); return new RestContextFactory().createContextSpec("transient", "identity", "credential", new Properties());
} }

View File

@ -22,68 +22,43 @@
(:import (:import
[org.jclouds.ssh SshClient ExecResponse] [org.jclouds.ssh SshClient ExecResponse]
com.google.inject.Module com.google.inject.Module
com.google.common.collect.ImmutableSet
org.jclouds.domain.Credentials
org.jclouds.net.IPSocket org.jclouds.net.IPSocket
[org.jclouds.compute ComputeService ComputeServiceContextFactory] [org.jclouds.compute ComputeService ComputeServiceContextFactory StandaloneComputeServiceContextSpec]
java.util.Set [java.util Set Map]
[org.jclouds.compute.domain NodeMetadata Template] [org.jclouds.compute.domain NodeMetadata Template]
[com.google.common.base Supplier Predicate] [com.google.common.base Supplier Predicate]
[org.jclouds.compute.strategy AddNodeWithTagStrategy DestroyNodeStrategy RebootNodeStrategy GetNodeMetadataStrategy ListNodesStrategy]
org.jclouds.compute.domain.NodeMetadataBuilder)) org.jclouds.compute.domain.NodeMetadataBuilder))
(defn compute-module (defn compute-module
[] []
(.. (org.jclouds.compute.config.StandaloneComputeServiceContextModule$Builder.) (org.jclouds.compute.config.JCloudsNativeStandaloneComputeServiceContextModule
(defineAddNodeWithTagStrategy (defrecord ClojureAddNodeWithTagStrategy [] (defrecord ClojureComputeServiceAdapter []
AddNodeWithTagStrategy org.jclouds.compute.JCloudsNativeComputeServiceAdapter
(^NodeMetadata execute [this ^String tag ^String name ^Template template] (^NodeMetadata runNodeWithTagAndNameAndStoreCredentials [this ^String tag ^String name ^Template template ^Map credentialStore]
())))
(defineDestroyNodeStrategy (defrecord ClojureDestroyNodeStrategy []
DestroyNodeStrategy
(^NodeMetadata execute [this ^String id]
())))
(defineRebootNodeStrategy (defrecord ClojureRebootNodeStrategy []
RebootNodeStrategy
(^NodeMetadata execute [this ^String id]
())))
(defineGetNodeMetadataStrategy (defrecord ClojureGetNodeMetadataStrategy []
GetNodeMetadataStrategy
(^NodeMetadata execute [this ^String id]
())))
(defineListNodesStrategy (defrecord ClojureListNodesStrategy []
ListNodesStrategy
(^Iterable list [this ]
()) ())
(^Iterable listDetailsOnNodesMatching [this ^Predicate filter] (^Iterable listNodes [this ]
()) ())
)) (^Iterable listImages [this ]
;; this needs to return Set<Hardware> ())
(^Iterable listHardwareProfiles [this ]
())
(^Iterable listLocations [this ]
())
(^NodeMetadata getNode [this ^String id]
())
(^void destroyNode [this ^String id]
())
(^void rebootNode [this ^String id]
()))))
(defineHardwareSupplier (defn compute-context [^RestContextSpec spec]
(defrecord HardwareSupplier [] (.createContext (ComputeServiceContextFactory.) spec))
Supplier
(get [this]
())
))
;; this needs to return Set<Image>
(defineImageSupplier (defrecord ImageSupplier [] (^RestContextSpec defn context-spec [^StandaloneComputeServiceContextModule module]
Supplier (StandaloneComputeServiceContextSpec. "servermanager", "http://host", "1", "identity", "credential", module, (ImmutableSet/of)))
( get [this]
())
))
;; this needs to return Set<Location>
(defineLocationSupplier (defrecord LocationSupplier []
Supplier
( get [this]
())
))
(build)
))
(defn compute-context [module]
(ComputeServiceContextFactory/createStandaloneContext module))
(defrecord NodeListComputeService (defrecord NodeListComputeService
[node-list] [node-list]
@ -101,6 +76,9 @@
[ctor] [ctor]
(reify (reify
org.jclouds.ssh.SshClient$Factory org.jclouds.ssh.SshClient$Factory
(^org.jclouds.ssh.SshClient create
[_ ^IPSocket socket ^Credentials credentials]
(ctor socket credentials))
(^org.jclouds.ssh.SshClient create (^org.jclouds.ssh.SshClient create
[_ ^IPSocket socket ^String username ^String password-or-key] [_ ^IPSocket socket ^String username ^String password-or-key]
(ctor socket username password-or-key)) (ctor socket username password-or-key))

View File

@ -0,0 +1,97 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute;
import java.util.Map;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
/**
* A means of specifying the interface between the {@link ComputeServices} and a concrete compute
* cloud implementation, jclouds or otherwise.
*
* @author Adrian Cole
*
*/
public interface ComputeServiceAdapter<N, H, I, L> {
/**
* {@link ComputeService#runNodesWithTag(String, int, Template)} generates the parameters passed
* into this method such that each node in the set has a unique name.
* <p/>
* Your responsibility is to create a node with the underlying library and return after storing
* its credentials in the supplied map.
* <p/>
* Note that it is intentional to return the library native node object, as generic type
* {@code N}. If you are not using library-native objects (such as libvirt {@code Domain}) use
* {@link JCloudsNativeComputeServiceAdapter} instead.
*
* @param tag
* used to aggregate nodes with identical configuration
* @param name
* unique supplied name for the node, which has the tag encoded into it.
* @param template
* includes {@code imageId}, {@code locationId}, and {@code hardwareId} used to start
* the instance.
* @param credentialStore
* once the node is started, its login user and password will be encoded based on the
* node {@code id}
* @return library-native representation of a node.
*
* @see ComputeService#runNodesWithTag(String, int, Template)
*/
N runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
Map<String, Credentials> credentialStore);
/**
* Hardware profiles describe available cpu, memory, and disk configurations that can be used to
* run a node.
* <p/>
* To implement this method, return the library native hardware profiles available to the user.
* These will be used to launch nodes as a part of the template.
*
* @return a non-null iterable of available hardware profiles.
* @see ComputeService#listHardwareProfiles()
*/
Iterable<H> listHardwareProfiles();
/**
* Images are the available configured operating systems that someone can run a node with. *
* <p/>
* To implement this method, return the library native images available to the user. These will
* be used to launch nodes as a part of the template.
*
* @return a non-null iterable of available images.
* @see ComputeService#listImages()
*/
Iterable<I> listImages();
Iterable<L> listLocations();
N getNode(String id);
void destroyNode(String id);
void rebootNode(String id);
Iterable<N> listNodes();
}

View File

@ -26,12 +26,9 @@ import java.util.Properties;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.PropertiesBuilder;
import org.jclouds.compute.config.StandaloneComputeServiceContextModule;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module; import com.google.inject.Module;
/** /**
@ -69,7 +66,7 @@ public class ComputeServiceContextFactory {
} }
public static <S, A> ComputeServiceContext buildContextUnwrappingExceptions( public static <S, A> ComputeServiceContext buildContextUnwrappingExceptions(
ComputeServiceContextBuilder<S, A> builder) { ComputeServiceContextBuilder<S, A> builder) {
try { try {
return builder.buildComputeServiceContext(); return builder.buildComputeServiceContext();
} catch (Exception e) { } catch (Exception e) {
@ -82,7 +79,7 @@ public class ComputeServiceContextFactory {
*/ */
public ComputeServiceContext createContext(String provider, String identity, String credential) { public ComputeServiceContext createContext(String provider, String identity, String credential) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory
.createContextBuilder(provider, identity, credential)); .createContextBuilder(provider, identity, credential));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -91,7 +88,7 @@ public class ComputeServiceContextFactory {
*/ */
public ComputeServiceContext createContext(String provider, Properties overrides) { public ComputeServiceContext createContext(String provider, Properties overrides) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory
.createContextBuilder(provider, overrides)); .createContextBuilder(provider, overrides));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -100,7 +97,7 @@ public class ComputeServiceContextFactory {
*/ */
public ComputeServiceContext createContext(String provider, Iterable<? extends Module> modules, Properties overrides) { public ComputeServiceContext createContext(String provider, Iterable<? extends Module> modules, Properties overrides) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory
.createContextBuilder(provider, modules, overrides)); .createContextBuilder(provider, modules, overrides));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -109,9 +106,9 @@ public class ComputeServiceContextFactory {
* @see RestContextFactory#createContextBuilder(String, String,String, Iterable) * @see RestContextFactory#createContextBuilder(String, String,String, Iterable)
*/ */
public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential, public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential,
Iterable<? extends Module> modules) { Iterable<? extends Module> modules) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory
.createContextBuilder(provider, identity, credential, modules)); .createContextBuilder(provider, identity, credential, modules));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -119,42 +116,39 @@ public class ComputeServiceContextFactory {
* @see RestContextFactory#createContextBuilder(String, String,String, Iterable, Properties) * @see RestContextFactory#createContextBuilder(String, String,String, Iterable, Properties)
*/ */
public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential, public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential,
Iterable<? extends Module> modules, Properties overrides) { Iterable<? extends Module> modules, Properties overrides) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(contextFactory
.createContextBuilder(provider, identity, credential, modules, overrides)); .createContextBuilder(provider, identity, credential, modules, overrides));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec) * @see RestContextFactory#createContextBuilder(RestContextSpec)
*/ */
public <S, A> ComputeServiceContext createContext(ContextSpec<S, A> contextSpec) { public <S, A> ComputeServiceContext createContext(RestContextSpec<S, A> contextSpec) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class
.cast(createContextBuilder(contextSpec)); .cast(createContextBuilder(contextSpec));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec, Properties) * @see RestContextFactory#createContextBuilder(RestContextSpec, Properties)
*/ */
public <S, A> ComputeServiceContext createContext(ContextSpec<S, A> contextSpec, Properties overrides) { public <S, A> ComputeServiceContext createContext(RestContextSpec<S, A> contextSpec, Properties overrides) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(createContextBuilder( ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(createContextBuilder(
contextSpec, overrides)); contextSpec, overrides));
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
public static ComputeServiceContext createStandaloneContext(StandaloneComputeServiceContextModule contextModule) { /**
return createStandaloneContext(contextModule, ImmutableSet.<Module> of()); * @see RestContextFactory#createContextBuilder(RestContextSpec, Iterable, Properties)
*/
public <S, A> ComputeServiceContext createContext(RestContextSpec<S, A> contextSpec, Iterable<Module> modules,
Properties overrides) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class.cast(createContextBuilder(
contextSpec, modules, overrides));
return buildContextUnwrappingExceptions(builder);
} }
@SuppressWarnings("unchecked")
public static ComputeServiceContext createStandaloneContext(StandaloneComputeServiceContextModule contextModule,
Iterable<Module> modules) {
return new ComputeServiceContextFactory().createContext(RestContextFactory
.<ComputeService, ComputeService> contextSpec("standalone", "standalone", "1", "standalone", null,
(Class) null, (Class) null, PropertiesBuilder.class,
(Class) StandaloneComputeServiceContextBuilder.class, ImmutableSet.<Module> builder().add(
contextModule).addAll(modules).build()));
}
} }

View File

@ -0,0 +1,88 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute;
import java.util.Map;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
/**
* A means of specifying the implementation of a service that uses jclouds types.
*
* @author Adrian Cole
*
*/
public interface JCloudsNativeComputeServiceAdapter extends
ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location> {
/**
* {@inheritDoc}
*/
@Override
NodeMetadata runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
Map<String, Credentials> credentialStore);
/**
* {@inheritDoc}
*/
@Override
Iterable<NodeMetadata> listNodes();
/**
* {@inheritDoc}
*/
@Override
Iterable<Image> listImages();
/**
* {@inheritDoc}
*/
@Override
Iterable<Hardware> listHardwareProfiles();
/**
* {@inheritDoc}
*/
@Override
Iterable<Location> listLocations();
/**
* {@inheritDoc}
*/
@Override
NodeMetadata getNode(String id);
/**
* {@inheritDoc}
*/
@Override
void destroyNode(String id);
/**
* {@inheritDoc}
*/
@Override
void rebootNode(String id);
}

View File

@ -26,6 +26,7 @@ import static org.jclouds.Constants.PROPERTY_IDENTITY;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import org.jclouds.PropertiesBuilder;
import org.jclouds.compute.config.StandaloneComputeServiceClientModule; import org.jclouds.compute.config.StandaloneComputeServiceClientModule;
import com.google.inject.Module; import com.google.inject.Module;
@ -35,10 +36,14 @@ import com.google.inject.Module;
* @author Adrian Cole * @author Adrian Cole
*/ */
public class StandaloneComputeServiceContextBuilder extends public class StandaloneComputeServiceContextBuilder extends
ComputeServiceContextBuilder<ComputeService, ComputeService> { ComputeServiceContextBuilder<ComputeService, ComputeService> {
public StandaloneComputeServiceContextBuilder(Properties props) { public StandaloneComputeServiceContextBuilder(Properties props) {
super(ComputeService.class, ComputeService.class, props); super(ComputeService.class, ComputeService.class, props);
if (properties.size() == 0)
properties.putAll(new PropertiesBuilder().build());
if (!properties.containsKey("jclouds.provider"))
properties.setProperty("jclouds.provider", "standalone");
if (!properties.containsKey(PROPERTY_ENDPOINT)) if (!properties.containsKey(PROPERTY_ENDPOINT))
properties.setProperty(PROPERTY_ENDPOINT, "standalone"); properties.setProperty(PROPERTY_ENDPOINT, "standalone");
if (!properties.containsKey(PROPERTY_API_VERSION)) if (!properties.containsKey(PROPERTY_API_VERSION))
@ -49,7 +54,7 @@ public class StandaloneComputeServiceContextBuilder extends
@Override @Override
protected void addClientModule(List<Module> modules) { protected void addClientModule(List<Module> modules) {
modules.add(new StandaloneComputeServiceClientModule()); modules.add(new StandaloneComputeServiceClientModule<ComputeService>(ComputeService.class));
} }
} }

View File

@ -0,0 +1,43 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute;
import org.jclouds.PropertiesBuilder;
import org.jclouds.compute.config.StandaloneComputeServiceContextModule;
import org.jclouds.rest.RestContextSpec;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Module;
/**
* @author Adrian Cole
*/
public class StandaloneComputeServiceContextSpec<N, H, I, L> extends RestContextSpec<ComputeService, ComputeService> {
@SuppressWarnings({ "unchecked", "rawtypes" })
public StandaloneComputeServiceContextSpec(String provider, String endpoint, String apiVersion, String identity,
String credential, StandaloneComputeServiceContextModule<N, H, I, L> contextModule, Iterable<Module> modules) {
super(provider, endpoint, apiVersion, identity, credential, ComputeService.class, ComputeService.class,
PropertiesBuilder.class, (Class) StandaloneComputeServiceContextBuilder.class, Iterables.concat(
ImmutableSet.of(contextModule), modules));
}
}

View File

@ -21,9 +21,11 @@ package org.jclouds.compute;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.internal.UtilsImpl; import org.jclouds.compute.internal.UtilsImpl;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import com.google.common.base.Function;
import com.google.inject.ImplementedBy; import com.google.inject.ImplementedBy;
/** /**
@ -37,4 +39,9 @@ public interface Utils extends org.jclouds.rest.Utils {
@Nullable @Nullable
SshClient.Factory sshFactory(); SshClient.Factory sshFactory();
/**
* @return function that gets an ssh client for a node that is available via ssh.
*/
Function<NodeMetadata, SshClient> sshForNode();
} }

View File

@ -24,7 +24,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections; import java.util.Collections;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.util.ComputeServiceUtils;
import org.jclouds.compute.util.ComputeServiceUtils.SshCallable; import org.jclouds.compute.util.ComputeServiceUtils.SshCallable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.InitBuilder; import org.jclouds.scriptbuilder.InitBuilder;
@ -33,6 +32,7 @@ import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.ExecResponse;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
@ -77,8 +77,9 @@ public class InitAndStartScriptOnNode implements SshCallable<ExecResponse> {
protected ExecResponse runCommand(String command) { protected ExecResponse runCommand(String command) {
ExecResponse returnVal; ExecResponse returnVal;
logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().credential, "XXXXX"), node logger.debug(">> running [%s] as %s@%s", command.replace(node.getAdminPassword() != null ? node
.getCredentials().identity, Iterables.get(node.getPublicAddresses(), 0)); .getAdminPassword() : "XXXXX", "XXXXX"), node.getCredentials().identity, Iterables.get(node
.getPublicAddresses(), 0));
returnVal = ssh.exec(command); returnVal = ssh.exec(command);
return returnVal; return returnVal;
} }
@ -89,15 +90,15 @@ public class InitAndStartScriptOnNode implements SshCallable<ExecResponse> {
this.ssh = checkNotNull(ssh, "ssh"); this.ssh = checkNotNull(ssh, "ssh");
} }
protected String execScriptAsRoot(String action) { @VisibleForTesting
public String execScriptAsRoot(String action) {
String command; String command;
if (node.getCredentials().identity.equals("root")) { if (node.getCredentials().identity.equals("root")) {
command = "./" + init.getInstanceName() + " " + action; command = "./" + init.getInstanceName() + " " + action;
} else if (ComputeServiceUtils.isKeyAuth(node)) { } else if (node.getAdminPassword() != null) {
command = "sudo ./" + init.getInstanceName() + " " + action; command = String.format("echo '%s'|sudo -S ./%s %s", node.getAdminPassword(), init.getInstanceName(), action);
} else { } else {
command = String.format("echo '%s'|sudo -S ./%s %s", node.getCredentials().credential, init.getInstanceName(), command = "sudo ./" + init.getInstanceName() + " " + action;
action);
} }
return command; return command;
} }

View File

@ -26,7 +26,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -35,24 +34,17 @@ import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.functions.CreateSshClientOncePortIsListeningOnNode;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier; import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier;
import org.jclouds.ssh.SshClient;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Injector; import com.google.inject.Injector;
@ -69,147 +61,28 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
install(new ComputeServiceTimeoutsModule()); install(new ComputeServiceTimeoutsModule());
bindRunNodesAndAddToSetStrategy(defineRunNodesAndAddToSetStrategy());
bindAddNodeWithTagStrategy(defineAddNodeWithTagStrategy());
bindListNodesStrategy(defineListNodesStrategy());
bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy());
bindRebootNodeStrategy(defineRebootNodeStrategy());
bindDestroyNodeStrategy(defineDestroyNodeStrategy());
bindImageSupplier(defineImageSupplier());
bindLocationSupplier(defineLocationSupplier());
bindHardwareSupplier(defineHardwareSupplier());
bindDefaultLocationSupplier(defineDefaultLocationSupplier());
bindLoadBalancerService(); bindLoadBalancerService();
} bind(new TypeLiteral<Function<NodeMetadata, SshClient>>() {
}).to(CreateSshClientOncePortIsListeningOnNode.class);
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class;
}
/**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it
*/
protected abstract Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy();
protected abstract Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy();
protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy();
protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();
protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();
protected abstract Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier();
protected abstract Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier();
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return LocationSupplier.class;
}
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return DefaultLocationSupplier.class;
} }
protected void bindLoadBalancerService() { protected void bindLoadBalancerService() {
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null)).in(Scopes.SINGLETON); bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null)).in(Scopes.SINGLETON);
} }
protected void bindRunNodesAndAddToSetStrategy(Class<? extends RunNodesAndAddToSetStrategy> clazz) {
bind(RunNodesAndAddToSetStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
/** /**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it * The default template if none is provided.
*/ */
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
bind(AddNodeWithTagStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDestroyNodeStrategy(Class<? extends DestroyNodeStrategy> clazz) {
bind(DestroyNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindRebootNodeStrategy(Class<? extends RebootNodeStrategy> clazz) {
bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) {
bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindListNodesStrategy(Class<? extends ListNodesStrategy> clazz) {
bind(ListNodesStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindImageSupplier(Class<? extends Supplier<Set<? extends Image>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Image>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindLocationSupplier(Class<? extends Supplier<Set<? extends Location>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Location>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDefaultLocationSupplier(Class<? extends Supplier<Location>> clazz) {
bind(new TypeLiteral<Supplier<Location>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindHardwareSupplier(Class<? extends Supplier<Set<? extends Hardware>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Hardware>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
/**
* By default allows you to use a static set of locations bound to Set<? extends Location>
*/
@Singleton
public static class LocationSupplier implements Supplier<Set<? extends Location>> {
private final Set<? extends Location> locations;
@Inject
LocationSupplier(Set<? extends Location> locations) {
this.locations = locations;
}
@Override
public Set<? extends Location> get() {
return locations;
}
}
@Singleton
public static class DefaultLocationSupplier implements Supplier<Location> {
private final Supplier<Set<? extends Location>> locations;
@Inject
DefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> locations) {
this.locations = locations;
}
@Override
public Location get() {
return Iterables.find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
});
}
}
@Provides @Provides
@Named("DEFAULT") @Named("DEFAULT")
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(UBUNTU); return template.osFamily(UBUNTU);
} }
/**
* supplies how the tag is encoded into the name. A string of hex characters is the last argument
* and tag is the first
*/
@Provides @Provides
@Named("NAMING_CONVENTION") @Named("NAMING_CONVENTION")
@Singleton @Singleton
@ -243,20 +116,20 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Singleton @Singleton
@Memoized @Memoized
protected Supplier<Set<? extends Image>> supplyImageCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, protected Supplier<Set<? extends Image>> supplyImageCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Supplier<Set<? extends Image>> imageSupplier) { final Supplier<Set<? extends Image>> imageSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Image>>(authException, seconds, return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Image>>(authException, seconds,
new Supplier<Set<? extends Image>>() { new Supplier<Set<? extends Image>>() {
@Override @Override
public Set<? extends Image> get() { public Set<? extends Image> get() {
return imageSupplier.get(); return imageSupplier.get();
} }
}); });
} }
@Provides @Provides
@Singleton @Singleton
protected Supplier<Map<String, ? extends Location>> provideLocationMap( protected Supplier<Map<String, ? extends Location>> provideLocationMap(
@Memoized Supplier<Set<? extends Location>> locations) { @Memoized Supplier<Set<? extends Location>> locations) {
return Suppliers.compose(new Function<Set<? extends Location>, Map<String, ? extends Location>>() { return Suppliers.compose(new Function<Set<? extends Location>, Map<String, ? extends Location>>() {
@Override @Override
@ -278,14 +151,14 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Singleton @Singleton
@Memoized @Memoized
protected Supplier<Set<? extends Location>> supplyLocationCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, protected Supplier<Set<? extends Location>> supplyLocationCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Supplier<Set<? extends Location>> locationSupplier) { final Supplier<Set<? extends Location>> locationSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Location>>(authException, seconds, return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Location>>(authException, seconds,
new Supplier<Set<? extends Location>>() { new Supplier<Set<? extends Location>>() {
@Override @Override
public Set<? extends Location> get() { public Set<? extends Location> get() {
return locationSupplier.get(); return locationSupplier.get();
} }
}); });
} }
@Provides @Provides
@ -312,14 +185,14 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Singleton @Singleton
@Memoized @Memoized
protected Supplier<Set<? extends Hardware>> supplySizeCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, protected Supplier<Set<? extends Hardware>> supplySizeCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Supplier<Set<? extends Hardware>> hardwareSupplier) { final Supplier<Set<? extends Hardware>> hardwareSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Hardware>>(authException, seconds, return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Hardware>>(authException, seconds,
new Supplier<Set<? extends Hardware>>() { new Supplier<Set<? extends Hardware>>() {
@Override @Override
public Set<? extends Hardware> get() { public Set<? extends Hardware> get() {
return hardwareSupplier.get(); return hardwareSupplier.get();
} }
}); });
} }
@Provides @Provides

View File

@ -0,0 +1,91 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.config;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
/**
*
* @author Adrian Cole
*
*/
public abstract class BindComputeStrategiesByClass extends AbstractModule {
protected void configure() {
bindRunNodesAndAddToSetStrategy(defineRunNodesAndAddToSetStrategy());
bindAddNodeWithTagStrategy(defineAddNodeWithTagStrategy());
bindListNodesStrategy(defineListNodesStrategy());
bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy());
bindRebootNodeStrategy(defineRebootNodeStrategy());
bindDestroyNodeStrategy(defineDestroyNodeStrategy());
}
protected void bindRunNodesAndAddToSetStrategy(Class<? extends RunNodesAndAddToSetStrategy> clazz) {
bind(RunNodesAndAddToSetStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
/**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it
*/
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
bind(AddNodeWithTagStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDestroyNodeStrategy(Class<? extends DestroyNodeStrategy> clazz) {
bind(DestroyNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindRebootNodeStrategy(Class<? extends RebootNodeStrategy> clazz) {
bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) {
bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindListNodesStrategy(Class<? extends ListNodesStrategy> clazz) {
bind(ListNodesStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class;
}
/**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it
*/
protected abstract Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy();
protected abstract Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy();
protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy();
protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();
protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();
}

View File

@ -0,0 +1,79 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.config;
import java.util.Set;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.suppliers.DefaultLocationSupplier;
import org.jclouds.compute.suppliers.LocationSupplier;
import org.jclouds.domain.Location;
import com.google.common.base.Supplier;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
/**
* @author Adrian Cole
*/
public abstract class BindComputeSuppliersByClass extends AbstractModule {
@Override
protected void configure() {
bindImageSupplier(defineImageSupplier());
bindLocationSupplier(defineLocationSupplier());
bindHardwareSupplier(defineHardwareSupplier());
bindDefaultLocationSupplier(defineDefaultLocationSupplier());
}
protected abstract Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier();
protected abstract Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier();
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return LocationSupplier.class;
}
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return DefaultLocationSupplier.class;
}
protected void bindImageSupplier(Class<? extends Supplier<Set<? extends Image>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Image>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindLocationSupplier(Class<? extends Supplier<Set<? extends Location>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Location>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDefaultLocationSupplier(Class<? extends Supplier<Location>> clazz) {
bind(new TypeLiteral<Supplier<Location>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindHardwareSupplier(Class<? extends Supplier<Set<? extends Hardware>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Hardware>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
}

View File

@ -30,9 +30,7 @@ import org.jclouds.compute.predicates.NodeTerminated;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero; import org.jclouds.compute.predicates.ScriptStatusReturnsZero;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
@ -50,7 +48,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
@Named("NODE_RUNNING") @Named("NODE_RUNNING")
protected Predicate<NodeMetadata> nodeRunning(NodeRunning stateRunning, Timeouts timeouts) { protected Predicate<NodeMetadata> nodeRunning(NodeRunning stateRunning, Timeouts timeouts) {
return timeouts.nodeRunning == 0 ? stateRunning : new RetryablePredicate<NodeMetadata>(stateRunning, return timeouts.nodeRunning == 0 ? stateRunning : new RetryablePredicate<NodeMetadata>(stateRunning,
timeouts.nodeRunning); timeouts.nodeRunning);
} }
@Provides @Provides
@ -58,7 +56,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
@Named("NODE_TERMINATED") @Named("NODE_TERMINATED")
protected Predicate<NodeMetadata> serverTerminated(NodeTerminated stateTerminated, Timeouts timeouts) { protected Predicate<NodeMetadata> serverTerminated(NodeTerminated stateTerminated, Timeouts timeouts) {
return timeouts.nodeTerminated == 0 ? stateTerminated : new RetryablePredicate<NodeMetadata>(stateTerminated, return timeouts.nodeTerminated == 0 ? stateTerminated : new RetryablePredicate<NodeMetadata>(stateTerminated,
timeouts.nodeTerminated); timeouts.nodeTerminated);
} }
@Provides @Provides
@ -66,13 +64,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
@Named("SCRIPT_COMPLETE") @Named("SCRIPT_COMPLETE")
protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero stateRunning, Timeouts timeouts) { protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero stateRunning, Timeouts timeouts) {
return timeouts.scriptComplete == 0 ? not(stateRunning) : new RetryablePredicate<CommandUsingClient>( return timeouts.scriptComplete == 0 ? not(stateRunning) : new RetryablePredicate<CommandUsingClient>(
not(stateRunning), timeouts.scriptComplete); not(stateRunning), timeouts.scriptComplete);
}
@Provides
@Singleton
protected Predicate<IPSocket> socketTester(SocketOpen open, Timeouts timeouts) {
return timeouts.portOpen == 0 ? open : new RetryablePredicate<IPSocket>(open, timeouts.portOpen);
} }
@Override @Override

View File

@ -0,0 +1,43 @@
package org.jclouds.compute.config;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.StandaloneComputeServiceContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.domain.Location;
import com.google.common.base.Function;
import com.google.inject.TypeLiteral;
public class JCloudsNativeStandaloneComputeServiceContextModule extends
StandaloneComputeServiceContextModule<NodeMetadata, Hardware, Image, Location> {
private final Class<? extends ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>> adapter;
public JCloudsNativeStandaloneComputeServiceContextModule(
Class<? extends ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>> adapter) {
this.adapter = adapter;
}
/**
* This binds the converters to {@link IdentityFunction} as that ensure the same value is
* returned.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
protected void configure() {
bind(new TypeLiteral<ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>>() {
}).to(adapter);
bind(IdentityFunction.class).toInstance(IdentityFunction.INSTANCE);
bind(new TypeLiteral<Function<NodeMetadata, NodeMetadata>>() {
}).to((Class) StandaloneComputeServiceContextModule.IdentityFunction.class);
bind(new TypeLiteral<Function<Image, Image>>() {
}).to((Class) StandaloneComputeServiceContextModule.IdentityFunction.class);
bind(new TypeLiteral<Function<Hardware, Hardware>>() {
}).to((Class) StandaloneComputeServiceContextModule.IdentityFunction.class);
bind(new TypeLiteral<Function<Location, Location>>() {
}).to((Class) StandaloneComputeServiceContextModule.IdentityFunction.class);
super.configure();
}
}

View File

@ -19,17 +19,16 @@
package org.jclouds.compute.config; package org.jclouds.compute.config;
import org.jclouds.compute.ComputeService;
import org.jclouds.http.RequiresHttp; import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
@ConfiguresRestClient @ConfiguresRestClient
@RequiresHttp @RequiresHttp
public class StandaloneComputeServiceClientModule extends RestClientModule<ComputeService, ComputeService> { public class StandaloneComputeServiceClientModule<C> extends RestClientModule<C, C> {
public StandaloneComputeServiceClientModule() { public StandaloneComputeServiceClientModule(Class<C> clazz) {
super(ComputeService.class, ComputeService.class); super(clazz, clazz);
} }
@Override @Override

View File

@ -19,9 +19,16 @@
package org.jclouds.compute.config; package org.jclouds.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newHashSet;
import java.util.Set; import java.util.Set;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
@ -31,11 +38,13 @@ import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies;
import org.jclouds.compute.suppliers.DefaultLocationSupplier;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import com.google.common.base.Function;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.Sets; import com.google.inject.Provides;
import com.google.inject.Module;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -43,125 +52,122 @@ import com.google.inject.TypeLiteral;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public abstract class StandaloneComputeServiceContextModule extends BaseComputeServiceContextModule { public class StandaloneComputeServiceContextModule<N, H, I, L> extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
super.configure(); super.configure();
bindDefaultLocation();
bind(new TypeLiteral<ComputeServiceContext>() { bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<ComputeService, ComputeService>>() { }).to(new TypeLiteral<ComputeServiceContextImpl<ComputeService, ComputeService>>() {
}).in(Scopes.SINGLETON); }).in(Scopes.SINGLETON);
} }
public static Builder builder() { public class TransformingSetSupplier<F, T> implements Supplier<Set<? extends T>> {
return new Builder(); private final Supplier<Iterable<F>> backingSupplier;
private final Function<F, T> converter;
public TransformingSetSupplier(Supplier<Iterable<F>> backingSupplier, Function<F, T> converter) {
this.backingSupplier = checkNotNull(backingSupplier, "backingSupplier");
this.converter = checkNotNull(converter, "converter");
}
@Override
public Set<? extends T> get() {
return newHashSet(transform(backingSupplier.get(), converter));
}
} }
public static class Builder { @Provides
private Set<Module> modules = Sets.newLinkedHashSet(); @Singleton
private Class<? extends AddNodeWithTagStrategy> addNodeWithTagStrategy; protected Supplier<Set<? extends Hardware>> provideHardware(final ComputeServiceAdapter<N, H, I, L> adapter,
private Class<? extends DestroyNodeStrategy> destroyNodeStrategy; Function<H, Hardware> transformer) {
private Class<? extends GetNodeMetadataStrategy> getNodeMetadataStrategy; return new TransformingSetSupplier<H, Hardware>(new Supplier<Iterable<H>>() {
private Class<? extends ListNodesStrategy> listNodesStrategy;
private Class<? extends RebootNodeStrategy> rebootNodeStrategy;
private Class<? extends Supplier<Set<? extends Hardware>>> hardwareSupplier;
private Class<? extends Supplier<Set<? extends Image>>> imageSupplier;
private Class<? extends Supplier<Set<? extends Location>>> locationSupplier = LocationSupplier.class;
public Builder install(Module module) { @Override
this.modules.add(module); public Iterable<H> get() {
return this; return adapter.listHardwareProfiles();
}
}, transformer);
}
@Provides
@Singleton
protected Supplier<Set<? extends Image>> provideImages(final ComputeServiceAdapter<N, H, I, L> adapter,
Function<I, Image> transformer) {
return new TransformingSetSupplier<I, Image>(new Supplier<Iterable<I>>() {
@Override
public Iterable<I> get() {
return adapter.listImages();
}
}, transformer);
}
protected void bindDefaultLocation() {
bind(new TypeLiteral<Supplier<Location>>() {
}).to(DefaultLocationSupplier.class);
}
@Provides
@Singleton
protected Supplier<Set<? extends Location>> provideLocations(final ComputeServiceAdapter<N, H, I, L> adapter,
Function<L, Location> transformer) {
return new TransformingSetSupplier<L, Location>(new Supplier<Iterable<L>>() {
@Override
public Iterable<L> get() {
return adapter.listLocations();
}
}, transformer);
}
@Provides
@Singleton
protected AddNodeWithTagStrategy defineAddNodeWithTagStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
@Provides
@Singleton
protected DestroyNodeStrategy defineDestroyNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
@Provides
@Singleton
protected GetNodeMetadataStrategy defineGetNodeMetadataStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
@Provides
@Singleton
protected ListNodesStrategy defineListNodesStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
@Provides
@Singleton
protected RebootNodeStrategy defineRebootNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {
return in;
}
// enum singleton pattern
public static enum IdentityFunction implements Function<Object, Object> {
INSTANCE;
public Object apply(Object o) {
return o;
} }
public Builder defineAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> addNodeWithTagStrategy) { @Override
this.addNodeWithTagStrategy = addNodeWithTagStrategy; public String toString() {
return this; return "identity";
}
public Builder defineDestroyNodeStrategy(Class<? extends DestroyNodeStrategy> destroyNodeStrategy) {
this.destroyNodeStrategy = destroyNodeStrategy;
return this;
}
public Builder defineGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> getNodeMetadataStrategy) {
this.getNodeMetadataStrategy = getNodeMetadataStrategy;
return this;
}
public Builder defineListNodesStrategy(Class<? extends ListNodesStrategy> listNodesStrategy) {
this.listNodesStrategy = listNodesStrategy;
return this;
}
public Builder defineRebootNodeStrategy(Class<? extends RebootNodeStrategy> rebootNodeStrategy) {
this.rebootNodeStrategy = rebootNodeStrategy;
return this;
}
public Builder defineHardwareSupplier(Class<? extends Supplier<Set<? extends Hardware>>> hardwareSupplier) {
this.hardwareSupplier = hardwareSupplier;
return this;
}
public Builder defineImageSupplier(Class<? extends Supplier<Set<? extends Image>>> imageSupplier) {
this.imageSupplier = imageSupplier;
return this;
}
public Builder defineLocationSupplier(Class<? extends Supplier<Set<? extends Location>>> locationSupplier) {
this.locationSupplier = locationSupplier;
return this;
}
public StandaloneComputeServiceContextModule build() {
return new StandaloneComputeServiceContextModule() {
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return addNodeWithTagStrategy;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return destroyNodeStrategy;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return getNodeMetadataStrategy;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return hardwareSupplier;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return imageSupplier;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return listNodesStrategy;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return rebootNodeStrategy;
}
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return locationSupplier;
}
@Override
protected void configure() {
for (Module module : modules)
install(module);
super.configure();
}
};
} }
} }
} }

View File

@ -19,6 +19,8 @@
package org.jclouds.compute.domain; package org.jclouds.compute.domain;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.ImageImpl; import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
@ -48,6 +50,17 @@ public interface Image extends ComputeMetadata {
*/ */
String getDescription(); String getDescription();
/**
* secures access to root with a password. This password is required to access either the console
* or run sudo as root.
* <p/>
* ex. {@code echo 'password' |sudo -S command}
*
* @return root or console password, if configured, or null.
*/
@Nullable
String getAdminPassword();
/** /**
* Default credentials for the current image * Default credentials for the current image
*/ */

View File

@ -37,6 +37,8 @@ public class ImageBuilder extends ComputeMetadataBuilder {
private OperatingSystem operatingSystem; private OperatingSystem operatingSystem;
private String version; private String version;
private String description; private String description;
@Nullable
private String adminPassword;
private Credentials defaultCredentials; private Credentials defaultCredentials;
public ImageBuilder() { public ImageBuilder() {
@ -58,6 +60,11 @@ public class ImageBuilder extends ComputeMetadataBuilder {
return this; return this;
} }
public ImageBuilder adminPassword(@Nullable String adminPassword) {
this.adminPassword = adminPassword;
return this;
}
public ImageBuilder defaultCredentials(@Nullable Credentials defaultCredentials) { public ImageBuilder defaultCredentials(@Nullable Credentials defaultCredentials) {
this.defaultCredentials = defaultCredentials; this.defaultCredentials = defaultCredentials;
return this; return this;
@ -101,7 +108,14 @@ public class ImageBuilder extends ComputeMetadataBuilder {
@Override @Override
public Image build() { public Image build() {
return new ImageImpl(providerId, name, id, location, uri, userMetadata, operatingSystem, description, version, return new ImageImpl(providerId, name, id, location, uri, userMetadata, operatingSystem, description, version,
defaultCredentials); adminPassword, defaultCredentials);
}
public static ImageBuilder fromImage(Image image) {
return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()).location(
image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()).version(
image.getVersion()).description(image.getDescription()).operatingSystem(image.getOperatingSystem())
.adminPassword(image.getAdminPassword()).defaultCredentials(image.getDefaultCredentials());
} }
} }

View File

@ -43,7 +43,7 @@ public interface NodeMetadata extends ComputeMetadata {
* *
*/ */
String getTag(); String getTag();
/** /**
* *
* The harware this node is running, if possible to determine. * The harware this node is running, if possible to determine.
@ -70,6 +70,28 @@ public interface NodeMetadata extends ComputeMetadata {
*/ */
NodeState getState(); NodeState getState();
/**
* @return the TCP port used for terminal connections. Generally, this is port 22 for ssh.
*/
int getLoginPort();
/**
* secures access to root with a password. This password is required to access either the console
* or run sudo as root.
* <p/>
* ex. {@code echo 'password' |sudo -S command}
*
* @return root or console password, if configured, or null.
*/
@Nullable
String getAdminPassword();
/**
* If possible, these are returned upon all detail requests. However, it is often the case that
* credentials are only available at "run" time.
*/
Credentials getCredentials();
/** /**
* All public IP addresses, potentially including shared ips. * All public IP addresses, potentially including shared ips.
*/ */
@ -80,10 +102,4 @@ public interface NodeMetadata extends ComputeMetadata {
*/ */
Set<String> getPrivateAddresses(); Set<String> getPrivateAddresses();
/**
* If possible, these are returned upon all detail requests. However, it is often the case that
* credentials are only available at "run" time.
*/
Credentials getCredentials();
} }

View File

@ -42,9 +42,12 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
private Set<String> publicAddresses = Sets.newLinkedHashSet(); private Set<String> publicAddresses = Sets.newLinkedHashSet();
private Set<String> privateAddresses = Sets.newLinkedHashSet(); private Set<String> privateAddresses = Sets.newLinkedHashSet();
@Nullable @Nullable
private String adminPassword;
@Nullable
private Credentials credentials; private Credentials credentials;
@Nullable @Nullable
private String tag; private String tag;
private int loginPort = 22;
@Nullable @Nullable
private String imageId; private String imageId;
@Nullable @Nullable
@ -56,6 +59,11 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
super(ComputeType.NODE); super(ComputeType.NODE);
} }
public NodeMetadataBuilder loginPort(int loginPort) {
this.loginPort = loginPort;
return this;
}
public NodeMetadataBuilder state(NodeState state) { public NodeMetadataBuilder state(NodeState state) {
this.state = checkNotNull(state, "state"); this.state = checkNotNull(state, "state");
return this; return this;
@ -76,6 +84,11 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
return this; return this;
} }
public NodeMetadataBuilder adminPassword(@Nullable String adminPassword) {
this.adminPassword = adminPassword;
return this;
}
public NodeMetadataBuilder tag(@Nullable String tag) { public NodeMetadataBuilder tag(@Nullable String tag) {
this.tag = tag; this.tag = tag;
return this; return this;
@ -134,15 +147,16 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
@Override @Override
public NodeMetadata build() { public NodeMetadata build() {
return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tag, hardware, imageId, os, state, return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tag, hardware, imageId, os, state,
publicAddresses, privateAddresses, credentials); loginPort, publicAddresses, privateAddresses, adminPassword, credentials);
} }
public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) { public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) {
return new NodeMetadataBuilder().providerId(node.getProviderId()).name(node.getName()).id(node.getId()) return new NodeMetadataBuilder().providerId(node.getProviderId()).name(node.getName()).id(node.getId()).location(
.location(node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tag(node.getTag()) node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tag(node.getTag()).hardware(
.hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem(node.getOperatingSystem()) node.getHardware()).imageId(node.getImageId()).operatingSystem(node.getOperatingSystem()).state(
.state(node.getState()).publicAddresses(node.getPublicAddresses()) node.getState()).loginPort(node.getLoginPort()).publicAddresses(node.getPublicAddresses())
.privateAddresses(node.getPrivateAddresses()).credentials(node.getCredentials()); .privateAddresses(node.getPrivateAddresses()).adminPassword(node.getAdminPassword()).credentials(
node.getCredentials());
} }
} }

View File

@ -43,15 +43,18 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
private final OperatingSystem operatingSystem; private final OperatingSystem operatingSystem;
private final String version; private final String version;
private final String description; private final String description;
@Nullable
private final String adminPassword;
private final Credentials defaultCredentials; private final Credentials defaultCredentials;
public ImageImpl(String providerId, String name, String id, Location location, URI uri, public ImageImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, OperatingSystem operatingSystem, String description, Map<String, String> userMetadata, OperatingSystem operatingSystem, String description,
@Nullable String version, @Nullable Credentials defaultCredentials) { @Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) {
super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata); super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata);
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
this.version = version; this.version = version;
this.description = checkNotNull(description, "description"); this.description = checkNotNull(description, "description");
this.adminPassword = adminPassword;
this.defaultCredentials = defaultCredentials; this.defaultCredentials = defaultCredentials;
} }
@ -87,18 +90,27 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
return defaultCredentials; return defaultCredentials;
} }
/**
* {@inheritDoc}
*/
@Override
public String getAdminPassword() {
return adminPassword;
}
@Override @Override
public String toString() { public String toString() {
return "[id=" + getId() + ", name=" + getName() + ", operatingSystem=" + operatingSystem + ", description=" return "[id=" + getId() + ", name=" + getName() + ", operatingSystem=" + operatingSystem + ", description="
+ description + ", version=" + version + ", location=" + getLocation() + ", loginUser=" + description + ", version=" + version + ", location=" + getLocation() + ", loginUser="
+ ((defaultCredentials != null) ? defaultCredentials.identity : null) + ", userMetadata=" + ((defaultCredentials != null) ? defaultCredentials.identity : null) + ", userMetadata="
+ getUserMetadata() + "]"; + getUserMetadata() + "]";
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = super.hashCode(); int result = super.hashCode();
result = prime * result + ((adminPassword == null) ? 0 : adminPassword.hashCode());
result = prime * result + ((defaultCredentials == null) ? 0 : defaultCredentials.hashCode()); result = prime * result + ((defaultCredentials == null) ? 0 : defaultCredentials.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode()); result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode());
@ -115,6 +127,11 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
ImageImpl other = (ImageImpl) obj; ImageImpl other = (ImageImpl) obj;
if (adminPassword == null) {
if (other.adminPassword != null)
return false;
} else if (!adminPassword.equals(other.adminPassword))
return false;
if (defaultCredentials == null) { if (defaultCredentials == null) {
if (other.defaultCredentials != null) if (other.defaultCredentials != null)
return false; return false;

View File

@ -47,9 +47,12 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
private static final long serialVersionUID = 7924307572338157887L; private static final long serialVersionUID = 7924307572338157887L;
private final NodeState state; private final NodeState state;
private final int loginPort;
private final Set<String> publicAddresses; private final Set<String> publicAddresses;
private final Set<String> privateAddresses; private final Set<String> privateAddresses;
@Nullable @Nullable
private final String adminPassword;
@Nullable
private final Credentials credentials; private final Credentials credentials;
@Nullable @Nullable
private final String tag; private final String tag;
@ -61,17 +64,20 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
private final OperatingSystem os; private final OperatingSystem os;
public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, @Nullable String tag, @Nullable Hardware hardware, @Nullable String imageId, Map<String, String> userMetadata, @Nullable String tag, @Nullable Hardware hardware,
@Nullable OperatingSystem os, NodeState state, Iterable<String> publicAddresses, @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort,
Iterable<String> privateAddresses, @Nullable Credentials credentials) { Iterable<String> publicAddresses, Iterable<String> privateAddresses, @Nullable String adminPassword,
@Nullable Credentials credentials) {
super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata); super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata);
this.tag = tag; this.tag = tag;
this.hardware = hardware; this.hardware = hardware;
this.imageId = imageId; this.imageId = imageId;
this.os = os; this.os = os;
this.state = checkNotNull(state, "state"); this.state = checkNotNull(state, "state");
this.loginPort = loginPort;
this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses"));
this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses"));
this.adminPassword = adminPassword;
this.credentials = credentials; this.credentials = credentials;
} }
@ -91,6 +97,14 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
return hardware; return hardware;
} }
/**
* {@inheritDoc}
*/
@Override
public String getAdminPassword() {
return adminPassword;
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -123,6 +137,14 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
return state; return state;
} }
/**
* {@inheritDoc}
*/
@Override
public int getLoginPort() {
return this.loginPort;
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -142,22 +164,25 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
@Override @Override
public String toString() { public String toString() {
return "[id=" + getId() + ", providerId=" + getProviderId() + ", tag=" + getTag() + ", name=" + getName() return "[id=" + getId() + ", providerId=" + getProviderId() + ", tag=" + getTag() + ", name=" + getName()
+ ", location=" + getLocation() + ", uri=" + getUri() + ", imageId=" + getImageId() + ", os=" + ", location=" + getLocation() + ", uri=" + getUri() + ", imageId=" + getImageId() + ", os="
+ getOperatingSystem() + ", state=" + getState() + ", privateAddresses=" + privateAddresses + getOperatingSystem() + ", state=" + getState() + ", loginPort=" + getLoginPort()
+ ", publicAddresses=" + publicAddresses + ", hardware=" + getHardware() + ", loginUser=" + ", privateAddresses=" + privateAddresses + ", publicAddresses=" + publicAddresses + ", hardware="
+ ((credentials != null) ? credentials.identity : null) + ", userMetadata=" + getUserMetadata() + "]"; + getHardware() + ", loginUser=" + ((credentials != null) ? credentials.identity : null)
+ ", userMetadata=" + getUserMetadata() + "]";
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = super.hashCode(); int result = super.hashCode();
result = prime * result + loginPort;
result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode()); result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode());
result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode()); result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode());
result = prime * result + ((tag == null) ? 0 : tag.hashCode()); result = prime * result + ((tag == null) ? 0 : tag.hashCode());
result = prime * result + ((imageId == null) ? 0 : imageId.hashCode()); result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());
result = prime * result + ((hardware == null) ? 0 : hardware.hashCode()); result = prime * result + ((hardware == null) ? 0 : hardware.hashCode());
result = prime * result + ((os == null) ? 0 : os.hashCode()); result = prime * result + ((os == null) ? 0 : os.hashCode());
result = prime * result + ((adminPassword == null) ? 0 : adminPassword.hashCode());
result = prime * result + ((credentials == null) ? 0 : credentials.hashCode()); result = prime * result + ((credentials == null) ? 0 : credentials.hashCode());
return result; return result;
} }
@ -171,6 +196,8 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
NodeMetadataImpl other = (NodeMetadataImpl) obj; NodeMetadataImpl other = (NodeMetadataImpl) obj;
if (loginPort != other.loginPort)
return false;
if (privateAddresses == null) { if (privateAddresses == null) {
if (other.privateAddresses != null) if (other.privateAddresses != null)
return false; return false;
@ -201,6 +228,11 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
return false; return false;
} else if (!os.equals(other.os)) } else if (!os.equals(other.os))
return false; return false;
if (adminPassword == null) {
if (other.adminPassword != null)
return false;
} else if (!adminPassword.equals(other.adminPassword))
return false;
if (credentials == null) { if (credentials == null) {
if (other.credentials != null) if (other.credentials != null)
return false; return false;

View File

@ -116,9 +116,9 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Inject @Inject
protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations, protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares, @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
Supplier<Location> defaultLocation2, Provider<TemplateOptions> optionsProvider, Supplier<Location> defaultLocation2, Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) { @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
this.locations = locations; this.locations = locations;
this.images = images; this.images = images;
this.hardwares = hardwares; this.hardwares = hardwares;
@ -140,7 +140,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
boolean returnVal = true; boolean returnVal = true;
if (location != null && input.getLocation() != null) if (location != null && input.getLocation() != null)
returnVal = location.equals(input.getLocation()) || location.getParent() != null returnVal = location.equals(input.getLocation()) || location.getParent() != null
&& location.getParent().equals(input.getLocation()); && location.getParent().equals(input.getLocation());
return returnVal; return returnVal;
} }
@ -180,6 +180,10 @@ public class TemplateBuilderImpl implements TemplateBuilder {
return returnVal; return returnVal;
} }
@Override
public String toString() {
return "osFamily(" + osFamily + ")";
}
}; };
private final Predicate<OperatingSystem> osNamePredicate = new Predicate<OperatingSystem>() { private final Predicate<OperatingSystem> osNamePredicate = new Predicate<OperatingSystem>() {
@ -210,7 +214,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
returnVal = false; returnVal = false;
else else
returnVal = input.getDescription().contains(osDescription) returnVal = input.getDescription().contains(osDescription)
|| input.getDescription().matches(osDescription); || input.getDescription().matches(osDescription);
} }
return returnVal; return returnVal;
} }
@ -324,8 +328,8 @@ public class TemplateBuilderImpl implements TemplateBuilder {
returnVal = false; returnVal = false;
else else
returnVal = input.getDescription().equals(imageDescription) returnVal = input.getDescription().equals(imageDescription)
|| input.getDescription().contains(imageDescription) || input.getDescription().contains(imageDescription)
|| input.getDescription().matches(imageDescription); || input.getDescription().matches(imageDescription);
} }
return returnVal; return returnVal;
} }
@ -380,12 +384,12 @@ public class TemplateBuilderImpl implements TemplateBuilder {
} }
}; };
private final Predicate<Hardware> hardwarePredicate = and(hardwareIdPredicate, locationPredicate, private final Predicate<Hardware> hardwarePredicate = and(hardwareIdPredicate, locationPredicate,
hardwareCoresPredicate, hardwareRamPredicate); hardwareCoresPredicate, hardwareRamPredicate);
static final Ordering<Hardware> DEFAULT_SIZE_ORDERING = new Ordering<Hardware>() { static final Ordering<Hardware> DEFAULT_SIZE_ORDERING = new Ordering<Hardware>() {
public int compare(Hardware left, Hardware right) { public int compare(Hardware left, Hardware right) {
return ComparisonChain.start().compare(getCores(left), getCores(right)).compare(left.getRam(), right.getRam()) return ComparisonChain.start().compare(getCores(left), getCores(right)).compare(left.getRam(), right.getRam())
.compare(getSpace(left), getSpace(right)).result(); .compare(getSpace(left), getSpace(right)).result();
} }
}; };
static final Ordering<Hardware> BY_CORES_ORDERING = new Ordering<Hardware>() { static final Ordering<Hardware> BY_CORES_ORDERING = new Ordering<Hardware>() {
@ -395,16 +399,16 @@ public class TemplateBuilderImpl implements TemplateBuilder {
}; };
static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() { static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() {
public int compare(Image left, Image right) { public int compare(Image left, Image right) {
return ComparisonChain.start().compare(left.getName(), right.getName(), return ComparisonChain.start()
Ordering.<String> natural().nullsLast()).compare(left.getVersion(), right.getVersion(), .compare(left.getName(), right.getName(), Ordering.<String> natural().nullsLast())
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getName(), .compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsLast())
right.getOperatingSystem().getName(),// .compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getVersion(), Ordering.<String> natural().nullsLast())
right.getOperatingSystem().getVersion(),// .compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getDescription(), Ordering.<String> natural().nullsLast())
right.getOperatingSystem().getDescription(),// .compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getArch(), Ordering.<String> natural().nullsLast())
right.getOperatingSystem().getArch()).result(); .compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch()).result();
} }
}; };
@ -535,7 +539,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
Iterable<? extends Image> supportedImages = filter(images, buildImagePredicate()); Iterable<? extends Image> supportedImages = filter(images, buildImagePredicate());
if (Iterables.size(supportedImages) == 0) if (Iterables.size(supportedImages) == 0)
throw new NoSuchElementException(String.format( throw new NoSuchElementException(String.format(
"no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images)); "no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images));
Hardware hardware = resolveSize(hardwareSorter(), supportedImages); Hardware hardware = resolveSize(hardwareSorter(), supportedImages);
Image image = resolveImage(hardware, supportedImages); Image image = resolveImage(hardware, supportedImages);
logger.debug("<< matched image(%s)", image); logger.debug("<< matched image(%s)", image);
@ -548,29 +552,29 @@ public class TemplateBuilderImpl implements TemplateBuilder {
Hardware hardware; Hardware hardware;
try { try {
Iterable<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl, Iterable<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl,
new Predicate<Hardware>() { new Predicate<Hardware>() {
@Override @Override
public boolean apply(final Hardware hardware) { public boolean apply(final Hardware hardware) {
return Iterables.any(images, new Predicate<Image>() { return Iterables.any(images, new Predicate<Image>() {
@Override @Override
public boolean apply(Image input) { public boolean apply(Image input) {
return hardware.supportsImage().apply(input); return hardware.supportsImage().apply(input);
} }
@Override @Override
public String toString() { public String toString() {
return "hardware(" + hardware + ").supportsImage()"; return "hardware(" + hardware + ").supportsImage()";
} }
}); });
} }
}); });
hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate)); hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate));
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
throw new NoSuchElementException("hardwares don't support any images: " + toString() + "\n" + hardwaresl throw new NoSuchElementException("hardwares don't support any images: " + toString() + "\n" + hardwaresl
+ "\n" + images); + "\n" + images);
} }
logger.debug("<< matched hardware(%s)", hardware); logger.debug("<< matched hardware(%s)", hardware);
return hardware; return hardware;
@ -637,7 +641,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Override @Override
public String toString() { public String toString() {
return locationPredicate.toString(); return "location(" + location + ")";
} }
}); });
@ -678,7 +682,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
// looks verbose, but explicit <Image> type needed for this to compile // looks verbose, but explicit <Image> type needed for this to compile
// properly // properly
Predicate<Image> imagePredicate = predicates.size() == 1 ? Iterables.<Predicate<Image>> get(predicates, 0) Predicate<Image> imagePredicate = predicates.size() == 1 ? Iterables.<Predicate<Image>> get(predicates, 0)
: Predicates.<Image> and(predicates); : Predicates.<Image> and(predicates);
return imagePredicate; return imagePredicate;
} }
@ -826,9 +830,8 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@VisibleForTesting @VisibleForTesting
boolean nothingChangedExceptOptions() { boolean nothingChangedExceptOptions() {
return osFamily == null && location == null && imageId == null && hardwareId == null && osName == null return osFamily == null && location == null && imageId == null && hardwareId == null && osName == null
&& osDescription == null && imageVersion == null && osVersion == null && osArch == null && osDescription == null && imageVersion == null && osVersion == null && osArch == null && os64Bit == null
&& os64Bit == null && imageName == null && imageDescription == null && minCores == 0 && minRam == 0 && imageName == null && imageDescription == null && minCores == 0 && minRam == 0 && !biggest && !fastest;
&& !biggest && !fastest;
} }
/** /**
@ -842,10 +845,10 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Override @Override
public String toString() { public String toString() {
return "[biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName + ", imageDescription=" return "[biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName + ", imageDescription="
+ imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location=" + imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location=" + location
+ location + ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName=" + ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName=" + osName
+ osName + ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch + ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch + ", os64Bit="
+ ", os64Bit=" + os64Bit + ", hardwareId=" + hardwareId + "]"; + os64Bit + ", hardwareId=" + hardwareId + "]";
} }
@Override @Override

View File

@ -0,0 +1,60 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen;
import org.jclouds.compute.util.ComputeServiceUtils;
import org.jclouds.net.IPSocket;
import org.jclouds.ssh.SshClient;
import com.google.common.base.Function;
import com.google.inject.Inject;
/**
*
* @author Adrian Cole
*
*/
@Singleton
public class CreateSshClientOncePortIsListeningOnNode implements Function<NodeMetadata, SshClient> {
@Inject(optional = true)
SshClient.Factory sshFactory;
private final RetryIfSocketNotYetOpen socketTester;
@Inject
public CreateSshClientOncePortIsListeningOnNode(RetryIfSocketNotYetOpen socketTester) {
this.socketTester = socketTester;
}
@Override
public SshClient apply(NodeMetadata node) {
checkState(sshFactory != null, "ssh requested, but no SshModule configured");
checkNotNull(node.getCredentials(), "credentials for node " + node.getName());
checkNotNull(node.getCredentials().credential, "credentials.credential for node " + node.getName());
IPSocket socket = ComputeServiceUtils.findReachableSocketOnNode(socketTester, node, node.getLoginPort());
return sshFactory.create(socket, node.getCredentials());
}
}

View File

@ -214,7 +214,7 @@ public class BaseComputeService implements ComputeService {
@Override @Override
public boolean apply(String input) { public boolean apply(String input) {
try { try {
NodeMetadata md = destroyNodeStrategy.execute(id); NodeMetadata md = destroyNodeStrategy.destroyNode(id);
if (md != null) if (md != null)
node.set(md); node.set(md);
return true; return true;
@ -269,7 +269,7 @@ public class BaseComputeService implements ComputeService {
@Override @Override
public Set<ComputeMetadata> listNodes() { public Set<ComputeMetadata> listNodes() {
logger.debug(">> listing nodes"); logger.debug(">> listing nodes");
Set<ComputeMetadata> set = newLinkedHashSet(listNodesStrategy.list()); Set<ComputeMetadata> set = newLinkedHashSet(listNodesStrategy.listNodes());
logger.debug("<< list(%d)", set.size()); logger.debug("<< list(%d)", set.size());
return set; return set;
} }
@ -324,7 +324,7 @@ public class BaseComputeService implements ComputeService {
@Override @Override
public NodeMetadata getNodeMetadata(String id) { public NodeMetadata getNodeMetadata(String id) {
checkNotNull(id, "id"); checkNotNull(id, "id");
return getNodeMetadataStrategy.execute(id); return getNodeMetadataStrategy.getNode(id);
} }
/** /**
@ -334,7 +334,7 @@ public class BaseComputeService implements ComputeService {
public void rebootNode(String id) { public void rebootNode(String id) {
checkNotNull(id, "id"); checkNotNull(id, "id");
logger.debug(">> rebooting node(%s)", id); logger.debug(">> rebooting node(%s)", id);
NodeMetadata node = rebootNodeStrategy.execute(id); NodeMetadata node = rebootNodeStrategy.rebootNode(id);
boolean successful = nodeRunning.apply(node); boolean successful = nodeRunning.apply(node);
logger.debug("<< rebooted node(%s) success(%s)", id, successful); logger.debug("<< rebooted node(%s) success(%s)", id, successful);
} }

View File

@ -26,14 +26,17 @@ import javax.inject.Singleton;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.compute.Utils; import org.jclouds.compute.Utils;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.crypto.Crypto; import org.jclouds.crypto.Crypto;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.logging.Logger.LoggerFactory; import org.jclouds.logging.Logger.LoggerFactory;
import org.jclouds.rest.HttpAsyncClient; import org.jclouds.rest.HttpAsyncClient;
import org.jclouds.rest.HttpClient; import org.jclouds.rest.HttpClient;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshClient.Factory; import org.jclouds.ssh.SshClient.Factory;
import com.google.common.base.Function;
import com.google.inject.Inject; import com.google.inject.Inject;
/** /**
@ -44,15 +47,15 @@ import com.google.inject.Inject;
public class UtilsImpl extends org.jclouds.rest.internal.UtilsImpl implements Utils { public class UtilsImpl extends org.jclouds.rest.internal.UtilsImpl implements Utils {
@Inject(optional = true) @Inject(optional = true)
private Factory sshFactory; private Factory sshFactory;
private final Function<NodeMetadata, SshClient> sshForNode;
@Inject @Inject
UtilsImpl(Json json, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient, UtilsImpl(Json json, HttpClient simpleClient, HttpAsyncClient simpleAsyncClient, Crypto encryption,
Crypto encryption, DateService date, DateService date, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userThreads, @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, LoggerFactory loggerFactory,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioThreads, Function<NodeMetadata, SshClient> sshForNode) {
LoggerFactory loggerFactory) { super(json, simpleClient, simpleAsyncClient, encryption, date, userThreads, ioThreads, loggerFactory);
super(json, simpleClient, simpleAsyncClient, encryption, date, userThreads, ioThreads, this.sshForNode = sshForNode;
loggerFactory);
} }
@Override @Override
@ -65,4 +68,9 @@ public class UtilsImpl extends org.jclouds.rest.internal.UtilsImpl implements Ut
return sshFactory; return sshFactory;
} }
@Override
public Function<NodeMetadata, SshClient> sshForNode() {
return sshForNode;
}
} }

View File

@ -0,0 +1,86 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.predicates;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.predicates.SocketOpen;
import com.google.common.base.Predicate;
/**
*
*
* Not singleton as seconds are mutable
*
* @author Adrian Cole
*
*/
public class RetryIfSocketNotYetOpen implements Predicate<IPSocket> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
private Logger logger = Logger.NULL;
private final SocketOpen socketTester;
private long seconds;
public RetryIfSocketNotYetOpen seconds(long seconds) {
this.seconds = seconds;
return this;
}
@Inject
public RetryIfSocketNotYetOpen(SocketOpen socketTester, Timeouts timeouts) {
this.socketTester = socketTester;
this.seconds = timeouts.portOpen;
}
public RetryIfSocketNotYetOpen(SocketOpen socketTester, Logger logger, long seconds) {
this.socketTester = socketTester;
this.logger = logger;
this.seconds = seconds;
}
@Override
public String toString() {
return "retryIfSocketNotYetOpen(" + seconds + ")";
}
@Override
public boolean apply(IPSocket socket) {
logger.debug(">> blocking on socket %s for %d seconds", socket, seconds);
RetryablePredicate<IPSocket> tester = new RetryablePredicate<IPSocket>(socketTester, seconds, 1, TimeUnit.SECONDS);
boolean passed = tester.apply(socket);
if (passed)
logger.debug("<< socket %s opened", socket);
else
logger.warn("<< socket %s didn't open after %d seconds", socket, seconds);
return passed;
}
}

View File

@ -29,6 +29,19 @@ import org.jclouds.compute.domain.Template;
*/ */
public interface AddNodeWithTagStrategy { public interface AddNodeWithTagStrategy {
NodeMetadata execute(String tag, String name, Template template); /**
* create a node given the name and template parameters such as imageid, hardwareid, and
* locationid.
*
* @param tag
* tag supplied by the user
* @param name
* supplied by {@link RunNodesAndAddToSetStrategy } and must have the tag encoded into
* it.
* @param template
* supplied by the user
* @return NodeMetadata from the new object, most likely in some pending state.
*/
NodeMetadata addNodeWithTag(String tag, String name, Template template);
} }

View File

@ -32,6 +32,6 @@ public interface DestroyNodeStrategy {
* *
* @return null if the node wasn't found * @return null if the node wasn't found
*/ */
NodeMetadata execute(String id); NodeMetadata destroyNode(String id);
} }

View File

@ -28,6 +28,6 @@ import org.jclouds.compute.domain.NodeMetadata;
*/ */
public interface GetNodeMetadataStrategy { public interface GetNodeMetadataStrategy {
NodeMetadata execute(String id); NodeMetadata getNode(String id);
} }

View File

@ -30,7 +30,7 @@ import com.google.common.base.Predicate;
*/ */
public interface ListNodesStrategy { public interface ListNodesStrategy {
Iterable<? extends ComputeMetadata> list(); Iterable<? extends ComputeMetadata> listNodes();
Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter); Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter);

View File

@ -28,6 +28,6 @@ import org.jclouds.compute.domain.NodeMetadata;
*/ */
public interface RebootNodeStrategy { public interface RebootNodeStrategy {
NodeMetadata execute(String id); NodeMetadata rebootNode(String id);
} }

View File

@ -0,0 +1,136 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.strategy.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*
*/
@Singleton
public class AdaptingComputeServiceStrategies<N, H, I, L> implements AddNodeWithTagStrategy, DestroyNodeStrategy,
GetNodeMetadataStrategy, ListNodesStrategy, RebootNodeStrategy {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Map<String, Credentials> credentialStore;
private final ComputeServiceAdapter<N, H, I, L> client;
private final Function<N, NodeMetadata> nodeMetadataAdapter;
@Inject
public AdaptingComputeServiceStrategies(Map<String, Credentials> credentialStore,
ComputeServiceAdapter<N, H, I, L> client, Function<N, NodeMetadata> nodeMetadataAdapter) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.client = checkNotNull(client, "client");
this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter");
}
@Override
public Iterable<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listNodes(), nodeMetadataAdapter), filter);
}
@Override
public NodeMetadata getNode(String id) {
N node = client.getNode(id);
return node == null ? null : nodeMetadataAdapter.apply(node);
}
@Override
public NodeMetadata rebootNode(String id) {
NodeMetadata node = getNode(id);
if (node == null || node.getState() == NodeState.TERMINATED)
return node;
logger.debug(">> rebooting node(%s)", id);
client.rebootNode(id);
logger.debug("<< rebooted node(%s)", id);
return node;
}
@Override
public NodeMetadata destroyNode(String id) {
NodeMetadata node = getNode(id);
if (node == null)
return node;
logger.debug(">> destroying node(%s)", id);
client.destroyNode(id);
logger.debug("<< destroyed node(%s)", id);
return node;
}
/**
* {@inheritDoc}
*/
@Override
public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
checkState(tag != null, "tag (that which groups identical nodes together) must be specified");
checkState(name != null && name.indexOf(tag) != -1, "name should have %s encoded into it", tag);
logger.debug(">> instantiating node location(%s) name(%s) image(%s) hardware(%s)",
template.getLocation().getId(), name, template.getImage().getProviderId(), template.getHardware()
.getProviderId());
N from = client.runNodeWithTagAndNameAndStoreCredentials(tag, name, template, credentialStore);
NodeMetadata node = nodeMetadataAdapter.apply(from);
logger.debug("<< instantiated node(%s)", node.getId());
return node;
}
}

View File

@ -88,7 +88,7 @@ public class EncodeTagIntoNameRunNodesAndAddToSetStrategy implements RunNodesAnd
public Void call() throws Exception { public Void call() throws Exception {
NodeMetadata node = null; NodeMetadata node = null;
logger.debug(">> starting node(%s) tag(%s)", name, tag); logger.debug(">> starting node(%s) tag(%s)", name, tag);
node = addNodeWithTagStrategy.execute(tag, name, template); node = addNodeWithTagStrategy.addNodeWithTag(tag, name, template);
logger.debug("<< %s node(%s)", node.getState(), node.getId()); logger.debug("<< %s node(%s)", node.getState(), node.getId());
utils.runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes, nodes, utils.runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes, nodes,
template.getOptions()).call(); template.getOptions()).call();
@ -111,7 +111,7 @@ public class EncodeTagIntoNameRunNodesAndAddToSetStrategy implements RunNodesAnd
*/ */
protected Set<String> getNextNames(final String tag, final Template template, int count) { protected Set<String> getNextNames(final String tag, final Template template, int count) {
Set<String> names = Sets.newHashSet(); Set<String> names = Sets.newHashSet();
Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.list(); Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.listNodes();
int maxTries = 100; int maxTries = 100;
int currentTries = 0; int currentTries = 0;
while (names.size() < count && currentTries++ < maxTries) { while (names.size() < count && currentTries++ < maxTries) {

View File

@ -0,0 +1,192 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.stub.config;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.jclouds.compute.JCloudsNativeComputeServiceAdapter;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.ResourceNotFoundException;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
/**
*
* @author Adrian Cole
*/
@Singleton
public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAdapter {
private final Supplier<Location> location;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final Provider<Integer> idProvider;
private final String publicIpPrefix;
private final String privateIpPrefix;
private final String passwordPrefix;
private final String providerName;
@Inject
public StubComputeServiceAdapter(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
@org.jclouds.rest.annotations.Provider String providerName) {
this.nodes = nodes;
this.location = location;
this.idProvider = idProvider;
this.publicIpPrefix = publicIpPrefix;
this.privateIpPrefix = privateIpPrefix;
this.passwordPrefix = passwordPrefix;
this.providerName = providerName;
}
@Override
public NodeMetadata runNodeWithTagAndNameAndStoreCredentials(String tag, String name, Template template,
Map<String, Credentials> credentialStore) {
NodeMetadataBuilder builder = new NodeMetadataBuilder();
String id = idProvider.get() + "";
builder.ids(id);
builder.name(name);
builder.tag(tag);
builder.location(location.get());
builder.imageId(template.getImage().getId());
builder.operatingSystem(template.getImage().getOperatingSystem());
builder.state(NodeState.PENDING);
builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
builder.credentials(new Credentials("root", passwordPrefix + id));
NodeMetadata node = builder.build();
nodes.put(node.getId(), node);
credentialStore.put(node.getId(), node.getCredentials());
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100);
return node;
}
@Override
public Iterable<Hardware> listHardwareProfiles() {
return ImmutableSet.<Hardware> of(StubComputeServiceDependenciesModule.stub("small", 1, 1740, 160),
StubComputeServiceDependenciesModule.stub("medium", 4, 7680, 850),
StubComputeServiceDependenciesModule.stub("large", 8, 15360, 1690));
}
@Override
public Iterable<Image> listImages() {
Location zone = location.get().getParent();
String parentId = zone.getId();
Credentials defaultCredentials = new Credentials("root", null);
return ImmutableSet
.<Image> of(
new ImageBuilder()
.providerId("1")
.name(OsFamily.UBUNTU.name())
.id(parentId + "/1")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false))
.description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), //
new ImageBuilder()
.providerId("2")
.name(OsFamily.UBUNTU.name())
.id(parentId + "/2")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true))
.description("stub ubuntu 64").defaultCredentials(defaultCredentials).build(), //
new ImageBuilder()
.providerId("3")
.name(OsFamily.CENTOS.name())
.id(parentId + "/3")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true))
.description("stub centos 64").defaultCredentials(defaultCredentials).build() //
);
}
@Override
public Iterable<NodeMetadata> listNodes() {
return nodes.values();
}
@Override
public Iterable<Location> listLocations() {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
provider);
return ImmutableSet.<Location> of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName
+ "zone", region));
}
@Override
public NodeMetadata getNode(String id) {
return nodes.get(id);
}
@Override
public void destroyNode(final String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
return;
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
StubComputeServiceDependenciesModule.setState(node, NodeState.TERMINATED, 50);
StubComputeServiceDependenciesModule.service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Throwables.propagate(e);
} finally {
nodes.remove(id);
}
}
});
}
@Override
public void rebootNode(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
StubComputeServiceDependenciesModule.setState(node, NodeState.PENDING, 0);
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 50);
}
}

View File

@ -19,72 +19,32 @@
package org.jclouds.compute.stub.config; package org.jclouds.compute.stub.config;
import java.util.Set; import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.JCloudsNativeStandaloneComputeServiceContextModule;
import org.jclouds.compute.config.StandaloneComputeServiceContextModule;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubAddNodeWithTagStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubDestroyNodeStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubGetNodeMetadataStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubHardwareSupplier;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubImageSupplier;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubListNodesStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubRebootNodeStrategy;
import org.jclouds.concurrent.SingleThreaded; import org.jclouds.concurrent.SingleThreaded;
import org.jclouds.domain.Location;
import com.google.common.base.Supplier; import com.google.inject.TypeLiteral;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@SingleThreaded @SingleThreaded
public class StubComputeServiceContextModule extends StandaloneComputeServiceContextModule { public class StubComputeServiceContextModule extends JCloudsNativeStandaloneComputeServiceContextModule {
public StubComputeServiceContextModule() {
super(StubComputeServiceAdapter.class);
}
@Override @Override
protected void configure() { protected void configure() {
install(new StubComputeServiceDependenciesModule()); install(new StubComputeServiceDependenciesModule());
bind(new TypeLiteral<ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>>() {
}).to(StubComputeServiceAdapter.class);
super.configure(); super.configure();
} }
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return StubAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return StubDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return StubGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return StubListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return StubRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return StubHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return StubImageSupplier.class;
}
} }

View File

@ -19,10 +19,6 @@
package org.jclouds.compute.stub.config; package org.jclouds.compute.stub.config;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
@ -31,43 +27,20 @@ import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.ResourceNotFoundException;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -93,7 +66,7 @@ public class StubComputeServiceDependenciesModule extends AbstractModule {
// STUB STUFF STATIC SO MULTIPLE CONTEXTS CAN SEE IT // STUB STUFF STATIC SO MULTIPLE CONTEXTS CAN SEE IT
private static final AtomicInteger nodeIds = new AtomicInteger(0); private static final AtomicInteger nodeIds = new AtomicInteger(0);
private static final ExecutorService service = Executors.newCachedThreadPool(); static final ExecutorService service = Executors.newCachedThreadPool();
@Provides @Provides
@Named("NODE_ID") @Named("NODE_ID")
@ -150,53 +123,6 @@ public class StubComputeServiceDependenciesModule extends AbstractModule {
} }
@Singleton
public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final Supplier<Location> location;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final Provider<Integer> idProvider;
private final String publicIpPrefix;
private final String privateIpPrefix;
private final String passwordPrefix;
private final Map<String, Credentials> credentialStore;
@Inject
public StubAddNodeWithTagStrategy(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
Map<String, Credentials> credentialStore) {
this.nodes = nodes;
this.location = location;
this.idProvider = idProvider;
this.publicIpPrefix = publicIpPrefix;
this.privateIpPrefix = privateIpPrefix;
this.passwordPrefix = passwordPrefix;
this.credentialStore = credentialStore;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation());
NodeMetadataBuilder builder = new NodeMetadataBuilder();
String id = idProvider.get() + "";
builder.ids(id);
builder.name(name);
builder.tag(tag);
builder.location(location.get());
builder.imageId(template.getImage().getId());
builder.operatingSystem(template.getImage().getOperatingSystem());
builder.state(NodeState.PENDING);
builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
builder.credentials(new Credentials("root", passwordPrefix + id));
NodeMetadata node = builder.build();
nodes.put(node.getId(), node);
credentialStore.put(node.getId(), node.getCredentials());
setState(node, NodeState.RUNNING, 100);
return node;
}
}
protected static void nodeWithState(NodeMetadata node, NodeState state) { protected static void nodeWithState(NodeMetadata node, NodeState state) {
backing.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build()); backing.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build());
} }
@ -220,158 +146,10 @@ public class StubComputeServiceDependenciesModule extends AbstractModule {
}); });
} }
@Singleton static Hardware stub(String type, int cores, int ram, float disk) {
public static class StubGetNodeMetadataStrategy implements GetNodeMetadataStrategy { return new org.jclouds.compute.domain.HardwareBuilder().ids(type).name(type)
private final ConcurrentMap<String, NodeMetadata> nodes; .processors(ImmutableList.of(new Processor(cores, 1.0))).ram(ram)
.volumes(ImmutableList.<Volume> of(new VolumeImpl(disk, true, false))).build();
@Inject
protected StubGetNodeMetadataStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
return nodes.get(id);
}
}
@Singleton
public static class StubListNodesStrategy implements ListNodesStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubListNodesStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(nodes.values(), filter);
}
}
@Singleton
public static class StubRebootNodeStrategy implements RebootNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubRebootNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.RUNNING, 50);
return node;
}
}
@Singleton
public static class StubDestroyNodeStrategy implements DestroyNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
private final ExecutorService service;
@Inject
protected StubDestroyNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) {
this.nodes = nodes;
this.service = service;
}
@Override
public NodeMetadata execute(final String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
return node;
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.TERMINATED, 50);
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Throwables.propagate(e);
} finally {
nodes.remove(id);
}
}
});
return node;
}
}
@Singleton
public static class StubImageSupplier implements Supplier<Set<? extends Image>> {
private final Supplier<Location> defaultLocation;
@Inject
StubImageSupplier(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation;
}
@Override
public Set<? extends Image> get() {
Location zone = defaultLocation.get().getParent();
String parentId = zone.getId();
Credentials defaultCredentials = new Credentials("root", null);
return ImmutableSet
.<Image> of(new ImageBuilder().providerId("1").name(OsFamily.UBUNTU.name()).id(parentId + "/1")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32",
false)).description("stub ubuntu 32").defaultCredentials(
defaultCredentials).build(), //
new ImageBuilder().providerId("2").name(OsFamily.UBUNTU.name()).id(parentId + "/2")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64",
"ubuntu 64", true)).description("stub ubuntu 64")
.defaultCredentials(defaultCredentials).build(), //
new ImageBuilder().providerId("3").name(OsFamily.CENTOS.name()).id(parentId + "/3")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64",
"centos 64", true)).description("stub centos 64")
.defaultCredentials(defaultCredentials).build() //
);
}
}
@Provides
@Singleton
protected Set<? extends Location> provideLocations(@org.jclouds.rest.annotations.Provider String providerName) {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
provider);
return ImmutableSet
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
}
@Singleton
public static class StubHardwareSupplier implements Supplier<Set<? extends Hardware>> {
static Hardware stub(String type, int cores, int ram, float disk) {
return new org.jclouds.compute.domain.HardwareBuilder().id(type).providerId(type).name(type).processors(
ImmutableList.of(new Processor(cores, 1.0))).ram(ram).volumes(
ImmutableList.<Volume> of(new VolumeImpl(disk, true, false))).build();
}
@Override
public Set<? extends Hardware> get() {
return ImmutableSet.<Hardware> of(stub("small", 1, 1740, 160), stub("medium", 4, 7680, 850), stub("large", 8,
15360, 1690));
}
} }
} }

View File

@ -0,0 +1,61 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.suppliers;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.collect.Memoized;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*
*/
@Singleton
public class DefaultLocationSupplier implements Supplier<Location> {
private final Supplier<Set<? extends Location>> locations;
@Inject
DefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> locations) {
this.locations = locations;
}
@Override
public Location get() {
return Iterables.find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
});
}
}

View File

@ -0,0 +1,51 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.compute.suppliers;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.domain.Location;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*
* By default allows you to use a static set of locations bound to Set<? extends Location>
*/
@Singleton
public class LocationSupplier implements Supplier<Set<? extends Location>> {
private final Set<? extends Location> locations;
@Inject
LocationSupplier(Set<? extends Location> locations) {
this.locations = locations;
}
@Override
public Set<? extends Location> get() {
return locations;
}
}

View File

@ -19,10 +19,15 @@
package org.jclouds.compute.util; package org.jclouds.compute.util;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.getStackTraceAsString; import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.size;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash; import static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash;
import static org.jclouds.util.Utils.getSupportedProvidersOfType;
import java.net.URI; import java.net.URI;
import java.util.Formatter; import java.util.Formatter;
@ -33,6 +38,7 @@ import java.util.concurrent.Callable;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.jclouds.compute.ComputeServiceContextBuilder; import org.jclouds.compute.ComputeServiceContextBuilder;
import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
@ -40,13 +46,15 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.util.Utils;
import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
@ -212,13 +220,33 @@ public class ComputeServiceUtils {
void setConnection(SshClient ssh, Logger logger); void setConnection(SshClient ssh, Logger logger);
} }
public static boolean isKeyAuth(NodeMetadata createdNode) { public static Iterable<String> getSupportedProviders() {
return createdNode.getCredentials().credential != null return getSupportedProvidersOfType(ComputeServiceContextBuilder.class);
&& createdNode.getCredentials().credential.startsWith("-----BEGIN RSA PRIVATE KEY-----");
} }
public static Iterable<String> getSupportedProviders() { public static IPSocket findReachableSocketOnNode(RetryIfSocketNotYetOpen socketTester, final NodeMetadata node,
return Utils.getSupportedProvidersOfType(ComputeServiceContextBuilder.class); final int port) {
checkNodeHasIps(node);
IPSocket socket = null;
try {
socket = find(
transform(concat(node.getPublicAddresses(), node.getPrivateAddresses()),
new Function<String, IPSocket>() {
@Override
public IPSocket apply(String from) {
return new IPSocket(from, port);
}
}), socketTester);
} catch (NoSuchElementException e) {
throw new RuntimeException(String.format("could not connect to any ip address port %d on node %s", port, node));
}
return socket;
}
public static void checkNodeHasIps(NodeMetadata node) {
checkState(size(concat(node.getPublicAddresses(), node.getPrivateAddresses())) > 0,
"node does not have IP addresses configured: " + node);
} }
} }

View File

@ -19,9 +19,12 @@
package org.jclouds.compute.util; package org.jclouds.compute.util;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.getRootCause;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.propagate;
import static org.jclouds.compute.util.ComputeServiceUtils.isKeyAuth; import static com.google.common.collect.Iterables.size;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
import static org.jclouds.compute.util.ComputeServiceUtils.findReachableSocketOnNode;
import static org.jclouds.concurrent.FutureIterables.awaitCompletion; import static org.jclouds.concurrent.FutureIterables.awaitCompletion;
import java.util.List; import java.util.List;
@ -31,11 +34,11 @@ import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants; import org.jclouds.Constants;
@ -45,14 +48,13 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.RetryIfSocketNotYetOpen;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.util.ComputeServiceUtils.SshCallable; import org.jclouds.compute.util.ComputeServiceUtils.SshCallable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.scriptbuilder.domain.AuthorizeRSAPublicKey; import org.jclouds.scriptbuilder.domain.AuthorizeRSAPublicKey;
import org.jclouds.scriptbuilder.domain.InstallRSAPrivateKey; import org.jclouds.scriptbuilder.domain.InstallRSAPrivateKey;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
@ -60,11 +62,8 @@ import org.jclouds.scriptbuilder.domain.StatementList;
import org.jclouds.ssh.ExecResponse; import org.jclouds.ssh.ExecResponse;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject; import com.google.inject.Inject;
/** /**
@ -76,20 +75,20 @@ public class ComputeUtils {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject(optional = true) protected final Function<NodeMetadata, SshClient> sshFactory;
protected SshClient.Factory sshFactory;
protected final Predicate<CommandUsingClient> runScriptNotRunning; protected final Predicate<CommandUsingClient> runScriptNotRunning;
protected final Predicate<IPSocket> socketTester; protected final Provider<RetryIfSocketNotYetOpen> socketTester;
protected final ExecutorService executor; protected final ExecutorService executor;
protected final Predicate<NodeMetadata> nodeRunning; protected final Predicate<NodeMetadata> nodeRunning;
protected final GetNodeMetadataStrategy getNode; protected final GetNodeMetadataStrategy getNode;
protected final Timeouts timeouts; protected final Timeouts timeouts;
@Inject @Inject
public ComputeUtils(Predicate<IPSocket> socketTester, public ComputeUtils(Provider<RetryIfSocketNotYetOpen> socketTester, Function<NodeMetadata, SshClient> sshFactory,
@Named("SCRIPT_COMPLETE") Predicate<CommandUsingClient> runScriptNotRunning, GetNodeMetadataStrategy getNode, @Named("SCRIPT_COMPLETE") Predicate<CommandUsingClient> runScriptNotRunning, GetNodeMetadataStrategy getNode,
Timeouts timeouts, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning, Timeouts timeouts, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.sshFactory = sshFactory;
this.nodeRunning = nodeRunning; this.nodeRunning = nodeRunning;
this.timeouts = timeouts; this.timeouts = timeouts;
this.getNode = getNode; this.getNode = getNode;
@ -101,7 +100,7 @@ public class ComputeUtils {
public Map<?, Future<Void>> runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(final TemplateOptions options, public Map<?, Future<Void>> runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(final TemplateOptions options,
Iterable<NodeMetadata> runningNodes, final Set<NodeMetadata> goodNodes, Iterable<NodeMetadata> runningNodes, final Set<NodeMetadata> goodNodes,
final Map<NodeMetadata, Exception> badNodes) { final Map<NodeMetadata, Exception> badNodes) {
Map<NodeMetadata, Future<Void>> responses = Maps.newHashMap(); Map<NodeMetadata, Future<Void>> responses = newHashMap();
for (final NodeMetadata node : runningNodes) { for (final NodeMetadata node : runningNodes) {
responses.put(node, executor.submit(runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes, responses.put(node, executor.submit(runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes,
goodNodes, options))); goodNodes, options)));
@ -119,8 +118,7 @@ public class ComputeUtils {
logger.debug("<< options applied node(%s)", node1.getId()); logger.debug("<< options applied node(%s)", node1.getId());
goodNodes.add(node1); goodNodes.add(node1);
} catch (Exception e) { } catch (Exception e) {
logger.error(e, "<< problem applying options to node(%s): ", node.getId(), Throwables.getRootCause(e) logger.error(e, "<< problem applying options to node(%s): ", node.getId(), getRootCause(e).getMessage());
.getMessage());
badNodes.put(node, e); badNodes.put(node, e);
} }
return null; return null;
@ -133,13 +131,13 @@ public class ComputeUtils {
return node; return node;
if (nodeRunning.apply(node)) if (nodeRunning.apply(node))
node = NodeMetadataBuilder.fromNodeMetadata(getNode.execute(node.getId())) node = NodeMetadataBuilder.fromNodeMetadata(getNode.getNode(node.getId())).credentials(node.getCredentials())
.credentials(node.getCredentials()).build(); .build();
else else
throw new IllegalStateException(String.format( throw new IllegalStateException(String.format(
"node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(), "node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(),
timeouts.nodeRunning / 1000, node.getState())); timeouts.nodeRunning / 1000, node.getState()));
List<Statement> bootstrap = Lists.newArrayList(); List<Statement> bootstrap = newArrayList();
if (options.getRunScript() != null) if (options.getRunScript() != null)
bootstrap.add(options.getRunScript()); bootstrap.add(options.getRunScript());
if (options.getPublicKey() != null) if (options.getPublicKey() != null)
@ -151,14 +149,10 @@ public class ComputeUtils {
return node; return node;
} }
public void checkNodeHasPublicIps(NodeMetadata node) {
checkState(node.getPublicAddresses().size() > 0, "node does not have IP addresses configured: " + node);
}
public ExecResponse runScriptOnNode(NodeMetadata node, Statement runScript, RunScriptOptions options) { public ExecResponse runScriptOnNode(NodeMetadata node, Statement runScript, RunScriptOptions options) {
InitAndStartScriptOnNode callable = generateScript(node, runScript, options); InitAndStartScriptOnNode callable = generateScript(node, runScript, options);
ExecResponse response; ExecResponse response;
SshClient ssh = createSshClientOncePortIsListeningOnNode(node); SshClient ssh = sshFactory.apply(node);
try { try {
ssh.connect(); ssh.connect();
callable.setConnection(ssh, logger); callable.setConnection(ssh, logger);
@ -168,24 +162,11 @@ public class ComputeUtils {
ssh.disconnect(); ssh.disconnect();
} }
if (options.getPort() > 0) { if (options.getPort() > 0) {
checkNodeHasPublicIps(node); findReachableSocketOnNode(socketTester.get().seconds(options.getSeconds()), node, options.getPort());
blockUntilPortIsListeningOnPublicIp(options.getPort(), options.getSeconds(),
Iterables.get(node.getPublicAddresses(), 0));
} }
return response; return response;
} }
public void blockUntilPortIsListeningOnPublicIp(int port, int seconds, String inetAddress) {
logger.debug(">> blocking on port %s:%d for %d seconds", inetAddress, port, seconds);
RetryablePredicate<IPSocket> tester = new RetryablePredicate<IPSocket>(socketTester, seconds, 1, TimeUnit.SECONDS);
IPSocket socket = new IPSocket(inetAddress, port);
boolean passed = tester.apply(socket);
if (passed)
logger.debug("<< port %s:%d opened", inetAddress, port);
else
logger.warn("<< port %s:%d didn't open after %d seconds", inetAddress, port, seconds);
}
public InitAndStartScriptOnNode generateScript(NodeMetadata node, Statement script, RunScriptOptions options) { public InitAndStartScriptOnNode generateScript(NodeMetadata node, Statement script, RunScriptOptions options) {
return options.shouldBlockOnComplete() ? new RunScriptOnNode(runScriptNotRunning, node, options.getTaskName(), return options.shouldBlockOnComplete() ? new RunScriptOnNode(runScriptNotRunning, node, options.getTaskName(),
script, options.shouldRunAsRoot()) : new InitAndStartScriptOnNode(node, options.getTaskName(), script, script, options.shouldRunAsRoot()) : new InitAndStartScriptOnNode(node, options.getTaskName(), script,
@ -194,11 +175,7 @@ public class ComputeUtils {
public Map<SshCallable<?>, ?> runCallablesOnNode(NodeMetadata node, Iterable<SshCallable<?>> parallel, public Map<SshCallable<?>, ?> runCallablesOnNode(NodeMetadata node, Iterable<SshCallable<?>> parallel,
@Nullable SshCallable<?> last) { @Nullable SshCallable<?> last) {
checkState(this.sshFactory != null, "runScript requested, but no SshModule configured"); SshClient ssh = sshFactory.apply(node);
checkNodeHasPublicIps(node);
checkNotNull(node.getCredentials(), "credentials for node " + node.getName());
checkNotNull(node.getCredentials().credential, "credentials.credential for node " + node.getName());
SshClient ssh = createSshClientOncePortIsListeningOnNode(node);
try { try {
ssh.connect(); ssh.connect();
return runTasksUsingSshClient(parallel, last, ssh); return runTasksUsingSshClient(parallel, last, ssh);
@ -210,8 +187,8 @@ public class ComputeUtils {
private Map<SshCallable<?>, ?> runTasksUsingSshClient(Iterable<SshCallable<?>> parallel, SshCallable<?> last, private Map<SshCallable<?>, ?> runTasksUsingSshClient(Iterable<SshCallable<?>> parallel, SshCallable<?> last,
SshClient ssh) { SshClient ssh) {
Map<SshCallable<?>, Object> responses = Maps.newHashMap(); Map<SshCallable<?>, Object> responses = newHashMap();
if (Iterables.size(parallel) > 0) { if (size(parallel) > 0) {
responses.putAll(runCallablesUsingSshClient(parallel, ssh)); responses.putAll(runCallablesUsingSshClient(parallel, ssh));
} }
if (last != null) { if (last != null) {
@ -219,24 +196,15 @@ public class ComputeUtils {
try { try {
responses.put(last, last.call()); responses.put(last, last.call());
} catch (Exception e) { } catch (Exception e) {
Throwables.propagate(e); propagate(e);
} }
} }
return responses; return responses;
} }
public SshClient createSshClientOncePortIsListeningOnNode(NodeMetadata node) {
IPSocket socket = new IPSocket(Iterables.get(node.getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient ssh = isKeyAuth(node) ? sshFactory.create(socket, node.getCredentials().identity,
node.getCredentials().credential.getBytes()) : sshFactory.create(socket, node.getCredentials().identity,
node.getCredentials().credential);
return ssh;
}
// TODO refactor // TODO refactor
private Map<SshCallable<?>, Object> runCallablesUsingSshClient(Iterable<SshCallable<?>> parallel, SshClient ssh) { private Map<SshCallable<?>, Object> runCallablesUsingSshClient(Iterable<SshCallable<?>> parallel, SshClient ssh) {
Map<SshCallable<?>, Future<?>> parallelResponses = Maps.newHashMap(); Map<SshCallable<?>, Future<?>> parallelResponses = newHashMap();
for (SshCallable<?> callable : parallel) { for (SshCallable<?> callable : parallel) {
callable.setConnection(ssh, logger); callable.setConnection(ssh, logger);
@ -252,14 +220,14 @@ public class ComputeUtils {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> Map<SshCallable<?>, T> transform(Map<SshCallable<?>, Future<?>> responses) { public <T> Map<SshCallable<?>, T> transform(Map<SshCallable<?>, Future<?>> responses) {
Map<SshCallable<?>, T> actualResponses = Maps.newHashMap(); Map<SshCallable<?>, T> actualResponses = newHashMap();
for (Map.Entry<SshCallable<?>, Future<?>> entry : responses.entrySet()) { for (Map.Entry<SshCallable<?>, Future<?>> entry : responses.entrySet()) {
try { try {
actualResponses.put(entry.getKey(), (T) entry.getValue().get()); actualResponses.put(entry.getKey(), (T) entry.getValue().get());
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw Throwables.propagate(e); throw propagate(e);
} catch (ExecutionException e) { } catch (ExecutionException e) {
throw Throwables.propagate(e); throw propagate(e);
} }
} }
return actualResponses; return actualResponses;

View File

@ -22,6 +22,7 @@ package org.jclouds.ssh;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
import org.jclouds.domain.Credentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
@ -31,9 +32,24 @@ import org.jclouds.net.IPSocket;
public interface SshClient { public interface SshClient {
interface Factory { interface Factory {
/**
* please use {@link Factory#create(IPSocket, Credentials)}
*
* @return
*/
@Deprecated
SshClient create(IPSocket socket, String username, String password); SshClient create(IPSocket socket, String username, String password);
/**
* please use {@link Factory#create(IPSocket, Credentials)}
*
* @return
*/
@Deprecated
SshClient create(IPSocket socket, String username, byte[] privateKey); SshClient create(IPSocket socket, String username, byte[] privateKey);
SshClient create(IPSocket socket, Credentials credentials);
} }
String getUsername(); String getUsername();

View File

@ -158,8 +158,8 @@ public abstract class BaseComputeServiceLiveTest {
if (context != null) if (context != null)
context.close(); context.close();
Properties props = setupProperties(); Properties props = setupProperties();
context = new ComputeServiceContextFactory().createContext(provider, context = new ComputeServiceContextFactory().createContext(provider, ImmutableSet.of(new Log4JLoggingModule(),
ImmutableSet.of(new Log4JLoggingModule(), getSshModule()), props); getSshModule()), props);
client = context.getComputeService(); client = context.getComputeService();
} }
@ -170,8 +170,8 @@ public abstract class BaseComputeServiceLiveTest {
public void testCorrectAuthException() throws Exception { public void testCorrectAuthException() throws Exception {
ComputeServiceContext context = null; ComputeServiceContext context = null;
try { try {
context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ImmutableSet
ImmutableSet.<Module> of(new Log4JLoggingModule())); .<Module> of(new Log4JLoggingModule()));
context.getComputeService().listNodes(); context.getComputeService().listNodes();
} catch (AuthorizationException e) { } catch (AuthorizationException e) {
throw e; throw e;
@ -214,7 +214,7 @@ public abstract class BaseComputeServiceLiveTest {
OperatingSystem os = get(nodes, 0).getOperatingSystem(); OperatingSystem os = get(nodes, 0).getOperatingSystem();
try { try {
Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(tag, os, new Credentials( Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(tag, os, new Credentials(
good.identity, "romeo")); good.identity, "romeo"));
assert false : "shouldn't pass with a bad password\n" + responses; assert false : "shouldn't pass with a bad password\n" + responses;
} catch (RunScriptOnNodesException e) { } catch (RunScriptOnNodesException e) {
assert getRootCause(e).getMessage().contains("Auth fail") : e; assert getRootCause(e).getMessage().contains("Auth fail") : e;
@ -247,11 +247,11 @@ public abstract class BaseComputeServiceLiveTest {
} }
template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080))
.build(); .build();
// note this is a dependency on the template resolution // note this is a dependency on the template resolution
template.getOptions().runScript( template.getOptions().runScript(
RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage()
.getOperatingSystem())); .getOperatingSystem()));
try { try {
NodeMetadata node = getOnlyElement(client.runNodesWithTag(tag, 1, template)); NodeMetadata node = getOnlyElement(client.runNodesWithTag(tag, 1, template));
@ -299,7 +299,7 @@ public abstract class BaseComputeServiceLiveTest {
template = buildTemplate(client.templateBuilder()); template = buildTemplate(client.templateBuilder());
template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public"))
.runScript(newStringPayload(buildScript(template.getImage().getOperatingSystem()))); .runScript(newStringPayload(buildScript(template.getImage().getOperatingSystem())));
} }
protected void checkImageIdMatchesTemplate(NodeMetadata node) { protected void checkImageIdMatchesTemplate(NodeMetadata node) {
@ -310,8 +310,8 @@ public abstract class BaseComputeServiceLiveTest {
protected void checkOsMatchesTemplate(NodeMetadata node) { protected void checkOsMatchesTemplate(NodeMetadata node) {
if (node.getOperatingSystem() != null) if (node.getOperatingSystem() != null)
assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String
.format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node
node.getOperatingSystem()); .getOperatingSystem());
} }
void assertLocationSameOrChild(Location test, Location expected) { void assertLocationSameOrChild(Location test, Location expected) {
@ -343,10 +343,10 @@ public abstract class BaseComputeServiceLiveTest {
} }
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OperatingSystem os, protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OperatingSystem os,
Credentials creds) throws RunScriptOnNodesException { Credentials creds) throws RunScriptOnNodesException {
try { try {
return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(os)), return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(os)),
overrideCredentialsWith(creds).nameTask("runScriptWithCreds")); overrideCredentialsWith(creds).nameTask("runScriptWithCreds"));
} catch (SshException e) { } catch (SshException e) {
throw e; throw e;
} }
@ -358,7 +358,8 @@ public abstract class BaseComputeServiceLiveTest {
assertNotNull(node.getTag()); assertNotNull(node.getTag());
assertEquals(node.getTag(), tag); assertEquals(node.getTag(), tag);
assertEquals(node.getState(), NodeState.RUNNING); assertEquals(node.getState(), NodeState.RUNNING);
assertEquals(context.getCredentialStore().get(node.getId()), node.getCredentials()); Credentials fromStore = context.getCredentialStore().get(node.getId());
assertEquals(fromStore, node.getCredentials());
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
assertNotNull(node.getCredentials()); assertNotNull(node.getCredentials());
if (node.getCredentials().identity != null) { if (node.getCredentials().identity != null) {
@ -375,16 +376,16 @@ public abstract class BaseComputeServiceLiveTest {
@Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
public void testGet() throws Exception { public void testGet() throws Exception {
Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex( Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(filter(client
filter(client.listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED))), .listNodesDetailsMatching(all()), and(withTag(tag), not(TERMINATED))),
new Function<NodeMetadata, String>() { new Function<NodeMetadata, String>() {
@Override @Override
public String apply(NodeMetadata from) { public String apply(NodeMetadata from) {
return from.getId(); return from.getId();
} }
})); }));
for (NodeMetadata node : nodes) { for (NodeMetadata node : nodes) {
metadataMap.remove(node.getId()); metadataMap.remove(node.getId());
NodeMetadata metadata = client.getNodeMetadata(node.getId()); NodeMetadata metadata = client.getNodeMetadata(node.getId());
@ -402,7 +403,7 @@ public abstract class BaseComputeServiceLiveTest {
protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet) { protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet) {
assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]",
metadataSet, nodes); metadataSet, nodes);
} }
@Test(enabled = true, dependsOnMethods = "testGet") @Test(enabled = true, dependsOnMethods = "testGet")
@ -463,26 +464,26 @@ public abstract class BaseComputeServiceLiveTest {
assert location != location.getParent() : location; assert location != location.getParent() : location;
assert location.getScope() != null : location; assert location.getScope() != null : location;
switch (location.getScope()) { switch (location.getScope()) {
case PROVIDER: case PROVIDER:
assertProvider(location); assertProvider(location);
break; break;
case REGION: case REGION:
assertProvider(location.getParent()); assertProvider(location.getParent());
break; break;
case ZONE: case ZONE:
Location provider = location.getParent().getParent(); Location provider = location.getParent().getParent();
// zone can be a direct descendant of provider // zone can be a direct descendant of provider
if (provider == null) if (provider == null)
provider = location.getParent(); provider = location.getParent();
assertProvider(provider); assertProvider(provider);
break; break;
case HOST: case HOST:
Location provider2 = location.getParent().getParent().getParent(); Location provider2 = location.getParent().getParent().getParent();
// zone can be a direct descendant of provider // zone can be a direct descendant of provider
if (provider2 == null) if (provider2 == null)
provider2 = location.getParent().getParent(); provider2 = location.getParent().getParent();
assertProvider(provider2); assertProvider(provider2);
break; break;
} }
} }
} }
@ -564,20 +565,7 @@ public abstract class BaseComputeServiceLiveTest {
} }
protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException {
IPSocket socket = new IPSocket(get(node.getPublicAddresses(), 0), 22); SshClient ssh = context.utils().sshForNode().apply(node);
socketTester.apply(socket); // TODO add transitionTo option that accepts
// a socket conection
// state.
SshClient ssh = (node.getCredentials().credential != null && !node.getCredentials().credential
.startsWith("-----BEGIN RSA PRIVATE KEY-----")) ? context.utils().sshFactory()
.create(socket, node.getCredentials().identity, node.getCredentials().credential) : context
.utils()
.sshFactory()
.create(
socket,
node.getCredentials().identity,
node.getCredentials().credential != null ? node.getCredentials().credential.getBytes() : keyPair.get(
"private").getBytes());
try { try {
ssh.connect(); ssh.connect();
ExecResponse hello = ssh.exec("echo hello"); ExecResponse hello = ssh.exec("echo hello");

View File

@ -19,18 +19,16 @@
package org.jclouds.compute; package org.jclouds.compute;
import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.stub.config.StubComputeServiceContextModule; import org.jclouds.compute.stub.config.StubComputeServiceContextModule;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule; import org.jclouds.domain.Location;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubAddNodeWithTagStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubDestroyNodeStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubGetNodeMetadataStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubHardwareSupplier;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubImageSupplier;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubListNodesStrategy;
import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubRebootNodeStrategy;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
@ -41,21 +39,11 @@ public class ComputeServiceContextFactoryTest {
@Test @Test
public void testStandalone() { public void testStandalone() {
ComputeServiceContext context = ComputeServiceContextFactory ComputeServiceContext context = new ComputeServiceContextFactory()
.createStandaloneContext(new StubComputeServiceContextModule()); .createContext(new StandaloneComputeServiceContextSpec<NodeMetadata, Hardware, Image, Location>("stub",
context.getComputeService().listNodes(); "stub", "1", "identity", "credential", new StubComputeServiceContextModule(), ImmutableSet
} .<Module> of()));
@Test
public void testStandaloneWithBuilder() {
ComputeServiceContext context = ComputeServiceContextFactory
.createStandaloneContext(StandaloneComputeServiceContextModule.builder().install(
new StubComputeServiceDependenciesModule()).defineAddNodeWithTagStrategy(
StubAddNodeWithTagStrategy.class).defineDestroyNodeStrategy(StubDestroyNodeStrategy.class)
.defineGetNodeMetadataStrategy(StubGetNodeMetadataStrategy.class).defineListNodesStrategy(
StubListNodesStrategy.class).defineRebootNodeStrategy(StubRebootNodeStrategy.class)
.defineHardwareSupplier(StubHardwareSupplier.class)
.defineImageSupplier(StubImageSupplier.class).build());
context.getComputeService().listNodes(); context.getComputeService().listNodes();
} }
} }

View File

@ -19,7 +19,6 @@
package org.jclouds.compute; package org.jclouds.compute;
import static org.easymock.EasyMock.aryEq;
import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.reportMatcher; import static org.easymock.EasyMock.reportMatcher;
@ -41,6 +40,7 @@ import org.easymock.IArgumentMatcher;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
@ -120,15 +120,14 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
SshClient client4 = createMock(SshClient.class); SshClient client4 = createMock(SshClient.class);
SshClient client5 = createMock(SshClient.class); SshClient client5 = createMock(SshClient.class);
expect(factory.create(new IPSocket("144.175.1.1", 22), "root", "password1")).andReturn(client1) expect(factory.create(new IPSocket("144.175.1.1", 22), new Credentials("root", "password1"))).andReturn(
.atLeastOnce(); client1);
runScriptAndService(client1, 1); runScriptAndService(client1, 1);
expect(factory.create(new IPSocket("144.175.1.2", 22), "root", "romeo")).andThrow( expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "password2"))).andReturn(
client2).times(2);
expect(factory.create(new IPSocket("144.175.1.2", 22), new Credentials("root", "romeo"))).andThrow(
new SshException("Auth fail")); new SshException("Auth fail"));
expect(factory.create(new IPSocket("144.175.1.2", 22), "root", "password2")).andReturn(client2)
.atLeastOnce();
client2.connect(); client2.connect();
try { try {
runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
@ -138,32 +137,32 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
} }
client2.disconnect(); client2.disconnect();
expect(factory.create(new IPSocket("144.175.1.3", 22), "root", "password3")).andReturn(client3) expect(factory.create(new IPSocket("144.175.1.3", 22), new Credentials("root", "password3"))).andReturn(
.atLeastOnce(); client3).times(2);
expect(factory.create(new IPSocket("144.175.1.4", 22), "root", "password4")).andReturn(client4) expect(factory.create(new IPSocket("144.175.1.4", 22), new Credentials("root", "password4"))).andReturn(
.atLeastOnce(); client4).times(2);
expect(factory.create(new IPSocket("144.175.1.5", 22), "root", "password5")).andReturn(client5) expect(factory.create(new IPSocket("144.175.1.5", 22), new Credentials("root", "password5"))).andReturn(
.atLeastOnce(); client5).times(2);
runScriptAndInstallSsh(client3, "bootstrap", 3); runScriptAndInstallSsh(client3, "bootstrap", 3);
runScriptAndInstallSsh(client4, "bootstrap", 4); runScriptAndInstallSsh(client4, "bootstrap", 4);
runScriptAndInstallSsh(client5, "bootstrap", 5); runScriptAndInstallSsh(client5, "bootstrap", 5);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.1", 22)), eq("root"), aryEq(keyPair.get("private") factory.create(eq(new IPSocket("144.175.1.1", 22)),
.getBytes()))).andReturn(client1).atLeastOnce(); eq(new Credentials("root", keyPair.get("private"))))).andReturn(client1);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.2", 22)), eq("root"), aryEq(keyPair.get("private") factory.create(eq(new IPSocket("144.175.1.2", 22)),
.getBytes()))).andReturn(client2).atLeastOnce(); eq(new Credentials("root", keyPair.get("private"))))).andReturn(client2);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.3", 22)), eq("root"), aryEq(keyPair.get("private") factory.create(eq(new IPSocket("144.175.1.3", 22)),
.getBytes()))).andReturn(client3).atLeastOnce(); eq(new Credentials("root", keyPair.get("private"))))).andReturn(client3);
expect( expect(
factory.create(eq(new IPSocket("144.175.1.4", 22)), eq("root"), aryEq(keyPair.get("private") factory.create(eq(new IPSocket("144.175.1.4", 22)),
.getBytes()))).andReturn(client4).atLeastOnce(); eq(new Credentials("root", keyPair.get("private"))))).andReturn(client4);
expect( expect(
factory.create(eq(new IPSocket("155.175.1.5", 22)), eq("root"), aryEq(keyPair.get("private") factory.create(eq(new IPSocket("144.175.1.5", 22)),
.getBytes()))).andReturn(client5).atLeastOnce(); eq(new Credentials("root", keyPair.get("private"))))).andReturn(client5);
helloAndJava(client2); helloAndJava(client2);
helloAndJava(client3); helloAndJava(client3);

View File

@ -0,0 +1,70 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*/
@Singleton
public abstract class FindResourceInSet<F, T> implements Function<F, T> {
@Resource
protected Logger logger = Logger.NULL;
private final Supplier<Set<? extends T>> set;
@Inject
public FindResourceInSet(@Memoized Supplier<Set<? extends T>> set) {
this.set = checkNotNull(set, "set");
}
public abstract boolean matches(F from, T input);
public T apply(final F from) {
try {
return Iterables.find(set.get(), new Predicate<T>() {
@Override
public boolean apply(T input) {
return matches(from, input);
}
});
} catch (NoSuchElementException e) {
logger.warn("could not find a match in set for %s", from);
}
return null;
}
}

View File

@ -0,0 +1,49 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newHashSet;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*/
public class TransformingSetSupplier<F, T> implements Supplier<Set<? extends T>> {
private final Supplier<Iterable<F>> backingSupplier;
private final Function<F, T> converter;
public TransformingSetSupplier(Supplier<Iterable<F>> backingSupplier, Function<F, T> converter) {
this.backingSupplier = checkNotNull(backingSupplier, "backingSupplier");
this.converter = checkNotNull(converter, "converter");
}
@Override
public Set<? extends T> get() {
return newHashSet(transform(backingSupplier.get(), converter));
}
}

View File

@ -65,7 +65,9 @@ public class ExceptionParsingListenableFuture<T> implements ListenableFuture<T>
} }
private T attemptConvert(Exception e) { private T attemptConvert(Exception e) {
return function.apply(e instanceof ExecutionException ? (Exception) e.getCause() : e); if (e instanceof ExecutionException && e.getCause() instanceof Exception)
return function.apply((Exception) e.getCause());
return function.apply(e);
} }
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {

View File

@ -61,8 +61,8 @@ public class Credentials {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((identity == null) ? 0 : identity.hashCode());
result = prime * result + ((credential == null) ? 0 : credential.hashCode()); result = prime * result + ((credential == null) ? 0 : credential.hashCode());
result = prime * result + ((identity == null) ? 0 : identity.hashCode());
return result; return result;
} }
@ -72,20 +72,19 @@ public class Credentials {
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (!(obj instanceof Credentials))
return false; return false;
Credentials other = (Credentials) obj; Credentials other = (Credentials) obj;
if (identity == null) {
if (other.identity != null)
return false;
} else if (!identity.equals(other.identity))
return false;
if (credential == null) { if (credential == null) {
if (other.credential != null) if (other.credential != null)
return false; return false;
} else if (!credential.equals(other.credential)) } else if (!credential.equals(other.credential))
return false; return false;
if (identity == null) {
if (other.identity != null)
return false;
} else if (!identity.equals(other.identity))
return false;
return true; return true;
} }

View File

@ -85,11 +85,11 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
@Inject @Inject
public JavaUrlHttpCommandExecutorService(HttpUtils utils, public JavaUrlHttpCommandExecutorService(HttpUtils utils,
@Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor, @Named(Constants.PROPERTY_IO_WORKER_THREADS) ExecutorService ioWorkerExecutor,
DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler, DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,
DelegatingErrorHandler errorHandler, HttpWire wire, @Named("untrusted") HostnameVerifier verifier, DelegatingErrorHandler errorHandler, HttpWire wire, @Named("untrusted") HostnameVerifier verifier,
@Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider) throws SecurityException, @Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider) throws SecurityException,
NoSuchFieldException { NoSuchFieldException {
super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire); super(utils, ioWorkerExecutor, retryHandler, ioRetryHandler, errorHandler, wire);
if (utils.getMaxConnections() > 0) if (utils.getMaxConnections() > 0)
System.setProperty("http.maxConnections", String.valueOf(checkNotNull(utils, "utils").getMaxConnections())); System.setProperty("http.maxConnections", String.valueOf(checkNotNull(utils, "utils").getMaxConnections()));
@ -218,21 +218,23 @@ public class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorSe
} }
// writeTo will close the output stream // writeTo will close the output stream
try { try {
request.getPayload().writeTo(connection.getOutputStream()); request.getPayload().writeTo(connection.getOutputStream());
} catch (IOException e){ } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
throw e; throw e;
} }
} else { } else {
connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0"); connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0");
// for some reason POST undoes the content length header above.
if (connection.getRequestMethod().equals("POST"))
connection.setChunkedStreamingMode(0);
} }
return connection; return connection;
} }
/** /**
* Only disconnect if there is no content, as disconnecting will throw away * Only disconnect if there is no content, as disconnecting will throw away unconsumed content.
* unconsumed content.
*/ */
@Override @Override
protected void cleanup(HttpURLConnection connection) { protected void cleanup(HttpURLConnection connection) {

View File

@ -95,7 +95,7 @@ public abstract class Wire {
out = new FileBackedOutputStream(limit); out = new FileBackedOutputStream(limit);
long bytesRead = ByteStreams.copy(instream, out); long bytesRead = ByteStreams.copy(instream, out);
if (bytesRead >= limit) if (bytesRead >= limit)
logger.warn("over limit %d/%d: wrote temp file", bytesRead, limit); logger.debug("over limit %d/%d: wrote temp file", bytesRead, limit);
wire(header, out.getSupplier().getInput()); wire(header, out.getSupplier().getInput());
return out.getSupplier().getInput(); return out.getSupplier().getInput();
} catch (IOException e) { } catch (IOException e) {

View File

@ -31,74 +31,74 @@ import org.jclouds.logging.Logger;
* *
*/ */
public class JDKLogger extends BaseLogger { public class JDKLogger extends BaseLogger {
private final java.util.logging.Logger logger; private final java.util.logging.Logger logger;
public static class JDKLoggerFactory implements LoggerFactory { public static class JDKLoggerFactory implements LoggerFactory {
public Logger getLogger(String category) { public Logger getLogger(String category) {
return new JDKLogger(java.util.logging.Logger.getLogger(category)); return new JDKLogger(java.util.logging.Logger.getLogger(category));
} }
} }
public JDKLogger(java.util.logging.Logger logger) { public JDKLogger(java.util.logging.Logger logger) {
this.logger = logger; this.logger = logger;
} }
@Override @Override
protected void logTrace(String message) { protected void logTrace(String message) {
logger.finest(message); logger.finest(message);
} }
public boolean isTraceEnabled() { public boolean isTraceEnabled() {
return logger.isLoggable(Level.FINEST); return logger.isLoggable(Level.FINEST);
} }
@Override @Override
protected void logDebug(String message) { protected void logDebug(String message) {
logger.fine(message); logger.fine(message);
} }
public boolean isDebugEnabled() { public boolean isDebugEnabled() {
return logger.isLoggable(Level.FINE); return logger.isLoggable(Level.FINE);
} }
@Override @Override
protected void logInfo(String message) { protected void logInfo(String message) {
logger.info(message); logger.info(message);
} }
public boolean isInfoEnabled() { public boolean isInfoEnabled() {
return logger.isLoggable(Level.INFO); return logger.isLoggable(Level.INFO);
} }
@Override @Override
protected void logWarn(String message) { protected void logWarn(String message) {
logger.warning(message); logger.warning(message);
} }
@Override @Override
protected void logWarn(String message, Throwable e) { protected void logWarn(String message, Throwable e) {
logger.log(Level.WARNING, message, e); logger.log(Level.WARNING, message, e);
} }
public boolean isWarnEnabled() { public boolean isWarnEnabled() {
return logger.isLoggable(Level.WARNING); return logger.isLoggable(Level.WARNING);
} }
@Override @Override
protected void logError(String message) { protected void logError(String message) {
logger.severe(message); logger.severe(message);
} }
@Override @Override
protected void logError(String message, Throwable e) { protected void logError(String message, Throwable e) {
logger.log(Level.SEVERE, message, e); logger.log(Level.SEVERE, message, e);
} }
public boolean isErrorEnabled() { public boolean isErrorEnabled() {
return logger.isLoggable(Level.SEVERE); return logger.isLoggable(Level.SEVERE);
} }
public String getCategory() { public String getCategory() {
return logger.getName(); return logger.getName();
} }
} }

View File

@ -17,7 +17,7 @@
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.ssh.jsch.predicates; package org.jclouds.predicates;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -29,7 +29,6 @@ import javax.inject.Singleton;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.SocketOpen;
import com.google.inject.Inject; import com.google.inject.Inject;

View File

@ -19,7 +19,6 @@
package org.jclouds.rest; package org.jclouds.rest;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate; import static com.google.common.base.Throwables.propagate;
import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.concat;
@ -73,143 +72,24 @@ import com.google.inject.Module;
*/ */
public class RestContextFactory { public class RestContextFactory {
public static <S, A> ContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion, public static <S, A> RestContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion,
String identity, String credential, Class<S> sync, Class<A> async, String identity, String credential, Class<S> sync, Class<A> async,
Class<PropertiesBuilder> propertiesBuilderClass, Class<RestContextBuilder<S, A>> contextBuilderClass, Class<PropertiesBuilder> propertiesBuilderClass, Class<RestContextBuilder<S, A>> contextBuilderClass,
Iterable<Module> modules) { Iterable<Module> modules) {
return new ContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async, return new RestContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async,
propertiesBuilderClass, contextBuilderClass, modules); propertiesBuilderClass, contextBuilderClass, modules);
} }
public static <S, A> ContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion, public static <S, A> RestContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion,
String identity, String credential, Class<S> sync, Class<A> async) { String identity, String credential, Class<S> sync, Class<A> async) {
return new ContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async); return new RestContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <S, A> ContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion, public static <S, A> RestContextSpec<S, A> contextSpec(String provider, String endpoint, String apiVersion,
String identity, String credential, Class<S> sync, Class<A> async, Iterable<Module> modules) { String identity, String credential, Class<S> sync, Class<A> async, Iterable<Module> modules) {
return new ContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async, return new RestContextSpec<S, A>(provider, endpoint, apiVersion, identity, credential, sync, async,
PropertiesBuilder.class, (Class) RestContextBuilder.class, modules); PropertiesBuilder.class, (Class) RestContextBuilder.class, modules);
}
public static class ContextSpec<S, A> {
final String provider;
final String endpoint;
final String apiVersion;
final String identity;
final String credential;
final Class<S> sync;
final Class<A> async;
final Class<PropertiesBuilder> propertiesBuilderClass;
final Class<RestContextBuilder<S, A>> contextBuilderClass;
final Iterable<Module> modules;
ContextSpec(String provider, String endpoint, String apiVersion, String identity, String credential,
Class<S> sync, Class<A> async, Class<PropertiesBuilder> propertiesBuilderClass,
Class<RestContextBuilder<S, A>> contextBuilderClass, Iterable<Module> modules) {
this.provider = checkNotNull(provider, "provider");
this.endpoint = endpoint;
this.apiVersion = apiVersion;
this.identity = identity;
this.credential = credential;
this.sync = sync;
this.async = async;
checkArgument(RestContextBuilder.class.isAssignableFrom(contextBuilderClass), contextBuilderClass.getName()
+ " is not a subclass of " + RestContextBuilder.class.getName());
checkArgument(PropertiesBuilder.class.isAssignableFrom(propertiesBuilderClass), propertiesBuilderClass
.getName()
+ " is not a subclass of " + PropertiesBuilder.class.getName());
this.propertiesBuilderClass = propertiesBuilderClass;
this.contextBuilderClass = contextBuilderClass;
this.modules = modules;
}
@SuppressWarnings("unchecked")
public ContextSpec(String provider, String endpoint, String apiVersion, String identity, String credential,
Class<S> sync, Class<A> async) {
this(provider, endpoint, apiVersion, identity, credential, sync, async, PropertiesBuilder.class,
(Class) RestContextBuilder.class, EMPTY_LIST);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((apiVersion == null) ? 0 : apiVersion.hashCode());
result = prime * result + ((async == null) ? 0 : async.hashCode());
result = prime * result + ((contextBuilderClass == null) ? 0 : contextBuilderClass.hashCode());
result = prime * result + ((credential == null) ? 0 : credential.hashCode());
result = prime * result + ((endpoint == null) ? 0 : endpoint.hashCode());
result = prime * result + ((identity == null) ? 0 : identity.hashCode());
result = prime * result + ((propertiesBuilderClass == null) ? 0 : propertiesBuilderClass.hashCode());
result = prime * result + ((provider == null) ? 0 : provider.hashCode());
result = prime * result + ((sync == null) ? 0 : sync.hashCode());
return result;
}
@Override
public String toString() {
return "[provider=" + provider + ", endpoint=" + endpoint + ", apiVersion=" + apiVersion + ", identity="
+ identity + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ContextSpec<?, ?> other = (ContextSpec<?, ?>) obj;
if (apiVersion == null) {
if (other.apiVersion != null)
return false;
} else if (!apiVersion.equals(other.apiVersion))
return false;
if (async == null) {
if (other.async != null)
return false;
} else if (!async.equals(other.async))
return false;
if (contextBuilderClass == null) {
if (other.contextBuilderClass != null)
return false;
} else if (!contextBuilderClass.equals(other.contextBuilderClass))
return false;
if (credential == null) {
if (other.credential != null)
return false;
} else if (!credential.equals(other.credential))
return false;
if (endpoint == null) {
if (other.endpoint != null)
return false;
} else if (!endpoint.equals(other.endpoint))
return false;
if (identity == null) {
if (other.identity != null)
return false;
} else if (!identity.equals(other.identity))
return false;
if (propertiesBuilderClass == null) {
if (other.propertiesBuilderClass != null)
return false;
} else if (!propertiesBuilderClass.equals(other.propertiesBuilderClass))
return false;
if (provider == null) {
if (other.provider != null)
return false;
} else if (!provider.equals(other.provider))
return false;
if (sync == null) {
if (other.sync != null)
return false;
} else if (!sync.equals(other.sync))
return false;
return true;
}
} }
private final static Properties NO_PROPERTIES = new Properties(); private final static Properties NO_PROPERTIES = new Properties();
@ -300,9 +180,9 @@ public class RestContextFactory {
/** /**
* *
* Identity will be found by searching {@code jclouds.identity} failing that {@code * Identity will be found by searching {@code jclouds.identity} failing that
* provider.identity} where provider corresponds to the parameter. Same pattern is used for * {@code provider.identity} where provider corresponds to the parameter. Same pattern is used
* credential ({@code jclouds.credential} failing that {@code provider.credential}). * for credential ({@code jclouds.credential} failing that {@code provider.credential}).
* *
* @param <S> * @param <S>
* Type of the provider specific client * Type of the provider specific client
@ -318,18 +198,18 @@ public class RestContextFactory {
* properties to pass to the context. * properties to pass to the context.
*/ */
public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, Iterable<? extends Module> wiring, public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, Iterable<? extends Module> wiring,
Properties overrides) { Properties overrides) {
return createContextBuilder(provider, null, null, wiring, overrides); return createContextBuilder(provider, null, null, wiring, overrides);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, @Nullable String identity, public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, @Nullable String identity,
@Nullable String credential, Properties properties) { @Nullable String credential, Properties properties) {
return createContextBuilder(provider, identity, credential, EMPTY_LIST, properties); return createContextBuilder(provider, identity, credential, EMPTY_LIST, properties);
} }
public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, @Nullable String identity, public <S, A> RestContextBuilder<S, A> createContextBuilder(String provider, @Nullable String identity,
@Nullable String credential, Iterable<? extends Module> wiring) { @Nullable String credential, Iterable<? extends Module> wiring) {
return createContextBuilder(provider, identity, credential, wiring, NO_PROPERTIES); return createContextBuilder(provider, identity, credential, wiring, NO_PROPERTIES);
} }
@ -349,13 +229,13 @@ public class RestContextFactory {
* @return initialized context ready for use * @return initialized context ready for use
*/ */
public <S, A> RestContextBuilder<S, A> createContextBuilder(String providerName, @Nullable String identity, public <S, A> RestContextBuilder<S, A> createContextBuilder(String providerName, @Nullable String identity,
@Nullable String credential, Iterable<? extends Module> wiring, Properties _overrides) { @Nullable String credential, Iterable<? extends Module> wiring, Properties _overrides) {
checkNotNull(wiring, "wiring"); checkNotNull(wiring, "wiring");
ContextSpec<S, A> contextSpec = createContextSpec(providerName, identity, credential, wiring, _overrides); RestContextSpec<S, A> contextSpec = createContextSpec(providerName, identity, credential, wiring, _overrides);
return createContextBuilder(contextSpec, _overrides); return createContextBuilder(contextSpec, _overrides);
} }
public static Properties toProperties(ContextSpec<?, ?> contextSpec) { public static Properties toProperties(RestContextSpec<?, ?> contextSpec) {
checkNotNull(contextSpec, "contextSpec"); checkNotNull(contextSpec, "contextSpec");
Properties props = new Properties(); Properties props = new Properties();
@ -368,37 +248,37 @@ public class RestContextFactory {
if (contextSpec.sync != null) { if (contextSpec.sync != null) {
props.setProperty(contextSpec.provider + ".sync", contextSpec.sync.getName()); props.setProperty(contextSpec.provider + ".sync", contextSpec.sync.getName());
props.setProperty(contextSpec.provider + ".async", checkNotNull(contextSpec.async, "contextSpec.async") props.setProperty(contextSpec.provider + ".async", checkNotNull(contextSpec.async, "contextSpec.async")
.getName()); .getName());
} else { } else {
props.setProperty(contextSpec.provider + ".contextbuilder", checkNotNull(contextSpec.contextBuilderClass, props.setProperty(contextSpec.provider + ".contextbuilder",
"contextSpec.contextBuilderClass").getName()); checkNotNull(contextSpec.contextBuilderClass, "contextSpec.contextBuilderClass").getName());
props.setProperty(contextSpec.provider + ".propertiesbuilder", checkNotNull( props.setProperty(contextSpec.provider + ".propertiesbuilder",
contextSpec.propertiesBuilderClass, "contextSpec.propertiesBuilderClass").getName()); checkNotNull(contextSpec.propertiesBuilderClass, "contextSpec.propertiesBuilderClass").getName());
} }
if (size(contextSpec.modules) > 0) { if (size(contextSpec.modules) > 0) {
props.setProperty(contextSpec.provider + ".modules", Joiner.on(',').join( props.setProperty(contextSpec.provider + ".modules",
transform(contextSpec.modules, new Function<Module, String>() { Joiner.on(',').join(transform(contextSpec.modules, new Function<Module, String>() {
@Override @Override
public String apply(Module from) { public String apply(Module from) {
return from.getClass().getName(); return from.getClass().getName();
} }
}))); })));
} }
return props; return props;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <S, A> ContextSpec<S, A> createContextSpec(String providerName, String identity, String credential, public <S, A> RestContextSpec<S, A> createContextSpec(String providerName, String identity, String credential,
Properties _overrides) { Properties _overrides) {
return createContextSpec(providerName, identity, credential, EMPTY_LIST, _overrides); return createContextSpec(providerName, identity, credential, EMPTY_LIST, _overrides);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <S, A> ContextSpec<S, A> createContextSpec(String providerName, String identity, String credential, public <S, A> RestContextSpec<S, A> createContextSpec(String providerName, String identity, String credential,
Iterable<? extends Module> wiring, Properties _overrides) { Iterable<? extends Module> wiring, Properties _overrides) {
checkNotNull(providerName, "providerName"); checkNotNull(providerName, "providerName");
checkNotNull(_overrides, "overrides"); checkNotNull(_overrides, "overrides");
@ -409,8 +289,8 @@ public class RestContextFactory {
String endpoint = props.getProperty(providerName + ".endpoint", null); String endpoint = props.getProperty(providerName + ".endpoint", null);
String apiVersion = props.getProperty(providerName + ".apiversion", null); String apiVersion = props.getProperty(providerName + ".apiversion", null);
identity = props.getProperty(providerName + ".identity", props.getProperty("jclouds.identity", identity)); identity = props.getProperty(providerName + ".identity", props.getProperty("jclouds.identity", identity));
credential = loadCredentialOrDefault(props, providerName + ".credential", loadCredentialOrDefault(props, credential = loadCredentialOrDefault(props, providerName + ".credential",
"jclouds.credential", credential)); loadCredentialOrDefault(props, "jclouds.credential", credential));
String syncClassName = props.getProperty(providerName + ".sync", null); String syncClassName = props.getProperty(providerName + ".sync", null);
String asyncClassName = props.getProperty(providerName + ".async", null); String asyncClassName = props.getProperty(providerName + ".async", null);
Iterable<Module> modules = concat(modulesForProviderInProperties(providerName, props), wiring); Iterable<Module> modules = concat(modulesForProviderInProperties(providerName, props), wiring);
@ -429,8 +309,8 @@ public class RestContextFactory {
assert false : "exception should have propogated " + e; assert false : "exception should have propogated " + e;
return null; return null;
} }
ContextSpec<S, A> contextSpec = new ContextSpec<S, A>(providerName, endpoint, apiVersion, identity, credential, RestContextSpec<S, A> contextSpec = new RestContextSpec<S, A>(providerName, endpoint, apiVersion, identity,
sync, async, propertiesBuilderClass, contextBuilderClass, modules); credential, sync, async, propertiesBuilderClass, contextBuilderClass, modules);
return contextSpec; return contextSpec;
} }
@ -440,7 +320,7 @@ public class RestContextFactory {
else if (properties.containsKey(property + ".resource")) else if (properties.containsKey(property + ".resource"))
try { try {
return toStringAndClose(RestContextFactory.class.getResourceAsStream(properties.getProperty(property return toStringAndClose(RestContextFactory.class.getResourceAsStream(properties.getProperty(property
+ ".resource"))); + ".resource")));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("error reading resource: " + properties.getProperty(property + ".resource")); throw new RuntimeException("error reading resource: " + properties.getProperty(property + ".resource"));
} }
@ -454,26 +334,26 @@ public class RestContextFactory {
return credential; return credential;
} }
public static <S, A> RestContextBuilder<S, A> createContextBuilder(ContextSpec<S, A> contextSpec) { public static <S, A> RestContextBuilder<S, A> createContextBuilder(RestContextSpec<S, A> contextSpec) {
return createContextBuilder(contextSpec, NO_PROPERTIES); return createContextBuilder(contextSpec, NO_PROPERTIES);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <S, A> RestContextBuilder<S, A> createContextBuilder(ContextSpec<S, A> contextSpec, public static <S, A> RestContextBuilder<S, A> createContextBuilder(RestContextSpec<S, A> contextSpec,
Properties overrides) { Properties overrides) {
return createContextBuilder(contextSpec, EMPTY_LIST, overrides); return createContextBuilder(contextSpec, EMPTY_LIST, overrides);
} }
public static <S, A> RestContextBuilder<S, A> createContextBuilder(ContextSpec<S, A> contextSpec, public static <S, A> RestContextBuilder<S, A> createContextBuilder(RestContextSpec<S, A> contextSpec,
Iterable<Module> modules) { Iterable<Module> modules) {
return createContextBuilder(contextSpec, modules, NO_PROPERTIES); return createContextBuilder(contextSpec, modules, NO_PROPERTIES);
} }
public static <S, A> RestContextBuilder<S, A> createContextBuilder(ContextSpec<S, A> contextSpec, public static <S, A> RestContextBuilder<S, A> createContextBuilder(RestContextSpec<S, A> contextSpec,
Iterable<Module> modules, Properties overrides) { Iterable<Module> modules, Properties overrides) {
try { try {
PropertiesBuilder builder = contextSpec.propertiesBuilderClass.getConstructor(Properties.class).newInstance( PropertiesBuilder builder = contextSpec.propertiesBuilderClass.getConstructor(Properties.class).newInstance(
overrides); overrides);
builder.provider(contextSpec.provider); builder.provider(contextSpec.provider);
if (contextSpec.apiVersion != null) if (contextSpec.apiVersion != null)
@ -484,7 +364,7 @@ public class RestContextFactory {
builder.endpoint(contextSpec.endpoint); builder.endpoint(contextSpec.endpoint);
RestContextBuilder<S, A> contextBuilder = initContextBuilder(contextSpec.contextBuilderClass, RestContextBuilder<S, A> contextBuilder = initContextBuilder(contextSpec.contextBuilderClass,
contextSpec.sync, contextSpec.async, builder.build()); contextSpec.sync, contextSpec.async, builder.build());
contextBuilder.withModules(concat(modules, contextSpec.modules)); contextBuilder.withModules(concat(modules, contextSpec.modules));
@ -522,7 +402,7 @@ public class RestContextFactory {
* @see RestContextFactory#createContextBuilder(String, Iterable) * @see RestContextFactory#createContextBuilder(String, Iterable)
*/ */
public <S, A> RestContext<S, A> createContext(String provider, Iterable<? extends Module> wiring, public <S, A> RestContext<S, A> createContext(String provider, Iterable<? extends Module> wiring,
Properties overrides) { Properties overrides) {
RestContextBuilder<S, A> builder = createContextBuilder(provider, wiring, overrides); RestContextBuilder<S, A> builder = createContextBuilder(provider, wiring, overrides);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -531,7 +411,7 @@ public class RestContextFactory {
* @see RestContextFactory#createContextBuilder(String, String,String, Properties) * @see RestContextFactory#createContextBuilder(String, String,String, Properties)
*/ */
public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity, public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity,
@Nullable String credential, Properties properties) { @Nullable String credential, Properties properties) {
RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, properties); RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, properties);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -540,7 +420,7 @@ public class RestContextFactory {
* @see RestContextFactory#createContextBuilder(String, String,String, Iterable) * @see RestContextFactory#createContextBuilder(String, String,String, Iterable)
*/ */
public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity, public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity,
@Nullable String credential, Iterable<? extends Module> wiring) { @Nullable String credential, Iterable<? extends Module> wiring) {
RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, wiring); RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, wiring);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
@ -549,40 +429,40 @@ public class RestContextFactory {
* @see RestContextFactory#createContextBuilder(String, String,String, Iterable, Properties) * @see RestContextFactory#createContextBuilder(String, String,String, Iterable, Properties)
*/ */
public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity, public <S, A> RestContext<S, A> createContext(String provider, @Nullable String identity,
@Nullable String credential, Iterable<? extends Module> wiring, Properties overrides) { @Nullable String credential, Iterable<? extends Module> wiring, Properties overrides) {
RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, wiring, overrides); RestContextBuilder<S, A> builder = createContextBuilder(provider, identity, credential, wiring, overrides);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec) * @see RestContextFactory#createContextBuilder(RestContextSpec)
*/ */
public static <S, A> RestContext<S, A> createContext(ContextSpec<S, A> contextSpec) { public static <S, A> RestContext<S, A> createContext(RestContextSpec<S, A> contextSpec) {
RestContextBuilder<S, A> builder = createContextBuilder(contextSpec); RestContextBuilder<S, A> builder = createContextBuilder(contextSpec);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec, Properties) * @see RestContextFactory#createContextBuilder(RestContextSpec, Properties)
*/ */
public static <S, A> RestContext<S, A> createContext(ContextSpec<S, A> contextSpec, Properties overrides) { public static <S, A> RestContext<S, A> createContext(RestContextSpec<S, A> contextSpec, Properties overrides) {
RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, overrides); RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, overrides);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec, Iterable) * @see RestContextFactory#createContextBuilder(RestContextSpec, Iterable)
*/ */
public static <S, A> RestContext<S, A> createContext(ContextSpec<S, A> contextSpec, Iterable<Module> modules) { public static <S, A> RestContext<S, A> createContext(RestContextSpec<S, A> contextSpec, Iterable<Module> modules) {
RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, modules); RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, modules);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }
/** /**
* @see RestContextFactory#createContextBuilder(ContextSpec, Iterable, Properties) * @see RestContextFactory#createContextBuilder(RestContextSpec, Iterable, Properties)
*/ */
public static <S, A> RestContext<S, A> createContext(ContextSpec<S, A> contextSpec, Iterable<Module> modules, public static <S, A> RestContext<S, A> createContext(RestContextSpec<S, A> contextSpec, Iterable<Module> modules,
Properties overrides) { Properties overrides) {
RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, modules, overrides); RestContextBuilder<S, A> builder = createContextBuilder(contextSpec, modules, overrides);
return buildContextUnwrappingExceptions(builder); return buildContextUnwrappingExceptions(builder);
} }

View File

@ -0,0 +1,106 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.rest;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Collections.EMPTY_LIST;
import org.jclouds.PropertiesBuilder;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.inject.Module;
/**
* @author Adrian Cole
*/
public class RestContextSpec<S, A> {
protected final String provider;
protected final String endpoint;
protected final String apiVersion;
protected final String identity;
protected final String credential;
protected final Class<S> sync;
protected final Class<A> async;
protected final Class<PropertiesBuilder> propertiesBuilderClass;
protected final Class<RestContextBuilder<S, A>> contextBuilderClass;
protected final Iterable<Module> modules;
public RestContextSpec(String provider, String endpoint, String apiVersion, String identity, String credential,
Class<S> sync, Class<A> async, Class<PropertiesBuilder> propertiesBuilderClass,
Class<RestContextBuilder<S, A>> contextBuilderClass, Iterable<Module> modules) {
this.provider = checkNotNull(provider, "provider");
this.endpoint = endpoint;
this.apiVersion = apiVersion;
this.identity = identity;
this.credential = credential;
this.sync = sync;
this.async = async;
checkArgument(RestContextBuilder.class.isAssignableFrom(contextBuilderClass), contextBuilderClass.getName()
+ " is not a subclass of " + RestContextBuilder.class.getName());
checkArgument(PropertiesBuilder.class.isAssignableFrom(propertiesBuilderClass), propertiesBuilderClass.getName()
+ " is not a subclass of " + PropertiesBuilder.class.getName());
this.propertiesBuilderClass = propertiesBuilderClass;
this.contextBuilderClass = contextBuilderClass;
this.modules = ImmutableList.copyOf(modules);
}
@SuppressWarnings("unchecked")
public RestContextSpec(String provider, String endpoint, String apiVersion, String identity, String credential,
Class<S> sync, Class<A> async) {
this(provider, endpoint, apiVersion, identity, credential, sync, async, PropertiesBuilder.class,
(Class) RestContextBuilder.class, EMPTY_LIST);
}
/**
* this uses the inefficient {@link Objects} implementation as the object count will be
* relatively small and therefore efficiency is not a concern.
*/
@Override
public int hashCode() {
return Objects.hashCode(provider, endpoint, apiVersion, identity, credential, sync, async,
propertiesBuilderClass, contextBuilderClass, modules);
}
/**
* this uses the inefficient {@link Objects} implementation as the object count will be
* relatively small and therefore efficiency is not a concern.
*/
@Override
public boolean equals(Object that) {
if (that == null)
return false;
return Objects.equal(this.toString(), that.toString());
}
/**
* this uses the inefficient {@link Objects} implementation as the object count will be
* relatively small and therefore efficiency is not a concern.
*/
@Override
public String toString() {
return Objects.toStringHelper(this).add("provider", provider).add("endpoint", endpoint)
.add("apiVersion", apiVersion).add("identity", identity).add("sync", sync).add("async", async)
.add("propertiesBuilderClass", propertiesBuilderClass).add("contextBuilderClass", contextBuilderClass)
.add("modules", modules).toString();
}
}

View File

@ -58,6 +58,8 @@ import javax.annotation.Nullable;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.jclouds.PropertiesBuilder; import org.jclouds.PropertiesBuilder;
import org.jclouds.crypto.Pems;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.RestContextBuilder; import org.jclouds.rest.RestContextBuilder;
@ -246,15 +248,14 @@ public class Utils {
} }
/** /**
* Encode the given string with the given encoding, if possible. If the * Encode the given string with the given encoding, if possible. If the encoding fails with
* encoding fails with {@link UnsupportedEncodingException}, log a warning * {@link UnsupportedEncodingException}, log a warning and fall back to the system's default
* and fall back to the system's default encoding. * encoding.
* *
* @param str * @param str
* what to encode * what to encode
* @param charsetName * @param charsetName
* the name of a supported {@link java.nio.charset.Charset * the name of a supported {@link java.nio.charset.Charset </code>charset<code>}
* </code>charset<code>}
* @return properly encoded String. * @return properly encoded String.
*/ */
public static byte[] encodeString(String str, String charsetName) { public static byte[] encodeString(String str, String charsetName) {
@ -268,10 +269,9 @@ public class Utils {
} }
/** /**
* Encode the given string with the UTF-8 encoding, the sane default. In the * Encode the given string with the UTF-8 encoding, the sane default. In the very unlikely event
* very unlikely event the encoding fails with * the encoding fails with {@link UnsupportedEncodingException}, log a warning and fall back to
* {@link UnsupportedEncodingException}, log a warning and fall back to the * the system's default encoding.
* system's default encoding.
* *
* @param str * @param str
* what to encode * what to encode
@ -322,8 +322,7 @@ public class Utils {
} }
/** /**
* Will throw an exception if the argument is null or empty. Accepts a custom * Will throw an exception if the argument is null or empty. Accepts a custom error message.
* error message.
* *
* @param nullableString * @param nullableString
* string to verify. Can be null or empty. * string to verify. Can be null or empty.
@ -335,8 +334,8 @@ public class Utils {
} }
/** /**
* Gets a set of supported providers. Idea stolen from pallets * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses
* (supported-clouds). Uses rest.properties to populate the set. * rest.properties to populate the set.
* *
*/ */
public static Iterable<String> getSupportedProviders() { public static Iterable<String> getSupportedProviders() {
@ -344,8 +343,8 @@ public class Utils {
} }
/** /**
* Gets a set of supported providers. Idea stolen from pallets * Gets a set of supported providers. Idea stolen from pallets (supported-clouds). Uses
* (supported-clouds). Uses rest.properties to populate the set. * rest.properties to populate the set.
* *
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -468,4 +467,24 @@ public class Utils {
} }
return modules; return modules;
} }
public static boolean isPrivateKeyCredential(Credentials credentials) {
return credentials != null
&& credentials.credential != null
&& (credentials.credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credentials.credential
.startsWith(Pems.PRIVATE_PKCS8_MARKER));
}
public static Credentials overrideCredentialsIfSupplied(Credentials defaultCredentials,
@Nullable Credentials overridingCredentials) {
if (overridingCredentials == null)
return defaultCredentials;
String identity = overridingCredentials.identity != null ? overridingCredentials.identity : checkNotNull(
defaultCredentials, "defaultCredentials").identity;
String credential = overridingCredentials.credential != null ? overridingCredentials.credential : checkNotNull(
defaultCredentials, "defaultCredentials").credential;
return new Credentials(identity, credential);
}
} }

View File

@ -32,8 +32,8 @@ import org.testng.annotations.Test;
public class CredentialsTest { public class CredentialsTest {
public void testAzure() { public void testAzure() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials
.create("compute://identity:Base64==@azureblob/container-hyphen/prefix")); .parse(URI.create("compute://identity:Base64==@azureblob/container-hyphen/prefix"));
assertEquals(creds.identity, "identity"); assertEquals(creds.identity, "identity");
assertEquals(creds.credential, "Base64=="); assertEquals(creds.credential, "Base64==");
} }
@ -46,36 +46,31 @@ public class CredentialsTest {
} }
public void testDollar() { public void testDollar() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://user%40domain:pa%24sword@hostingdotcom"));
.create("compute://user%40domain:pa%24sword@hostingdotcom"));
assertEquals(creds.identity, "user@domain"); assertEquals(creds.identity, "user@domain");
assertEquals(creds.credential, "pa$sword"); assertEquals(creds.credential, "pa$sword");
} }
public void testTerremark() { public void testTerremark() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://user%40domain:password@terremark"));
.create("compute://user%40domain:password@terremark"));
assertEquals(creds.identity, "user@domain"); assertEquals(creds.identity, "user@domain");
assertEquals(creds.credential, "password"); assertEquals(creds.credential, "password");
} }
public void testTerremark2() { public void testTerremark2() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://user%40domain:passw%40rd@terremark"));
.create("compute://user%40domain:passw%40rd@terremark"));
assertEquals(creds.identity, "user@domain"); assertEquals(creds.identity, "user@domain");
assertEquals(creds.credential, "passw@rd"); assertEquals(creds.credential, "passw@rd");
} }
public void testTerremark3() { public void testTerremark3() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://user%40domain:AbC%21%40943%21@terremark"));
.create("compute://user%40domain:AbC%21%40943%21@terremark"));
assertEquals(creds.identity, "user@domain"); assertEquals(creds.identity, "user@domain");
assertEquals(creds.credential, "AbC!@943!"); assertEquals(creds.credential, "AbC!@943!");
} }
public void testCloudFiles() { public void testCloudFiles() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://identity:h3c@cloudfiles/container-hyphen/prefix"));
.create("compute://identity:h3c@cloudfiles/container-hyphen/prefix"));
assertEquals(creds.identity, "identity"); assertEquals(creds.identity, "identity");
assertEquals(creds.credential, "h3c"); assertEquals(creds.credential, "h3c");
@ -83,18 +78,22 @@ public class CredentialsTest {
public void testS3() { public void testS3() {
Credentials creds = Credentials Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/prefix"));
.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/prefix"));
assertEquals(creds.identity, "0AB"); assertEquals(creds.identity, "0AB");
assertEquals(creds.credential, "aA+/0"); assertEquals(creds.credential, "aA+/0");
} }
public void testS3Space() { public void testS3Space() {
Credentials creds = Credentials.parse(URI Credentials creds = Credentials.parse(URI.create("compute://0AB:aA%2B%2F0@s3/buck-et/pre%20fix"));
.create("compute://0AB:aA%2B%2F0@s3/buck-et/pre%20fix"));
assertEquals(creds.identity, "0AB"); assertEquals(creds.identity, "0AB");
assertEquals(creds.credential, "aA+/0"); assertEquals(creds.credential, "aA+/0");
} }
public void testSubClassEquals() {
Credentials creds = new Credentials("user", "pass");
assertEquals(creds, new Credentials("user", "pass") {
});
}
} }

View File

@ -51,7 +51,7 @@ import org.jclouds.crypto.CryptoStreams;
import org.jclouds.io.InputSuppliers; import org.jclouds.io.InputSuppliers;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextBuilder; import org.jclouds.rest.RestContextBuilder;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.mortbay.jetty.Connector; import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler; import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Request; import org.mortbay.jetty.Request;
@ -264,7 +264,7 @@ public abstract class BaseJettyTest {
Properties properties, Module... connectionModules) { Properties properties, Module... connectionModules) {
properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true");
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test", RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test",
"http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class, "http://localhost:" + testPort, "1", "identity", null, IntegrationTestClient.class,
IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules)); IntegrationTestAsyncClient.class, ImmutableSet.<Module> copyOf(connectionModules));
return createContextBuilder(contextSpec, properties); return createContextBuilder(contextSpec, properties);

View File

@ -33,7 +33,6 @@ import org.jclouds.concurrent.Timeout;
import org.jclouds.http.IntegrationTestAsyncClient; import org.jclouds.http.IntegrationTestAsyncClient;
import org.jclouds.http.IntegrationTestClient; import org.jclouds.http.IntegrationTestClient;
import org.jclouds.predicates.validators.AllLowerCaseValidator; import org.jclouds.predicates.validators.AllLowerCaseValidator;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.annotations.ParamValidators; import org.jclouds.rest.annotations.ParamValidators;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
@ -145,7 +144,7 @@ public class InputParamValidatorTest {
@BeforeClass @BeforeClass
void setupFactory() { void setupFactory() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test", RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec("test",
"http://localhost:9999", "1", "userFoo", null, IntegrationTestClient.class, "http://localhost:9999", "1", "userFoo", null, IntegrationTestClient.class,
IntegrationTestAsyncClient.class); IntegrationTestAsyncClient.class);

View File

@ -27,7 +27,6 @@ import java.util.Properties;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.logging.config.NullLoggingModule; import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
@ -45,7 +44,7 @@ public abstract class RestClientTest<T> extends BaseRestClientTest {
protected abstract void checkFilters(HttpRequest request); protected abstract void checkFilters(HttpRequest request);
abstract public ContextSpec<?, ?> createContextSpec(); abstract public RestContextSpec<?, ?> createContextSpec();
protected Module createModule() { protected Module createModule() {
return new Module() { return new Module() {
@ -60,7 +59,7 @@ public abstract class RestClientTest<T> extends BaseRestClientTest {
@BeforeClass @BeforeClass
protected void setupFactory() throws IOException { protected void setupFactory() throws IOException {
ContextSpec<?, ?> contextSpec = createContextSpec(); RestContextSpec<?, ?> contextSpec = createContextSpec();
injector = createContextBuilder(contextSpec, injector = createContextBuilder(contextSpec,
ImmutableSet.of(new MockModule(), new NullLoggingModule(), createModule()), ImmutableSet.of(new MockModule(), new NullLoggingModule(), createModule()),
getProperties()).buildInjector(); getProperties()).buildInjector();

View File

@ -34,7 +34,6 @@ import org.jclouds.PropertiesBuilder;
import org.jclouds.http.IntegrationTestAsyncClient; import org.jclouds.http.IntegrationTestAsyncClient;
import org.jclouds.http.IntegrationTestClient; import org.jclouds.http.IntegrationTestClient;
import org.jclouds.http.RequiresHttp; import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.config.RestClientModule; import org.jclouds.rest.config.RestClientModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -54,14 +53,14 @@ public class RestContextFactoryTest {
private static final String provider = "test"; private static final String provider = "test";
public void testBuilder() { public void testBuilder() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, IntegrationTestClient.class, IntegrationTestAsyncClient.class); "http://localhost", "1", "dummy", null, IntegrationTestClient.class, IntegrationTestAsyncClient.class);
createContextBuilder(contextSpec); createContextBuilder(contextSpec);
} }
public void testBuilderProperties() { public void testBuilderProperties() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, IntegrationTestClient.class, IntegrationTestAsyncClient.class); "http://localhost", "1", "dummy", null, IntegrationTestClient.class, IntegrationTestAsyncClient.class);
Properties props = RestContextFactory.toProperties(contextSpec); Properties props = RestContextFactory.toProperties(contextSpec);
@ -79,7 +78,7 @@ public class RestContextFactoryTest {
} }
public void testBuilderPropertiesWithCredential() { public void testBuilderPropertiesWithCredential() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", "credential", IntegrationTestClient.class, "http://localhost", "1", "dummy", "credential", IntegrationTestClient.class,
IntegrationTestAsyncClient.class); IntegrationTestAsyncClient.class);
@ -99,7 +98,7 @@ public class RestContextFactoryTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testBuilderPropertiesWithContextBuilder() { public void testBuilderPropertiesWithContextBuilder() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class,
(Class) IntegrationTestContextBuilder.class, Collections.EMPTY_LIST); (Class) IntegrationTestContextBuilder.class, Collections.EMPTY_LIST);
@ -119,7 +118,7 @@ public class RestContextFactoryTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testBuilderPropertiesWithModule() { public void testBuilderPropertiesWithModule() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class,
(Class) IntegrationTestContextBuilder.class, Collections.<Module> singleton(new A())); (Class) IntegrationTestContextBuilder.class, Collections.<Module> singleton(new A()));
@ -139,7 +138,7 @@ public class RestContextFactoryTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testBuilderPropertiesWithModules() { public void testBuilderPropertiesWithModules() {
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class, "http://localhost", "1", "dummy", null, (Class) null, (Class) null, PropertiesBuilder.class,
(Class) IntegrationTestContextBuilder.class, Arrays.<Module> asList(new A(), new B())); (Class) IntegrationTestContextBuilder.class, Arrays.<Module> asList(new A(), new B()));
@ -174,9 +173,9 @@ public class RestContextFactoryTest {
@SuppressWarnings("hiding") @SuppressWarnings("hiding")
@Override @Override
public <S, A> ContextSpec<S, A> createContextSpec(String providerName, String identity, String credential, public <S, A> RestContextSpec<S, A> createContextSpec(String providerName, String identity, String credential,
Iterable<? extends Module> wiring, Properties _overrides) { Iterable<? extends Module> wiring, Properties _overrides) {
ContextSpec<S, A> spec = super.createContextSpec(providerName, identity, credential, wiring, _overrides); RestContextSpec<S, A> spec = super.createContextSpec(providerName, identity, credential, wiring, _overrides);
assertEquals(spec.identity, "foo"); assertEquals(spec.identity, "foo");
assertEquals(spec.credential, "bar"); assertEquals(spec.credential, "bar");
assertEquals(Iterables.size(spec.modules), 2); assertEquals(Iterables.size(spec.modules), 2);
@ -206,9 +205,9 @@ public class RestContextFactoryTest {
@SuppressWarnings("hiding") @SuppressWarnings("hiding")
@Override @Override
public <S, A> ContextSpec<S, A> createContextSpec(String providerName, String identity, String credential, public <S, A> RestContextSpec<S, A> createContextSpec(String providerName, String identity, String credential,
Iterable<? extends Module> wiring, Properties _overrides) { Iterable<? extends Module> wiring, Properties _overrides) {
ContextSpec<S, A> spec = super.createContextSpec(providerName, identity, credential, wiring, _overrides); RestContextSpec<S, A> spec = super.createContextSpec(providerName, identity, credential, wiring, _overrides);
assertEquals(spec.identity, "foo"); assertEquals(spec.identity, "foo");
assertEquals(spec.credential, "bar"); assertEquals(spec.credential, "bar");
assertEquals(Iterables.size(spec.modules), 2); assertEquals(Iterables.size(spec.modules), 2);
@ -240,7 +239,7 @@ public class RestContextFactoryTest {
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testBuilderPropertiesWithWrongConfig() { public void testBuilderPropertiesWithWrongConfig() {
@SuppressWarnings("unused") @SuppressWarnings("unused")
ContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider, RestContextSpec<IntegrationTestClient, IntegrationTestAsyncClient> contextSpec = contextSpec(provider,
"http://localhost", "1", "dummy", null, (Class) null, (Class) null, "http://localhost", "1", "dummy", null, (Class) null, (Class) null,
(Class) IntegrationTestContextBuilder.class, (Class) PropertiesBuilder.class, Collections.EMPTY_LIST); (Class) IntegrationTestContextBuilder.class, (Class) PropertiesBuilder.class, Collections.EMPTY_LIST);
} }

View File

@ -108,7 +108,7 @@ import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.rest.BaseRestClientTest; import org.jclouds.rest.BaseRestClientTest;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.InvocationContext; import org.jclouds.rest.InvocationContext;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.annotations.Delegate;
import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.Endpoint;
@ -278,7 +278,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
private Injector injectorForClient() { private Injector injectorForClient() {
ContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, RestContextSpec<Caller, AsyncCaller> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null,
Caller.class, AsyncCaller.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), Caller.class, AsyncCaller.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(),
new CallerCalleeModule())); new CallerCalleeModule()));
@ -2081,7 +2081,7 @@ public class RestAnnotationProcessorTest extends BaseRestClientTest {
@BeforeClass @BeforeClass
void setupFactory() { void setupFactory() {
ContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null, RestContextSpec<String, Integer> contextSpec = contextSpec("test", "http://localhost:9999", "1", "userfoo", null,
String.class, Integer.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), String.class, Integer.class, ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(),
new AbstractModule() { new AbstractModule() {

View File

@ -25,6 +25,7 @@ import static org.testng.Assert.assertEquals;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.jclouds.domain.Credentials;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -42,6 +43,33 @@ import com.google.inject.spi.Message;
@Test(groups = "unit", testName = "jclouds.UtilsTest") @Test(groups = "unit", testName = "jclouds.UtilsTest")
public class UtilsTest { public class UtilsTest {
public void testOverridingCredentialsWhenOverridingIsNull() {
Credentials defaultCredentials = new Credentials("foo", "bar");
Credentials overridingCredentials = null;
assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), defaultCredentials);
}
public void testOverridingCredentialsWhenOverridingLoginIsNull() {
Credentials defaultCredentials = new Credentials("foo", "bar");
Credentials overridingCredentials = new Credentials(null, "baz");
assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials(
"foo", "baz"));
}
public void testOverridingCredentialsWhenOverridingCredentialIsNull() {
Credentials defaultCredentials = new Credentials("foo", "bar");
Credentials overridingCredentials = new Credentials("fooble", null);
assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials(
"fooble", "bar"));
}
public void testOverridingCredentialsWhenOverridingCredentialsAreNull() {
Credentials defaultCredentials = new Credentials("foo", "bar");
Credentials overridingCredentials = new Credentials(null, null);
assertEquals(Utils.overrideCredentialsIfSupplied(defaultCredentials, overridingCredentials), new Credentials(
"foo", "bar"));
}
public void testGetCause() { public void testGetCause() {
AuthorizationException aex = createMock(AuthorizationException.class); AuthorizationException aex = createMock(AuthorizationException.class);
Message message = new Message(ImmutableList.of(), "test", aex); Message message = new Message(ImmutableList.of(), "test", aex);

View File

@ -19,16 +19,19 @@
package org.jclouds.ssh.jsch.config; package org.jclouds.ssh.jsch.config;
import static org.jclouds.util.Utils.isPrivateKeyCredential;
import javax.inject.Named; import javax.inject.Named;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.domain.Credentials;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler; import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.SocketOpen; import org.jclouds.predicates.SocketOpen;
import org.jclouds.ssh.ConfiguresSshClient; import org.jclouds.ssh.ConfiguresSshClient;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.JschSshClient;
import org.jclouds.ssh.jsch.predicates.InetSocketAddressConnect;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Inject; import com.google.inject.Inject;
@ -74,5 +77,10 @@ public class JschSshClientModule extends AbstractModule {
return client; return client;
} }
@Override
public SshClient create(IPSocket socket, Credentials credentials) {
return isPrivateKeyCredential(credentials) ? create(socket, credentials.identity,
credentials.credential.getBytes()) : create(socket, credentials.identity, credentials.credential);
}
} }
} }

View File

@ -26,6 +26,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.jclouds.domain.Credentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
@ -101,7 +102,7 @@ public class JschSshClientLiveTest {
@Override @Override
public void put(String path, String contents) { public void put(String path, String contents) {
} }
}; };
@ -110,10 +111,10 @@ public class JschSshClientLiveTest {
SshClient.Factory factory = i.getInstance(SshClient.Factory.class); SshClient.Factory factory = i.getInstance(SshClient.Factory.class);
SshClient connection; SshClient connection;
if (sshKeyFile != null && !sshKeyFile.trim().equals("")) { if (sshKeyFile != null && !sshKeyFile.trim().equals("")) {
connection = factory.create(new IPSocket(sshHost, port), sshUser, Utils.toStringAndClose( connection = factory.create(new IPSocket(sshHost, port),
new FileInputStream(sshKeyFile)).getBytes()); new Credentials(sshUser, Utils.toStringAndClose(new FileInputStream(sshKeyFile))));
} else { } else {
connection = factory.create(new IPSocket(sshHost, port), sshUser, sshPass); connection = factory.create(new IPSocket(sshHost, port), new Credentials(sshUser, sshPass));
} }
connection.connect(); connection.connect();
return connection; return connection;

View File

@ -23,6 +23,7 @@ import java.io.IOException;
import java.net.ConnectException; import java.net.ConnectException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.ssh.jsch.config.JschSshClientModule;
@ -51,8 +52,8 @@ public class JschSshClientTest {
protected JschSshClient createClient() throws UnknownHostException { protected JschSshClient createClient() throws UnknownHostException {
Injector i = Guice.createInjector(module()); Injector i = Guice.createInjector(module());
SshClient.Factory factory = i.getInstance(SshClient.Factory.class); SshClient.Factory factory = i.getInstance(SshClient.Factory.class);
JschSshClient ssh = JschSshClient.class.cast(factory.create(new IPSocket("localhost", 22), JschSshClient ssh = JschSshClient.class.cast(factory.create(new IPSocket("localhost", 22), new Credentials(
"username", "password")); "username", "password")));
return ssh; return ssh;
} }
@ -68,10 +69,8 @@ public class JschSshClientTest {
} }
public void testExceptionMessagesRetry() { public void testExceptionMessagesRetry() {
assert ssh.shouldRetry(new JSchException( assert ssh.shouldRetry(new JSchException("Session.connect: java.io.IOException: End of IO Stream Read"));
"Session.connect: java.io.IOException: End of IO Stream Read"));
assert ssh.shouldRetry(new JSchException("Session.connect: invalid data")); assert ssh.shouldRetry(new JSchException("Session.connect: invalid data"));
assert ssh.shouldRetry(new JSchException( assert ssh.shouldRetry(new JSchException("Session.connect: java.net.SocketException: Connection reset"));
"Session.connect: java.net.SocketException: Connection reset"));
} }
} }

View File

@ -21,6 +21,7 @@ package org.jclouds.ssh.jsch.config;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.JschSshClient;
@ -41,7 +42,7 @@ public class JschSshClientModuleTest {
Injector i = Guice.createInjector(new JschSshClientModule()); Injector i = Guice.createInjector(new JschSshClientModule());
SshClient.Factory factory = i.getInstance(SshClient.Factory.class); SshClient.Factory factory = i.getInstance(SshClient.Factory.class);
SshClient connection = factory.create(new IPSocket("localhost", 22), "username", "password"); SshClient connection = factory.create(new IPSocket("localhost", 22), new Credentials("username", "password"));
assert connection instanceof JschSshClient; assert connection instanceof JschSshClient;
} }
} }

View File

@ -0,0 +1,64 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.gogrid.compute.config;
import org.jclouds.compute.config.BindComputeStrategiesByClass;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridGetNodeMetadataStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridListNodesStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridRebootNodeStrategy;
/**
*
* @author Adrian Cole
*
*/
public class GoGridBindComputeStrategiesByClass extends BindComputeStrategiesByClass {
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return GoGridAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return GoGridDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return GoGridGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return GoGridListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return GoGridRebootNodeStrategy.class;
}
}

View File

@ -0,0 +1,60 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed 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.jclouds.gogrid.compute.config;
import java.util.Set;
import org.jclouds.compute.config.BindComputeSuppliersByClass;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import org.jclouds.gogrid.compute.suppliers.GoGridDefaultLocationSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridHardwareSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridImageSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridLocationSupplier;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*
*/
public class GoGridBindComputeSuppliersByClass extends BindComputeSuppliersByClass {
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return GoGridHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return GoGridImageSupplier.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return GoGridDefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return GoGridLocationSupplier.class;
}
}

View File

@ -21,30 +21,10 @@ package org.jclouds.gogrid.compute.config;
import static org.jclouds.compute.domain.OsFamily.CENTOS; import static org.jclouds.compute.domain.OsFamily.CENTOS;
import java.util.Set;
import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.domain.Location;
import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridGetNodeMetadataStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridListNodesStrategy;
import org.jclouds.gogrid.compute.strategy.GoGridRebootNodeStrategy;
import org.jclouds.gogrid.compute.suppliers.GoGridDefaultLocationSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridHardwareSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridImageSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridLocationSupplier;
import com.google.common.base.Supplier;
import com.google.inject.Injector; import com.google.inject.Injector;
/** /**
@ -56,6 +36,8 @@ public class GoGridComputeServiceContextModule extends BaseComputeServiceContext
@Override @Override
protected void configure() { protected void configure() {
install(new GoGridComputeServiceDependenciesModule()); install(new GoGridComputeServiceDependenciesModule());
install(new GoGridBindComputeStrategiesByClass());
install(new GoGridBindComputeSuppliersByClass());
super.configure(); super.configure();
} }
@ -63,49 +45,4 @@ public class GoGridComputeServiceContextModule extends BaseComputeServiceContext
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(CENTOS).imageNameMatches(".*w/ None.*"); return template.osFamily(CENTOS).imageNameMatches(".*w/ None.*");
} }
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return GoGridAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return GoGridDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return GoGridGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return GoGridHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return GoGridImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return GoGridListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return GoGridRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return GoGridDefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return GoGridLocationSupplier.class;
}
} }

View File

@ -71,7 +71,7 @@ public class GoGridAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
} }
@Override @Override
public NodeMetadata execute(String tag, String name, Template template) { public NodeMetadata addNodeWithTag(String tag, String name, Template template) {
Server addedServer = null; Server addedServer = null;
boolean notStarted = true; boolean notStarted = true;
int numOfRetries = 20; int numOfRetries = 20;

View File

@ -43,9 +43,9 @@ public class GoGridDestroyNodeStrategy implements DestroyNodeStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata destroyNode(String id) {
client.getServerServices().deleteById(new Long(id)); client.getServerServices().deleteById(new Long(id));
return getNode.execute(id); return getNode.getNode(id);
} }
} }

View File

@ -50,7 +50,7 @@ public class GoGridGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata getNode(String id) {
try { try {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById( Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(
new Long(checkNotNull(id, "id")))); new Long(checkNotNull(id, "id"))));

View File

@ -49,7 +49,7 @@ public class GoGridListNodesStrategy implements ListNodesStrategy {
} }
@Override @Override
public Iterable<? extends ComputeMetadata> list() { public Iterable<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all()); return listDetailsOnNodesMatching(NodePredicates.all());
} }

View File

@ -56,12 +56,12 @@ public class GoGridRebootNodeStrategy implements RebootNodeStrategy {
} }
@Override @Override
public NodeMetadata execute(String id) { public NodeMetadata rebootNode(String id) {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id))); Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
client.getServerServices().power(server.getName(), PowerCommand.RESTART); client.getServerServices().power(server.getName(), PowerCommand.RESTART);
serverLatestJobCompleted.apply(server); serverLatestJobCompleted.apply(server);
client.getServerServices().power(server.getName(), PowerCommand.START); client.getServerServices().power(server.getName(), PowerCommand.START);
serverLatestJobCompletedShort.apply(server); serverLatestJobCompletedShort.apply(server);
return getNode.execute(id); return getNode.getNode(id);
} }
} }

View File

@ -59,11 +59,11 @@ import org.jclouds.gogrid.predicates.ServerLatestJobCompleted;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler; import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.InetSocketAddressConnect;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.JschSshClient;
import org.jclouds.ssh.jsch.predicates.InetSocketAddressConnect;
import org.testng.SkipException; import org.testng.SkipException;
import org.testng.TestException; import org.testng.TestException;
import org.testng.annotations.AfterTest; import org.testng.annotations.AfterTest;

View File

@ -31,7 +31,7 @@ import org.jclouds.http.RequiresHttp;
import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec; import org.jclouds.rest.RestContextSpec;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.inject.Module; import com.google.inject.Module;
@ -67,7 +67,7 @@ public abstract class BaseGoGridAsyncClientTest<T> extends RestClientTest<T> {
} }
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public RestContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("gogrid", "foo", "bar", new Properties()); return new RestContextFactory().createContextSpec("gogrid", "foo", "bar", new Properties());
} }

Some files were not shown because too many files have changed in this diff Show More