Issue 335: took initialization code out of injection providers and into memoized suppliers, this will allow us to tune caching and speed up injection as guice is single-threaded; fixed broken windows along the way

This commit is contained in:
Adrian Cole 2010-08-17 02:08:39 -07:00
parent df6fddb49d
commit 462a6e5617
131 changed files with 5190 additions and 2803 deletions

View File

@ -59,6 +59,7 @@ import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
/** /**
@ -79,8 +80,8 @@ public class AtmosAsyncBlobStore extends BaseAsyncBlobStore {
@Inject @Inject
AtmosAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, AtmosAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Set<? extends Location> locations, AtmosStorageAsyncClient async, AtmosStorageClient sync, Supplier<Set<? extends Location>> locations, AtmosStorageAsyncClient async, AtmosStorageClient sync,
ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,
BlobStoreListOptionsToListOptions container2ContainerListOptions, BlobStoreListOptionsToListOptions container2ContainerListOptions,
DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto, DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,

View File

@ -49,6 +49,8 @@ import org.jclouds.crypto.Crypto;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import com.google.common.base.Supplier;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@ -65,13 +67,12 @@ public class AtmosBlobStore extends BaseBlobStore {
private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider; private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider;
@Inject @Inject
AtmosBlobStore(BlobStoreContext context, BlobUtils blobUtils, Location defaultLocation, AtmosBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,
Set<? extends Location> locations, AtmosStorageClient sync, ObjectToBlob object2Blob, Supplier<Set<? extends Location>> locations, AtmosStorageClient sync, ObjectToBlob object2Blob,
ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,
BlobStoreListOptionsToListOptions container2ContainerListOptions, BlobStoreListOptionsToListOptions container2ContainerListOptions,
DirectoryEntryListToResourceMetadataList container2ResourceList, DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,
Crypto crypto, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToHttpGetOptions blob2ObjectGetOptions, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, defaultLocation, locations); super(context, blobUtils, defaultLocation, locations);
this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions"); this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions");
this.sync = checkNotNull(sync, "sync"); this.sync = checkNotNull(sync, "sync");
@ -82,8 +83,7 @@ public class AtmosBlobStore extends BaseBlobStore {
this.blob2Object = checkNotNull(blob2Object, "blob2Object"); this.blob2Object = checkNotNull(blob2Object, "blob2Object");
this.object2BlobMd = checkNotNull(object2BlobMd, "object2BlobMd"); this.object2BlobMd = checkNotNull(object2BlobMd, "object2BlobMd");
this.crypto = checkNotNull(crypto, "crypto"); this.crypto = checkNotNull(crypto, "crypto");
this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, "fetchBlobMetadataProvider");
"fetchBlobMetadataProvider");
} }
/** /**
@ -169,8 +169,7 @@ public class AtmosBlobStore extends BaseBlobStore {
* This implementation invokes {@link AtmosStorageClient#readFile} * This implementation invokes {@link AtmosStorageClient#readFile}
*/ */
@Override @Override
public Blob getBlob(String container, String key, public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions options) {
org.jclouds.blobstore.options.GetOptions options) {
GetOptions httpOptions = blob2ObjectGetOptions.apply(options); GetOptions httpOptions = blob2ObjectGetOptions.apply(options);
return object2Blob.apply(sync.readFile(container + "/" + key, httpOptions)); return object2Blob.apply(sync.readFile(container + "/" + key, httpOptions));
} }
@ -192,10 +191,9 @@ public class AtmosBlobStore extends BaseBlobStore {
container = AtmosStorageUtils.adjustContainerIfDirOptionPresent(container, options); container = AtmosStorageUtils.adjustContainerIfDirOptionPresent(container, options);
ListOptions nativeOptions = container2ContainerListOptions.apply(options); ListOptions nativeOptions = container2ContainerListOptions.apply(options);
// until includeMeta() option works for namespace interface // until includeMeta() option works for namespace interface
PageSet<? extends StorageMetadata> list = container2ResourceList.apply(sync.listDirectory( PageSet<? extends StorageMetadata> list = container2ResourceList.apply(sync.listDirectory(container,
container, nativeOptions)); nativeOptions));
return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container) return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container).apply(list) : list;
.apply(list) : list;
} }
/** /**

View File

@ -40,6 +40,8 @@ import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -52,7 +54,6 @@ import com.google.inject.TypeLiteral;
* @author Adrian Cole * @author Adrian Cole
*/ */
public class AtmosBlobStoreContextModule extends AbstractModule { public class AtmosBlobStoreContextModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
@ -60,22 +61,22 @@ public class AtmosBlobStoreContextModule extends AbstractModule {
bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL); bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);
bind(AsyncBlobStore.class).to(AtmosAsyncBlobStore.class).in(Scopes.SINGLETON); bind(AsyncBlobStore.class).to(AtmosAsyncBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStore.class).to(AtmosBlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(AtmosBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStoreContext.class) bind(BlobStoreContext.class).to(
.to( new TypeLiteral<BlobStoreContextImpl<AtmosStorageClient, AtmosStorageAsyncClient>>() {
new TypeLiteral<BlobStoreContextImpl<AtmosStorageClient, AtmosStorageAsyncClient>>() { }).in(Scopes.SINGLETON);
}).in(Scopes.SINGLETON);
bind(ContainsValueInListStrategy.class).to(FindMD5InUserMetadata.class); bind(ContainsValueInListStrategy.class).to(FindMD5InUserMetadata.class);
} }
@Provides @Provides
@Singleton @Singleton
Location getLocation(@Provider String providerName) { Supplier<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
} }
@Provides @Provides
@Singleton @Singleton
Set<? extends Location> provideLocations(Location location) { Supplier<Location> provideDefaultLocation(@Provider String providerName) {
return ImmutableSet.of(location); return Suppliers
.<Location> ofInstance(new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null));
} }
} }

View File

@ -34,6 +34,7 @@ import org.jclouds.blobstore.domain.internal.StorageMetadataImpl;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@ -43,10 +44,10 @@ import com.google.common.collect.Maps;
@Singleton @Singleton
public class DirectoryEntryListToResourceMetadataList implements public class DirectoryEntryListToResourceMetadataList implements
Function<BoundedSet<? extends DirectoryEntry>, PageSet<? extends StorageMetadata>> { Function<BoundedSet<? extends DirectoryEntry>, PageSet<? extends StorageMetadata>> {
private Location defaultLocation; private Supplier<Location> defaultLocation;
@Inject @Inject
DirectoryEntryListToResourceMetadataList(Location defaultLocation) { DirectoryEntryListToResourceMetadataList(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation; this.defaultLocation = defaultLocation;
} }
@ -56,16 +57,13 @@ public class DirectoryEntryListToResourceMetadataList implements
new Function<DirectoryEntry, StorageMetadata>() { new Function<DirectoryEntry, StorageMetadata>() {
public StorageMetadata apply(DirectoryEntry from) { public StorageMetadata apply(DirectoryEntry from) {
StorageType type = from.getType() == FileType.DIRECTORY ? StorageType.FOLDER StorageType type = from.getType() == FileType.DIRECTORY ? StorageType.FOLDER : StorageType.BLOB;
: StorageType.BLOB;
if (type == StorageType.FOLDER) if (type == StorageType.FOLDER)
return new StorageMetadataImpl(type, from.getObjectID(), from return new StorageMetadataImpl(type, from.getObjectID(), from.getObjectName(), defaultLocation.get(),
.getObjectName(), defaultLocation, null, null, null, null, Maps null, null, null, null, Maps.<String, String> newHashMap());
.<String, String> newHashMap());
else else
return new BlobMetadataImpl(from.getObjectID(), from.getObjectName(), return new BlobMetadataImpl(from.getObjectID(), from.getObjectName(), defaultLocation.get(), null,
defaultLocation, null, null, null, null, Maps null, null, null, Maps.<String, String> newHashMap(), null, null);
.<String, String> newHashMap(), null, null);
} }
}), from.getToken()); }), from.getToken());

View File

@ -59,6 +59,7 @@ import org.jclouds.domain.Location;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
/** /**
@ -73,8 +74,8 @@ public class EC2ComputeService extends BaseComputeService {
private final Predicate<PlacementGroup> placementGroupDeleted; private final Predicate<PlacementGroup> placementGroupDeleted;
@Inject @Inject
protected EC2ComputeService(ComputeServiceContext context, Provider<Set<? extends Image>> images, protected EC2ComputeService(ComputeServiceContext context, Supplier<Set<? extends Image>> images,
Provider<Set<? extends Size>> sizes, Provider<Set<? extends Location>> locations, Supplier<Set<? extends Size>> sizes, Supplier<Set<? extends Location>> locations,
ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,
RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
DestroyNodeStrategy destroyNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider, DestroyNodeStrategy destroyNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,

View File

@ -19,89 +19,62 @@
package org.jclouds.aws.ec2.compute.config; package org.jclouds.aws.ec2.compute.config;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.collect.Iterables.toArray; import static com.google.common.collect.Iterables.toArray;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Maps.newLinkedHashMap; import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.uniqueIndex; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.imageIds;
import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.ownedBy;
import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS; import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;
import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs; import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs;
import static org.jclouds.aws.ec2.util.EC2Utils.getAllRunningInstancesInRegion;
import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle;
import static org.jclouds.compute.domain.OsFamily.CENTOS; 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 static org.jclouds.concurrent.FutureIterables.transformParallel;
import java.net.URI;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.aws.Region; import org.jclouds.aws.Region;
import org.jclouds.aws.config.DefaultLocationProvider;
import org.jclouds.aws.ec2.EC2AsyncClient; import org.jclouds.aws.ec2.EC2AsyncClient;
import org.jclouds.aws.ec2.EC2Client; import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.EC2ComputeService; import org.jclouds.aws.ec2.compute.EC2ComputeService;
import org.jclouds.aws.ec2.compute.domain.EC2Size;
import org.jclouds.aws.ec2.compute.domain.RegionAndName; import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded; import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded;
import org.jclouds.aws.ec2.compute.functions.CreateSecurityGroupIfNeeded; import org.jclouds.aws.ec2.compute.functions.CreateSecurityGroupIfNeeded;
import org.jclouds.aws.ec2.compute.functions.CreateUniqueKeyPair; import org.jclouds.aws.ec2.compute.functions.CreateUniqueKeyPair;
import org.jclouds.aws.ec2.compute.functions.ImageParser;
import org.jclouds.aws.ec2.compute.functions.RegionAndIdToImage; import org.jclouds.aws.ec2.compute.functions.RegionAndIdToImage;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.compute.internal.EC2TemplateBuilderImpl; import org.jclouds.aws.ec2.compute.internal.EC2TemplateBuilderImpl;
import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions; import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.aws.ec2.compute.strategy.DescribeImagesParallel;
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.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.strategy.EC2RunNodesAndAddToSetStrategy;
import org.jclouds.aws.ec2.domain.InstanceType; import org.jclouds.aws.ec2.compute.suppliers.EC2LocationSupplier;
import org.jclouds.aws.ec2.compute.suppliers.EC2SizeSupplier;
import org.jclouds.aws.ec2.compute.suppliers.RegionAndNameToImageSupplier;
import org.jclouds.aws.ec2.domain.KeyPair; import org.jclouds.aws.ec2.domain.KeyPair;
import org.jclouds.aws.ec2.domain.PlacementGroup; import org.jclouds.aws.ec2.domain.PlacementGroup;
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.functions.RunningInstanceToStorageMappingUnix; import org.jclouds.aws.ec2.functions.RunningInstanceToStorageMappingUnix;
import org.jclouds.aws.ec2.options.DescribeImagesOptions;
import org.jclouds.aws.ec2.predicates.InstancePresent; import org.jclouds.aws.ec2.predicates.InstancePresent;
import org.jclouds.aws.ec2.predicates.PlacementGroupAvailable; import org.jclouds.aws.ec2.predicates.PlacementGroupAvailable;
import org.jclouds.aws.ec2.predicates.PlacementGroupDeleted; import org.jclouds.aws.ec2.predicates.PlacementGroupDeleted;
import org.jclouds.aws.ec2.services.InstanceClient; import org.jclouds.aws.suppliers.DefaultLocationSupplier;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.DestroyLoadBalancerStrategy; import org.jclouds.compute.strategy.DestroyLoadBalancerStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
@ -110,24 +83,20 @@ import org.jclouds.compute.strategy.LoadBalanceNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MapMaker; import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps; import com.google.inject.Injector;
import com.google.inject.AbstractModule; import com.google.inject.Key;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -138,7 +107,7 @@ import com.google.inject.name.Names;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class EC2ComputeServiceContextModule extends AbstractModule { public class EC2ComputeServiceContextModule extends BaseComputeServiceContextModule {
@Provides @Provides
@Singleton @Singleton
@ -164,7 +133,6 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
install(new ComputeServiceTimeoutsModule()); install(new ComputeServiceTimeoutsModule());
bind(Location.class).toProvider(DefaultLocationProvider.class).in(Scopes.SINGLETON);
bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class);
bind(TemplateOptions.class).to(EC2TemplateOptions.class); bind(TemplateOptions.class).to(EC2TemplateOptions.class);
bind(ComputeService.class).to(EC2ComputeService.class); bind(ComputeService.class).to(EC2ComputeService.class);
@ -199,111 +167,14 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
} }
@Provides @Override
@Named("DEFAULT") protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected TemplateBuilder provideTemplate(@Region String region, TemplateBuilder template) { String region = injector.getInstance(Key.get(String.class, Region.class));
return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() : template.architecture( return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() : template.architecture(
Architecture.X86_32).osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*").osDescriptionMatches( Architecture.X86_32).osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*").osDescriptionMatches(
"^ubuntu-images.*"); "^ubuntu-images.*");
} }
// TODO make this more efficient for listNodes(); currently
// RunningInstanceToNodeMetadata is slow
// due to image parsing; consider using MapMaker. computing map
@Singleton
public static class EC2ListNodesStrategy implements ListNodesStrategy {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final EC2AsyncClient client;
private final Map<String, URI> regionMap;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
private final ExecutorService executor;
@Inject
protected EC2ListNodesStrategy(EC2AsyncClient client, @Region Map<String, URI> regionMap,
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.client = client;
this.regionMap = regionMap;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
this.executor = executor;
}
@Override
public Set<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Set<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
Iterable<Set<? extends Reservation<? extends RunningInstance>>> reservations = transformParallel(regionMap
.keySet(), new Function<String, Future<Set<? extends Reservation<? extends RunningInstance>>>>() {
@Override
public Future<Set<? extends Reservation<? extends RunningInstance>>> apply(String from) {
return client.getInstanceServices().describeInstancesInRegion(from);
}
}, executor, null, logger, "reservations");
Iterable<? extends RunningInstance> instances = concat(concat(reservations));
Iterable<? extends NodeMetadata> nodes = filter(transform(instances, runningInstanceToNodeMetadata), filter);
return newLinkedHashSet(nodes);
}
}
@Singleton
public static class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final EC2Client client;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
@Inject
protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) {
this.client = client;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
String[] parts = parseHandle(id);
String region = parts[0];
String instanceId = parts[1];
try {
RunningInstance runningInstance = getOnlyElement(getAllRunningInstancesInRegion(client
.getInstanceServices(), region, instanceId));
return runningInstanceToNodeMetadata.apply(runningInstance);
} catch (NoSuchElementException e) {
return null;
}
}
}
@Singleton
public static class EC2RebootNodeStrategy implements RebootNodeStrategy {
private final InstanceClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected EC2RebootNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) {
this.client = client.getInstanceServices();
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
String[] parts = parseHandle(id);
String region = parts[0];
String instanceId = parts[1];
client.rebootInstancesInRegion(region, instanceId);
return getNode.execute(id);
}
}
@Provides @Provides
@Singleton @Singleton
protected final Map<RegionAndName, KeyPair> credentialsMap(CreateUniqueKeyPair in) { protected final Map<RegionAndName, KeyPair> credentialsMap(CreateUniqueKeyPair in) {
@ -330,65 +201,6 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
return newLinkedHashMap(); return newLinkedHashMap();
} }
@Provides
@Singleton
Function<ComputeMetadata, String> indexer() {
return new Function<ComputeMetadata, String>() {
@Override
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
}
@Provides
@Singleton
Set<? extends Size> provideSizes(Set<? extends Location> locations, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
Set<Size> sizes = newHashSet();
for (String ccAmi : ccAmis) {
final String region = ccAmi.split("/")[0];
Location location = find(locations, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.REGION && input.getId().equals(region);
}
});
sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690, ccAmis));
}
sizes.addAll(ImmutableSet.<Size> of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL,
EC2Size.M1_XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE));
return sizes;
}
@Provides
Set<? extends Location> provideLocations(Map<String, String> availabilityZoneToRegionMap,
@Provider String providerName) {
Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Set<Location> locations = newLinkedHashSet();
for (String region : newLinkedHashSet(availabilityZoneToRegionMap.values())) {
locations.add(new LocationImpl(LocationScope.REGION, region, region, ec2));
}
ImmutableMap<String, Location> idToLocation = uniqueIndex(locations, new Function<Location, String>() {
@Override
public String apply(Location from) {
return from.getId();
}
});
for (String zone : availabilityZoneToRegionMap.keySet()) {
locations.add(new LocationImpl(LocationScope.ZONE, zone, zone, idToLocation.get(availabilityZoneToRegionMap
.get(zone))));
}
return locations;
}
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
}
@Provides @Provides
@Singleton @Singleton
@Named(PROPERTY_EC2_AMI_OWNERS) @Named(PROPERTY_EC2_AMI_OWNERS)
@ -407,11 +219,6 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
return toArray(Splitter.on(',').split(ccAmis), String.class); return toArray(Splitter.on(',').split(ccAmis), String.class);
} }
@Provides
protected Set<? extends Image> provideImages(Map<RegionAndName, ? extends Image> map) {
return ImmutableSet.copyOf(map.values());
}
@Provides @Provides
@Singleton @Singleton
protected ConcurrentMap<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) { protected ConcurrentMap<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) {
@ -420,62 +227,42 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
protected Map<RegionAndName, ? extends Image> provideImages(@Region Map<String, URI> regionMap, protected Supplier<Map<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache(
DescribeImagesParallel describer, LogHolder holder, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) {
@Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, final ImageParser parser, return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Map<RegionAndName, ? extends Image>>(
final ConcurrentMap<RegionAndName, Image> images) throws InterruptedException, ExecutionException, authException, seconds, new Supplier<Map<RegionAndName, ? extends Image>>() {
TimeoutException { @Override
if (amiOwners.length == 0) { public Map<RegionAndName, ? extends Image> get() {
holder.logger.debug(">> no owners specified, skipping image parsing"); return supplier.get();
} else { }
holder.logger.debug(">> providing images"); });
Iterable<Entry<String, DescribeImagesOptions>> queries = concat(getDescribeQueriesForOwnersInRegions(
regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis).entrySet());
Iterable<? extends Image> parsedImages = filter(transform(describer.apply(queries), parser), Predicates
.notNull());
images.putAll(Maps.uniqueIndex(parsedImages, new Function<Image, RegionAndName>() {
@Override
public RegionAndName apply(Image from) {
return new RegionAndName(from.getLocation().getId(), from.getProviderId());
}
}));
holder.logger.debug("<< images(%d)", images.size());
}
return images;
} }
private Map<String, DescribeImagesOptions> ccAmisToDescribeQueries(String[] ccAmis) { @Override
Map<String, DescribeImagesOptions> queries = Maps.newLinkedHashMap(); protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
for (String from : ccAmis) { Supplier<Map<RegionAndName, ? extends Image>> map = injector.getInstance(Key
queries.put(from.split("/")[0], imageIds(from.split("/")[1])); .get(new TypeLiteral<Supplier<Map<RegionAndName, ? extends Image>>>() {
} }));
return queries; return Suppliers.compose(new Function<Map<RegionAndName, ? extends Image>, Set<? extends Image>>() {
}
private Map<String, DescribeImagesOptions> getDescribeQueriesForOwnersInRegions(Map<String, URI> regionMap,
final String[] amiOwners) {
final DescribeImagesOptions options = getOptionsForOwners(amiOwners);
return Maps.transformValues(regionMap, new Function<URI, DescribeImagesOptions>() {
@Override @Override
public DescribeImagesOptions apply(URI from) { public Set<? extends Image> apply(Map<RegionAndName, ? extends Image> from) {
return options; return ImmutableSet.copyOf(from.values());
} }
}); }, map);
} }
private DescribeImagesOptions getOptionsForOwners(final String[] amiOwners) { @Override
final DescribeImagesOptions options; protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
if (amiOwners.length == 1 && amiOwners[0].equals("*")) return injector.getInstance(EC2LocationSupplier.class);
options = new DescribeImagesOptions(); }
else
options = ownedBy(amiOwners); @Override
return options; protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(EC2SizeSupplier.class);
}
@Override
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
return injector.getInstance(DefaultLocationSupplier.class);
} }
} }

View File

@ -20,6 +20,7 @@
package org.jclouds.aws.ec2.compute.config; package org.jclouds.aws.ec2.compute.config;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import org.jclouds.aws.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.compute.config.ResolvesImages; import org.jclouds.compute.config.ResolvesImages;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;

View File

@ -48,6 +48,7 @@ import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -60,8 +61,7 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
public static final Pattern CANONICAL_PATTERN = Pattern public static final Pattern CANONICAL_PATTERN = Pattern.compile(".*/([^-]*)-([^-]*)-.*-(.*)(\\.manifest.xml)?");
.compile(".*/([^-]*)-([^-]*)-.*-(.*)(\\.manifest.xml)?");
// ex rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml // ex rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml
public static final Pattern RIGHTSCALE_PATTERN = Pattern public static final Pattern RIGHTSCALE_PATTERN = Pattern
@ -72,13 +72,13 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
.compile("[^/]*/RightImage_([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?"); .compile("[^/]*/RightImage_([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?");
private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider; private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;
private final Set<? extends Location> locations; private final Supplier<Set<? extends Location>> locations;
private final Location defaultLocation; private final Supplier<Location> defaultLocation;
@Inject @Inject
ImageParser(PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, ImageParser(PopulateDefaultLoginCredentialsForImageStrategy credentialProvider,
Set<? extends Location> locations, Location defaultLocation) { Supplier<Set<? extends Location>> locations, Supplier<Location> defaultLocation) {
this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider"); this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider");
this.locations = checkNotNull(locations, "locations"); this.locations = checkNotNull(locations, "locations");
this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation"); this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation");
@ -97,8 +97,7 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
} }
OsFamily os = parseOsFamilyOrNull(from.getImageLocation()); OsFamily os = parseOsFamilyOrNull(from.getImageLocation());
String name = parseVersionOrReturnEmptyString(os, from.getImageLocation()); String name = parseVersionOrReturnEmptyString(os, from.getImageLocation());
String description = from.getDescription() != null ? from.getDescription() : from String description = from.getDescription() != null ? from.getDescription() : from.getImageLocation();
.getImageLocation();
String osDescription = from.getImageLocation(); String osDescription = from.getImageLocation();
String version = ""; String version = "";
@ -117,7 +116,7 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
Location location = null; Location location = null;
try { try {
location = Iterables.find(locations, new Predicate<Location>() { location = Iterables.find(locations.get(), new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
@ -126,24 +125,14 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
}); });
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
System.err.printf("unknown region %s for image %s; not in %s", from.getRegion(), from System.err.printf("unknown region %s for image %s; not in %s", from.getRegion(), from.getId(), locations);
.getId(), locations); location = new LocationImpl(LocationScope.REGION, from.getRegion(), from.getRegion(), defaultLocation.get()
location = new LocationImpl(LocationScope.REGION, from.getRegion(), from.getRegion(), .getParent());
defaultLocation.getParent());
} }
return new ImageImpl( return new ImageImpl(from.getId(), name, from.getRegion() + "/" + from.getId(), location, null, ImmutableMap
from.getId(), .<String, String> of("owner", from.getImageOwnerId()), description, version, os, osDescription, from
name, .getArchitecture() == org.jclouds.aws.ec2.domain.Image.Architecture.I386 ? Architecture.X86_32
from.getRegion() + "/" + from.getId(), : Architecture.X86_64, defaultCredentials);
location,
null,
ImmutableMap.<String, String> of("owner", from.getImageOwnerId()),
description,
version,
os,
osDescription,
from.getArchitecture() == org.jclouds.aws.ec2.domain.Image.Architecture.I386 ? Architecture.X86_32
: Architecture.X86_64, defaultCredentials);
} }
@ -153,8 +142,7 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
* if no configured matcher matches the manifest. * if no configured matcher matches the manifest.
*/ */
private Matcher getMatcherAndFind(String manifest) { private Matcher getMatcherAndFind(String manifest) {
for (Pattern pattern : new Pattern[] { CANONICAL_PATTERN, RIGHTIMAGE_PATTERN, for (Pattern pattern : new Pattern[] { CANONICAL_PATTERN, RIGHTIMAGE_PATTERN, RIGHTSCALE_PATTERN }) {
RIGHTSCALE_PATTERN }) {
Matcher matcher = pattern.matcher(manifest); Matcher matcher = pattern.matcher(manifest);
if (matcher.find()) if (matcher.find())
return matcher; return matcher;

View File

@ -31,7 +31,6 @@ import java.util.concurrent.ConcurrentMap;
import javax.annotation.Resource; import javax.annotation.Resource;
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.aws.ec2.EC2Client; import org.jclouds.aws.ec2.EC2Client;
@ -52,6 +51,7 @@ import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@ -65,80 +65,28 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@VisibleForTesting
static class FindImageForInstance implements Predicate<Image> {
private final Location location;
private final RunningInstance instance;
FindImageForInstance(Location location, RunningInstance instance) {
this.location = checkNotNull(location, "location");
this.instance = checkNotNull(instance, "instance");
}
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId())
&& (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation().equals(
location.getParent()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((instance.getId() == null) ? 0 : instance.getId().hashCode());
result = prime * result + ((location.getId() == null) ? 0 : location.getId().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FindImageForInstance other = (FindImageForInstance) obj;
if (instance.getId() == null) {
if (other.instance.getId() != null)
return false;
} else if (!instance.getId().equals(other.instance.getId()))
return false;
if (location.getId() == null) {
if (other.location.getId() != null)
return false;
} else if (!location.getId().equals(other.location.getId()))
return false;
return true;
}
}
@VisibleForTesting @VisibleForTesting
static final Map<InstanceState, NodeState> instanceToNodeState = ImmutableMap.<InstanceState, NodeState> builder() static final Map<InstanceState, NodeState> instanceToNodeState = ImmutableMap.<InstanceState, NodeState> builder()
.put(InstanceState.PENDING, NodeState.PENDING).put(InstanceState.RUNNING, NodeState.RUNNING).put( .put(InstanceState.PENDING, NodeState.PENDING).put(InstanceState.RUNNING, NodeState.RUNNING).put(
InstanceState.SHUTTING_DOWN, NodeState.PENDING).put(InstanceState.TERMINATED, NodeState.TERMINATED).put( InstanceState.SHUTTING_DOWN, NodeState.PENDING)
InstanceState.STOPPING, NodeState.PENDING).put(InstanceState.STOPPED, NodeState.SUSPENDED).build(); .put(InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING).put(
InstanceState.STOPPED, NodeState.SUSPENDED).build();
private final EC2Client client; private final EC2Client client;
private final Map<RegionAndName, KeyPair> credentialsMap; private final Map<RegionAndName, KeyPair> credentialsMap;
private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider; private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;
private final Provider<Set<? extends Image>> images; private final Supplier<Set<? extends Location>> locations;
private final Set<? extends Location> locations;
private final Function<RunningInstance, Map<String, String>> instanceToStorageMapping; private final Function<RunningInstance, Map<String, String>> instanceToStorageMapping;
private final ConcurrentMap<RegionAndName, Image> imageMap; private final ConcurrentMap<RegionAndName, Image> imageMap;
@Inject @Inject
RunningInstanceToNodeMetadata(EC2Client client, Map<RegionAndName, KeyPair> credentialsMap, RunningInstanceToNodeMetadata(EC2Client client, Map<RegionAndName, KeyPair> credentialsMap,
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, PopulateDefaultLoginCredentialsForImageStrategy credentialProvider,
Provider<Set<? extends Image>> images, // to facilitate on-demand ConcurrentMap<RegionAndName, Image> imageMap, Supplier<Set<? extends Location>> locations,
// refresh of image list @Named("volumeMapping") Function<RunningInstance, Map<String, String>> instanceToStorageMapping) {
ConcurrentMap<RegionAndName, Image> imageMap, Set<? extends Location> locations,
@Named("volumeMapping") Function<RunningInstance, Map<String, String>> instanceToStorageMapping) {
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider"); this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider");
this.images = checkNotNull(images, "images");
this.locations = checkNotNull(locations, "locations"); this.locations = checkNotNull(locations, "locations");
this.instanceToStorageMapping = checkNotNull(instanceToStorageMapping, "instanceToStorageMapping"); this.instanceToStorageMapping = checkNotNull(instanceToStorageMapping, "instanceToStorageMapping");
this.imageMap = checkNotNull(imageMap, "imageMap"); this.imageMap = checkNotNull(imageMap, "imageMap");
@ -169,7 +117,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
Image image = resolveImageForInstanceInLocation(instance, location); Image image = resolveImageForInstanceInLocation(instance, location);
return new NodeMetadataImpl(id, name, instance.getRegion() + "/" + instance.getId(), location, uri, userMetadata, return new NodeMetadataImpl(id, name, instance.getRegion() + "/" + instance.getId(), location, uri, userMetadata,
tag, image, state, publicAddresses, privateAddresses, extra, credentials); tag, image, state, publicAddresses, privateAddresses, extra, credentials);
} }
private Credentials getCredentialsForInstanceWithTag(final RunningInstance instance, String tag) { private Credentials getCredentialsForInstanceWithTag(final RunningInstance instance, String tag) {
@ -197,7 +145,8 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
logger.debug("no tag parsed from %s's groups: %s", instance.getId(), instance.getGroupIds()); logger.debug("no tag parsed from %s's groups: %s", instance.getId(), instance.getGroupIds());
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
logger logger
.debug("too many groups match %s; %s's groups: %s", "jclouds#", instance.getId(), instance.getGroupIds()); .debug("too many groups match %s; %s's groups: %s", "jclouds#", instance.getId(), instance
.getGroupIds());
} }
return tag; return tag;
} }
@ -205,7 +154,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
private Location getLocationForAvailabilityZone(final RunningInstance instance) { private Location getLocationForAvailabilityZone(final RunningInstance instance) {
final String locationId = instance.getAvailabilityZone(); final String locationId = instance.getAvailabilityZone();
Location location = Iterables.find(locations, new Predicate<Location>() { Location location = Iterables.find(locations.get(), new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
@ -219,15 +168,11 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@VisibleForTesting @VisibleForTesting
Image resolveImageForInstanceInLocation(final RunningInstance instance, final Location location) { Image resolveImageForInstanceInLocation(final RunningInstance instance, final Location location) {
Image image = null; Image image = null;
RegionAndName key = new RegionAndName(instance.getRegion(), instance.getImageId());
try { try {
image = Iterables.find(images.get(), new FindImageForInstance(location, instance)); image = imageMap.get(key);
} catch (NoSuchElementException e) { } catch (NullPointerException nex) {
RegionAndName key = new RegionAndName(instance.getRegion(), instance.getImageId()); logger.debug("could not find a matching image for instance %s in location %s", instance, location);
try {
image = imageMap.get(key);
} catch (NullPointerException nex) {
logger.debug("could not find a matching image for instance %s in location %s", instance, location);
}
} }
return image; return image;
} }
@ -265,7 +210,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@VisibleForTesting @VisibleForTesting
String getLoginAccountFor(RunningInstance from) { String getLoginAccountFor(RunningInstance from) {
org.jclouds.aws.ec2.domain.Image image = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion( org.jclouds.aws.ec2.domain.Image image = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion(
from.getRegion(), DescribeImagesOptions.Builder.imageIds(from.getImageId()))); from.getRegion(), DescribeImagesOptions.Builder.imageIds(from.getImageId())));
return checkNotNull(credentialProvider.execute(image), "login from image: " + from.getImageId()).identity; return checkNotNull(credentialProvider.execute(image), "login from image: " + from.getImageId()).identity;
} }

View File

@ -38,6 +38,7 @@ import org.jclouds.compute.internal.TemplateBuilderImpl;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
/** /**
@ -49,8 +50,9 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
private final ConcurrentMap<RegionAndName, Image> imageMap; private final ConcurrentMap<RegionAndName, Image> imageMap;
@Inject @Inject
protected EC2TemplateBuilderImpl(Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images, protected EC2TemplateBuilderImpl(Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Provider<Set<? extends Size>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider, Supplier<Set<? extends Size>> sizes, Supplier<Location> defaultLocation,
Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider, @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider,
ConcurrentMap<RegionAndName, Image> imageMap) { ConcurrentMap<RegionAndName, Image> imageMap) {
super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider); super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider);
@ -102,9 +104,9 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
* if the image is not found * if the image is not found
*/ */
@Override @Override
protected Image resolveImage(Size size) { protected Image resolveImage(Size size, Iterable<? extends Image> supportedImages) {
try { try {
return super.resolveImage(size); return super.resolveImage(size, supportedImages);
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
Image returnVal = lazyImageProvider.get(); Image returnVal = lazyImageProvider.get();
if (returnVal != null) if (returnVal != null)

View File

@ -0,0 +1,67 @@
/**
*
* 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.strategy;
import static com.google.common.collect.Iterables.getOnlyElement;
import static org.jclouds.aws.ec2.util.EC2Utils.getAllRunningInstancesInRegion;
import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle;
import java.util.NoSuchElementException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
/**
*
* @author Adrian Cole
*/
@Singleton
public class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final EC2Client client;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
@Inject
protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) {
this.client = client;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
String[] parts = parseHandle(id);
String region = parts[0];
String instanceId = parts[1];
try {
RunningInstance runningInstance = getOnlyElement(getAllRunningInstancesInRegion(client.getInstanceServices(),
region, instanceId));
return runningInstanceToNodeMetadata.apply(runningInstance);
} catch (NoSuchElementException e) {
return null;
}
}
}

View File

@ -0,0 +1,101 @@
/**
*
* 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.strategy;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static org.jclouds.concurrent.FutureIterables.transformParallel;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.EC2AsyncClient;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.domain.Reservation;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
/**
*
* @author Adrian Cole
*/
@Singleton
public class EC2ListNodesStrategy implements ListNodesStrategy {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final EC2AsyncClient client;
private final Map<String, URI> regionMap;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
private final ExecutorService executor;
@Inject
protected EC2ListNodesStrategy(EC2AsyncClient client, @Region Map<String, URI> regionMap,
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.client = client;
this.regionMap = regionMap;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
this.executor = executor;
}
@Override
public Set<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Set<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
Iterable<Set<? extends Reservation<? extends RunningInstance>>> reservations = transformParallel(regionMap
.keySet(), new Function<String, Future<Set<? extends Reservation<? extends RunningInstance>>>>() {
@Override
public Future<Set<? extends Reservation<? extends RunningInstance>>> apply(String from) {
return client.getInstanceServices().describeInstancesInRegion(from);
}
}, executor, null, logger, "reservations");
Iterable<? extends RunningInstance> instances = concat(concat(reservations));
Iterable<? extends NodeMetadata> nodes = filter(transform(instances, runningInstanceToNodeMetadata), filter);
return newLinkedHashSet(nodes);
}
}

View File

@ -0,0 +1,57 @@
/**
*
* 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.strategy;
import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.services.InstanceClient;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
/**
*
* @author Adrian Cole
*/
@Singleton
public class EC2RebootNodeStrategy implements RebootNodeStrategy {
private final InstanceClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected EC2RebootNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) {
this.client = client.getInstanceServices();
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
String[] parts = parseHandle(id);
String region = parts[0];
String instanceId = parts[1];
client.rebootInstancesInRegion(region, instanceId);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,75 @@
/**
*
* 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.suppliers;
import static com.google.common.collect.Maps.uniqueIndex;
import static com.google.common.collect.Sets.newLinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
/**
*
* @author Adrian Cole
*/
@Singleton
public class EC2LocationSupplier implements Supplier<Set<? extends Location>> {
private final Map<String, String> availabilityZoneToRegionMap;
private final String providerName;
@Inject
EC2LocationSupplier(Map<String, String> availabilityZoneToRegionMap, @Provider String providerName) {
this.availabilityZoneToRegionMap = availabilityZoneToRegionMap;
this.providerName = providerName;
}
@Override
public Set<? extends Location> get() {
Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Set<Location> locations = newLinkedHashSet();
for (String region : newLinkedHashSet(availabilityZoneToRegionMap.values())) {
locations.add(new LocationImpl(LocationScope.REGION, region, region, ec2));
}
ImmutableMap<String, Location> idToLocation = uniqueIndex(locations, new Function<Location, String>() {
@Override
public String apply(Location from) {
return from.getId();
}
});
for (String zone : availabilityZoneToRegionMap.keySet()) {
locations.add(new LocationImpl(LocationScope.ZONE, zone, zone, idToLocation.get(availabilityZoneToRegionMap
.get(zone))));
}
return locations;
}
}

View File

@ -0,0 +1,82 @@
/**
*
* 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.suppliers;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Sets.newHashSet;
import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.compute.domain.EC2Size;
import org.jclouds.aws.ec2.domain.InstanceType;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
/**
*
* @author Adrian Cole
*/
@Singleton
public class EC2SizeSupplier implements Supplier<Set<? extends Size>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Supplier<Set<? extends Location>> locations;
private final String[] ccAmis;
@Inject
EC2SizeSupplier(Supplier<Set<? extends Location>> locations, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
this.locations = locations;
this.ccAmis = ccAmis;
}
@Override
public Set<? extends Size> get() {
Set<Size> sizes = newHashSet();
for (String ccAmi : ccAmis) {
final String region = ccAmi.split("/")[0];
Location location = find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.REGION && input.getId().equals(region);
}
});
sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690, ccAmis));
}
sizes.addAll(ImmutableSet.<Size> of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL,
EC2Size.M1_XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE));
return sizes;
}
}

View File

@ -0,0 +1,159 @@
/**
*
* 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.suppliers;
/**
*
* 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.
* ====================================================================
*/
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Maps.transformValues;
import static com.google.common.collect.Maps.uniqueIndex;
import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.imageIds;
import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.ownedBy;
import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;
import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs;
import java.net.URI;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.compute.functions.ImageParser;
import org.jclouds.aws.ec2.compute.strategy.DescribeImagesParallel;
import org.jclouds.aws.ec2.options.DescribeImagesOptions;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RegionAndNameToImageSupplier implements Supplier<Map<RegionAndName, ? extends Image>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Map<String, URI> regionMap;
private final DescribeImagesParallel describer;
private final String[] ccAmis;
private final String[] amiOwners;
private final ImageParser parser;
private final ConcurrentMap<RegionAndName, Image> images;
@Inject
RegionAndNameToImageSupplier(@Region Map<String, URI> regionMap, DescribeImagesParallel describer,
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners,
final ImageParser parser, final ConcurrentMap<RegionAndName, Image> images) {
this.regionMap = regionMap;
this.describer = describer;
this.ccAmis = ccAmis;
this.amiOwners = amiOwners;
this.parser = parser;
this.images = images;
}
@Override
public Map<RegionAndName, ? extends Image> get() {
if (amiOwners.length == 0) {
logger.debug(">> no owners specified, skipping image parsing");
} else {
logger.debug(">> providing images");
Iterable<Entry<String, DescribeImagesOptions>> queries = concat(getDescribeQueriesForOwnersInRegions(
regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis).entrySet());
Iterable<? extends Image> parsedImages = filter(transform(describer.apply(queries), parser), Predicates
.notNull());
images.putAll(uniqueIndex(parsedImages, new Function<Image, RegionAndName>() {
@Override
public RegionAndName apply(Image from) {
return new RegionAndName(from.getLocation().getId(), from.getProviderId());
}
}));
logger.debug("<< images(%d)", images.size());
}
return images;
}
private static Map<String, DescribeImagesOptions> ccAmisToDescribeQueries(String[] ccAmis) {
Map<String, DescribeImagesOptions> queries = newLinkedHashMap();
for (String from : ccAmis) {
queries.put(from.split("/")[0], imageIds(from.split("/")[1]));
}
return queries;
}
private static Map<String, DescribeImagesOptions> getDescribeQueriesForOwnersInRegions(Map<String, URI> regionMap,
final String[] amiOwners) {
final DescribeImagesOptions options = getOptionsForOwners(amiOwners);
return transformValues(regionMap, new Function<URI, DescribeImagesOptions>() {
@Override
public DescribeImagesOptions apply(URI from) {
return options;
}
});
}
private static DescribeImagesOptions getOptionsForOwners(final String[] amiOwners) {
final DescribeImagesOptions options;
if (amiOwners.length == 1 && amiOwners[0].equals("*"))
options = new DescribeImagesOptions();
else
options = ownedBy(amiOwners);
return options;
}
}

View File

@ -60,6 +60,7 @@ import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -83,8 +84,8 @@ public class S3AsyncBlobStore extends BaseAsyncBlobStore {
@Inject @Inject
S3AsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, S3AsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Set<? extends Location> locations, S3AsyncClient async, S3Client sync, Supplier<Set<? extends Location>> locations, S3AsyncClient async, S3Client sync,
BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions, BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions,
BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob, BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob,
BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd,
@ -136,7 +137,7 @@ public class S3AsyncBlobStore extends BaseAsyncBlobStore {
*/ */
@Override @Override
public ListenableFuture<Boolean> createContainerInLocation(Location location, String container) { public ListenableFuture<Boolean> createContainerInLocation(Location location, String container) {
location = location != null ? location : defaultLocation; location = location != null ? location : defaultLocation.get();
return async.putBucketInRegion(location.getId(), container); return async.putBucketInRegion(location.getId(), container);
} }

View File

@ -74,26 +74,21 @@ public class S3BlobStore extends BaseBlobStore {
private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider; private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider;
@Inject @Inject
S3BlobStore(BlobStoreContext context, BlobUtils blobUtils, Location defaultLocation, S3BlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,
Set<? extends Location> locations, S3Client sync, Supplier<Set<? extends Location>> locations, S3Client sync, BucketToResourceMetadata bucket2ResourceMd,
BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList,
ContainerToBucketListOptions container2BucketListOptions, ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object,
BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object,
ObjectToBlobMetadata object2BlobMd,
Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, defaultLocation, locations); super(context, blobUtils, defaultLocation, locations);
this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions"); this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions");
this.sync = checkNotNull(sync, "sync"); this.sync = checkNotNull(sync, "sync");
this.bucket2ResourceMd = checkNotNull(bucket2ResourceMd, "bucket2ResourceMd"); this.bucket2ResourceMd = checkNotNull(bucket2ResourceMd, "bucket2ResourceMd");
this.container2BucketListOptions = checkNotNull(container2BucketListOptions, this.container2BucketListOptions = checkNotNull(container2BucketListOptions, "container2BucketListOptions");
"container2BucketListOptions");
this.bucket2ResourceList = checkNotNull(bucket2ResourceList, "bucket2ResourceList"); this.bucket2ResourceList = checkNotNull(bucket2ResourceList, "bucket2ResourceList");
this.object2Blob = checkNotNull(object2Blob, "object2Blob"); this.object2Blob = checkNotNull(object2Blob, "object2Blob");
this.blob2Object = checkNotNull(blob2Object, "blob2Object"); this.blob2Object = checkNotNull(blob2Object, "blob2Object");
this.object2BlobMd = checkNotNull(object2BlobMd, "object2BlobMd"); this.object2BlobMd = checkNotNull(object2BlobMd, "object2BlobMd");
this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, "fetchBlobMetadataProvider");
"fetchBlobMetadataProvider");
} }
/** /**
@ -102,10 +97,8 @@ public class S3BlobStore extends BaseBlobStore {
@Override @Override
public PageSet<? extends StorageMetadata> list() { public PageSet<? extends StorageMetadata> list() {
return new Function<Set<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() { return new Function<Set<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply( public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(Set<BucketMetadata> from) {
Set<BucketMetadata> from) { return new PageSetImpl<StorageMetadata>(Iterables.transform(from, bucket2ResourceMd), null);
return new PageSetImpl<StorageMetadata>(Iterables.transform(from, bucket2ResourceMd),
null);
} }
}.apply(sync.listOwnedBuckets()); }.apply(sync.listOwnedBuckets());
} }
@ -131,7 +124,7 @@ public class S3BlobStore extends BaseBlobStore {
*/ */
@Override @Override
public boolean createContainerInLocation(Location location, String container) { public boolean createContainerInLocation(Location location, String container) {
location = location != null ? location : defaultLocation; location = location != null ? location : defaultLocation.get();
return sync.putBucketInRegion(location.getId(), container); return sync.putBucketInRegion(location.getId(), container);
} }
@ -144,10 +137,8 @@ public class S3BlobStore extends BaseBlobStore {
@Override @Override
public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) { public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {
ListBucketOptions httpOptions = container2BucketListOptions.apply(options); ListBucketOptions httpOptions = container2BucketListOptions.apply(options);
PageSet<? extends StorageMetadata> list = bucket2ResourceList.apply(sync.listBucket( PageSet<? extends StorageMetadata> list = bucket2ResourceList.apply(sync.listBucket(container, httpOptions));
container, httpOptions)); return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container).apply(list) : list;
return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container)
.apply(list) : list;
} }
/** /**
@ -215,8 +206,7 @@ public class S3BlobStore extends BaseBlobStore {
* object key * object key
*/ */
@Override @Override
public Blob getBlob(String container, String key, public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions optionsList) {
org.jclouds.blobstore.options.GetOptions optionsList) {
GetOptions httpOptions = blob2ObjectGetOptions.apply(optionsList); GetOptions httpOptions = blob2ObjectGetOptions.apply(optionsList);
return object2Blob.apply(sync.getObject(container, key, httpOptions)); return object2Blob.apply(sync.getObject(container, key, httpOptions));
} }

View File

@ -24,11 +24,11 @@ import java.util.Set;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.aws.Region; import org.jclouds.aws.Region;
import org.jclouds.aws.config.DefaultLocationProvider;
import org.jclouds.aws.s3.S3AsyncClient; import org.jclouds.aws.s3.S3AsyncClient;
import org.jclouds.aws.s3.S3Client; import org.jclouds.aws.s3.S3Client;
import org.jclouds.aws.s3.blobstore.S3AsyncBlobStore; import org.jclouds.aws.s3.blobstore.S3AsyncBlobStore;
import org.jclouds.aws.s3.blobstore.S3BlobStore; import org.jclouds.aws.s3.blobstore.S3BlobStore;
import org.jclouds.aws.suppliers.DefaultLocationSupplier;
import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.AsyncBlobStore;
import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStore;
import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.BlobStoreContext;
@ -40,6 +40,8 @@ import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -56,25 +58,24 @@ public class S3BlobStoreContextModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
install(new BlobStoreMapModule()); install(new BlobStoreMapModule());
bind(Location.class).toProvider(DefaultLocationProvider.class).in(Scopes.SINGLETON); bind(new TypeLiteral<Supplier<Location>>() {
}).to(new TypeLiteral<DefaultLocationSupplier>() {
});
bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL); bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);
bind(AsyncBlobStore.class).to(S3AsyncBlobStore.class).in(Scopes.SINGLETON); bind(AsyncBlobStore.class).to(S3AsyncBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStore.class).to(S3BlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(S3BlobStore.class).in(Scopes.SINGLETON);
bind(BlobStoreContext.class).to( bind(BlobStoreContext.class).to(new TypeLiteral<BlobStoreContextImpl<S3Client, S3AsyncClient>>() {
new TypeLiteral<BlobStoreContextImpl<S3Client, S3AsyncClient>>() { }).in(Scopes.SINGLETON);
}).in(Scopes.SINGLETON);
} }
@Provides @Provides
@Singleton @Singleton
Set<? extends Location> provideLocations(@Region Set<String> regions, Supplier<Set<? extends Location>> provideLocations(@Region Set<String> regions, @Provider String providerName) {
@Provider String providerName) {
Set<Location> locations = Sets.newHashSet(); Set<Location> locations = Sets.newHashSet();
Location s3 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); Location s3 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (String zone : regions) { for (String zone : regions) {
locations locations.add(new LocationImpl(LocationScope.REGION, zone.toString(), zone.toString(), s3));
.add(new LocationImpl(LocationScope.REGION, zone.toString(), zone.toString(), s3));
} }
return locations; return Suppliers.<Set<? extends Location>> ofInstance(locations);
} }
} }

View File

@ -38,26 +38,25 @@ import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class BucketToResourceMetadata implements public class BucketToResourceMetadata implements Function<BucketMetadata, StorageMetadata> {
Function<BucketMetadata, StorageMetadata> {
private final S3Client client; private final S3Client client;
private final Location onlyLocation; private final Location onlyLocation;
private final Set<? extends Location> locations; private final Supplier<Set<? extends Location>> locations;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@Inject @Inject
BucketToResourceMetadata(S3Client client, Set<? extends Location> locations) { BucketToResourceMetadata(S3Client client, Supplier<Set<? extends Location>> locations) {
this.client = client; this.client = client;
this.onlyLocation = locations.size() == 1 ? Iterables.get(locations, 0) this.onlyLocation = locations.get().size() == 1 ? Iterables.get(locations.get(), 0) : null;
: null;
this.locations = locations; this.locations = locations;
} }
@ -74,7 +73,7 @@ public class BucketToResourceMetadata implements
final String region = client.getBucketLocation(from.getName()); final String region = client.getBucketLocation(from.getName());
if (region != null) { if (region != null) {
try { try {
return Iterables.find(locations, new Predicate<Location>() { return Iterables.find(locations.get(), new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
@ -83,18 +82,13 @@ public class BucketToResourceMetadata implements
}); });
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
logger.error("could not get location for region %s in %s", logger.error("could not get location for region %s in %s", region, locations.get());
region, locations);
} }
} else { } else {
logger.error("could not get region for %s", from.getName()); logger.error("could not get region for %s", from.getName());
} }
} catch (ContainerNotFoundException e) { } catch (ContainerNotFoundException e) {
logger logger.error(e, "could not get region for %s, as service suggests the bucket doesn't exist", from.getName());
.error(
e,
"could not get region for %s, as service suggests the bucket doesn't exist",
from.getName());
} }
return null; return null;
} }

View File

@ -17,7 +17,7 @@
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.aws.config; package org.jclouds.aws.suppliers;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
@ -30,18 +30,19 @@ import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class DefaultLocationProvider implements javax.inject.Provider<Location> { public class DefaultLocationSupplier implements Supplier<Location> {
private final String region; private final String region;
private final Set<? extends Location> set; private final Supplier<Set<? extends Location>> set;
@Inject @Inject
DefaultLocationProvider(@Region final String region, Set<? extends Location> set) { DefaultLocationSupplier(@Region final String region, Supplier<Set<? extends Location>> set) {
this.region = region; this.region = region;
this.set = set; this.set = set;
} }
@ -50,7 +51,7 @@ public class DefaultLocationProvider implements javax.inject.Provider<Location>
@Singleton @Singleton
public Location get() { public Location get() {
try { try {
Location toReturn = Iterables.find(set, new Predicate<Location>() { Location toReturn = Iterables.find(set.get(), new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {

View File

@ -96,7 +96,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
assertEquals(defaultTemplate.getSize().getCores(), 1.0d); assertEquals(defaultTemplate.getSize().getCores(), 1.0d);
} }
@Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder") @Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testExtendedOptionsAndLogin() throws Exception { public void testExtendedOptionsAndLogin() throws Exception {
SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
.getSecurityGroupServices(); .getSecurityGroupServices();
@ -180,7 +180,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
} }
} }
@Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder") @Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testExtendedOptionsNoKeyPair() throws Exception { public void testExtendedOptionsNoKeyPair() throws Exception {
SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi()) SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
.getSecurityGroupServices(); .getSecurityGroupServices();
@ -234,7 +234,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
} }
} }
@Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder") @Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testExtendedOptionsWithSubnetId() throws Exception { public void testExtendedOptionsWithSubnetId() throws Exception {
String subnetId = System.getProperty("jclouds.test.subnetId"); String subnetId = System.getProperty("jclouds.test.subnetId");

View File

@ -46,9 +46,10 @@ import org.jclouds.domain.internal.LocationImpl;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.inject.util.Providers;
/** /**
* Tests compute service specifically to EC2. * Tests compute service specifically to EC2.
@ -63,8 +64,8 @@ import com.google.inject.util.Providers;
public class EC2ComputeServiceTest { public class EC2ComputeServiceTest {
private static final Location location = new LocationImpl(LocationScope.REGION, "us-east-1", "us east", null); private static final Location location = new LocationImpl(LocationScope.REGION, "us-east-1", "us east", null);
public static final EC2Size CC1_4XLARGE = new EC2Size(location, public static final EC2Size CC1_4XLARGE = new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690,
InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690, new String[]{"us-east-1/cc-image"}); new String[] { "us-east-1/cc-image" });
/** /**
* Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based * Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based
@ -74,13 +75,13 @@ public class EC2ComputeServiceTest {
*/ */
@Test @Test
public void testTemplateChoiceForInstanceBySizeId() throws Exception { public void testTemplateChoiceForInstanceBySizeId() throws Exception {
Template template = newTemplateBuilder().architecture(Architecture.X86_64) Template template = newTemplateBuilder().architecture(Architecture.X86_64).sizeId("m2.xlarge").locationId(
.sizeId("m2.xlarge").locationId("us-east-1").build(); "us-east-1").build();
assert template != null : "The returned template was null, but it should have a value."; assert template != null : "The returned template was null, but it should have a value.";
assert EC2Size.M2_XLARGE.equals(template.getSize()) : format( assert EC2Size.M2_XLARGE.equals(template.getSize()) : format(
"Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", "Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", String
String.valueOf(template.getSize())); .valueOf(template.getSize()));
} }
@Test @Test
@ -89,11 +90,10 @@ public class EC2ComputeServiceTest {
assert template != null : "The returned template was null, but it should have a value."; assert template != null : "The returned template was null, but it should have a value.";
assert CC1_4XLARGE.equals(template.getSize()) : format( assert CC1_4XLARGE.equals(template.getSize()) : format(
"Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE.getId(), "Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE.getId(), String
String.valueOf(template.getSize())); .valueOf(template.getSize()));
} }
/** /**
* Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based * Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based
* on physical attributes (# of cores, ram, etc). * on physical attributes (# of cores, ram, etc).
@ -102,13 +102,13 @@ public class EC2ComputeServiceTest {
*/ */
@Test @Test
public void testTemplateChoiceForInstanceByAttributes() throws Exception { public void testTemplateChoiceForInstanceByAttributes() throws Exception {
Template template = newTemplateBuilder().architecture(Architecture.X86_64).minRam(17510) Template template = newTemplateBuilder().architecture(Architecture.X86_64).minRam(17510).minCores(6.5).smallest()
.minCores(6.5).smallest().locationId("us-east-1").build(); .locationId("us-east-1").build();
assert template != null : "The returned template was null, but it should have a value."; assert template != null : "The returned template was null, but it should have a value.";
assert EC2Size.M2_XLARGE.equals(template.getSize()) : format( assert EC2Size.M2_XLARGE.equals(template.getSize()) : format(
"Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", "Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", String
String.valueOf(template.getSize())); .valueOf(template.getSize()));
} }
/** /**
@ -121,13 +121,13 @@ public class EC2ComputeServiceTest {
*/ */
@Test @Test
public void testNegativeTemplateChoiceForInstanceByAttributes() throws Exception { public void testNegativeTemplateChoiceForInstanceByAttributes() throws Exception {
Template template = newTemplateBuilder().architecture(Architecture.X86_64).minRam(17510) Template template = newTemplateBuilder().architecture(Architecture.X86_64).minRam(17510).minCores(6.7).smallest()
.minCores(6.7).smallest().locationId("us-east-1").build(); .locationId("us-east-1").build();
assert template != null : "The returned template was null, but it should have a value."; assert template != null : "The returned template was null, but it should have a value.";
assert !EC2Size.M2_XLARGE.equals(template.getSize()) : format( assert !EC2Size.M2_XLARGE.equals(template.getSize()) : format(
"Incorrect image determined by the template. Expected: not %s. Found: %s.", "Incorrect image determined by the template. Expected: not %s. Found: %s.", "m2.xlarge", String
"m2.xlarge", String.valueOf(template.getSize())); .valueOf(template.getSize()));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -140,20 +140,19 @@ public class EC2ComputeServiceTest {
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
Image image = new ImageImpl("cc-image", "image", "us-east-1/cc-image", location, null, Maps Image image = new ImageImpl("cc-image", "image", "us-east-1/cc-image", location, null, Maps
.<String, String> newHashMap(), "description", "1.0", null, "ubuntu", .<String, String> newHashMap(), "description", "1.0", null, "ubuntu", Architecture.X86_64,
Architecture.X86_64, new Credentials("root", null)); new Credentials("root", null));
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(image)); .<Image> of(image));
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(
.<Size> of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL, EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL, EC2Size.M1_XLARGE,
EC2Size.M1_XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE, CC1_4XLARGE));
EC2Size.M2_4XLARGE, CC1_4XLARGE ));
return new TemplateBuilderImpl(locations, images, sizes, location, optionsProvider, return new TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(location), optionsProvider,
templateBuilderProvider) { templateBuilderProvider) {
}; };

View File

@ -39,6 +39,7 @@ import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.internal.GeneratedHttpRequest; import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -55,8 +56,9 @@ public class ImageParserTest extends BaseEC2HandlerTest {
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
assertEquals(result.size(), 7); assertEquals(result.size(), 7);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Location> of(defaultLocation), defaultLocation); .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation));
org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables.get(result, 0)); org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables.get(result, 0));
assertEquals(ubuntuHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
@ -65,7 +67,7 @@ public class ImageParserTest extends BaseEC2HandlerTest {
assertEquals(ubuntuHardy.getLocation(), defaultLocation); assertEquals(ubuntuHardy.getLocation(), defaultLocation);
assertEquals(ubuntuHardy.getName(), "8.04"); assertEquals(ubuntuHardy.getName(), "8.04");
assertEquals(ubuntuHardy.getOsDescription(), assertEquals(ubuntuHardy.getOsDescription(),
"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml"); "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuHardy.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477")); assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuHardy.getVersion(), "20091130"); assertEquals(ubuntuHardy.getVersion(), "20091130");
@ -86,12 +88,12 @@ public class ImageParserTest extends BaseEC2HandlerTest {
assertEquals(ubuntuKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
assertEquals(ubuntuKarmic.getDescription(), assertEquals(ubuntuKarmic.getDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2"); assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2");
assertEquals(ubuntuKarmic.getLocation(), defaultLocation); assertEquals(ubuntuKarmic.getLocation(), defaultLocation);
assertEquals(ubuntuKarmic.getName(), "9.10"); assertEquals(ubuntuKarmic.getName(), "9.10");
assertEquals(ubuntuKarmic.getOsDescription(), assertEquals(ubuntuKarmic.getOsDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuKarmic.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477")); assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuKarmic.getVersion(), "20100121"); assertEquals(ubuntuKarmic.getVersion(), "20100121");
@ -115,12 +117,12 @@ public class ImageParserTest extends BaseEC2HandlerTest {
assertEquals(ubuntuLucid.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuLucid.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
assertEquals(ubuntuLucid.getDescription(), assertEquals(ubuntuLucid.getDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680"); assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680");
assertEquals(ubuntuLucid.getLocation(), defaultLocation); assertEquals(ubuntuLucid.getLocation(), defaultLocation);
assertEquals(ubuntuLucid.getName(), "10.04"); assertEquals(ubuntuLucid.getName(), "10.04");
assertEquals(ubuntuLucid.getOsDescription(), assertEquals(ubuntuLucid.getOsDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuLucid.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477")); assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuLucid.getVersion(), "20100427.1"); assertEquals(ubuntuLucid.getVersion(), "20100427.1");
@ -136,8 +138,9 @@ public class ImageParserTest extends BaseEC2HandlerTest {
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Location> of(defaultLocation), defaultLocation); .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation));
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
@ -158,8 +161,9 @@ public class ImageParserTest extends BaseEC2HandlerTest {
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Location> of(defaultLocation), defaultLocation); .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation));
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
@ -192,8 +196,9 @@ public class ImageParserTest extends BaseEC2HandlerTest {
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
assertEquals(result.size(), 4); assertEquals(result.size(), 4);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Location> of(defaultLocation), defaultLocation); .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation));
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0)); org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));

View File

@ -31,8 +31,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import javax.inject.Provider;
import org.jclouds.aws.domain.Region; import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.EC2Client; import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.domain.RegionAndName; import org.jclouds.aws.ec2.compute.domain.RegionAndName;
@ -52,6 +50,8 @@ import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
/** /**
@ -68,19 +68,6 @@ public class RunningInstanceToNodeMetadataTest {
} }
private static class ImageProvider implements Provider<Set<? extends org.jclouds.compute.domain.Image>> {
private final Set<? extends org.jclouds.compute.domain.Image> images;
private ImageProvider(org.jclouds.compute.domain.Image jcImage) {
this.images = ImmutableSet.<org.jclouds.compute.domain.Image> of(jcImage);
}
@Override
public Set<? extends org.jclouds.compute.domain.Image> get() {
return images;
}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testImageNotFoundAndLazyReturnsNull() throws UnknownHostException { public void testImageNotFoundAndLazyReturnsNull() throws UnknownHostException {
@ -93,7 +80,8 @@ public class RunningInstanceToNodeMetadataTest {
ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class); ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
RunningInstance instance = createMock(RunningInstance.class); RunningInstance instance = createMock(RunningInstance.class);
@ -111,7 +99,6 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("notImageId").atLeastOnce();
expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce(); expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andReturn(null); expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andReturn(null);
@ -127,11 +114,10 @@ public class RunningInstanceToNodeMetadataTest {
replay(instance); replay(instance);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getLocation(), locations.iterator().next()); assertEquals(metadata.getLocation(), locations.get().iterator().next());
assertEquals(metadata.getImage(), null); assertEquals(metadata.getImage(), null);
assertEquals(metadata.getTag(), "NOTAG-id"); assertEquals(metadata.getTag(), "NOTAG-id");
assertEquals(metadata.getCredentials(), null); assertEquals(metadata.getCredentials(), null);
@ -156,7 +142,8 @@ public class RunningInstanceToNodeMetadataTest {
ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class); ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
RunningInstance instance = createMock(RunningInstance.class); RunningInstance instance = createMock(RunningInstance.class);
@ -174,11 +161,10 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("notImageId").atLeastOnce();
expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce(); expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andThrow(new NullPointerException()) expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andThrow(new NullPointerException())
.atLeastOnce(); .atLeastOnce();
expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce(); expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
@ -191,11 +177,10 @@ public class RunningInstanceToNodeMetadataTest {
replay(instance); replay(instance);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getLocation(), locations.iterator().next()); assertEquals(metadata.getLocation(), locations.get().iterator().next());
assertEquals(metadata.getImage(), null); assertEquals(metadata.getImage(), null);
assertEquals(metadata.getTag(), "NOTAG-id"); assertEquals(metadata.getTag(), "NOTAG-id");
assertEquals(metadata.getCredentials(), null); assertEquals(metadata.getCredentials(), null);
@ -220,7 +205,8 @@ public class RunningInstanceToNodeMetadataTest {
ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class); ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
RunningInstance instance = createMock(RunningInstance.class); RunningInstance instance = createMock(RunningInstance.class);
@ -238,7 +224,6 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("notImageId").atLeastOnce();
expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce(); expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
org.jclouds.compute.domain.Image lateImage = createMock(org.jclouds.compute.domain.Image.class); org.jclouds.compute.domain.Image lateImage = createMock(org.jclouds.compute.domain.Image.class);
@ -257,11 +242,10 @@ public class RunningInstanceToNodeMetadataTest {
replay(instance); replay(instance);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getLocation(), locations.iterator().next()); assertEquals(metadata.getLocation(), locations.get().iterator().next());
assertEquals(metadata.getImage(), lateImage); assertEquals(metadata.getImage(), lateImage);
assertEquals(metadata.getTag(), "NOTAG-id"); assertEquals(metadata.getTag(), "NOTAG-id");
assertEquals(metadata.getCredentials(), null); assertEquals(metadata.getCredentials(), null);
@ -287,7 +271,8 @@ public class RunningInstanceToNodeMetadataTest {
ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class); ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
RunningInstance instance = createMock(RunningInstance.class); RunningInstance instance = createMock(RunningInstance.class);
@ -306,8 +291,7 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("imageId").atLeastOnce(); expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
expect(jcImage.getLocation()).andReturn(location).atLeastOnce();
expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce(); expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
@ -320,11 +304,10 @@ public class RunningInstanceToNodeMetadataTest {
replay(instance); replay(instance);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getLocation(), locations.iterator().next()); assertEquals(metadata.getLocation(), locations.get().iterator().next());
assertEquals(metadata.getImage(), jcImage); assertEquals(metadata.getImage(), jcImage);
assertEquals(metadata.getTag(), "NOTAG-id"); assertEquals(metadata.getTag(), "NOTAG-id");
assertEquals(metadata.getCredentials(), null); assertEquals(metadata.getCredentials(), null);
@ -348,7 +331,8 @@ public class RunningInstanceToNodeMetadataTest {
ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class); ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
RunningInstance instance = createMock(RunningInstance.class); RunningInstance instance = createMock(RunningInstance.class);
@ -367,8 +351,7 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("imageId").atLeastOnce(); expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
expect(jcImage.getLocation()).andReturn(location).atLeastOnce();
expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce(); expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
@ -381,11 +364,10 @@ public class RunningInstanceToNodeMetadataTest {
replay(instance); replay(instance);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getLocation(), locations.iterator().next()); assertEquals(metadata.getLocation(), locations.get().iterator().next());
assertEquals(metadata.getImage(), jcImage); assertEquals(metadata.getImage(), jcImage);
assertEquals(metadata.getTag(), "tag"); assertEquals(metadata.getTag(), "tag");
assertEquals(metadata.getCredentials(), null); assertEquals(metadata.getCredentials(), null);
@ -421,7 +403,8 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getSubnetId()).andReturn(null); expect(instance.getSubnetId()).andReturn(null);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
expect(instance.getIpAddress()).andReturn("127.0.0.1"); expect(instance.getIpAddress()).andReturn("127.0.0.1");
@ -430,16 +413,15 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce(); expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("imageId").atLeastOnce(); expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
expect(jcImage.getLocation()).andReturn(location).atLeastOnce();
expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn( expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn(
(Set) ImmutableSet.<Image> of(image)); (Set) ImmutableSet.<Image> of(image));
expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass")); expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn( expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn(
new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass")); new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass"));
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
@ -454,8 +436,7 @@ public class RunningInstanceToNodeMetadataTest {
replay(jcImage); replay(jcImage);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);
assertEquals(metadata.getTag(), "tag"); assertEquals(metadata.getTag(), "tag");
@ -496,7 +477,8 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getSubnetId()).andReturn(null); expect(instance.getSubnetId()).andReturn(null);
Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
Set<Location> locations = ImmutableSet.<Location> of(location); Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
expect(instance.getIpAddress()).andReturn("127.0.0.1"); expect(instance.getIpAddress()).andReturn("127.0.0.1");
@ -505,16 +487,15 @@ public class RunningInstanceToNodeMetadataTest {
expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce(); expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
expect(instance.getImageId()).andReturn("imageId").atLeastOnce(); expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
expect(jcImage.getProviderId()).andReturn("imageId").atLeastOnce(); expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
expect(jcImage.getLocation()).andReturn(location).atLeastOnce();
expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn( expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn(
(Set) ImmutableSet.<Image> of(image)); (Set) ImmutableSet.<Image> of(image));
expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass")); expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn( expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn(
new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass")); new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass"));
expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce(); expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
@ -529,8 +510,7 @@ public class RunningInstanceToNodeMetadataTest {
replay(jcImage); replay(jcImage);
RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap, RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(client, credentialsMap,
credentialProvider, new ImageProvider(jcImage), imageMap, locations, credentialProvider, imageMap, locations, new RunningInstanceToStorageMappingUnix());
new RunningInstanceToStorageMappingUnix());
NodeMetadata metadata = parser.apply(instance); NodeMetadata metadata = parser.apply(instance);

View File

@ -21,7 +21,6 @@ package org.jclouds.aws.ec2.compute.internal;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock; import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.createNiceMock;
import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify; import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -46,14 +45,14 @@ import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MapMaker; import com.google.common.collect.MapMaker;
import com.google.inject.util.Providers;
/** /**
* *
@ -62,33 +61,29 @@ import com.google.inject.util.Providers;
@Test(groups = "unit", sequential = true) @Test(groups = "unit", sequential = true)
public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
RegionAndName knownRegionAndName = new RegionAndName("region", "ami");
Image knownImage = createNiceMock(Image.class);
ConcurrentMap<RegionAndName, Image> imageMap = new MapMaker().makeComputingMap(new Function<RegionAndName, Image>() {
@Override
public Image apply(RegionAndName from) {
return from.equals(knownRegionAndName) ? knownImage : null;
}
});
@BeforeTest
void setup() {
knownImage = createNiceMock(Image.class);
}
@Override @Override
protected TemplateOptions provideTemplateOptions() { protected TemplateOptions provideTemplateOptions() {
return new EC2TemplateOptions(); return new EC2TemplateOptions();
} }
@Override @Override
protected EC2TemplateBuilderImpl createTemplateBuilder(Provider<Set<? extends Location>> locations, protected EC2TemplateBuilderImpl createTemplateBuilder(final Image knownImage,
Provider<Set<? extends Image>> images, Provider<Set<? extends Size>> sizes, Location defaultLocation, Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) { Supplier<Set<? extends Size>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider,
return new EC2TemplateBuilderImpl(locations, images, sizes, defaultLocation, optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
templateBuilderProvider, imageMap); final RegionAndName knownRegionAndName = new RegionAndName("region", "ami");
ConcurrentMap<RegionAndName, Image> imageMap = new MapMaker()
.makeComputingMap(new Function<RegionAndName, Image>() {
@Override
public Image apply(RegionAndName from) {
return from.equals(knownRegionAndName) ? knownImage : null;
}
});
return new EC2TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(defaultLocation),
optionsProvider, templateBuilderProvider, imageMap);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -96,26 +91,27 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
public void testParseOnDemand() { public void testParseOnDemand() {
Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1", Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet
"1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any()))); .<Size> of(new SizeImpl("1", "1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1,
1, ImagePredicates.any())));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateOptions defaultOptions = createMock(TemplateOptions.class); TemplateOptions defaultOptions = createMock(TemplateOptions.class);
knownImage = createMock(Image.class); Image knownImage = createMock(Image.class);
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
expect(knownImage.getId()).andReturn("region/ami"); expect(knownImage.getId()).andReturn("region/ami").atLeastOnce();
expect(knownImage.getLocation()).andReturn(location).atLeastOnce(); expect(knownImage.getLocation()).andReturn(location).atLeastOnce();
expect(knownImage.getOsFamily()).andReturn(null); expect(knownImage.getOsFamily()).andReturn(null).atLeastOnce();
expect(knownImage.getName()).andReturn(null); expect(knownImage.getName()).andReturn(null).atLeastOnce();
expect(knownImage.getDescription()).andReturn(null); expect(knownImage.getDescription()).andReturn(null).atLeastOnce();
expect(knownImage.getOsDescription()).andReturn(null); expect(knownImage.getOsDescription()).andReturn(null).atLeastOnce();
expect(knownImage.getVersion()).andReturn(null); expect(knownImage.getVersion()).andReturn(null).atLeastOnce();
expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce(); expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce();
replay(knownImage); replay(knownImage);
@ -123,8 +119,8 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, location,
templateBuilderProvider); optionsProvider, templateBuilderProvider);
assertEquals(template.imageId("region/ami").build().getImage(), knownImage); assertEquals(template.imageId("region/ami").build().getImage(), knownImage);
@ -139,16 +135,17 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
public void testParseOnDemandWithoutRegionEncodedIntoId() { public void testParseOnDemandWithoutRegionEncodedIntoId() {
Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1", Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet
"1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any()))); .<Size> of(new SizeImpl("1", "1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1,
1, ImagePredicates.any())));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateOptions defaultOptions = createMock(TemplateOptions.class); TemplateOptions defaultOptions = createMock(TemplateOptions.class);
knownImage = createMock(Image.class); Image knownImage = createMock(Image.class);
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
@ -157,8 +154,8 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, location,
templateBuilderProvider); optionsProvider, templateBuilderProvider);
try { try {
template.imageId("ami").build(); template.imageId("ami").build();
assert false; assert false;
@ -176,17 +173,18 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
public void testParseOnDemandNotFound() { public void testParseOnDemandNotFound() {
Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1", Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet
"1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any()))); .<Size> of(new SizeImpl("1", "1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1,
1, ImagePredicates.any())));
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateOptions defaultOptions = createMock(TemplateOptions.class); TemplateOptions defaultOptions = createMock(TemplateOptions.class);
knownImage = createMock(Image.class); Image knownImage = createMock(Image.class);
expect(defaultLocation.getId()).andReturn("region"); expect(defaultLocation.getId()).andReturn("region");
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
@ -198,8 +196,8 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, defaultLocation,
templateBuilderProvider); optionsProvider, templateBuilderProvider);
assertEquals(template.imageId("region/bad").build().getImage(), knownImage); assertEquals(template.imageId("region/bad").build().getImage(), knownImage);

View File

@ -58,6 +58,7 @@ import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -77,8 +78,8 @@ public class AzureAsyncBlobStore extends BaseAsyncBlobStore {
@Inject @Inject
AzureAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, AzureAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Set<? extends Location> locations, AzureBlobAsyncClient async, Supplier<Set<? extends Location>> locations, AzureBlobAsyncClient async,
ContainerToResourceMetadata container2ResourceMd, ContainerToResourceMetadata container2ResourceMd,
ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions, ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions,
ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob, ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob,

View File

@ -51,6 +51,7 @@ import org.jclouds.domain.Location;
import org.jclouds.http.options.GetOptions; import org.jclouds.http.options.GetOptions;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
@ -68,20 +69,19 @@ public class AzureBlobStore extends BaseBlobStore {
private final BlobToHttpGetOptions blob2ObjectGetOptions; private final BlobToHttpGetOptions blob2ObjectGetOptions;
@Inject @Inject
AzureBlobStore(BlobStoreContext context, BlobUtils blobUtils, Location defaultLocation, AzureBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,
Set<? extends Location> locations, AzureBlobClient sync, Supplier<Set<? extends Location>> locations, AzureBlobClient sync,
ContainerToResourceMetadata container2ResourceMd, ContainerToResourceMetadata container2ResourceMd,
ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions, ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions,
ListBlobsResponseToResourceList azure2BlobStoreResourceList, ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob,
AzureBlobToBlob azureBlob2Blob, BlobToAzureBlob blob2AzureBlob, BlobToAzureBlob blob2AzureBlob, BlobPropertiesToBlobMetadata blob2BlobMd,
BlobPropertiesToBlobMetadata blob2BlobMd, BlobToHttpGetOptions blob2ObjectGetOptions) { BlobToHttpGetOptions blob2ObjectGetOptions) {
super(context, blobUtils, defaultLocation, locations); super(context, blobUtils, defaultLocation, locations);
this.sync = checkNotNull(sync, "sync"); this.sync = checkNotNull(sync, "sync");
this.container2ResourceMd = checkNotNull(container2ResourceMd, "container2ResourceMd"); this.container2ResourceMd = checkNotNull(container2ResourceMd, "container2ResourceMd");
this.blobStore2AzureContainerListOptions = checkNotNull(blobStore2AzureContainerListOptions, this.blobStore2AzureContainerListOptions = checkNotNull(blobStore2AzureContainerListOptions,
"blobStore2AzureContainerListOptions"); "blobStore2AzureContainerListOptions");
this.azure2BlobStoreResourceList = checkNotNull(azure2BlobStoreResourceList, this.azure2BlobStoreResourceList = checkNotNull(azure2BlobStoreResourceList, "azure2BlobStoreResourceList");
"azure2BlobStoreResourceList");
this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob");
this.blob2AzureBlob = checkNotNull(blob2AzureBlob, "blob2AzureBlob"); this.blob2AzureBlob = checkNotNull(blob2AzureBlob, "blob2AzureBlob");
this.blob2BlobMd = checkNotNull(blob2BlobMd, "blob2BlobMd"); this.blob2BlobMd = checkNotNull(blob2BlobMd, "blob2BlobMd");
@ -96,8 +96,8 @@ public class AzureBlobStore extends BaseBlobStore {
return new Function<BoundedSet<ContainerProperties>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() { return new Function<BoundedSet<ContainerProperties>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply( public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(
BoundedSet<ContainerProperties> from) { BoundedSet<ContainerProperties> from) {
return new PageSetImpl<StorageMetadata>( return new PageSetImpl<StorageMetadata>(Iterables.transform(from, container2ResourceMd), from
Iterables.transform(from, container2ResourceMd), from.getNextMarker()); .getNextMarker());
} }
// TODO this may be a list that isn't complete due to 1000 container limit // TODO this may be a list that isn't complete due to 1000 container limit
}.apply(sync.listContainers(includeMetadata())); }.apply(sync.listContainers(includeMetadata()));
@ -136,8 +136,7 @@ public class AzureBlobStore extends BaseBlobStore {
@Override @Override
public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) { public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {
ListBlobsOptions azureOptions = blobStore2AzureContainerListOptions.apply(options); ListBlobsOptions azureOptions = blobStore2AzureContainerListOptions.apply(options);
return azure2BlobStoreResourceList.apply(sync.listBlobs(container, azureOptions return azure2BlobStoreResourceList.apply(sync.listBlobs(container, azureOptions.includeMetadata()));
.includeMetadata()));
} }
/** /**
@ -173,8 +172,7 @@ public class AzureBlobStore extends BaseBlobStore {
* blob key * blob key
*/ */
@Override @Override
public Blob getBlob(String container, String key, public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions options) {
org.jclouds.blobstore.options.GetOptions options) {
GetOptions azureOptions = blob2ObjectGetOptions.apply(options); GetOptions azureOptions = blob2ObjectGetOptions.apply(options);
return azureBlob2Blob.apply(sync.getBlob(container, key, azureOptions)); return azureBlob2Blob.apply(sync.getBlob(container, key, azureOptions));

View File

@ -40,6 +40,8 @@ import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -59,21 +61,22 @@ public class AzureBlobStoreContextModule extends AbstractModule {
bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);
bind(AsyncBlobStore.class).to(AzureAsyncBlobStore.class).in(Scopes.SINGLETON); bind(AsyncBlobStore.class).to(AzureAsyncBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStore.class).to(AzureBlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(AzureBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStoreContext.class).to( bind(BlobStoreContext.class).to(new TypeLiteral<BlobStoreContextImpl<AzureBlobClient, AzureBlobAsyncClient>>() {
new TypeLiteral<BlobStoreContextImpl<AzureBlobClient, AzureBlobAsyncClient>>() { }).in(Scopes.SINGLETON);
}).in(Scopes.SINGLETON);
bind(ContainsValueInListStrategy.class).to(FindMD5InBlobProperties.class); bind(ContainsValueInListStrategy.class).to(FindMD5InBlobProperties.class);
} }
@Provides @Provides
@Singleton @Singleton
Location getLocation(@Provider String name) { Supplier<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return new LocationImpl(LocationScope.PROVIDER, name, name, null); return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
} }
@Provides @Provides
@Singleton @Singleton
Set<? extends Location> provideLocations(Location location) { Supplier<Location> provideDefaultLocation(@Provider String providerName) {
return ImmutableSet.of(location); return Suppliers
.<Location> ofInstance(new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null));
} }
} }

View File

@ -30,23 +30,24 @@ import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ContainerToResourceMetadata implements Function<ContainerProperties, StorageMetadata> { public class ContainerToResourceMetadata implements Function<ContainerProperties, StorageMetadata> {
private Location defaultLocation; private Supplier<Location> defaultLocation;
@Inject @Inject
ContainerToResourceMetadata(Location defaultLocation) { ContainerToResourceMetadata(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation; this.defaultLocation = defaultLocation;
} }
public StorageMetadata apply(ContainerProperties from) { public StorageMetadata apply(ContainerProperties from) {
MutableStorageMetadata to = new MutableStorageMetadataImpl(); MutableStorageMetadata to = new MutableStorageMetadataImpl();
to.setName(from.getName()); to.setName(from.getName());
to.setLocation(defaultLocation); to.setLocation(defaultLocation.get());
to.setETag(from.getETag()); to.setETag(from.getETag());
to.setLastModified(from.getLastModified()); to.setLastModified(from.getLastModified());
to.setUri(from.getUrl()); to.setUri(from.getUrl());

View File

@ -93,6 +93,7 @@ import org.jclouds.io.payloads.DelegatingPayload;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; 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.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Multimaps; import com.google.common.collect.Multimaps;
@ -101,8 +102,7 @@ import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.internal.Nullable; import com.google.inject.internal.Nullable;
/** /**
* Implementation of {@link BaseAsyncBlobStore} which keeps all data in a local * Implementation of {@link BaseAsyncBlobStore} which keeps all data in a local Map object.
* Map object.
* *
* @author Adrian Cole * @author Adrian Cole
* @author James Murty * @author James Murty
@ -119,11 +119,12 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
@Inject @Inject
protected TransientAsyncBlobStore(BlobStoreContext context, DateService dateService, Crypto crypto, protected TransientAsyncBlobStore(BlobStoreContext context, DateService dateService, Crypto crypto,
ConcurrentMap<String, ConcurrentMap<String, Blob>> containerToBlobs, ConcurrentMap<String, ConcurrentMap<String, Blob>> containerToBlobs,
ConcurrentMap<String, Location> containerToLocation, HttpGetOptionsListToGetOptions httpGetOptionsConverter, ConcurrentMap<String, Location> containerToLocation,
IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils, HttpGetOptionsListToGetOptions httpGetOptionsConverter,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils,
Set<Location> locations) { @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Supplier<Set<? extends Location>> locations) {
super(context, blobUtils, service, defaultLocation, locations); super(context, blobUtils, service, defaultLocation, locations);
this.blobFactory = blobFactory; this.blobFactory = blobFactory;
this.dateService = dateService; this.dateService = dateService;
@ -132,7 +133,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
this.containerToLocation = containerToLocation; this.containerToLocation = containerToLocation;
this.httpGetOptionsConverter = httpGetOptionsConverter; this.httpGetOptionsConverter = httpGetOptionsConverter;
this.ifDirectoryReturnName = ifDirectoryReturnName; this.ifDirectoryReturnName = ifDirectoryReturnName;
getContainerToLocation().put("stub", defaultLocation); getContainerToLocation().put("stub", defaultLocation.get());
getContainerToBlobs().put("stub", new ConcurrentHashMap<String, Blob>()); getContainerToBlobs().put("stub", new ConcurrentHashMap<String, Blob>());
} }
@ -147,21 +148,21 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
return immediateFailedFuture(cnfe(container)); return immediateFailedFuture(cnfe(container));
SortedSet<StorageMetadata> contents = newTreeSet(transform(realContents.keySet(), SortedSet<StorageMetadata> contents = newTreeSet(transform(realContents.keySet(),
new Function<String, StorageMetadata>() { new Function<String, StorageMetadata>() {
public StorageMetadata apply(String key) { public StorageMetadata apply(String key) {
Blob oldBlob = realContents.get(key); Blob oldBlob = realContents.get(key);
checkState(oldBlob != null, "blob " + key + " is not present although it was in the list of " checkState(oldBlob != null, "blob " + key + " is not present although it was in the list of "
+ container); + container);
checkState(oldBlob.getMetadata() != null, "blob " + container + "/" + key + " has no metadata"); checkState(oldBlob.getMetadata() != null, "blob " + container + "/" + key + " has no metadata");
MutableBlobMetadata md = copy(oldBlob.getMetadata()); MutableBlobMetadata md = copy(oldBlob.getMetadata());
String directoryName = ifDirectoryReturnName.execute(md); String directoryName = ifDirectoryReturnName.execute(md);
if (directoryName != null) { if (directoryName != null) {
md.setName(directoryName); md.setName(directoryName);
md.setType(StorageType.RELATIVE_PATH); md.setType(StorageType.RELATIVE_PATH);
}
return md;
} }
return md; }));
}
}));
if (options.getMarker() != null) { if (options.getMarker() != null) {
final String finalMarker = options.getMarker(); final String finalMarker = options.getMarker();
@ -206,14 +207,14 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
contents = newTreeSet(filter(contents, new DelimiterFilter(prefix != null ? prefix : null, delimiter))); contents = newTreeSet(filter(contents, new DelimiterFilter(prefix != null ? prefix : null, delimiter)));
Iterables.<StorageMetadata> addAll(contents, transform(commonPrefixes, Iterables.<StorageMetadata> addAll(contents, transform(commonPrefixes,
new Function<String, StorageMetadata>() { new Function<String, StorageMetadata>() {
public StorageMetadata apply(String o) { public StorageMetadata apply(String o) {
MutableStorageMetadata md = new MutableStorageMetadataImpl(); MutableStorageMetadata md = new MutableStorageMetadataImpl();
md.setType(StorageType.RELATIVE_PATH); md.setType(StorageType.RELATIVE_PATH);
md.setName(o); md.setName(o);
return md; return md;
} }
})); }));
} }
// trim metadata, if the response isn't supposed to be detailed. // trim metadata, if the response isn't supposed to be detailed.
@ -224,13 +225,13 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
} }
return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(contents, return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(contents,
marker)); marker));
} }
private ContainerNotFoundException cnfe(final String name) { private ContainerNotFoundException cnfe(final String name) {
return new ContainerNotFoundException(name, String.format("container %s not in %s", name, getContainerToBlobs() return new ContainerNotFoundException(name, String.format("container %s not in %s", name, getContainerToBlobs()
.keySet())); .keySet()));
} }
public static MutableBlobMetadata copy(MutableBlobMetadata in) { public static MutableBlobMetadata copy(MutableBlobMetadata in) {
@ -327,15 +328,15 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
@Override @Override
public ListenableFuture<PageSet<? extends StorageMetadata>> list() { public ListenableFuture<PageSet<? extends StorageMetadata>> list() {
return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(transform( return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(transform(
getContainerToBlobs().keySet(), new Function<String, StorageMetadata>() { getContainerToBlobs().keySet(), new Function<String, StorageMetadata>() {
public StorageMetadata apply(String name) { public StorageMetadata apply(String name) {
MutableStorageMetadata cmd = create(); MutableStorageMetadata cmd = create();
cmd.setName(name); cmd.setName(name);
cmd.setType(StorageType.CONTAINER); cmd.setType(StorageType.CONTAINER);
cmd.setLocation(getContainerToLocation().get(name)); cmd.setLocation(getContainerToLocation().get(name));
return cmd; return cmd;
} }
}), null)); }), null));
} }
protected MutableStorageMetadata create() { protected MutableStorageMetadata create() {
@ -349,7 +350,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
public ListenableFuture<Boolean> createContainerInLocation(final Location location, final String name) { public ListenableFuture<Boolean> createContainerInLocation(final Location location, final String name) {
if (!getContainerToBlobs().containsKey(name)) { if (!getContainerToBlobs().containsKey(name)) {
getContainerToBlobs().put(name, new ConcurrentHashMap<String, Blob>()); getContainerToBlobs().put(name, new ConcurrentHashMap<String, Blob>());
getContainerToLocation().put(name, location != null ? location : defaultLocation); getContainerToLocation().put(name, location != null ? location : defaultLocation.get());
} }
return immediateFuture(getContainerToBlobs().containsKey(name)); return immediateFuture(getContainerToBlobs().containsKey(name));
} }
@ -359,9 +360,9 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
*/ */
public ListenableFuture<Void> createContainerInLocationIfAbsent(final Location location, final String name) { public ListenableFuture<Void> createContainerInLocationIfAbsent(final Location location, final String name) {
ConcurrentMap<String, Blob> container = getContainerToBlobs().putIfAbsent(name, ConcurrentMap<String, Blob> container = getContainerToBlobs().putIfAbsent(name,
new ConcurrentHashMap<String, Blob>()); new ConcurrentHashMap<String, Blob>());
if (container == null) { if (container == null) {
getContainerToLocation().put(name, location != null ? location : defaultLocation); getContainerToLocation().put(name, location != null ? location : defaultLocation.get());
return immediateFuture((Void) null); return immediateFuture((Void) null);
} else { } else {
return Futures.immediateFailedFuture(new IllegalStateException("container " + name + " already exists")); return Futures.immediateFailedFuture(new IllegalStateException("container " + name + " already exists"));
@ -504,11 +505,11 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
protected Blob createUpdatedCopyOfBlob(Blob in) { protected Blob createUpdatedCopyOfBlob(Blob in) {
ByteArrayPayload payload = (in.getPayload() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(in ByteArrayPayload payload = (in.getPayload() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(in
.getPayload()) : null; .getPayload()) : null;
if (payload == null) if (payload == null)
payload = (in.getPayload() instanceof DelegatingPayload) ? (DelegatingPayload.class.cast(in.getPayload()) payload = (in.getPayload() instanceof DelegatingPayload) ? (DelegatingPayload.class.cast(in.getPayload())
.getDelegate() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(DelegatingPayload.class.cast( .getDelegate() instanceof ByteArrayPayload) ? ByteArrayPayload.class.cast(DelegatingPayload.class
in.getPayload()).getDelegate()) : null : null; .cast(in.getPayload()).getDelegate()) : null : null;
try { try {
if (payload == null || !(payload instanceof ByteArrayPayload)) { if (payload == null || !(payload instanceof ByteArrayPayload)) {
String oldContentType = in.getPayload().getContentType(); String oldContentType = in.getPayload().getContentType();
@ -534,13 +535,13 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
blob.getMetadata().setETag(eTag); blob.getMetadata().setETag(eTag);
// Set HTTP headers to match metadata // Set HTTP headers to match metadata
blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED, blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED,
Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified()))); Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified())));
blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, Collections.singleton(eTag)); blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, Collections.singleton(eTag));
blob.getAllHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, Collections.singleton(payload.getContentType())); blob.getAllHeaders().replaceValues(HttpHeaders.CONTENT_TYPE, Collections.singleton(payload.getContentType()));
blob.getAllHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH, blob.getAllHeaders().replaceValues(HttpHeaders.CONTENT_LENGTH,
Collections.singleton(payload.getContentLength() + "")); Collections.singleton(payload.getContentLength() + ""));
blob.getAllHeaders().replaceValues("Content-MD5", blob.getAllHeaders().replaceValues("Content-MD5",
Collections.singleton(CryptoStreams.base64(payload.getContentMD5()))); Collections.singleton(CryptoStreams.base64(payload.getContentMD5())));
blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata())); blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata()));
return blob; return blob;
} }
@ -582,7 +583,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
if (object.getMetadata().getLastModified().before(modifiedSince)) { if (object.getMetadata().getLastModified().before(modifiedSince)) {
HttpResponse response = new HttpResponse(304, null, null); HttpResponse response = new HttpResponse(304, null, null);
return immediateFailedFuture(new HttpResponseException(String.format("%1$s is before %2$s", object return immediateFailedFuture(new HttpResponseException(String.format("%1$s is before %2$s", object
.getMetadata().getLastModified(), modifiedSince), null, response)); .getMetadata().getLastModified(), modifiedSince), null, response));
} }
} }
@ -591,7 +592,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore {
if (object.getMetadata().getLastModified().after(unmodifiedSince)) { if (object.getMetadata().getLastModified().after(unmodifiedSince)) {
HttpResponse response = new HttpResponse(412, null, null); HttpResponse response = new HttpResponse(412, null, null);
return immediateFailedFuture(new HttpResponseException(String.format("%1$s is after %2$s", object return immediateFailedFuture(new HttpResponseException(String.format("%1$s is after %2$s", object
.getMetadata().getLastModified(), unmodifiedSince), null, response)); .getMetadata().getLastModified(), unmodifiedSince), null, response));
} }
} }
Blob returnVal = copyBlob(object); Blob returnVal = copyBlob(object);

View File

@ -35,7 +35,10 @@ import org.jclouds.blobstore.internal.BlobStoreContextImpl;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -67,12 +70,6 @@ public class TransientBlobStoreContextModule extends AbstractModule {
bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);
} }
@Provides
@Singleton
Set<Location> provideLocations(Location defaultLocation) {
return ImmutableSet.of(defaultLocation);
}
@Provides @Provides
@Singleton @Singleton
BlobStore provide(TransientBlobStore in) { BlobStore provide(TransientBlobStore in) {
@ -81,8 +78,14 @@ public class TransientBlobStoreContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
Location provideDefaultLocation() { Supplier<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return new LocationImpl(LocationScope.PROVIDER, "transient", "transient", null); return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
} }
@Provides
@Singleton
Supplier<Location> provideDefaultLocation(@Provider String providerName) {
return Suppliers
.<Location> ofInstance(new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null));
}
} }

View File

@ -55,13 +55,13 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
protected final BlobStoreContext context; protected final BlobStoreContext context;
protected final BlobUtils blobUtils; protected final BlobUtils blobUtils;
protected final ExecutorService service; protected final ExecutorService service;
protected final Location defaultLocation; protected final Supplier<Location> defaultLocation;
protected final Set<? extends Location> locations; protected final Supplier<Set<? extends Location>> locations;
@Inject @Inject
protected BaseAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, protected BaseAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Set<? extends Location> locations) { Supplier<Set<? extends Location>> locations) {
this.context = checkNotNull(context, "context"); this.context = checkNotNull(context, "context");
this.blobUtils = checkNotNull(blobUtils, "blobUtils"); this.blobUtils = checkNotNull(blobUtils, "blobUtils");
this.service = checkNotNull(service, "service"); this.service = checkNotNull(service, "service");
@ -262,7 +262,7 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore {
@Override @Override
public ListenableFuture<Set<? extends Location>> listAssignableLocations() { public ListenableFuture<Set<? extends Location>> listAssignableLocations() {
return Futures.<Set<? extends Location>> immediateFuture(locations); return Futures.<Set<? extends Location>> immediateFuture(locations.get());
} }
protected abstract boolean deleteAndVerifyContainerGone(String container); protected abstract boolean deleteAndVerifyContainerGone(String container);

View File

@ -48,12 +48,12 @@ public abstract class BaseBlobStore implements BlobStore {
protected final BlobStoreContext context; protected final BlobStoreContext context;
protected final BlobUtils blobUtils; protected final BlobUtils blobUtils;
protected final Location defaultLocation; protected final Supplier<Location> defaultLocation;
protected final Set<? extends Location> locations; protected final Supplier<Set<? extends Location>> locations;
@Inject @Inject
protected BaseBlobStore(BlobStoreContext context, BlobUtils blobUtils, protected BaseBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,
Location defaultLocation, Set<? extends Location> locations) { Supplier<Set<? extends Location>> locations) {
this.context = checkNotNull(context, "context"); this.context = checkNotNull(context, "context");
this.blobUtils = checkNotNull(blobUtils, "blobUtils"); this.blobUtils = checkNotNull(blobUtils, "blobUtils");
this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation"); this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation");
@ -215,7 +215,7 @@ public abstract class BaseBlobStore implements BlobStore {
@Override @Override
public Set<? extends Location> listAssignableLocations() { public Set<? extends Location> listAssignableLocations() {
return locations; return locations.get();
} }
protected abstract boolean deleteAndVerifyContainerGone(String container); protected abstract boolean deleteAndVerifyContainerGone(String container);

View File

@ -0,0 +1,218 @@
/**
*
* 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 static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;
import static org.jclouds.compute.domain.OsFamily.UBUNTU;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
/**
*
* @author Adrian Cole
*/
public abstract class BaseComputeServiceContextModule extends AbstractModule {
protected abstract Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector);
protected abstract Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector);
/**
* By default allows you to use a static set of locations bound to Set<? extends Location>
*/
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
Set<? extends Location> locations = injector.getInstance(Key.get(new TypeLiteral<Set<? extends Location>>() {
}));
return Suppliers.<Set<? extends Location>> ofInstance(locations);
}
@Provides
@Named("DEFAULT")
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
return template.osFamily(UBUNTU);
}
@Provides
@Named("NAMING_CONVENTION")
@Singleton
protected String provideNamingConvention() {
return "%s-%s";
}
protected AtomicReference<AuthorizationException> authException = new AtomicReference<AuthorizationException>();
@Provides
@Singleton
protected Supplier<Map<String, ? extends Image>> provideImageMap(Supplier<Set<? extends Image>> images) {
return Suppliers.compose(new Function<Set<? extends Image>, Map<String, ? extends Image>>() {
@Override
public Map<String, ? extends Image> apply(Set<? extends Image> from) {
return Maps.uniqueIndex(from, new Function<Image, String>() {
@Override
public String apply(Image from) {
return from.getId();
}
});
}
}, images);
}
@Provides
@Singleton
protected Supplier<Set<? extends Image>> supplyImageCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Image>>(authException, seconds,
new Supplier<Set<? extends Image>>() {
@Override
public Set<? extends Image> get() {
return getSourceImageSupplier(injector).get();
}
});
}
@Provides
@Singleton
protected Supplier<Map<String, ? extends Location>> provideLocationMap(Supplier<Set<? extends Location>> locations) {
return Suppliers.compose(new Function<Set<? extends Location>, Map<String, ? extends Location>>() {
@Override
public Map<String, ? extends Location> apply(Set<? extends Location> from) {
return Maps.uniqueIndex(from, new Function<Location, String>() {
@Override
public String apply(Location from) {
return from.getId();
}
});
}
}, locations);
}
@Provides
@Singleton
protected Supplier<Set<? extends Location>> supplyLocationCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Location>>(authException, seconds,
new Supplier<Set<? extends Location>>() {
@Override
public Set<? extends Location> get() {
return getSourceLocationSupplier(injector).get();
}
});
}
@Provides
@Singleton
protected Supplier<Map<String, ? extends Size>> provideSizeMap(Supplier<Set<? extends Size>> sizes) {
return Suppliers.compose(new Function<Set<? extends Size>, Map<String, ? extends Size>>() {
@Override
public Map<String, ? extends Size> apply(Set<? extends Size> from) {
return Maps.uniqueIndex(from, new Function<Size, String>() {
@Override
public String apply(Size from) {
return from.getId();
}
});
}
}, sizes);
}
@Provides
@Singleton
protected Supplier<Set<? extends Size>> supplySizeCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Size>>(authException, seconds,
new Supplier<Set<? extends Size>>() {
@Override
public Set<? extends Size> get() {
return getSourceSizeSupplier(injector).get();
}
});
}
@Provides
@Singleton
protected Function<ComputeMetadata, String> indexer() {
return new Function<ComputeMetadata, String>() {
@Override
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
}
@Provides
@Singleton
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
@Override
public Location apply(Set<? extends Location> from) {
return Iterables.find(from, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
});
}
}, locations);
}
}

View File

@ -69,6 +69,7 @@ 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.Predicate;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@ -86,9 +87,9 @@ public class BaseComputeService implements ComputeService {
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
protected final ComputeServiceContext context; protected final ComputeServiceContext context;
protected final Provider<Set<? extends Image>> images; protected final Supplier<Set<? extends Image>> images;
protected final Provider<Set<? extends Size>> sizes; protected final Supplier<Set<? extends Size>> sizes;
protected final Provider<Set<? extends Location>> locations; protected final Supplier<Set<? extends Location>> locations;
protected final ListNodesStrategy listNodesStrategy; protected final ListNodesStrategy listNodesStrategy;
protected final GetNodeMetadataStrategy getNodeMetadataStrategy; protected final GetNodeMetadataStrategy getNodeMetadataStrategy;
protected final RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy; protected final RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy;
@ -102,14 +103,15 @@ public class BaseComputeService implements ComputeService {
protected final ExecutorService executor; protected final ExecutorService executor;
@Inject @Inject
protected BaseComputeService(ComputeServiceContext context, Provider<Set<? extends Image>> images, protected BaseComputeService(ComputeServiceContext context, Supplier<Set<? extends Image>> images,
Provider<Set<? extends Size>> sizes, Provider<Set<? extends Location>> locations, Supplier<Set<? extends Size>> sizes, Supplier<Set<? extends Location>> locations,
ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,
RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
DestroyNodeStrategy destroyNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider, DestroyNodeStrategy destroyNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,
Provider<TemplateOptions> templateOptionsProvider, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { @Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.context = checkNotNull(context, "context"); this.context = checkNotNull(context, "context");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.sizes = checkNotNull(sizes, "sizes"); this.sizes = checkNotNull(sizes, "sizes");
@ -140,12 +142,12 @@ public class BaseComputeService implements ComputeService {
*/ */
@Override @Override
public Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, Template template) public Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, Template template)
throws RunNodesException { throws RunNodesException {
checkArgument(tag.indexOf('-') == -1, "tag cannot contain hyphens"); checkArgument(tag.indexOf('-') == -1, "tag cannot contain hyphens");
checkNotNull(template.getLocation(), "location"); checkNotNull(template.getLocation(), "location");
logger.debug(">> running %d node%s tag(%s) location(%s) image(%s) size(%s) options(%s)", count, count > 1 ? "s" logger.debug(">> running %d node%s tag(%s) location(%s) image(%s) size(%s) options(%s)", count, count > 1 ? "s"
: "", tag, template.getLocation().getId(), template.getImage().getProviderId(), template.getSize() : "", tag, template.getLocation().getId(), template.getImage().getId(), template.getSize().getId(),
.getProviderId(), template.getOptions()); template.getOptions());
Set<NodeMetadata> nodes = Sets.newHashSet(); Set<NodeMetadata> nodes = Sets.newHashSet();
Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap(); Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap();
Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes); Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes);
@ -161,7 +163,7 @@ public class BaseComputeService implements ComputeService {
*/ */
@Override @Override
public Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, TemplateOptions templateOptions) public Set<? extends NodeMetadata> runNodesWithTag(String tag, int count, TemplateOptions templateOptions)
throws RunNodesException { throws RunNodesException {
return runNodesWithTag(tag, count, templateBuilder().any().options(templateOptions).build()); return runNodesWithTag(tag, count, templateBuilder().any().options(templateOptions).build());
} }
@ -192,23 +194,23 @@ public class BaseComputeService implements ComputeService {
public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) { public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> destroying nodes matching(%s)", filter); logger.debug(">> destroying nodes matching(%s)", filter);
Set<NodeMetadata> set = Sets.newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter), Set<NodeMetadata> set = Sets.newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter),
new Function<NodeMetadata, Future<NodeMetadata>>() { new Function<NodeMetadata, Future<NodeMetadata>>() {
// TODO make an async interface instead of re-wrapping // TODO make an async interface instead of re-wrapping
@Override @Override
public Future<NodeMetadata> apply(final NodeMetadata from) { public Future<NodeMetadata> apply(final NodeMetadata from) {
return executor.submit(new Callable<NodeMetadata>() { return executor.submit(new Callable<NodeMetadata>() {
@Override @Override
public NodeMetadata call() throws Exception { public NodeMetadata call() throws Exception {
destroyNode(from.getId()); destroyNode(from.getId());
return from; return from;
} }
}); });
} }
}, executor, null, logger, "destroying nodes")); }, executor, null, logger, "destroying nodes"));
logger.debug("<< destroyed(%d)", set.size()); logger.debug("<< destroyed(%d)", set.size());
return set; return set;
} }
@ -316,7 +318,7 @@ public class BaseComputeService implements ComputeService {
*/ */
@Override @Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript) public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript)
throws RunScriptOnNodesException { throws RunScriptOnNodesException {
return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE); return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE);
} }
@ -325,9 +327,9 @@ public class BaseComputeService implements ComputeService {
*/ */
@Override @Override
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter,
final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException { final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException {
Iterable<NodeMetadata> nodes = verifyParametersAndListNodes(filter, runScript, (options != null) ? options Iterable<NodeMetadata> nodes = verifyParametersAndListNodes(filter, runScript, (options != null) ? options
: RunScriptOptions.NONE); : RunScriptOptions.NONE);
final Map<NodeMetadata, ExecResponse> execs = Maps.newHashMap(); final Map<NodeMetadata, ExecResponse> execs = Maps.newHashMap();
@ -373,7 +375,7 @@ public class BaseComputeService implements ComputeService {
} }
private Iterable<NodeMetadata> verifyParametersAndListNodes(Predicate<NodeMetadata> filter, Payload runScript, private Iterable<NodeMetadata> verifyParametersAndListNodes(Predicate<NodeMetadata> filter, Payload runScript,
final RunScriptOptions options) { final RunScriptOptions options) {
checkNotNull(filter, "Filter must be provided"); checkNotNull(filter, "Filter must be provided");
checkNotNull(runScript, "The script (represented by bytes array - use \"script\".getBytes() must be provided"); checkNotNull(runScript, "The script (represented by bytes array - use \"script\".getBytes() must be provided");
checkNotNull(options, "options"); checkNotNull(options, "options");
@ -394,9 +396,9 @@ public class BaseComputeService implements ComputeService {
// don't override // don't override
checkNotNull(node.getCredentials(), "If the default credentials need to be used, they can't be null"); checkNotNull(node.getCredentials(), "If the default credentials need to be used, they can't be null");
checkNotNull(node.getCredentials().identity, "Account name for ssh authentication must be " checkNotNull(node.getCredentials().identity, "Account name for ssh authentication must be "
+ "specified. Try passing RunScriptOptions with new credentials"); + "specified. Try passing RunScriptOptions with new credentials");
checkNotNull(node.getCredentials().credential, "Key or password for ssh authentication must be " checkNotNull(node.getCredentials().credential, "Key or password for ssh authentication must be "
+ "specified. Try passing RunScriptOptions with new credentials"); + "specified. Try passing RunScriptOptions with new credentials");
} }
return node; return node;
} }

View File

@ -50,6 +50,7 @@ import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ComparisonChain; import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -67,12 +68,12 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
protected final Provider<Set<? extends Image>> images; protected final Supplier<Set<? extends Image>> images;
protected final Provider<Set<? extends Size>> sizes; protected final Supplier<Set<? extends Size>> sizes;
protected final Provider<Set<? extends Location>> locations; protected final Supplier<Set<? extends Location>> locations;
protected final Supplier<Location> defaultLocation;
protected final Provider<TemplateOptions> optionsProvider; protected final Provider<TemplateOptions> optionsProvider;
protected final Provider<TemplateBuilder> defaultTemplateProvider; protected final Provider<TemplateBuilder> defaultTemplateProvider;
protected final Location defaultLocation;
@VisibleForTesting @VisibleForTesting
protected OsFamily os; protected OsFamily os;
@ -104,13 +105,14 @@ public class TemplateBuilderImpl implements TemplateBuilder {
protected TemplateOptions options; protected TemplateOptions options;
@Inject @Inject
protected TemplateBuilderImpl(Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images, protected TemplateBuilderImpl(Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Provider<Set<? extends Size>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider, Supplier<Set<? extends Size>> sizes, 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.sizes = sizes; this.sizes = sizes;
this.defaultLocation = defaultLocation; this.defaultLocation = defaultLocation2;
this.optionsProvider = optionsProvider; this.optionsProvider = optionsProvider;
this.defaultTemplateProvider = defaultTemplateProvider; this.defaultTemplateProvider = defaultTemplateProvider;
} }
@ -395,12 +397,14 @@ public class TemplateBuilderImpl implements TemplateBuilder {
return defaultTemplate.build(); return defaultTemplate.build();
} }
if (location == null) if (location == null)
location = defaultLocation; location = defaultLocation.get();
if (options == null) if (options == null)
options = optionsProvider.get(); options = optionsProvider.get();
logger.debug(">> searching params(%s)", this); logger.debug(">> searching params(%s)", this);
Size size = resolveSize(sizeSorter(), getImages()); Set<? extends Image> images = getImages();
Image image = resolveImage(size); Iterable<? extends Image> supportedImages = filter(images, buildImagePredicate());
Size size = resolveSize(sizeSorter(), supportedImages);
Image image = resolveImage(size, supportedImages);
logger.debug("<< matched image(%s)", image); logger.debug("<< matched image(%s)", image);
// ensure we have an architecture matching // ensure we have an architecture matching
@ -409,28 +413,26 @@ public class TemplateBuilderImpl implements TemplateBuilder {
} }
protected Size resolveSize(Ordering<Size> sizeOrdering, final Iterable<? extends Image> images) { protected Size resolveSize(Ordering<Size> sizeOrdering, final Iterable<? extends Image> images) {
Set<? extends Size> sizesl = sizes.get();
Size size; Size size;
try { try {
Iterable<? extends Size> sizesThatAreCompatibleWithOurImages = filter(sizes.get(), new Predicate<Size>() { Iterable<? extends Size> sizesThatAreCompatibleWithOurImages = filter(sizesl, new Predicate<Size>() {
@Override @Override
public boolean apply(final Size size) { public boolean apply(final Size size) {
boolean returnVal = false; return Iterables.any(images, new Predicate<Image>() {
if (size != null) {
returnVal = Iterables.any(images, new Predicate<Image>() {
@Override @Override
public boolean apply(Image input) { public boolean apply(Image input) {
return size.supportsImage(input); return size.supportsImage(input);
} }
});
});
}
return returnVal;
} }
}); });
size = sizeOrdering.max(filter(sizesThatAreCompatibleWithOurImages, sizePredicate)); size = sizeOrdering.max(filter(sizesThatAreCompatibleWithOurImages, sizePredicate));
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
throw new NoSuchElementException("sizes don't support any images: " + toString() + "\n" + sizes.get() + "\n" throw new NoSuchElementException("sizes don't support any images: " + toString() + "\n" + sizesl + "\n"
+ images); + images);
} }
logger.debug("<< matched size(%s)", size); logger.debug("<< matched size(%s)", size);
@ -449,20 +451,21 @@ public class TemplateBuilderImpl implements TemplateBuilder {
/** /**
* *
* @param size * @param size
* @param supportedImages
* @throws NoSuchElementException * @throws NoSuchElementException
* if there's no image that matches the predicate * if there's no image that matches the predicate
*/ */
protected Image resolveImage(final Size size) { protected Image resolveImage(final Size size, Iterable<? extends Image> supportedImages) {
Predicate<Image> imagePredicate = and(buildImagePredicate(), new Predicate<Image>() { Predicate<Image> imagePredicate = new Predicate<Image>() {
@Override @Override
public boolean apply(Image arg0) { public boolean apply(Image arg0) {
return size.supportsImage(arg0); return size.supportsImage(arg0);
} }
}); };
try { try {
Iterable<? extends Image> matchingImages = filter(getImages(), imagePredicate); Iterable<? extends Image> matchingImages = filter(supportedImages, imagePredicate);
if (logger.isTraceEnabled()) if (logger.isTraceEnabled())
logger.trace("<< matched images(%s)", matchingImages); logger.trace("<< matched images(%s)", matchingImages);
List<? extends Image> maxImages = multiMax(DEFAULT_IMAGE_ORDERING, matchingImages); List<? extends Image> maxImages = multiMax(DEFAULT_IMAGE_ORDERING, matchingImages);
@ -470,8 +473,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
logger.trace("<< best images(%s)", maxImages); logger.trace("<< best images(%s)", maxImages);
return maxImages.get(maxImages.size() - 1); return maxImages.get(maxImages.size() - 1);
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
Set<? extends Image> images = getImages(); throw new NoSuchElementException("image didn't match: " + toString() + "\n" + supportedImages);
throw new NoSuchElementException("image didn't match: " + toString() + "\n" + images);
} }
} }

View File

@ -20,7 +20,6 @@
package org.jclouds.compute.stub.config; package org.jclouds.compute.stub.config;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.compute.domain.OsFamily.UBUNTU;
import static org.jclouds.compute.predicates.ImagePredicates.architectureIn; import static org.jclouds.compute.predicates.ImagePredicates.architectureIn;
import java.net.URI; import java.net.URI;
@ -40,6 +39,7 @@ import javax.inject.Singleton;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.ComputeMetadata;
@ -49,7 +49,6 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl; import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl; import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
@ -69,11 +68,14 @@ import org.jclouds.predicates.SocketOpen;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.inject.AbstractModule; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -84,7 +86,7 @@ import com.google.inject.util.Providers;
* @author Adrian Cole * @author Adrian Cole
*/ */
@SingleThreaded @SingleThreaded
public class StubComputeServiceContextModule extends AbstractModule { public class StubComputeServiceContextModule extends BaseComputeServiceContextModule {
// 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 ConcurrentMap<Integer, StubNodeMetadata> nodes = new ConcurrentHashMap<Integer, StubNodeMetadata>(); private static final ConcurrentMap<Integer, StubNodeMetadata> nodes = new ConcurrentHashMap<Integer, StubNodeMetadata>();
@ -168,12 +170,6 @@ public class StubComputeServiceContextModule extends AbstractModule {
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null)); bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
} }
@Provides
@Named("DEFAULT")
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.osFamily(UBUNTU);
}
public static class StubNodeMetadata extends NodeMetadataImpl { public static class StubNodeMetadata extends NodeMetadataImpl {
/** The serialVersionUID */ /** The serialVersionUID */
@ -219,7 +215,7 @@ public class StubComputeServiceContextModule extends AbstractModule {
@Singleton @Singleton
public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy { public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final Location location; private final Supplier<Location> location;
private final ExecutorService service; private final ExecutorService service;
private final ConcurrentMap<Integer, StubNodeMetadata> nodes; private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
private final Provider<Integer> idProvider; private final Provider<Integer> idProvider;
@ -228,7 +224,7 @@ public class StubComputeServiceContextModule extends AbstractModule {
private final String passwordPrefix; private final String passwordPrefix;
@Inject @Inject
public StubAddNodeWithTagStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes, Location location, public StubAddNodeWithTagStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes, Supplier<Location> location,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, @Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix) { @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix) {
@ -243,9 +239,9 @@ public class StubComputeServiceContextModule extends AbstractModule {
@Override @Override
public NodeMetadata execute(String tag, String name, Template template) { public NodeMetadata execute(String tag, String name, Template template) {
checkArgument(location.equals(template.getLocation()), "invalid location: " + template.getLocation()); checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation());
int id = idProvider.get(); int id = idProvider.get();
StubNodeMetadata node = new StubNodeMetadata(id + "", name, id + "", location, null, ImmutableMap StubNodeMetadata node = new StubNodeMetadata(id + "", name, id + "", location.get(), null, ImmutableMap
.<String, String> of(), tag, template.getImage(), NodeState.PENDING, ImmutableSet .<String, String> of(), tag, template.getImage(), NodeState.PENDING, ImmutableSet
.<String> of(publicIpPrefix + id), ImmutableSet.<String> of(privateIpPrefix + id), ImmutableMap .<String> of(publicIpPrefix + id), ImmutableSet.<String> of(privateIpPrefix + id), ImmutableMap
.<String, String> of(), new Credentials("root", passwordPrefix + id), service); .<String, String> of(), new Credentials("root", passwordPrefix + id), service);
@ -349,19 +345,37 @@ public class StubComputeServiceContextModule extends AbstractModule {
} }
} }
@Provides @Override
@Named("NAMING_CONVENTION") protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
@Singleton Supplier<Location> defaultLocation = injector.getInstance(Key.get(new TypeLiteral<Supplier<Location>>() {
protected String provideNamingConvention() { }));
return "%s-%s"; Location zone = defaultLocation.get().getParent();
String parentId = zone.getId();
return Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(new ImageImpl("1", OsFamily.UBUNTU
.name(), parentId + "/1", zone, null, ImmutableMap.<String, String> of(), "stub ubuntu 32", "",
OsFamily.UBUNTU, "ubuntu 64", Architecture.X86_64, new Credentials("root", null)), new ImageImpl("2",
OsFamily.UBUNTU.name(), parentId + "/2", zone, null, ImmutableMap.<String, String> of(),
"stub ubuntu 64", "", OsFamily.UBUNTU, "ubuntu 64", Architecture.X86_64, new Credentials("root", null)),
new ImageImpl("3", OsFamily.CENTOS.name(), parentId + "/3", zone, null, ImmutableMap
.<String, String> of(), "stub centos 64", "", OsFamily.CENTOS, "centos 64",
Architecture.X86_64, new Credentials("root", null))));
} }
@Provides @Provides
@Singleton @Singleton
protected Set<? extends Size> provideSizes() { protected Set<? extends Location> provideLocations(@org.jclouds.rest.annotations.Provider String providerName) {
return ImmutableSet.<Size> of(new StubSize("small", 1, 1740, 160, ImmutableSet.of(Architecture.X86_32)), Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
new StubSize("medium", 4, 7680, 850, ImmutableSet.of(Architecture.X86_64)), new StubSize("large", 8, Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
15360, 1690, ImmutableSet.of(Architecture.X86_64))); provider);
return ImmutableSet
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
}
@Override
protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
return Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(new StubSize("small", 1, 1740, 160,
ImmutableSet.of(Architecture.X86_32)), new StubSize("medium", 4, 7680, 850, ImmutableSet
.of(Architecture.X86_64)), new StubSize("large", 8, 15360, 1690, ImmutableSet.of(Architecture.X86_64))));
} }
private static class StubSize extends org.jclouds.compute.domain.internal.SizeImpl { private static class StubSize extends org.jclouds.compute.domain.internal.SizeImpl {
@ -374,32 +388,4 @@ public class StubComputeServiceContextModule extends AbstractModule {
} }
} }
@Provides
@Singleton
protected Set<? extends Image> provideImages(Location defaultLocation) {
String parentId = defaultLocation.getParent().getId();
return ImmutableSet.<Image> of(new ImageImpl("1", OsFamily.UBUNTU.name(), parentId + "/1", defaultLocation
.getParent(), null, ImmutableMap.<String, String> of(), "stub ubuntu 32", "", OsFamily.UBUNTU,
"ubuntu 64", Architecture.X86_64, new Credentials("root", null)), new ImageImpl("2", OsFamily.UBUNTU
.name(), parentId + "/2", defaultLocation.getParent(), null, ImmutableMap.<String, String> of(),
"stub ubuntu 64", "", OsFamily.UBUNTU, "ubuntu 64", Architecture.X86_64, new Credentials("root", null)),
new ImageImpl("3", OsFamily.CENTOS.name(), parentId + "/3", defaultLocation.getParent(), null,
ImmutableMap.<String, String> of(), "stub centos 64", "", OsFamily.CENTOS, "centos 64",
Architecture.X86_64, new Credentials("root", null)));
}
@Provides
@Singleton
Location getLocation(@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 new LocationImpl(LocationScope.ZONE, providerName+"zone", providerName+"zone", region);
}
@Provides
@Singleton
Set<? extends Location> provideLocations(Location location) {
return ImmutableSet.of(location);
}
} }

View File

@ -138,7 +138,7 @@ public abstract class BaseComputeServiceLiveTest {
String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8); String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);
assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret; assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret;
return ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile return ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile
+ ".pub"), Charsets.UTF_8)); + ".pub"), Charsets.UTF_8));
} }
protected void setupCredentials() { protected void setupCredentials() {
@ -154,7 +154,7 @@ public abstract class BaseComputeServiceLiveTest {
if (context != null) if (context != null)
context.close(); context.close();
context = new ComputeServiceContextFactory().createContext(provider, identity, credential, ImmutableSet.of( context = new ComputeServiceContextFactory().createContext(provider, identity, credential, ImmutableSet.of(
new Log4JLoggingModule(), getSshModule())); new Log4JLoggingModule(), getSshModule()));
client = context.getComputeService(); client = context.getComputeService();
} }
@ -170,8 +170,16 @@ public abstract class BaseComputeServiceLiveTest {
// wait up to 5 seconds for an auth exception // wait up to 5 seconds for an auth exception
@Test(enabled = true, expectedExceptions = AuthorizationException.class) @Test(enabled = true, expectedExceptions = AuthorizationException.class)
public void testCorrectAuthException() throws Exception { public void testCorrectAuthException() throws Exception {
new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ComputeServiceContext context = null;
ImmutableSet.<Module> of(new Log4JLoggingModule())).close(); try {
context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ImmutableSet
.<Module> of(new Log4JLoggingModule()));
context.getComputeService().listNodes();
} finally {
if (context != null)
context.close();
}
} }
@Test(enabled = true, dependsOnMethods = "testCorrectAuthException") @Test(enabled = true, dependsOnMethods = "testCorrectAuthException")
@ -185,7 +193,7 @@ public abstract class BaseComputeServiceLiveTest {
// since surefire and eclipse don't otherwise guarantee the order, we are // since surefire and eclipse don't otherwise guarantee the order, we are
// starting this one alphabetically before create2nodes.. // starting this one alphabetically before create2nodes..
@Test(enabled = true, dependsOnMethods = { "testImagesCache" }) @Test(enabled = true, dependsOnMethods = { "testCompareSizes" })
public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception {
String tag = this.tag + "run"; String tag = this.tag + "run";
try { try {
@ -204,7 +212,7 @@ public abstract class BaseComputeServiceLiveTest {
Image image = get(nodes, 0).getImage(); Image image = get(nodes, 0).getImage();
try { try {
Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(tag, image.getOsFamily(), Map<? extends NodeMetadata, ExecResponse> responses = runScriptWithCreds(tag, image.getOsFamily(),
new Credentials(good.identity, "romeo")); new Credentials(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;
@ -226,7 +234,7 @@ public abstract class BaseComputeServiceLiveTest {
assertEquals(toMatch.getImage(), template.getImage()); assertEquals(toMatch.getImage(), template.getImage());
} }
@Test(enabled = true, dependsOnMethods = "testTemplateMatch") @Test(enabled = true, dependsOnMethods = "testCompareSizes")
public void testCreateTwoNodesWithRunScript() throws Exception { public void testCreateTwoNodesWithRunScript() throws Exception {
try { try {
client.destroyNodesMatching(withTag(tag)); client.destroyNodesMatching(withTag(tag));
@ -238,8 +246,8 @@ public abstract class BaseComputeServiceLiveTest {
template = buildTemplate(client.templateBuilder()); template = buildTemplate(client.templateBuilder());
template.getOptions().installPrivateKey(newStringPayload(keyPair.get("private"))).authorizePublicKey( template.getOptions().installPrivateKey(newStringPayload(keyPair.get("private"))).authorizePublicKey(
newStringPayload(keyPair.get("public"))).runScript( newStringPayload(keyPair.get("public"))).runScript(
newStringPayload(buildScript(template.getImage().getOsFamily()))); newStringPayload(buildScript(template.getImage().getOsFamily())));
try { try {
nodes = newTreeSet(client.runNodesWithTag(tag, 2, template)); nodes = newTreeSet(client.runNodesWithTag(tag, 2, template));
} catch (RunNodesException e) { } catch (RunNodesException e) {
@ -283,10 +291,10 @@ public abstract class BaseComputeServiceLiveTest {
} }
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OsFamily osFamily, protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OsFamily osFamily,
Credentials creds) throws RunScriptOnNodesException { Credentials creds) throws RunScriptOnNodesException {
try { try {
return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(osFamily)), return client.runScriptOnNodesMatching(runningWithTag(tag), newStringPayload(buildScript(osFamily)),
overrideCredentialsWith(creds)); overrideCredentialsWith(creds));
} catch (SshException e) { } catch (SshException e) {
if (getRootCause(e).getMessage().contains("Auth fail")) { if (getRootCause(e).getMessage().contains("Auth fail")) {
// System.err.printf("bad credentials: %s:%s for %s%n", // System.err.printf("bad credentials: %s:%s for %s%n",
@ -319,31 +327,32 @@ public abstract class BaseComputeServiceLiveTest {
public static String buildScript(OsFamily osFamily) { public static String buildScript(OsFamily osFamily) {
switch (osFamily) { switch (osFamily) {
case UBUNTU: case UBUNTU:
return new StringBuilder()// return new StringBuilder()//
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")// .append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")//
.append("cp /etc/apt/sources.list /etc/apt/sources.list.old\n")// .append("cp /etc/apt/sources.list /etc/apt/sources.list.old\n")//
.append( .append(
"sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list\n")// "sed 's~us.archive.ubuntu.com~mirror.anl.gov/pub~g' /etc/apt/sources.list.old >/etc/apt/sources.list\n")//
.append("apt-get update\n")// .append("apt-get update\n")//
.append("apt-get install -f -y --force-yes openjdk-6-jdk\n")// .append("apt-get install -f -y --force-yes openjdk-6-jdk\n")//
.append("wget -qO/usr/bin/runurl run.alestic.com/runurl\n")// .append("wget -qO/usr/bin/runurl run.alestic.com/runurl\n")//
.append("chmod 755 /usr/bin/runurl\n")// .append("chmod 755 /usr/bin/runurl\n")//
.toString(); .toString();
case CENTOS: case CENTOS:
case RHEL: case RHEL:
return new StringBuilder() return new StringBuilder()
.append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n") .append("echo nameserver 208.67.222.222 >> /etc/resolv.conf\n")
.append("echo \"[jdkrepo]\" >> /etc/yum.repos.d/CentOS-Base.repo\n") .append("echo \"[jdkrepo]\" >> /etc/yum.repos.d/CentOS-Base.repo\n")
.append("echo \"name=jdkrepository\" >> /etc/yum.repos.d/CentOS-Base.repo\n") .append("echo \"name=jdkrepository\" >> /etc/yum.repos.d/CentOS-Base.repo\n")
.append( .append(
"echo \"baseurl=http://ec2-us-east-mirror.rightscale.com/epel/5/i386/\" >> /etc/yum.repos.d/CentOS-Base.repo\n") "echo \"baseurl=http://ec2-us-east-mirror.rightscale.com/epel/5/i386/\" >> /etc/yum.repos.d/CentOS-Base.repo\n")
.append("echo \"enabled=1\" >> /etc/yum.repos.d/CentOS-Base.repo\n").append( .append("echo \"enabled=1\" >> /etc/yum.repos.d/CentOS-Base.repo\n")
"yum --nogpgcheck -y install java-1.6.0-openjdk\n").append( .append("yum --nogpgcheck -y install java-1.6.0-openjdk\n")
"echo \"export PATH=\\\"/usr/lib/jvm/jre-1.6.0-openjdk/bin/:\\$PATH\\\"\" >> /root/.bashrc\n") .append(
.toString(); "echo \"export PATH=\\\"/usr/lib/jvm/jre-1.6.0-openjdk/bin/:\\$PATH\\\"\" >> /root/.bashrc\n")
default: .toString();
throw new IllegalArgumentException(osFamily.toString()); default:
throw new IllegalArgumentException(osFamily.toString());
} }
} }
@ -367,7 +376,7 @@ public abstract class BaseComputeServiceLiveTest {
protected void assertNodeZero(Set<? extends NodeMetadata> metadataSet) { protected void assertNodeZero(Set<? 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")
@ -377,7 +386,7 @@ public abstract class BaseComputeServiceLiveTest {
testGet(); testGet();
} }
@Test(enabled = true/* , dependsOnMethods = "testTemplateMatch" */) @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */)
public void testTemplateOptions() throws Exception { public void testTemplateOptions() throws Exception {
TemplateOptions options = new TemplateOptions().withMetadata(); TemplateOptions options = new TemplateOptions().withMetadata();
Template t = client.templateBuilder().smallest().options(options).build(); Template t = client.templateBuilder().smallest().options(options).build();
@ -428,26 +437,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;
} }
} }
} }
@ -489,6 +498,30 @@ public abstract class BaseComputeServiceLiveTest {
} }
} }
@Test(enabled = true)
public void testCompareSizes() throws Exception {
Size defaultSize = client.templateBuilder().build().getSize();
Size smallest = client.templateBuilder().smallest().build().getSize();
Size fastest = client.templateBuilder().fastest().build().getSize();
Size biggest = client.templateBuilder().biggest().build().getSize();
System.out.printf("smallest %s%n", smallest);
System.out.printf("fastest %s%n", fastest);
System.out.printf("biggest %s%n", biggest);
assertEquals(defaultSize, smallest);
assert smallest.getCores() <= fastest.getCores() : String.format("%d ! <= %d", smallest, fastest);
assert biggest.getCores() <= fastest.getCores() : String.format("%d ! <= %d", biggest, fastest);
assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest);
assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest);
assert fastest.getCores() >= biggest.getCores() : String.format("%d ! >= %d", fastest, biggest);
assert fastest.getCores() >= smallest.getCores() : String.format("%d ! >= %d", fastest, smallest);
}
private void sshPing(NodeMetadata node) throws IOException { private void sshPing(NodeMetadata node) throws IOException {
for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate. for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate.
try { try {

View File

@ -41,9 +41,10 @@ import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.util.Providers;
/** /**
* *
@ -62,11 +63,11 @@ public class TemplateBuilderImplTest {
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(),
1.0, 0, 0, ImagePredicates.any()); 1.0, 0, 0, ImagePredicates.any());
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
.<Image> of(image, image2)); image, image2));
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size)); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -87,10 +88,10 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
assertEquals(template.resolveImage(size), image2); assertEquals(template.resolveImage(size,images.get()), image2);
verify(image); verify(image);
verify(image2); verify(image2);
@ -110,11 +111,11 @@ public class TemplateBuilderImplTest {
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(),
1.0, 0, 0, ImagePredicates.any()); 1.0, 0, 0, ImagePredicates.any());
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
.<Image> of(image, image2)); image, image2));
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size)); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -134,7 +135,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
assertEquals(template.smallest().architecture(Architecture.X86_32).build().getImage(), image); assertEquals(template.smallest().architecture(Architecture.X86_32).build().getImage(), image);
@ -155,10 +156,11 @@ public class TemplateBuilderImplTest {
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0,
0, 0, ImagePredicates.idEquals("imageId")); 0, 0, ImagePredicates.idEquals("imageId"));
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of(image)); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size)); .<Image> of(image));
Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -166,11 +168,11 @@ public class TemplateBuilderImplTest {
expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(optionsProvider.get()).andReturn(new TemplateOptions());
expect(image.getId()).andReturn("imageId").atLeastOnce(); expect(image.getId()).andReturn("imageId").atLeastOnce();
expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce(); expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce();
expect(image.getOsFamily()).andReturn(null); expect(image.getOsFamily()).andReturn(null).atLeastOnce();
expect(image.getName()).andReturn(null); expect(image.getName()).andReturn(null).atLeastOnce();
expect(image.getDescription()).andReturn(null); expect(image.getDescription()).andReturn(null).atLeastOnce();
expect(image.getOsDescription()).andReturn(null); expect(image.getOsDescription()).andReturn(null).atLeastOnce();
expect(image.getVersion()).andReturn(null); expect(image.getVersion()).andReturn(null).atLeastOnce();
expect(image.getArchitecture()).andReturn(null).atLeastOnce(); expect(image.getArchitecture()).andReturn(null).atLeastOnce();
replay(image); replay(image);
@ -179,7 +181,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
template.imageId("imageId").build(); template.imageId("imageId").build();
@ -199,24 +201,32 @@ public class TemplateBuilderImplTest {
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0,
0, 0, ImagePredicates.idEquals("imageId")); 0, 0, ImagePredicates.idEquals("imageId"));
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of(image)); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size)); .<Image> of(image));
Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(optionsProvider.get()).andReturn(new TemplateOptions());
expect(image.getId()).andReturn("notImageId").atLeastOnce(); expect(image.getId()).andReturn("notImageId").atLeastOnce();
expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce();
expect(image.getOsFamily()).andReturn(null).atLeastOnce();
expect(image.getName()).andReturn(null).atLeastOnce();
expect(image.getDescription()).andReturn(null).atLeastOnce();
expect(image.getOsDescription()).andReturn(null).atLeastOnce();
expect(image.getVersion()).andReturn(null).atLeastOnce();
expect(image.getArchitecture()).andReturn(null).atLeastOnce();
replay(image); replay(image);
replay(defaultTemplate); replay(defaultTemplate);
replay(defaultLocation); replay(defaultLocation);
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(image, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("notImageId").build(); template.imageId("notImageId").build();
@ -236,10 +246,10 @@ public class TemplateBuilderImplTest {
TemplateOptions options = provideTemplateOptions(); TemplateOptions options = provideTemplateOptions();
TemplateOptions from = provideTemplateOptions(); TemplateOptions from = provideTemplateOptions();
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -255,7 +265,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
template.options(options).build(); template.options(options).build();
@ -270,10 +280,10 @@ public class TemplateBuilderImplTest {
@Test @Test
public void testNothingUsesDefaultTemplateBuilder() { public void testNothingUsesDefaultTemplateBuilder() {
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
@ -288,7 +298,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
template.build(); template.build();
@ -299,21 +309,21 @@ public class TemplateBuilderImplTest {
verify(templateBuilderProvider); verify(templateBuilderProvider);
} }
protected TemplateBuilderImpl createTemplateBuilder(Provider<Set<? extends Location>> locations, protected TemplateBuilderImpl createTemplateBuilder( Image knownImage, Supplier<Set<? extends Location>> locations,
Provider<Set<? extends Image>> images, Provider<Set<? extends Size>> sizes, Location defaultLocation, Supplier<Set<? extends Image>> images, Supplier<Set<? extends Size>> sizes, Location defaultLocation,
Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) { Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, defaultLocation, TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, Suppliers
optionsProvider, templateBuilderProvider); .ofInstance(defaultLocation), optionsProvider, templateBuilderProvider);
return template; return template;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testSuppliedLocationWithNoOptions() { public void testSuppliedLocationWithNoOptions() {
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -324,7 +334,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
try { try {
@ -345,10 +355,10 @@ public class TemplateBuilderImplTest {
public void testSuppliedLocationAndOptions() { public void testSuppliedLocationAndOptions() {
TemplateOptions from = provideTemplateOptions(); TemplateOptions from = provideTemplateOptions();
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -359,7 +369,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
try { try {
@ -377,10 +387,10 @@ public class TemplateBuilderImplTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testDefaultLocationWithNoOptionsNoSuchElement() { public void testDefaultLocationWithNoOptionsNoSuchElement() {
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -393,7 +403,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
try { try {
@ -416,10 +426,10 @@ public class TemplateBuilderImplTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testDefaultLocationWithOptions() { public void testDefaultLocationWithOptions() {
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
TemplateOptions from = provideTemplateOptions(); TemplateOptions from = provideTemplateOptions();
@ -433,7 +443,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
try { try {
@ -451,10 +461,10 @@ public class TemplateBuilderImplTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testImageIdNullsEverythingElse() { public void testImageIdNullsEverythingElse() {
Provider<Set<? extends Location>> locations = Providers Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Location> of());
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of()); Supplier<Set<? extends Size>> sizes = Suppliers.<Set<? extends Size>> ofInstance(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -463,7 +473,7 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider, TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation, optionsProvider,
templateBuilderProvider); templateBuilderProvider);
template.architecture(Architecture.X86_32); template.architecture(Architecture.X86_32);

View File

@ -19,86 +19,66 @@
package org.jclouds.gogrid.compute.config; package org.jclouds.gogrid.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.domain.OsFamily.CENTOS; import static org.jclouds.compute.domain.OsFamily.CENTOS;
import static org.jclouds.compute.predicates.ImagePredicates.architectureIn;
import static org.jclouds.gogrid.reference.GoGridConstants.PROPERTY_GOGRID_DEFAULT_DC; import static org.jclouds.gogrid.reference.GoGridConstants.PROPERTY_GOGRID_DEFAULT_DC;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; 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.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.gogrid.GoGridAsyncClient; import org.jclouds.gogrid.GoGridAsyncClient;
import org.jclouds.gogrid.GoGridClient; import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.compute.functions.ServerToNodeMetadata; import org.jclouds.gogrid.compute.functions.ServerToNodeMetadata;
import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy; import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy;
import org.jclouds.gogrid.domain.Option; import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy;
import org.jclouds.gogrid.domain.PowerCommand; 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.GoGridImageSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridLocationSupplier;
import org.jclouds.gogrid.compute.suppliers.GoGridSizeSupplier;
import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.Server;
import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.gogrid.domain.ServerState; import org.jclouds.gogrid.domain.ServerState;
import org.jclouds.gogrid.predicates.ServerLatestJobCompleted;
import org.jclouds.gogrid.util.GoGridUtils;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.inject.Injector;
import com.google.common.collect.Sets; import com.google.inject.Key;
import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
import com.google.inject.util.Providers; import com.google.inject.util.Providers;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
* @author Adrian Cole * @author Adrian Cole
*/ */
public class GoGridComputeServiceContextModule extends AbstractModule { public class GoGridComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
@ -119,135 +99,21 @@ public class GoGridComputeServiceContextModule extends AbstractModule {
bind(DestroyNodeStrategy.class).to(GoGridDestroyNodeStrategy.class); bind(DestroyNodeStrategy.class).to(GoGridDestroyNodeStrategy.class);
} }
@Provides @Override
@Singleton protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected Map<String, ? extends Location> provideLocationMap(Set<? extends Location> locations) {
return Maps.uniqueIndex(locations, new Function<Location, String>() {
@Override
public String apply(Location from) {
return from.getId();
}
});
}
@Provides
@Named("DEFAULT")
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.osFamily(CENTOS).imageNameMatches(".*w/ None.*"); return template.osFamily(CENTOS).imageNameMatches(".*w/ None.*");
} }
@Provides
@Named("NAMING_CONVENTION")
@Singleton
String provideNamingConvention() {
return "%s-%s";
}
@Singleton
public static class GoGridRebootNodeStrategy implements RebootNodeStrategy {
private final GoGridClient client;
private final RetryablePredicate<Server> serverLatestJobCompleted;
private final RetryablePredicate<Server> serverLatestJobCompletedShort;
private final GetNodeMetadataStrategy getNode;
@Inject
protected GoGridRebootNodeStrategy(GoGridClient client, GetNodeMetadataStrategy getNode, Timeouts timeouts) {
this.client = client;
this.serverLatestJobCompleted = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 9l / 10l);
this.serverLatestJobCompletedShort = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 1l / 10l);
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
client.getServerServices().power(server.getName(), PowerCommand.RESTART);
serverLatestJobCompleted.apply(server);
client.getServerServices().power(server.getName(), PowerCommand.START);
serverLatestJobCompletedShort.apply(server);
return getNode.execute(id);
}
}
@Singleton
public static class GoGridListNodesStrategy implements ListNodesStrategy {
private final GoGridClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected GoGridListNodesStrategy(GoGridClient client, Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.getServerServices().getServerList(), serverToNodeMetadata),
filter);
}
}
@Singleton
public static class GoGridGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final GoGridClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected GoGridGetNodeMetadataStrategy(GoGridClient client, Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
try {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(
new Long(checkNotNull(id, "id"))));
return server == null ? null : serverToNodeMetadata.apply(server);
} catch (NoSuchElementException e) {
return null;
}
}
}
@Singleton
public static class GoGridDestroyNodeStrategy implements DestroyNodeStrategy {
private final GoGridClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected GoGridDestroyNodeStrategy(GoGridClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
client.getServerServices().deleteById(new Long(id));
return getNode.execute(id);
}
}
@VisibleForTesting @VisibleForTesting
static final Map<ServerState, NodeState> serverStateToNodeState = ImmutableMap.<ServerState, NodeState> builder() static final Map<ServerState, NodeState> serverStateToNodeState = ImmutableMap.<ServerState, NodeState> builder()
.put(ServerState.ON, NodeState.RUNNING)// .put(ServerState.ON, NodeState.RUNNING)//
.put(ServerState.STARTING, NodeState.PENDING)// .put(ServerState.STARTING, NodeState.PENDING)//
.put(ServerState.OFF, NodeState.SUSPENDED)// .put(ServerState.OFF, NodeState.SUSPENDED)//
.put(ServerState.STOPPING, NodeState.PENDING)// .put(ServerState.STOPPING, NodeState.PENDING)//
.put(ServerState.RESTARTING, NodeState.PENDING)// .put(ServerState.RESTARTING, NodeState.PENDING)//
.put(ServerState.SAVING, NodeState.PENDING)// .put(ServerState.SAVING, NodeState.PENDING)//
.put(ServerState.RESTORING, NodeState.PENDING)// .put(ServerState.RESTORING, NodeState.PENDING)//
.put(ServerState.UPDATING, NodeState.PENDING).build(); .put(ServerState.UPDATING, NodeState.PENDING).build();
@Singleton @Singleton
@Provides @Provides
@ -256,13 +122,11 @@ public class GoGridComputeServiceContextModule extends AbstractModule {
} }
/** /**
* Finds matches to required configurations. GoGrid's documentation only * Finds matches to required configurations. GoGrid's documentation only specifies how much RAM
* specifies how much RAM one can get with different instance types. The # of * one can get with different instance types. The # of cores and disk sizes are purely empyrical
* cores and disk sizes are purely empyrical and aren't guaranteed. However, * and aren't guaranteed. However, these are the matches found: Ram: 512MB, CPU: 1 core, HDD: 28
* these are the matches found: Ram: 512MB, CPU: 1 core, HDD: 28 GB Ram: 1GB, * GB Ram: 1GB, CPU: 1 core, HDD: 57 GB Ram: 2GB, CPU: 1 core, HDD: 113 GB Ram: 4GB, CPU: 3
* CPU: 1 core, HDD: 57 GB Ram: 2GB, CPU: 1 core, HDD: 113 GB Ram: 4GB, CPU: * cores, HDD: 233 GB Ram: 8GB, CPU: 6 cores, HDD: 462 GB (as of March 2010)
* 3 cores, HDD: 233 GB Ram: 8GB, CPU: 6 cores, HDD: 462 GB (as of March
* 2010)
* *
* @return matched size * @return matched size
*/ */
@ -285,104 +149,39 @@ public class GoGridComputeServiceContextModule extends AbstractModule {
}; };
} }
@Provides @Override
@Singleton protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
Location getDefaultLocation(@Named(PROPERTY_GOGRID_DEFAULT_DC) final String defaultDC, final String defaultDC = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_GOGRID_DEFAULT_DC)));
Set<? extends Location> locations) { return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
return Iterables.find(locations, new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public Location apply(Set<? extends Location> from) {
return input.getId().equals(defaultDC); return Iterables.find(from, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultDC);
}
});
} }
}); }, locations);
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
Set<? extends Location> getAssignableLocations(@Provider String providerName, GoGridClient sync, LogHolder holder, return injector.getInstance(GoGridImageSupplier.class);
Function<ComputeMetadata, String> indexer) {
final Set<Location> locations = Sets.newHashSet();
holder.logger.debug(">> providing locations");
Location parent = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (Option dc : sync.getServerServices().getDatacenters())
locations.add(new LocationImpl(LocationScope.ZONE, dc.getId() + "", dc.getDescription(), parent));
holder.logger.debug("<< locations(%d)", locations.size());
return locations;
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
protected Function<ComputeMetadata, String> indexer() { return injector.getInstance(GoGridLocationSupplier.class);
return new Function<ComputeMetadata, String>() {
@Override
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
protected Set<? extends Size> provideSizes(GoGridClient sync, Set<? extends Image> images, LogHolder holder, return injector.getInstance(GoGridSizeSupplier.class);
Function<ComputeMetadata, String> indexer) throws InterruptedException, TimeoutException, ExecutionException {
final Set<Size> sizes = Sets.newHashSet();
holder.logger.debug(">> providing sizes");
sizes.add(new SizeImpl("1", "1", "1", null, null, ImmutableMap.<String, String> of(), 0.5, 512, 30,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("2", "2", "2", null, null, ImmutableMap.<String, String> of(), 1, 1024, 60,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("3", "3", "3", null, null, ImmutableMap.<String, String> of(), 2, 2048, 120,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("4", "4", "4", null, null, ImmutableMap.<String, String> of(), 4, 4096, 240,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("5", "5", "5", null, null, ImmutableMap.<String, String> of(), 8, 8192, 480,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
holder.logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
}
public static final Pattern GOGRID_OS_NAME_PATTERN = Pattern.compile("([a-zA-Z]*)(.*)");
@Provides
@Singleton
protected Set<? extends Image> provideImages(final GoGridClient sync, LogHolder holder,
Function<ComputeMetadata, String> indexer, Location location,
PopulateDefaultLoginCredentialsForImageStrategy authenticator) throws InterruptedException,
ExecutionException, TimeoutException {
final Set<Image> images = Sets.newHashSet();
holder.logger.debug(">> providing images");
Set<ServerImage> allImages = sync.getImageServices().getImageList();
for (ServerImage from : allImages) {
OsFamily os = null;
Architecture arch = (from.getOs().getName().indexOf("64") == -1 && from.getDescription().indexOf("64") == -1) ? Architecture.X86_32
: Architecture.X86_64;
String osDescription;
String version = "";
osDescription = from.getOs().getName();
String matchedOs = GoGridUtils.parseStringByPatternAndGetNthMatchGroup(from.getOs().getName(),
GOGRID_OS_NAME_PATTERN, 1);
try {
os = OsFamily.fromValue(matchedOs.toLowerCase());
} catch (IllegalArgumentException e) {
holder.logger.debug("<< didn't match os(%s)", matchedOs);
}
Credentials defaultCredentials = authenticator.execute(from);
images.add(new ImageImpl(from.getId() + "", from.getFriendlyName(), from.getId() + "", location, null,
ImmutableMap.<String, String> of(), from.getDescription(), version, os, osDescription, arch,
defaultCredentials));
}
holder.logger.debug("<< images(%d)", images.size());
return images;
} }
} }

View File

@ -43,6 +43,7 @@ import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -58,8 +59,8 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final Map<ServerState, NodeState> serverStateToNodeState; private final Map<ServerState, NodeState> serverStateToNodeState;
private final GoGridClient client; private final GoGridClient client;
private final Set<? extends Image> images; private final Supplier<Set<? extends Image>> images;
private final Map<String, ? extends Location> locations; private final Supplier<Map<String, ? extends Location>> locations;
private static class FindImageForServer implements Predicate<Image> { private static class FindImageForServer implements Predicate<Image> {
private final Server instance; private final Server instance;
@ -79,7 +80,7 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Inject @Inject
ServerToNodeMetadata(Map<ServerState, NodeState> serverStateToNodeState, GoGridClient client, ServerToNodeMetadata(Map<ServerState, NodeState> serverStateToNodeState, GoGridClient client,
Set<? extends Image> images, Map<String, ? extends Location> locations) { Supplier<Set<? extends Image>> images, Supplier<Map<String, ? extends Location>> locations) {
this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
@ -94,13 +95,12 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
Credentials creds = client.getServerServices().getServerCredentialsList().get(from.getName()); Credentials creds = client.getServerServices().getServerCredentialsList().get(from.getName());
Image image = null; Image image = null;
try { try {
image = Iterables.find(images, new FindImageForServer(from)); image = Iterables.find(images.get(), new FindImageForServer(from));
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s", from); logger.warn("could not find a matching image for server %s", from);
} }
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", locations.get(from return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", locations.get().get(
.getDatacenter().getId() from.getDatacenter().getId() + ""), null, ImmutableMap.<String, String> of(), tag, image, state, ipSet,
+ ""), null, ImmutableMap.<String, String> of(), tag, image, state, ipSet, ImmutableList.<String> of(), ImmutableList.<String> of(), ImmutableMap.<String, String> of(), creds);
ImmutableMap.<String, String> of(), creds);
} }
} }

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.gogrid.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.gogrid.GoGridClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridDestroyNodeStrategy implements DestroyNodeStrategy {
private final GoGridClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected GoGridDestroyNodeStrategy(GoGridClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
client.getServerServices().deleteById(new Long(id));
return getNode.execute(id);
}
}

View File

@ -0,0 +1,62 @@
/**
*
* 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.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.NoSuchElementException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.Server;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final GoGridClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected GoGridGetNodeMetadataStrategy(GoGridClient client, Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
try {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(
new Long(checkNotNull(id, "id"))));
return server == null ? null : serverToNodeMetadata.apply(server);
} catch (NoSuchElementException e) {
return null;
}
}
}

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.gogrid.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.Server;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridListNodesStrategy implements ListNodesStrategy {
private final GoGridClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected GoGridListNodesStrategy(GoGridClient client, Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.getServerServices().getServerList(), serverToNodeMetadata),
filter);
}
}

View File

@ -0,0 +1,67 @@
/**
*
* 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.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.PowerCommand;
import org.jclouds.gogrid.domain.Server;
import org.jclouds.gogrid.predicates.ServerLatestJobCompleted;
import org.jclouds.predicates.RetryablePredicate;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridRebootNodeStrategy implements RebootNodeStrategy {
private final GoGridClient client;
private final RetryablePredicate<Server> serverLatestJobCompleted;
private final RetryablePredicate<Server> serverLatestJobCompletedShort;
private final GetNodeMetadataStrategy getNode;
@Inject
protected GoGridRebootNodeStrategy(GoGridClient client, GetNodeMetadataStrategy getNode, Timeouts timeouts) {
this.client = client;
this.serverLatestJobCompleted = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 9l / 10l);
this.serverLatestJobCompletedShort = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client
.getJobServices()), timeouts.nodeRunning * 1l / 10l);
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(new Long(id)));
client.getServerServices().power(server.getName(), PowerCommand.RESTART);
serverLatestJobCompleted.apply(server);
client.getServerServices().power(server.getName(), PowerCommand.START);
serverLatestJobCompletedShort.apply(server);
return getNode.execute(id);
}
}

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.gogrid.compute.suppliers;
import java.util.Set;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.gogrid.util.GoGridUtils;
import org.jclouds.logging.Logger;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridImageSupplier implements Supplier<Set<? extends Image>> {
public static final Pattern GOGRID_OS_NAME_PATTERN = Pattern.compile("([a-zA-Z]*)(.*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final GoGridClient sync;
private final PopulateDefaultLoginCredentialsForImageStrategy authenticator;
@Inject
GoGridImageSupplier(final GoGridClient sync, PopulateDefaultLoginCredentialsForImageStrategy authenticator) {
this.sync = sync;
this.authenticator = authenticator;
}
@Override
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
logger.debug(">> providing images");
Set<ServerImage> allImages = sync.getImageServices().getImageList();
for (ServerImage from : allImages) {
OsFamily os = null;
Architecture arch = (from.getOs().getName().indexOf("64") == -1 && from.getDescription().indexOf("64") == -1) ? Architecture.X86_32
: Architecture.X86_64;
String osDescription;
String version = "";
osDescription = from.getOs().getName();
String matchedOs = GoGridUtils.parseStringByPatternAndGetNthMatchGroup(from.getOs().getName(),
GOGRID_OS_NAME_PATTERN, 1);
try {
os = OsFamily.fromValue(matchedOs.toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matchedOs);
}
Credentials defaultCredentials = authenticator.execute(from);
// TODO determine DC images are in
images.add(new ImageImpl(from.getId() + "", from.getFriendlyName(), from.getId() + "", null, null,
ImmutableMap.<String, String> of(), from.getDescription(), version, os, osDescription, arch,
defaultCredentials));
}
logger.debug("<< images(%d)", images.size());
return images;
}
}

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.gogrid.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.Option;
import org.jclouds.logging.Logger;
import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Supplier;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridLocationSupplier implements Supplier<Set<? extends Location>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final String providerName;
private final GoGridClient sync;
@Inject
GoGridLocationSupplier(@Provider String providerName, GoGridClient sync) {
this.providerName = providerName;
this.sync = sync;
}
@Override
public Set<? extends Location> get() {
final Set<Location> locations = Sets.newHashSet();
logger.debug(">> providing locations");
Location parent = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (Option dc : sync.getServerServices().getDatacenters())
locations.add(new LocationImpl(LocationScope.ZONE, dc.getId() + "", dc.getDescription(), parent));
logger.debug("<< locations(%d)", locations.size());
return locations;
}
}

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.suppliers;
import static org.jclouds.compute.predicates.ImagePredicates.architectureIn;
import java.util.Set;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.internal.SizeImpl;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class GoGridSizeSupplier implements Supplier<Set<? extends Size>> {
@Override
public Set<? extends Size> get() {
final Set<Size> sizes = Sets.newHashSet();
sizes.add(new SizeImpl("1", "1", "1", null, null, ImmutableMap.<String, String> of(), 0.5, 512, 30,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("2", "2", "2", null, null, ImmutableMap.<String, String> of(), 1, 1024, 60,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("3", "3", "3", null, null, ImmutableMap.<String, String> of(), 2, 2048, 120,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("4", "4", "4", null, null, ImmutableMap.<String, String> of(), 4, 4096, 240,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
sizes.add(new SizeImpl("5", "5", "5", null, null, ImmutableMap.<String, String> of(), 8, 8192, 480,
architectureIn(ImmutableSet.<Architecture> of(Architecture.X86_32, Architecture.X86_64))));
return sizes;
}
}

View File

@ -17,7 +17,7 @@
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.gogrid; package org.jclouds.gogrid.compute;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
@ -26,6 +26,8 @@ import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.Architecture;
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.gogrid.GoGridAsyncClient;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;

View File

@ -29,6 +29,7 @@ import java.net.UnknownHostException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
@ -44,6 +45,7 @@ import org.jclouds.gogrid.domain.ServerState;
import org.jclouds.gogrid.services.GridServerClient; import org.jclouds.gogrid.services.GridServerClient;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -63,7 +65,7 @@ public class ServerToNodeMetadataTest {
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter"); Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter");
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage); Set<? extends org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Server server = createMock(Server.class); Server server = createMock(Server.class);
expect(server.getId()).andReturn(1000l).atLeastOnce(); expect(server.getId()).andReturn(1000l).atLeastOnce();
@ -95,7 +97,9 @@ public class ServerToNodeMetadataTest {
replay(jcImage); replay(jcImage);
replay(credentialsMap); replay(credentialsMap);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, caller, images, locations); ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, caller, Suppliers
.<Set<? extends Image>> ofInstance(images), Suppliers
.<Map<String, ? extends Location>> ofInstance(locations));
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata.getLocation(), location); assertEquals(metadata.getLocation(), location);

View File

@ -22,7 +22,6 @@ package org.jclouds.ibmdev;
import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_API_VERSION;
import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.Constants.PROPERTY_ENDPOINT;
import static org.jclouds.compute.reference.ComputeServiceConstants.PROPERTY_TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.reference.ComputeServiceConstants.PROPERTY_TIMEOUT_NODE_RUNNING;
import static org.jclouds.ibmdev.reference.IBMDeveloperCloudConstants.PROPERTY_IBMDEVELOPERCLOUD_LOCATION;
import java.util.Properties; import java.util.Properties;
@ -39,7 +38,6 @@ public class IBMDeveloperCloudPropertiesBuilder extends PropertiesBuilder {
Properties properties = super.defaultProperties(); Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_API_VERSION, IBMDeveloperCloudAsyncClient.VERSION); properties.setProperty(PROPERTY_API_VERSION, IBMDeveloperCloudAsyncClient.VERSION);
properties.setProperty(PROPERTY_ENDPOINT, "https://www-147.ibm.com/computecloud/enterprise/api/rest"); properties.setProperty(PROPERTY_ENDPOINT, "https://www-147.ibm.com/computecloud/enterprise/api/rest");
properties.setProperty(PROPERTY_IBMDEVELOPERCLOUD_LOCATION, "1");
properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + ""); properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + "");
return properties; return properties;
} }

View File

@ -19,71 +19,51 @@
package org.jclouds.ibmdev.compute.config; package org.jclouds.ibmdev.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.domain.OsFamily.RHEL; import static org.jclouds.compute.domain.OsFamily.RHEL;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey;
import static org.jclouds.ibmdev.reference.IBMDeveloperCloudConstants.PROPERTY_IBMDEVELOPERCLOUD_LOCATION;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; 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.EncodeTagIntoNameRunNodesAndAddToSetStrategy;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient; import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient;
import org.jclouds.ibmdev.IBMDeveloperCloudClient; import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.compute.functions.InstanceToNodeMetadata; import org.jclouds.ibmdev.compute.functions.InstanceToNodeMetadata;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudAddNodeWithTagStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudDestroyNodeStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudGetNodeMetadataStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudListNodesStrategy;
import org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudRebootNodeStrategy;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudImageSupplier;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudLocationSupplier;
import org.jclouds.ibmdev.compute.suppliers.IBMDeveloperCloudSizeSupplier;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.ibmdev.reference.IBMDeveloperCloudConstants;
import org.jclouds.io.Payload;
import org.jclouds.logging.Logger;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.util.Utils;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
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.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.inject.Injector;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -92,7 +72,7 @@ import com.google.inject.util.Providers;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class IBMDeveloperCloudComputeServiceContextModule extends AbstractModule { public class IBMDeveloperCloudComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
@ -116,19 +96,11 @@ public class IBMDeveloperCloudComputeServiceContextModule extends AbstractModule
/** /**
* tested known configuration * tested known configuration
*/ */
@Provides @Override
@Named("DEFAULT") protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.osFamily(RHEL); return template.osFamily(RHEL);
} }
@Provides
@Named("NAMING_CONVENTION")
@Singleton
String provideNamingConvention() {
return "%s-%s";
}
@Provides @Provides
@Singleton @Singleton
@Named("CREDENTIALS") @Named("CREDENTIALS")
@ -136,103 +108,21 @@ public class IBMDeveloperCloudComputeServiceContextModule extends AbstractModule
return new ConcurrentHashMap<String, String>(); return new ConcurrentHashMap<String, String>();
} }
@Singleton
public static class CreateKeyPairEncodeTagIntoNameRunNodesAndAddToSet extends
EncodeTagIntoNameRunNodesAndAddToSetStrategy {
private final IBMDeveloperCloudClient client;
private final Map<String, String> credentialsMap;
@Inject
protected CreateKeyPairEncodeTagIntoNameRunNodesAndAddToSet(AddNodeWithTagStrategy addNodeWithTagStrategy,
ListNodesStrategy listNodesStrategy, @Named("NAMING_CONVENTION") String nodeNamingConvention,
ComputeUtils utils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,
IBMDeveloperCloudClient client, @Named("CREDENTIALS") Map<String, String> credentialsMap) {
super(addNodeWithTagStrategy, listNodesStrategy, nodeNamingConvention, utils, executor);
this.client = checkNotNull(client, "client");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
}
@Override
public Map<?, Future<Void>> execute(String tag, int count, Template template, Set<NodeMetadata> nodes,
Map<NodeMetadata, Exception> badNodes) {
Payload key = template.getOptions().getPublicKey();
if (key != null) {
String keyAsText;
try {
keyAsText = Utils.toStringAndClose(key.getInput());
} catch (IOException e1) {
throw new RuntimeException(e1);
}
template.getOptions().dontAuthorizePublicKey();
try {
client.addPublicKey(tag, keyAsText);
} catch (IllegalStateException e) {
// must not have been found
client.updatePublicKey(tag, keyAsText);
}
} else {
credentialsMap.put(tag, client.generateKeyPair(tag).getKeyMaterial());
}
return super.execute(tag, count, template, nodes, badNodes);
}
}
@Singleton
public static class IBMDeveloperCloudAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final IBMDeveloperCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudAddNodeWithTagStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = checkNotNull(client, "client");
this.instanceToNodeMetadata = checkNotNull(instanceToNodeMetadata, "instanceToNodeMetadata");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Instance instance = client.createInstanceInLocation(template.getLocation().getId(), name, template.getImage()
.getProviderId(), template.getSize().getProviderId(), authorizePublicKey(tag));
return instanceToNodeMetadata.apply(client.getInstance(instance.getId()));
}
}
@Singleton
public static class IBMDeveloperCloudRebootNodeStrategy implements RebootNodeStrategy {
private final IBMDeveloperCloudClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected IBMDeveloperCloudRebootNodeStrategy(IBMDeveloperCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode");
}
@Override
public NodeMetadata execute(String id) {
client.restartInstance(id);
return getNode.execute(id);
}
}
@VisibleForTesting @VisibleForTesting
static final Map<Instance.Status, NodeState> instanceStatusToNodeState = ImmutableMap static final Map<Instance.Status, NodeState> instanceStatusToNodeState = ImmutableMap
.<Instance.Status, NodeState> builder().put(Instance.Status.ACTIVE, NodeState.RUNNING)// .<Instance.Status, NodeState> builder().put(Instance.Status.ACTIVE, NodeState.RUNNING)//
.put(Instance.Status.STOPPED, NodeState.SUSPENDED)// .put(Instance.Status.STOPPED, NodeState.SUSPENDED)//
.put(Instance.Status.REMOVED, NodeState.TERMINATED)// .put(Instance.Status.REMOVED, NodeState.TERMINATED)//
.put(Instance.Status.DEPROVISIONING, NodeState.PENDING)// .put(Instance.Status.DEPROVISIONING, NodeState.PENDING)//
.put(Instance.Status.FAILED, NodeState.ERROR)// .put(Instance.Status.FAILED, NodeState.ERROR)//
.put(Instance.Status.NEW, NodeState.PENDING)// .put(Instance.Status.NEW, NodeState.PENDING)//
.put(Instance.Status.PROVISIONING, NodeState.PENDING)// .put(Instance.Status.PROVISIONING, NodeState.PENDING)//
.put(Instance.Status.REJECTED, NodeState.ERROR)// .put(Instance.Status.REJECTED, NodeState.ERROR)//
.put(Instance.Status.RESTARTING, NodeState.PENDING)// .put(Instance.Status.RESTARTING, NodeState.PENDING)//
.put(Instance.Status.STARTING, NodeState.PENDING)// .put(Instance.Status.STARTING, NodeState.PENDING)//
.put(Instance.Status.STOPPING, NodeState.PENDING)// .put(Instance.Status.STOPPING, NodeState.PENDING)//
.put(Instance.Status.DEPROVISION_PENDING, NodeState.PENDING)// .put(Instance.Status.DEPROVISION_PENDING, NodeState.PENDING)//
.put(Instance.Status.UNKNOWN, NodeState.UNKNOWN).build(); .put(Instance.Status.UNKNOWN, NodeState.UNKNOWN).build();
@Singleton @Singleton
@Provides @Provides
@ -240,211 +130,18 @@ public class IBMDeveloperCloudComputeServiceContextModule extends AbstractModule
return instanceStatusToNodeState; return instanceStatusToNodeState;
} }
@Singleton @Override
public static class IBMDeveloperCloudListNodesStrategy implements ListNodesStrategy { protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
private final IBMDeveloperCloudClient client; return injector.getInstance(IBMDeveloperCloudImageSupplier.class);
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudListNodesStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listInstances(), instanceToNodeMetadata), filter);
}
} }
@Singleton @Override
public static class IBMDeveloperCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy { protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
private final IBMDeveloperCloudClient client; return injector.getInstance(IBMDeveloperCloudSizeSupplier.class);
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudGetNodeMetadataStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
Instance instance = client.getInstance(checkNotNull(id, "id"));
return instance == null ? null : instanceToNodeMetadata.apply(instance);
}
} }
@Singleton @Override
public static class IBMDeveloperCloudDestroyNodeStrategy implements DestroyNodeStrategy { protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
private final IBMDeveloperCloudClient client; return injector.getInstance(IBMDeveloperCloudLocationSupplier.class);
private final GetNodeMetadataStrategy getNode;
@Inject
protected IBMDeveloperCloudDestroyNodeStrategy(IBMDeveloperCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode");
}
@Override
public NodeMetadata execute(String id) {
client.deleteInstance(id);
return getNode.execute(id);
}
}
@Provides
@Singleton
Location getDefaultLocation(@Named(PROPERTY_IBMDEVELOPERCLOUD_LOCATION) final String defaultLocation,
Set<? extends Location> locations) {
return Iterables.find(locations, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultLocation);
}
});
}
@Provides
@Singleton
Set<? extends Location> getAssignableLocations(IBMDeveloperCloudClient sync, LogHolder holder,
@org.jclouds.rest.annotations.Provider String providerName) {
final Set<Location> assignableLocations = Sets.newHashSet();
holder.logger.debug(">> providing locations");
Location parent = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (org.jclouds.ibmdev.domain.Location location : sync.listLocations())
assignableLocations.add(new LocationImpl(LocationScope.ZONE, location.getId(), location.getName(), parent));
holder.logger.debug("<< locations(%d)", assignableLocations.size());
return assignableLocations;
}
@Provides
@Singleton
protected Set<? extends Size> provideSizes(IBMDeveloperCloudClient sync, LogHolder holder,
Map<String, ? extends Location> locations) {
final Set<Size> sizes = Sets.newHashSet();
holder.logger.debug(">> providing sizes");
for (org.jclouds.ibmdev.domain.Location location : sync.listLocations()) {
Location assignedLocation = locations.get(location.getId());
// TODO we cannot query actual size, yet, so lets make the
// multipliers work out
int sizeMultiplier = 1;
for (String i386 : location.getCapabilities().get(IBMDeveloperCloudConstants.CAPABILITY_I386).keySet())
sizes.add(buildSize(location, i386, assignedLocation, sizeMultiplier++));
for (String x86_64 : location.getCapabilities().get(IBMDeveloperCloudConstants.CAPABILITY_x86_64).keySet())
sizes.add(buildSize(location, x86_64, assignedLocation, sizeMultiplier++));
}
holder.logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
private SizeImpl buildSize(org.jclouds.ibmdev.domain.Location location, final String id, Location assignedLocation,
int multiplier) {
return new SizeImpl(id, id, location.getId() + "/" + id, assignedLocation, null, ImmutableMap
.<String, String> of(), multiplier, multiplier * 1024, multiplier * 10, new Predicate<Image>() {
@Override
public boolean apply(Image input) {
if (input instanceof IBMImage)
return IBMImage.class.cast(input).rawImage.getSupportedInstanceTypes().contains(id);
return false;
}
});
}
@Provides
@Singleton
protected Map<String, ? extends Image> provideImageMap(Set<? extends Image> locations) {
return Maps.uniqueIndex(locations, new Function<Image, String>() {
@Override
public String apply(Image from) {
return from.getId();
}
});
}
@Provides
@Singleton
protected Map<String, ? extends Location> provideLocationMap(Set<? extends Location> locations) {
return Maps.uniqueIndex(locations, new Function<Location, String>() {
@Override
public String apply(Location from) {
return from.getId();
}
});
}
@Provides
@Singleton
protected Set<? extends Image> provideImages(final IBMDeveloperCloudClient sync, LogHolder holder,
Map<String, ? extends Location> locations) {
final Set<Image> images = Sets.newHashSet();
holder.logger.debug(">> providing images");
for (org.jclouds.ibmdev.domain.Image image : sync.listImages())
images.add(new IBMImage(image, locations.get(image.getLocation())));
holder.logger.debug("<< images(%d)", images.size());
return images;
}
private static class IBMImage extends ImageImpl {
/** The serialVersionUID */
private static final long serialVersionUID = -8520373150950058296L;
private final org.jclouds.ibmdev.domain.Image rawImage;
public IBMImage(org.jclouds.ibmdev.domain.Image in, Location location) {
// TODO parse correct OS
// TODO manifest fails to parse due to encoding issues in the path
// TODO get correct default credentials
// http://www-180.ibm.com/cloud/enterprise/beta/ram/community/_rlvid.jsp.faces?_rap=pc_DiscussionForum.doDiscussionTopic&_rvip=/community/discussionForum.jsp&guid={DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&submission=false&fid=1068&tid=1527
super(in.getId(), in.getName(), in.getId(), location, null, ImmutableMap.<String, String> of(), in
.getDescription(), in.getCreatedTime().getTime() + "",
(in.getPlatform().indexOf("Redhat") != -1) ? OsFamily.RHEL : OsFamily.SUSE, in.getPlatform(), (in
.getPlatform().indexOf("32") != -1) ? Architecture.X86_32 : Architecture.X86_64, new Credentials(
"idcuser", null));
this.rawImage = in;
}
@Override
public boolean equals(Object obj) {
return rawImage.equals(obj);
}
@Override
public int hashCode() {
return rawImage.hashCode();
}
@Override
public String toString() {
return rawImage.toString();
}
}
@Singleton
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
} }
} }

View File

@ -0,0 +1,57 @@
/**
*
* 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.ibmdev.compute.domain;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.collect.ImmutableMap;
/**
* @author Adrian Cole
*/
public class IBMImage extends ImageImpl {
/** The serialVersionUID */
private static final long serialVersionUID = -8520373150950058296L;
private final org.jclouds.ibmdev.domain.Image rawImage;
public IBMImage(org.jclouds.ibmdev.domain.Image in, Location location) {
// TODO parse correct OS
// TODO manifest fails to parse due to encoding issues in the path
// TODO get correct default credentials
// http://www-180.ibm.com/cloud/enterprise/beta/ram/community/_rlvid.jsp.faces?_rap=pc_DiscussionForum.doDiscussionTopic&_rvip=/community/discussionForum.jsp&guid={DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&submission=false&fid=1068&tid=1527
super(in.getId(), in.getName(), in.getId(), location, null, ImmutableMap.<String, String> of(), in
.getDescription(), in.getCreatedTime().getTime() + "",
(in.getPlatform().indexOf("Red Hat") != -1) ? OsFamily.RHEL : OsFamily.SUSE, in.getPlatform(), (in
.getPlatform().indexOf("32") != -1) ? Architecture.X86_32 : Architecture.X86_64,
new Credentials("idcuser", null));
this.rawImage = in;
}
public org.jclouds.ibmdev.domain.Image getRawImage() {
return rawImage;
}
}

View File

@ -0,0 +1,74 @@
/**
*
* 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.ibmdev.compute.domain;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.ibmdev.domain.InstanceType;
import com.google.common.collect.ImmutableMap;
/**
* @author Adrian Cole
*/
public class IBMSize extends SizeImpl {
/** The serialVersionUID */
private static final long serialVersionUID = -8520373150950058296L;
private final IBMImage image;
private final InstanceType instanceType;
// until we can lookup cores by id, we are multiplying price *100 to get a positive integer we
// can compare against.
public IBMSize(IBMImage in, InstanceType instanceType) {
super(instanceType.getId(), instanceType.getLabel(), in.getId() + "/" + instanceType.getId(), in.getLocation(),
in.getRawImage().getManifest(), ImmutableMap.<String, String> of(), (int) (instanceType.getPrice()
.getRate() * 100), (int) (instanceType.getPrice().getRate() * 1024d), (int) (instanceType
.getPrice().getRate() * 100d), null);
this.image = in;
this.instanceType = instanceType;
}
public IBMImage getImage() {
return image;
}
public InstanceType getInstanceType() {
return instanceType;
}
/**
* {@inheritDoc}
*/
@Override
public boolean supportsImage(Image input) {
return image.getId().equals(input.getId());
}
@Override
public String toString() {
return "[id=" + getId() + ", providerId=" + getProviderId() + ", name=" + getName() + ", cores=" + getCores()
+ ", ram=" + getRam() + ", disk=" + getDisk() + ", supportsImage=" + image.getId() + ", rate="
+ instanceType.getPrice().getRate() + "]";
}
}

View File

@ -40,6 +40,7 @@ import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -53,14 +54,14 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final Map<Instance.Status, NodeState> instanceStateToNodeState; private final Map<Instance.Status, NodeState> instanceStateToNodeState;
private final Map<String, ? extends Image> images; private final Supplier<Map<String, ? extends Image>> images;
private final Map<String, String> credentialsMap; private final Map<String, String> credentialsMap;
private final Map<String, ? extends Location> locations; private final Supplier<Map<String, ? extends Location>> locations;
@Inject @Inject
InstanceToNodeMetadata(Map<Instance.Status, NodeState> instanceStateToNodeState, InstanceToNodeMetadata(Map<Instance.Status, NodeState> instanceStateToNodeState,
Map<String, ? extends Image> images, @Named("CREDENTIALS") Map<String, String> credentialsMap, Supplier<Map<String, ? extends Image>> images, @Named("CREDENTIALS") Map<String, String> credentialsMap,
Map<String, ? extends Location> locations) { Supplier<Map<String, ? extends Location>> locations) {
this.instanceStateToNodeState = checkNotNull(instanceStateToNodeState, "instanceStateToNodeState"); this.instanceStateToNodeState = checkNotNull(instanceStateToNodeState, "instanceStateToNodeState");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
@ -72,10 +73,10 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
String tag = parseTagFromName(from.getName()); String tag = parseTagFromName(from.getName());
Set<String> ipSet = from.getIp() != null ? ImmutableSet.of(from.getIp()) : ImmutableSet.<String> of(); Set<String> ipSet = from.getIp() != null ? ImmutableSet.of(from.getIp()) : ImmutableSet.<String> of();
NodeState state = instanceStateToNodeState.get(from.getStatus()); NodeState state = instanceStateToNodeState.get(from.getStatus());
Image image = images.get(from.getImageId()); Image image = images.get().get(from.getImageId());
String key = tag != null ? credentialsMap.get(tag) : null; String key = tag != null ? credentialsMap.get(tag) : null;
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", locations.get(image return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", locations.get().get(
.getLocation()), null, ImmutableMap.<String, String> of(), tag, image, state, ipSet, ImmutableList image.getLocation()), null, ImmutableMap.<String, String> of(), tag, image, state, ipSet, ImmutableList
.<String> of(), ImmutableMap.<String, String> of(), new Credentials( .<String> of(), ImmutableMap.<String, String> of(), new Credentials(
image.getDefaultCredentials().identity, key)); image.getDefaultCredentials().identity, key));
} }

View File

@ -0,0 +1,284 @@
/**
*
* 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.ibmdev.compute.options;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.util.Arrays;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.io.Payload;
import org.jclouds.util.Utils;
/**
* Contains options supported in the {@code ComputeService#runNode} operation on the "ibmdev"
* provider. <h2>
* Usage</h2> The recommended way to instantiate a IBMDeveloperCloudTemplateOptions object is to
* statically import IBMDeveloperCloudTemplateOptions.* and invoke a static creation method followed
* by an instance mutator (if needed):
* <p/>
* <code>
* import static org.jclouds.ibmdev.compute.options.IBMDeveloperCloudTemplateOptions.Builder.*;
* <p/>
* ComputeService client = // get connection
* templateBuilder.options(inboundPorts(22, 80, 8080, 443));
* Set<? extends NodeMetadata> set = client.runNodesWithTag(tag, 2, templateBuilder.build());
* <code>
*
* @author Adrian Cole
*/
public class IBMDeveloperCloudTemplateOptions extends TemplateOptions {
private String keyPair = null;
private boolean noKeyPair;
public static final IBMDeveloperCloudTemplateOptions NONE = new IBMDeveloperCloudTemplateOptions();
/**
* Specifies the keypair used to run instances with
*/
public IBMDeveloperCloudTemplateOptions keyPair(String keyPair) {
checkNotNull(keyPair, "use noKeyPair option to request boot without a keypair");
checkState(!noKeyPair, "you cannot specify both options keyPair and noKeyPair");
Utils.checkNotEmpty(keyPair, "keypair must be non-empty");
this.keyPair = keyPair;
return this;
}
/**
* Do not use a keypair on instances
*/
public IBMDeveloperCloudTemplateOptions noKeyPair() {
checkState(keyPair == null, "you cannot specify both options keyPair and noKeyPair");
this.noKeyPair = true;
return this;
}
public static class Builder {
/**
* @see IBMDeveloperCloudTemplateOptions#keyPair
*/
public static IBMDeveloperCloudTemplateOptions keyPair(String keyPair) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.keyPair(keyPair));
}
/**
* @see IBMDeveloperCloudTemplateOptions#noKeyPair
*/
public static IBMDeveloperCloudTemplateOptions noKeyPair() {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.noKeyPair());
}
// methods that only facilitate returning the correct object type
/**
* @see TemplateOptions#inboundPorts
*/
public static IBMDeveloperCloudTemplateOptions inboundPorts(int... ports) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.inboundPorts(ports));
}
/**
* @see TemplateOptions#port
*/
public static IBMDeveloperCloudTemplateOptions blockOnPort(int port, int seconds) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.blockOnPort(port, seconds));
}
/**
* @see TemplateOptions#blockUntilRunning
*/
public static IBMDeveloperCloudTemplateOptions blockUntilRunning(boolean blockUntilRunning) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.blockUntilRunning(blockUntilRunning));
}
/**
* @see TemplateOptions#runScript
*/
public static IBMDeveloperCloudTemplateOptions runScript(byte[] script) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.runScript(script));
}
/**
* @see TemplateOptions#installPrivateKey
*/
public static IBMDeveloperCloudTemplateOptions installPrivateKey(String rsaKey) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.installPrivateKey(rsaKey));
}
/**
* @see TemplateOptions#authorizePublicKey
*/
public static IBMDeveloperCloudTemplateOptions authorizePublicKey(String rsaKey) {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.authorizePublicKey(rsaKey));
}
/**
* @see TemplateOptions#withDetails
*/
public static IBMDeveloperCloudTemplateOptions withDetails() {
IBMDeveloperCloudTemplateOptions options = new IBMDeveloperCloudTemplateOptions();
return IBMDeveloperCloudTemplateOptions.class.cast(options.withMetadata());
}
}
// methods that only facilitate returning the correct object type
/**
* @see TemplateOptions#blockOnPort
*/
@Override
public IBMDeveloperCloudTemplateOptions blockOnPort(int port, int seconds) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.blockOnPort(port, seconds));
}
/**
*
* special thing is that we do assume if you are passing groups that you have everything you need
* already defined. for example, our option inboundPorts normally creates ingress rules
* accordingly but if we notice you've specified securityGroups, we do not mess with rules at all
*
* @see TemplateOptions#inboundPorts
*/
@Override
public IBMDeveloperCloudTemplateOptions inboundPorts(int... ports) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.inboundPorts(ports));
}
/**
* @see TemplateOptions#authorizePublicKey(String)
*/
@Override
@Deprecated
public IBMDeveloperCloudTemplateOptions authorizePublicKey(String publicKey) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.authorizePublicKey(publicKey));
}
/**
* @see TemplateOptions#authorizePublicKey(Payload)
*/
@Override
public IBMDeveloperCloudTemplateOptions authorizePublicKey(Payload publicKey) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.authorizePublicKey(publicKey));
}
/**
* @see TemplateOptions#installPrivateKey(String)
*/
@Override
@Deprecated
public IBMDeveloperCloudTemplateOptions installPrivateKey(String privateKey) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.installPrivateKey(privateKey));
}
/**
* @see TemplateOptions#installPrivateKey(Payload)
*/
@Override
public IBMDeveloperCloudTemplateOptions installPrivateKey(Payload privateKey) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.installPrivateKey(privateKey));
}
/**
* @see TemplateOptions#runScript(Payload)
*/
@Override
public IBMDeveloperCloudTemplateOptions runScript(Payload script) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.runScript(script));
}
/**
* @see TemplateOptions#runScript(byte[])
*/
@Override
@Deprecated
public IBMDeveloperCloudTemplateOptions runScript(byte[] script) {
return IBMDeveloperCloudTemplateOptions.class.cast(super.runScript(script));
}
/**
* @see TemplateOptions#withMetadata
*/
@Override
public IBMDeveloperCloudTemplateOptions withMetadata() {
return IBMDeveloperCloudTemplateOptions.class.cast(super.withMetadata());
}
/**
* @return keyPair to use when running the instance or null, to generate a keypair.
*/
public String getKeyPair() {
return keyPair;
}
/**
* @return true (default) if we are supposed to use a keypair
*/
public boolean shouldAutomaticallyCreateKeyPair() {
return !noKeyPair;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((keyPair == null) ? 0 : keyPair.hashCode());
result = prime * result + (noKeyPair ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
IBMDeveloperCloudTemplateOptions other = (IBMDeveloperCloudTemplateOptions) obj;
if (keyPair == null) {
if (other.keyPair != null)
return false;
} else if (!keyPair.equals(other.keyPair))
return false;
if (noKeyPair != other.noKeyPair)
return false;
return true;
}
@Override
public String toString() {
return "IBMDeveloperCloudTemplateOptions [keyPair=" + keyPair + ", noKeyPair=" + noKeyPair + ", inboundPorts="
+ Arrays.toString(inboundPorts) + ", privateKey=" + (privateKey != null) + ", publicKey="
+ (publicKey != null) + ", runScript=" + (script != null) + ", port:seconds=" + port + ":" + seconds
+ ", metadata/details: " + includeMetadata + "]";
}
}

View File

@ -0,0 +1,87 @@
/**
*
* 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.ibmdev.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.io.Payload;
import org.jclouds.util.Utils;
/**
* @author Adrian Cole
*/
@Singleton
public class CreateKeyPairEncodeTagIntoNameRunNodesAndAddToSet extends EncodeTagIntoNameRunNodesAndAddToSetStrategy {
private final IBMDeveloperCloudClient client;
private final Map<String, String> credentialsMap;
@Inject
protected CreateKeyPairEncodeTagIntoNameRunNodesAndAddToSet(AddNodeWithTagStrategy addNodeWithTagStrategy,
ListNodesStrategy listNodesStrategy, @Named("NAMING_CONVENTION") String nodeNamingConvention,
ComputeUtils utils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,
IBMDeveloperCloudClient client, @Named("CREDENTIALS") Map<String, String> credentialsMap) {
super(addNodeWithTagStrategy, listNodesStrategy, nodeNamingConvention, utils, executor);
this.client = checkNotNull(client, "client");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
}
@Override
public Map<?, Future<Void>> execute(String tag, int count, Template template, Set<NodeMetadata> nodes,
Map<NodeMetadata, Exception> badNodes) {
Payload key = template.getOptions().getPublicKey();
if (key != null) {
String keyAsText;
try {
keyAsText = Utils.toStringAndClose(key.getInput());
} catch (IOException e1) {
throw new RuntimeException(e1);
}
template.getOptions().dontAuthorizePublicKey();
try {
client.addPublicKey(tag, keyAsText);
} catch (IllegalStateException e) {
// must not have been found
client.updatePublicKey(tag, keyAsText);
}
} else {
credentialsMap.put(tag, client.generateKeyPair(tag).getKeyMaterial());
}
return super.execute(tag, count, template, nodes, badNodes);
}
}

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.ibmdev.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.compute.domain.IBMImage;
import org.jclouds.ibmdev.compute.domain.IBMSize;
import org.jclouds.ibmdev.domain.Instance;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final IBMDeveloperCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudAddNodeWithTagStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = checkNotNull(client, "client");
this.instanceToNodeMetadata = checkNotNull(instanceToNodeMetadata, "instanceToNodeMetadata");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Instance instance = client.createInstanceInLocation(template.getLocation().getId(), name, IBMImage.class.cast(
template.getImage()).getRawImage().getId(), IBMSize.class.cast(template.getSize()).getInstanceType()
.getId(), authorizePublicKey(tag));
return instanceToNodeMetadata.apply(client.getInstance(instance.getId()));
}
}

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.ibmdev.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudDestroyNodeStrategy implements DestroyNodeStrategy {
private final IBMDeveloperCloudClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected IBMDeveloperCloudDestroyNodeStrategy(IBMDeveloperCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode");
}
@Override
public NodeMetadata execute(String id) {
client.deleteInstance(id);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,54 @@
/**
*
* 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.ibmdev.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.domain.Instance;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final IBMDeveloperCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudGetNodeMetadataStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
Instance instance = client.getInstance(checkNotNull(id, "id"));
return instance == null ? null : instanceToNodeMetadata.apply(instance);
}
}

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.ibmdev.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.domain.Instance;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudListNodesStrategy implements ListNodesStrategy {
private final IBMDeveloperCloudClient client;
private final Function<Instance, NodeMetadata> instanceToNodeMetadata;
@Inject
protected IBMDeveloperCloudListNodesStrategy(IBMDeveloperCloudClient client,
Function<Instance, NodeMetadata> instanceToNodeMetadata) {
this.client = client;
this.instanceToNodeMetadata = instanceToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listInstances(), instanceToNodeMetadata), filter);
}
}

View File

@ -0,0 +1,52 @@
/**
*
* 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.ibmdev.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudRebootNodeStrategy implements RebootNodeStrategy {
private final IBMDeveloperCloudClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected IBMDeveloperCloudRebootNodeStrategy(IBMDeveloperCloudClient client, GetNodeMetadataStrategy getNode) {
this.client = checkNotNull(client, "client");
this.getNode = checkNotNull(getNode, "getNode");
}
@Override
public NodeMetadata execute(String id) {
client.restartInstance(id);
return getNode.execute(id);
}
}

View File

@ -17,57 +17,55 @@
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.vcloud.compute.config.providers; package org.jclouds.ibmdev.compute.suppliers;
import static com.google.common.collect.Sets.newLinkedHashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
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.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.compute.domain.IBMImage;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.vcloud.compute.functions.ImagesInOrganization;
import org.jclouds.vcloud.functions.OrganizatonsForLocations;
import com.google.common.collect.Iterables; import com.google.common.base.Supplier;
import com.google.common.collect.Sets;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class VAppTemplatesInVDCs implements Provider<Set<? extends Image>> { public class IBMDeveloperCloudImageSupplier implements Supplier<Set<? extends Image>> {
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
public Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final IBMDeveloperCloudClient sync;
private final Set<? extends Location> locations; private final Supplier<Map<String, ? extends Location>> locations;
private final OrganizatonsForLocations organizatonsForLocations;
private final ImagesInOrganization imagesInOrganization;
@Inject @Inject
VAppTemplatesInVDCs(Set<? extends Location> locations, OrganizatonsForLocations organizatonsForLocations, IBMDeveloperCloudImageSupplier(final IBMDeveloperCloudClient sync,
ImagesInOrganization imagesInOrganization) { Supplier<Map<String, ? extends Location>> locations) {
this.sync = sync;
this.locations = locations; this.locations = locations;
this.organizatonsForLocations = organizatonsForLocations;
this.imagesInOrganization = imagesInOrganization;
} }
/**
* Terremark does not provide vApp templates in the vDC resourceEntity list. Rather, you must
* query the catalog.
*/
@Override @Override
public Set<? extends Image> get() { public Set<? extends Image> get() {
logger.debug(">> providing vAppTemplates"); final Set<Image> images = Sets.newHashSet();
return newLinkedHashSet(Iterables.concat(Iterables.transform(organizatonsForLocations.apply(locations), logger.debug(">> providing images");
imagesInOrganization)));
for (org.jclouds.ibmdev.domain.Image image : sync.listImages())
images.add(new IBMImage(image, locations.get().get(image.getLocation())));
logger.debug("<< images(%d)", images.size());
return images;
} }
} }

View File

@ -0,0 +1,73 @@
/**
*
* 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.ibmdev.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.logging.Logger;
import com.google.common.base.Supplier;
import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudLocationSupplier implements Supplier<Set<? extends Location>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final IBMDeveloperCloudClient sync;
private final String providerName;
@Inject
IBMDeveloperCloudLocationSupplier(IBMDeveloperCloudClient sync,
@org.jclouds.rest.annotations.Provider String providerName) {
this.sync = sync;
this.providerName = providerName;
}
@Override
public Set<? extends Location> get() {
final Set<Location> assignableLocations = Sets.newHashSet();
logger.debug(">> providing locations");
Location parent = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (org.jclouds.ibmdev.domain.Location location : sync.listLocations())
assignableLocations.add(new LocationImpl(LocationScope.ZONE, location.getId(), location.getName(), parent));
logger.debug("<< locations(%d)", assignableLocations.size());
return assignableLocations;
}
}

View File

@ -0,0 +1,68 @@
/**
*
* 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.ibmdev.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.ibmdev.compute.domain.IBMImage;
import org.jclouds.ibmdev.compute.domain.IBMSize;
import org.jclouds.ibmdev.domain.InstanceType;
import org.jclouds.logging.Logger;
import com.google.common.base.Supplier;
import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
@Singleton
public class IBMDeveloperCloudSizeSupplier implements Supplier<Set<? extends Size>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Supplier<Set<? extends Image>> images;
@Inject
IBMDeveloperCloudSizeSupplier(Supplier<Set<? extends Image>> images) {
this.images = images;
}
@Override
public Set<? extends Size> get() {
final Set<Size> sizes = Sets.newHashSet();
logger.debug(">> providing sizes");
for (Image in : images.get()) {
IBMImage image = IBMImage.class.cast(in);
for (InstanceType instanceType : image.getRawImage().getSupportedInstanceTypes())
sizes.add(new IBMSize(image, instanceType));
}
logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
}

View File

@ -19,12 +19,14 @@
package org.jclouds.ibmdev.domain; package org.jclouds.ibmdev.domain;
import com.google.common.collect.ComparisonChain;
/** /**
* *
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class InstanceType { public class InstanceType implements Comparable<InstanceType> {
protected String label; protected String label;
protected Price price; protected Price price;
@ -95,4 +97,8 @@ public class InstanceType {
return "[id=" + id + ", label=" + label + ", price=" + price + "]"; return "[id=" + id + ", label=" + label + ", price=" + price + "]";
} }
@Override
public int compareTo(InstanceType o) {
return ComparisonChain.start().compare(this.getPrice().getRate(), o.getPrice().getRate()).result();
}
} }

View File

@ -29,6 +29,5 @@ public interface IBMDeveloperCloudConstants {
public static final String CAPABILITY_FORMAT = "oss.storage.format"; public static final String CAPABILITY_FORMAT = "oss.storage.format";
public static final String CAPABILITY_I386 = "oss.instance.spec.i386"; public static final String CAPABILITY_I386 = "oss.instance.spec.i386";
public static final String CAPABILITY_x86_64 = "oss.instance.spec.x86_64"; public static final String CAPABILITY_x86_64 = "oss.instance.spec.x86_64";
public static final String PROPERTY_IBMDEVELOPERCLOUD_LOCATION = "jclouds.ibmdev.location";
} }

View File

@ -38,7 +38,7 @@ import org.testng.annotations.Test;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "live", enabled = false, sequential = true, testName = "ibmdevelopercloud.IBMDeveloperCloudComputeServiceLiveTest") @Test(groups = "live", enabled = true, sequential = true, testName = "ibmdevelopercloud.IBMDeveloperCloudComputeServiceLiveTest")
public class IBMDeveloperCloudComputeServiceLiveTestDisabled extends BaseComputeServiceLiveTest { public class IBMDeveloperCloudComputeServiceLiveTestDisabled extends BaseComputeServiceLiveTest {
@BeforeClass @BeforeClass

View File

@ -59,6 +59,7 @@ import org.jclouds.rackspace.cloudfiles.domain.MutableObjectInfoWithMetadata;
import org.jclouds.rackspace.cloudfiles.domain.ObjectInfo; import org.jclouds.rackspace.cloudfiles.domain.ObjectInfo;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -81,8 +82,8 @@ public class CloudFilesAsyncBlobStore extends BaseAsyncBlobStore {
@Inject @Inject
CloudFilesAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, CloudFilesAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Location defaultLocation, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
Set<? extends Location> locations, CloudFilesClient sync, CloudFilesAsyncClient async, Supplier<Set<? extends Location>> locations, CloudFilesClient sync, CloudFilesAsyncClient async,
ContainerToResourceMetadata container2ResourceMd, ContainerToResourceMetadata container2ResourceMd,
BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions,
ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object,

View File

@ -51,6 +51,7 @@ import org.jclouds.rackspace.cloudfiles.blobstore.functions.ObjectToBlobMetadata
import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata; import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
@ -70,13 +71,12 @@ public class CloudFilesBlobStore extends BaseBlobStore {
private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider; private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider;
@Inject @Inject
CloudFilesBlobStore(BlobStoreContext context, BlobUtils blobUtils, Location defaultLocation, CloudFilesBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,
Set<? extends Location> locations, CloudFilesClient sync, Supplier<Set<? extends Location>> locations, CloudFilesClient sync,
ContainerToResourceMetadata container2ResourceMd, ContainerToResourceMetadata container2ResourceMd,
BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions,
ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object,
BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, ObjectToBlobMetadata object2BlobMd, BlobToHttpGetOptions blob2ObjectGetOptions,
BlobToHttpGetOptions blob2ObjectGetOptions,
Provider<FetchBlobMetadata> fetchBlobMetadataProvider) { Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, defaultLocation, locations); super(context, blobUtils, defaultLocation, locations);
this.sync = sync; this.sync = sync;
@ -87,8 +87,7 @@ public class CloudFilesBlobStore extends BaseBlobStore {
this.blob2Object = blob2Object; this.blob2Object = blob2Object;
this.object2BlobMd = object2BlobMd; this.object2BlobMd = object2BlobMd;
this.blob2ObjectGetOptions = blob2ObjectGetOptions; this.blob2ObjectGetOptions = blob2ObjectGetOptions;
this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, "fetchBlobMetadataProvider");
"fetchBlobMetadataProvider");
} }
/** /**
@ -97,10 +96,8 @@ public class CloudFilesBlobStore extends BaseBlobStore {
@Override @Override
public PageSet<? extends StorageMetadata> list() { public PageSet<? extends StorageMetadata> list() {
return new Function<Set<ContainerMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() { return new Function<Set<ContainerMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply( public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(Set<ContainerMetadata> from) {
Set<ContainerMetadata> from) { return new PageSetImpl<StorageMetadata>(Iterables.transform(from, container2ResourceMd), null);
return new PageSetImpl<StorageMetadata>(
Iterables.transform(from, container2ResourceMd), null);
} }
}.apply(sync.listContainers()); }.apply(sync.listContainers());
} }
@ -139,10 +136,8 @@ public class CloudFilesBlobStore extends BaseBlobStore {
public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) { public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {
org.jclouds.rackspace.cloudfiles.options.ListContainerOptions httpOptions = container2ContainerListOptions org.jclouds.rackspace.cloudfiles.options.ListContainerOptions httpOptions = container2ContainerListOptions
.apply(options); .apply(options);
PageSet<? extends StorageMetadata> list = container2ResourceList.apply(sync.listObjects( PageSet<? extends StorageMetadata> list = container2ResourceList.apply(sync.listObjects(container, httpOptions));
container, httpOptions)); return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container).apply(list) : list;
return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container)
.apply(list) : list;
} }
/** /**
@ -180,8 +175,7 @@ public class CloudFilesBlobStore extends BaseBlobStore {
* file name * file name
*/ */
@Override @Override
public Blob getBlob(String container, String key, public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions optionsList) {
org.jclouds.blobstore.options.GetOptions optionsList) {
GetOptions httpOptions = blob2ObjectGetOptions.apply(optionsList); GetOptions httpOptions = blob2ObjectGetOptions.apply(optionsList);
return object2Blob.apply(sync.getObject(container, key, httpOptions)); return object2Blob.apply(sync.getObject(container, key, httpOptions));
} }

View File

@ -19,19 +19,28 @@
package org.jclouds.rackspace.cloudfiles.blobstore.config; package org.jclouds.rackspace.cloudfiles.blobstore.config;
import java.util.Set;
import javax.inject.Singleton;
import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.AsyncBlobStore;
import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStore;
import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.BlobStoreContext;
import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.attr.ConsistencyModel;
import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.config.BlobStoreMapModule;
import org.jclouds.blobstore.internal.BlobStoreContextImpl; import org.jclouds.blobstore.internal.BlobStoreContextImpl;
import org.jclouds.domain.Location;
import org.jclouds.rackspace.cloudfiles.CloudFilesAsyncClient; import org.jclouds.rackspace.cloudfiles.CloudFilesAsyncClient;
import org.jclouds.rackspace.cloudfiles.CloudFilesClient; import org.jclouds.rackspace.cloudfiles.CloudFilesClient;
import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesAsyncBlobStore; import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesAsyncBlobStore;
import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesBlobStore; import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesBlobStore;
import org.jclouds.rackspace.config.RackspaceLocationsModule; import org.jclouds.rackspace.config.RackspaceLocationsModule;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
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.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
@ -50,9 +59,20 @@ public class CloudFilesBlobStoreContextModule extends AbstractModule {
bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);
bind(AsyncBlobStore.class).to(CloudFilesAsyncBlobStore.class).in(Scopes.SINGLETON); bind(AsyncBlobStore.class).to(CloudFilesAsyncBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStore.class).to(CloudFilesBlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(CloudFilesBlobStore.class).in(Scopes.SINGLETON);
bind(BlobStoreContext.class).to( bind(BlobStoreContext.class).to(new TypeLiteral<BlobStoreContextImpl<CloudFilesClient, CloudFilesAsyncClient>>() {
new TypeLiteral<BlobStoreContextImpl<CloudFilesClient, CloudFilesAsyncClient>>() { }).in(Scopes.SINGLETON);
}).in(Scopes.SINGLETON); }
@Provides
@Singleton
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Set<? extends Location> locations) {
return Suppliers.<Set<? extends Location>> ofInstance(locations);
}
@Provides
@Singleton
protected Supplier<Location> getLocation(Set<? extends Location> locations) {
return Suppliers.<Location> ofInstance(Iterables.get(locations, 0));
} }
} }

View File

@ -30,23 +30,24 @@ import org.jclouds.domain.Location;
import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata; import org.jclouds.rackspace.cloudfiles.domain.ContainerMetadata;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ContainerToResourceMetadata implements Function<ContainerMetadata, StorageMetadata> { public class ContainerToResourceMetadata implements Function<ContainerMetadata, StorageMetadata> {
private Location defaultLocation; private Supplier<Location> defaultLocation;
@Inject @Inject
ContainerToResourceMetadata(Location defaultLocation) { ContainerToResourceMetadata(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation; this.defaultLocation = defaultLocation;
} }
public StorageMetadata apply(ContainerMetadata from) { public StorageMetadata apply(ContainerMetadata from) {
MutableStorageMetadata to = new MutableStorageMetadataImpl(); MutableStorageMetadata to = new MutableStorageMetadataImpl();
to.setName(from.getName()); to.setName(from.getName());
to.setLocation(defaultLocation); to.setLocation(defaultLocation.get());
to.setType(StorageType.CONTAINER); to.setType(StorageType.CONTAINER);
return to; return to;
} }

View File

@ -19,84 +19,62 @@
package org.jclouds.rackspace.cloudservers.compute.config; package org.jclouds.rackspace.cloudservers.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
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 java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; 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.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.rackspace.cloudservers.CloudServersAsyncClient; import org.jclouds.rackspace.cloudservers.CloudServersAsyncClient;
import org.jclouds.rackspace.cloudservers.CloudServersClient; import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.compute.functions.ServerToNodeMetadata; import org.jclouds.rackspace.cloudservers.compute.functions.ServerToNodeMetadata;
import org.jclouds.rackspace.cloudservers.domain.Flavor; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersAddNodeWithTagStrategy;
import org.jclouds.rackspace.cloudservers.domain.RebootType; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersDestroyNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersListNodesStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersRebootNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.suppliers.CloudServersImageSupplier;
import org.jclouds.rackspace.cloudservers.compute.suppliers.CloudServersSizeSupplier;
import org.jclouds.rackspace.cloudservers.domain.Server; import org.jclouds.rackspace.cloudservers.domain.Server;
import org.jclouds.rackspace.cloudservers.domain.ServerStatus; import org.jclouds.rackspace.cloudservers.domain.ServerStatus;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import org.jclouds.rackspace.config.RackspaceLocationsModule; import org.jclouds.rackspace.config.RackspaceLocationsModule;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
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.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.inject.Injector;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
import com.google.inject.util.Providers; import com.google.inject.util.Providers;
/** /**
* Configures the {@link CloudServersComputeServiceContext}; requires * Configures the {@link CloudServersComputeServiceContext}; requires {@link BaseComputeService}
* {@link BaseComputeService} bound. * bound.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class CloudServersComputeServiceContextModule extends AbstractModule { public class CloudServersComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
@ -118,153 +96,36 @@ public class CloudServersComputeServiceContextModule extends AbstractModule {
bind(DestroyNodeStrategy.class).to(CloudServersDestroyNodeStrategy.class); bind(DestroyNodeStrategy.class).to(CloudServersDestroyNodeStrategy.class);
} }
@Provides @Override
@Named("DEFAULT") protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*"); return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*");
} }
@Provides
@Named("NAMING_CONVENTION")
@Singleton
String provideNamingConvention() {
return "%s-%s";
}
@Singleton
public static class CloudServersRebootNodeStrategy implements RebootNodeStrategy {
private final CloudServersClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected CloudServersRebootNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.HARD);
return getNode.execute(id);
}
}
@Singleton
public static class CloudServersDestroyNodeStrategy implements DestroyNodeStrategy {
private final CloudServersClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected CloudServersDestroyNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.deleteServer(serverId);
return getNode.execute(id);
}
}
@Singleton
public static class CloudServersAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final CloudServersClient client;
@Inject
protected CloudServersAddNodeWithTagStrategy(CloudServersClient client) {
this.client = checkNotNull(client, "client");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Server server = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getSize().getProviderId()));
return new NodeMetadataImpl(server.getId() + "", name, server.getId() + "", new LocationImpl(
LocationScope.HOST, server.getHostId(), server.getHostId(), template.getLocation()), null, server
.getMetadata(), tag, template.getImage(), NodeState.PENDING, server.getAddresses().getPublicAddresses(),
server.getAddresses().getPrivateAddresses(), ImmutableMap.<String, String> of(), new Credentials("root",
server.getAdminPass()));
}
}
@Singleton
public static class CloudServersListNodesStrategy implements ListNodesStrategy {
private final CloudServersClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected CloudServersListNodesStrategy(CloudServersClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listServers(ListOptions.Builder.withDetails()),
serverToNodeMetadata), filter);
}
}
@Singleton
public static class CloudServersGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final CloudServersClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected CloudServersGetNodeMetadataStrategy(CloudServersClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
Server server = client.getServer(serverId);
return server == null ? null : serverToNodeMetadata.apply(server);
}
}
@VisibleForTesting @VisibleForTesting
static final Map<ServerStatus, NodeState> serverToNodeState = ImmutableMap.<ServerStatus, NodeState> builder().put( static final Map<ServerStatus, NodeState> serverToNodeState = ImmutableMap.<ServerStatus, NodeState> builder().put(
ServerStatus.ACTIVE, NodeState.RUNNING)// ServerStatus.ACTIVE, NodeState.RUNNING)//
.put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)//
.put(ServerStatus.DELETED, NodeState.TERMINATED)// .put(ServerStatus.DELETED, NodeState.TERMINATED)//
.put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)//
.put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)//
.put(ServerStatus.RESIZE, NodeState.PENDING)// .put(ServerStatus.RESIZE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)//
.put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)//
.put(ServerStatus.PREP_MOVE, NodeState.PENDING)// .put(ServerStatus.PREP_MOVE, NodeState.PENDING)//
.put(ServerStatus.MOVE, NodeState.PENDING)// .put(ServerStatus.MOVE, NodeState.PENDING)//
.put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)//
.put(ServerStatus.RESCUE, NodeState.PENDING)// .put(ServerStatus.RESCUE, NodeState.PENDING)//
.put(ServerStatus.ERROR, NodeState.ERROR)// .put(ServerStatus.ERROR, NodeState.ERROR)//
.put(ServerStatus.BUILD, NodeState.PENDING)// .put(ServerStatus.BUILD, NodeState.PENDING)//
.put(ServerStatus.RESTORING, NodeState.PENDING)// .put(ServerStatus.RESTORING, NodeState.PENDING)//
.put(ServerStatus.PASSWORD, NodeState.PENDING)// .put(ServerStatus.PASSWORD, NodeState.PENDING)//
.put(ServerStatus.REBUILD, NodeState.PENDING)// .put(ServerStatus.REBUILD, NodeState.PENDING)//
.put(ServerStatus.DELETE_IP, NodeState.PENDING)// .put(ServerStatus.DELETE_IP, NodeState.PENDING)//
.put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)//
.put(ServerStatus.SHARE_IP, NodeState.PENDING)// .put(ServerStatus.SHARE_IP, NodeState.PENDING)//
.put(ServerStatus.REBOOT, NodeState.PENDING)// .put(ServerStatus.REBOOT, NodeState.PENDING)//
.put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)//
.put(ServerStatus.UNKNOWN, NodeState.UNKNOWN).build(); .put(ServerStatus.UNKNOWN, NodeState.UNKNOWN).build();
@Singleton @Singleton
@Provides @Provides
@ -272,71 +133,13 @@ public class CloudServersComputeServiceContextModule extends AbstractModule {
return serverToNodeState; return serverToNodeState;
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
protected Function<ComputeMetadata, String> indexer() { return injector.getInstance(CloudServersImageSupplier.class);
return new Function<ComputeMetadata, String>() {
@Override
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
protected Set<? extends Size> provideSizes(CloudServersClient sync, Set<? extends Image> images, Location location, return injector.getInstance(CloudServersSizeSupplier.class);
LogHolder holder, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,
Function<ComputeMetadata, String> indexer) throws InterruptedException, TimeoutException, ExecutionException {
final Set<Size> sizes = Sets.newHashSet();
holder.logger.debug(">> providing sizes");
for (final Flavor from : sync.listFlavors(ListOptions.Builder.withDetails())) {
sizes.add(new SizeImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), from.getDisk() / 10, from.getRam(), from.getDisk(), ImagePredicates.any()));
}
holder.logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
}
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Provides
@Singleton
protected Set<? extends Image> provideImages(final CloudServersClient sync, Location location, LogHolder holder,
Function<ComputeMetadata, String> indexer) throws InterruptedException, ExecutionException, TimeoutException {
final Set<Image> images = Sets.newHashSet();
holder.logger.debug(">> providing images");
for (final org.jclouds.rackspace.cloudservers.domain.Image from : sync.listImages(ListOptions.Builder
.withDetails())) {
OsFamily os = null;
Architecture arch = Architecture.X86_64;
String osDescription = "";
String version = "";
Matcher matcher = RACKSPACE_PATTERN.matcher(from.getName());
osDescription = from.getName();
if (from.getName().indexOf("Red Hat EL") != -1) {
os = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
os = OsFamily.OEL;
} else if (matcher.find()) {
try {
os = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
holder.logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
images
.add(new ImageImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), from.getName(), version, os, osDescription, arch, new Credentials("root",
null)));
}
holder.logger.debug("<< images(%d)", images.size());
return images;
} }
} }

View File

@ -28,6 +28,7 @@ import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
@ -42,16 +43,18 @@ import org.jclouds.rackspace.cloudservers.domain.ServerStatus;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton
public class ServerToNodeMetadata implements Function<Server, NodeMetadata> { public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
private final Location location; private final Supplier<Location> location;
private final Map<ServerStatus, NodeState> serverToNodeState; private final Map<ServerStatus, NodeState> serverToNodeState;
private final Set<? extends Image> images; private final Supplier<Set<? extends Image>> images;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@ -73,8 +76,8 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
} }
@Inject @Inject
ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Set<? extends Image> images, ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Supplier<Set<? extends Image>> images,
Location location) { Supplier<Location> location) {
this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location"); this.location = checkNotNull(location, "location");
@ -83,10 +86,10 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override @Override
public NodeMetadata apply(Server from) { public NodeMetadata apply(Server from) {
String tag = parseTagFromName(from.getName()); String tag = parseTagFromName(from.getName());
Location host = new LocationImpl(LocationScope.HOST, from.getHostId(), from.getHostId(), location); Location host = new LocationImpl(LocationScope.HOST, from.getHostId(), from.getHostId(), location.get());
Image image = null; Image image = null;
try { try {
image = Iterables.find(images, new FindImageForServer(host, from)); image = Iterables.find(images.get(), new FindImageForServer(host, from));
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location); logger.warn("could not find a matching image for server %s in location %s", from, location);
} }

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.rackspace.cloudservers.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Server;
import com.google.common.collect.ImmutableMap;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final CloudServersClient client;
@Inject
protected CloudServersAddNodeWithTagStrategy(CloudServersClient client) {
this.client = checkNotNull(client, "client");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Server server = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getSize().getProviderId()));
return new NodeMetadataImpl(server.getId() + "", name, server.getId() + "", new LocationImpl(
LocationScope.HOST, server.getHostId(), server.getHostId(), template.getLocation()), null, server
.getMetadata(), tag, template.getImage(), NodeState.PENDING, server.getAddresses()
.getPublicAddresses(), server.getAddresses().getPrivateAddresses(), ImmutableMap
.<String, String> of(), new Credentials("root", server.getAdminPass()));
}
}

View File

@ -0,0 +1,52 @@
/**
*
* 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.rackspace.cloudservers.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersDestroyNodeStrategy implements DestroyNodeStrategy {
private final CloudServersClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected CloudServersDestroyNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.deleteServer(serverId);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,54 @@
/**
*
* 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.rackspace.cloudservers.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Server;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final CloudServersClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected CloudServersGetNodeMetadataStrategy(CloudServersClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
Server server = client.getServer(serverId);
return server == null ? null : serverToNodeMetadata.apply(server);
}
}

View File

@ -0,0 +1,62 @@
/**
*
* 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.rackspace.cloudservers.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Server;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersListNodesStrategy implements ListNodesStrategy {
private final CloudServersClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected CloudServersListNodesStrategy(CloudServersClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listServers(ListOptions.Builder.withDetails()),
serverToNodeMetadata), filter);
}
}

View File

@ -0,0 +1,53 @@
/**
*
* 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.rackspace.cloudservers.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.RebootType;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersRebootNodeStrategy implements RebootNodeStrategy {
private final CloudServersClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected CloudServersRebootNodeStrategy(CloudServersClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int serverId = Integer.parseInt(id);
// if false server wasn't around in the first place
client.rebootServer(serverId, RebootType.HARD);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,96 @@
/**
*
* 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.rackspace.cloudservers.compute.suppliers;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class CloudServersImageSupplier implements Supplier<Set<? extends Image>> {
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private CloudServersClient sync;
private Supplier<Location> location;
@Inject
CloudServersImageSupplier(CloudServersClient sync, Supplier<Location> location) {
this.sync = sync;
this.location = location;
}
@Override
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
logger.debug(">> providing images");
for (final org.jclouds.rackspace.cloudservers.domain.Image from : sync.listImages(ListOptions.Builder
.withDetails())) {
OsFamily os = null;
Architecture arch = Architecture.X86_64;
String osDescription = "";
String version = "";
Matcher matcher = RACKSPACE_PATTERN.matcher(from.getName());
osDescription = from.getName();
if (from.getName().indexOf("Red Hat EL") != -1) {
os = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
os = OsFamily.OEL;
} else if (matcher.find()) {
try {
os = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
images.add(new ImageImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), from.getName(), version, os, osDescription, arch,
new Credentials("root", null)));
}
logger.debug("<< images(%d)", images.size());
return images;
}
}

View File

@ -0,0 +1,77 @@
/**
*
* 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.rackspace.cloudservers.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Flavor;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class CloudServersSizeSupplier implements Supplier<Set<? extends Size>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final CloudServersClient sync;
private final Supplier<Location> location;
@Inject
CloudServersSizeSupplier(CloudServersClient sync, Supplier<Location> location,
Function<ComputeMetadata, String> indexer) {
this.sync = sync;
this.location = location;
}
@Override
public Set<? extends Size> get() {
final Set<Size> sizes = Sets.newHashSet();
logger.debug(">> providing sizes");
for (final Flavor from : sync.listFlavors(ListOptions.Builder.withDetails())) {
sizes.add(new SizeImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), from.getDisk() / 10, from.getRam(), from.getDisk(),
ImagePredicates.any()));
}
logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
}

View File

@ -45,14 +45,8 @@ public class RackspaceLocationsModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
Location getLocation(@Provider String providerName) { Set<? extends Location> provideLocations(@Provider String providerName) {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
return new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider); return ImmutableSet.of(new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider));
}
@Provides
@Singleton
Set<? extends Location> provideLocations(Location location) {
return ImmutableSet.of(location);
} }
} }

View File

@ -29,6 +29,7 @@ import java.net.UnknownHostException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
@ -39,6 +40,7 @@ import org.jclouds.rackspace.cloudservers.domain.Server;
import org.jclouds.rackspace.cloudservers.domain.ServerStatus; import org.jclouds.rackspace.cloudservers.domain.ServerStatus;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
@ -86,8 +88,8 @@ public class ServerToNodeMetadataTest {
replay(serverStateToNodeState); replay(serverStateToNodeState);
replay(server); replay(server);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, images, ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers
provider); .<Set<? extends Image>> ofInstance(images), Suppliers.ofInstance(provider));
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
assertEquals(metadata.getLocation(), location); assertEquals(metadata.getLocation(), location);

View File

@ -19,77 +19,62 @@
package org.jclouds.rimuhosting.miro.compute.config; package org.jclouds.rimuhosting.miro.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.domain.OsFamily.UBUNTU; import static org.jclouds.compute.domain.OsFamily.UBUNTU;
import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName;
import static org.jclouds.rimuhosting.miro.reference.RimuHostingConstants.PROPERTY_RIMUHOSTING_DEFAULT_DC; import static org.jclouds.rimuhosting.miro.reference.RimuHostingConstants.PROPERTY_RIMUHOSTING_DEFAULT_DC;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture; import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; 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.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.rimuhosting.miro.RimuHostingAsyncClient; import org.jclouds.rimuhosting.miro.RimuHostingAsyncClient;
import org.jclouds.rimuhosting.miro.RimuHostingClient; import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.NewServerResponse; import org.jclouds.rimuhosting.miro.compute.functions.ServerToNodeMetadata;
import org.jclouds.rimuhosting.miro.domain.PricingPlan; import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingAddNodeWithTagStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingDestroyNodeStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingGetNodeMetadataStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingListNodesStrategy;
import org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingRebootNodeStrategy;
import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingImageSupplier;
import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingLocationSupplier;
import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingSizeSupplier;
import org.jclouds.rimuhosting.miro.domain.Server; import org.jclouds.rimuhosting.miro.domain.Server;
import org.jclouds.rimuhosting.miro.domain.internal.RunningState; import org.jclouds.rimuhosting.miro.domain.internal.RunningState;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Sets; import com.google.inject.Injector;
import com.google.inject.AbstractModule; import com.google.inject.Key;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
import com.google.inject.util.Providers; import com.google.inject.util.Providers;
/** /**
@ -98,7 +83,7 @@ import com.google.inject.util.Providers;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class RimuHostingComputeServiceContextModule extends AbstractModule { public class RimuHostingComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
@ -121,136 +106,12 @@ public class RimuHostingComputeServiceContextModule extends AbstractModule {
bind(DestroyNodeStrategy.class).to(RimuHostingDestroyNodeStrategy.class); bind(DestroyNodeStrategy.class).to(RimuHostingDestroyNodeStrategy.class);
} }
@Provides @Override
@Named("DEFAULT") protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.sizeId("MIRO1B").osFamily(UBUNTU).architecture(Architecture.X86_32).imageNameMatches( return template.sizeId("MIRO1B").osFamily(UBUNTU).architecture(Architecture.X86_32).imageNameMatches(
".*10\\.?04.*"); ".*10\\.?04.*");
} }
@Provides
@Named("NAMING_CONVENTION")
@Singleton
String provideNamingConvention() {
return "%s-%s";
}
@Singleton
public static class RimuHostingRebootNodeStrategy implements RebootNodeStrategy {
private final RimuHostingClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected RimuHostingRebootNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Long serverId = Long.parseLong(id);
// if false server wasn't around in the first place
client.restartServer(serverId).getState();
return getNode.execute(id);
}
}
@Singleton
public static class RimuHostingDestroyNodeStrategy implements DestroyNodeStrategy {
private final RimuHostingClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected RimuHostingDestroyNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Long serverId = Long.parseLong(id);
client.destroyServer(serverId);
return getNode.execute(id);
}
}
@Singleton
public static class RimuHostingAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final RimuHostingClient client;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
@Inject
protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client,
Function<Server, Iterable<String>> getPublicAddresses,
Map<RunningState, NodeState> runningStateToNodeState) {
this.client = client;
this.getPublicAddresses = getPublicAddresses;
this.runningStateToNodeState = runningStateToNodeState;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
NewServerResponse serverResponse = client.createServer(name, checkNotNull(template.getImage().getProviderId(),
"imageId"), checkNotNull(template.getSize().getProviderId(), "sizeId"));
Server server = client.getServer(serverResponse.getServer().getId());
NodeMetadata node = new NodeMetadataImpl(server.getId().toString(), name, server.getId().toString(), template
.getLocation(), null, ImmutableMap.<String, String> of(), tag, template.getImage(),
runningStateToNodeState.get(server.getState()), getPublicAddresses.apply(server), ImmutableList
.<String> of(), ImmutableMap.<String, String> of(), new Credentials("root", serverResponse
.getNewInstanceRequest().getCreateOptions().getPassword()));
return node;
}
}
@Singleton
public static class RimuHostingListNodesStrategy implements ListNodesStrategy {
private final RimuHostingClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected RimuHostingListNodesStrategy(RimuHostingClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.getServerList(), serverToNodeMetadata), filter);
}
}
@Singleton
public static class RimuHostingGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final RimuHostingClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected RimuHostingGetNodeMetadataStrategy(RimuHostingClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
long serverId = Long.parseLong(id);
Server server = client.getServer(serverId);
return server == null ? null : serverToNodeMetadata.apply(server);
}
}
@VisibleForTesting @VisibleForTesting
static final Map<RunningState, NodeState> runningStateToNodeState = ImmutableMap.<RunningState, NodeState> builder() static final Map<RunningState, NodeState> runningStateToNodeState = ImmutableMap.<RunningState, NodeState> builder()
.put(RunningState.RUNNING, NodeState.RUNNING)// .put(RunningState.RUNNING, NodeState.RUNNING)//
@ -265,67 +126,6 @@ public class RimuHostingComputeServiceContextModule extends AbstractModule {
return runningStateToNodeState; return runningStateToNodeState;
} }
@Singleton
private static class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Resource
protected Logger logger = Logger.NULL;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
private final Set<? extends Image> images;
@SuppressWarnings("unused")
private final Set<? extends Location> locations;
private static class FindImageForServer implements Predicate<Image> {
private final Location location;
private final Server instance;
private FindImageForServer(Location location, Server instance) {
this.location = location;
this.instance = instance;
}
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId())
&& (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation()
.equals(location.getParent()));
}
}
@SuppressWarnings("unused")
@Inject
ServerToNodeMetadata(Function<Server, Iterable<String>> getPublicAddresses,
Map<RunningState, NodeState> runningStateToNodeState, Set<? extends Image> images,
Set<? extends Location> locations) {
this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState");
this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState");
this.images = checkNotNull(images, "images");
this.locations = checkNotNull(locations, "locations");
}
@Override
public NodeMetadata apply(Server from) {
Location location = new LocationImpl(LocationScope.ZONE, from.getLocation().getId(), from.getLocation()
.getName(), null);
String tag = parseTagFromName(from.getName());
Credentials creds = null;
Image image = null;
try {
image = Iterables.find(images, new FindImageForServer(location, from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}
NodeState state = runningStateToNodeState.get(from.getState());
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), tag, image, state, getPublicAddresses.apply(from), ImmutableList
.<String> of(), ImmutableMap.<String, String> of(), creds);
}
}
@Singleton @Singleton
private static class ServerToPublicAddresses implements Function<Server, Iterable<String>> { private static class ServerToPublicAddresses implements Function<Server, Iterable<String>> {
@Override @Override
@ -335,118 +135,40 @@ public class RimuHostingComputeServiceContextModule extends AbstractModule {
} }
} }
@Provides @Override
@Singleton protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
Location getDefaultLocation(@Named(PROPERTY_RIMUHOSTING_DEFAULT_DC) final String defaultDC, final String defaultDC = injector
Set<? extends Location> locations) { .getInstance(Key.get(String.class, Names.named(PROPERTY_RIMUHOSTING_DEFAULT_DC)));
return Iterables.find(locations, new Predicate<Location>() { return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
@Override @Override
public boolean apply(Location input) { public Location apply(Set<? extends Location> from) {
return input.getId().equals(defaultDC); return Iterables.find(from, new Predicate<Location>() {
}
});
}
@Provides
@Singleton
Set<? extends Location> getDefaultLocations(RimuHostingClient sync, LogHolder holder,
Function<ComputeMetadata, String> indexer, @Provider String providerName) {
final Set<Location> locations = Sets.newHashSet();
holder.logger.debug(">> providing locations");
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (final PricingPlan from : sync.getPricingPlanList()) {
try {
locations.add(new LocationImpl(LocationScope.ZONE, from.getDataCenter().getId(), from.getDataCenter()
.getName(), provider));
} catch (NullPointerException e) {
holder.logger.warn("datacenter not present in " + from.getId());
}
}
holder.logger.debug("<< locations(%d)", locations.size());
return locations;
}
@Provides
@Singleton
protected Function<ComputeMetadata, String> indexer() {
return new Function<ComputeMetadata, String>() {
@Override
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
}
@Provides
@Singleton
protected Set<? extends Size> provideSizes(RimuHostingClient sync, Set<? extends Image> images,
Set<? extends Location> locations, LogHolder holder,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService userExecutor,
Function<ComputeMetadata, String> indexer) throws InterruptedException, TimeoutException,
ExecutionException {
final Set<Size> sizes = Sets.newHashSet();
holder.logger.debug(">> providing sizes");
for (final PricingPlan from : sync.getPricingPlanList()) {
try {
final Location location = Iterables.find(locations, new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
return input.getId().equals(from.getDataCenter().getId()); return input.getId().equals(defaultDC);
} }
}); });
sizes.add(new SizeImpl(from.getId(), from.getId(), from.getId(), location, null, ImmutableMap
.<String, String> of(), 1, from.getRam(), from.getDiskSize(), ImagePredicates.any()));
} catch (NullPointerException e) {
holder.logger.warn("datacenter not present in " + from.getId());
}
}
holder.logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
}
public static final Pattern RIMU_PATTERN = Pattern.compile("([^0-9]*)(.*)");
@Provides
@Singleton
protected Set<? extends Image> provideImages(final RimuHostingClient sync, LogHolder holder,
Function<ComputeMetadata, String> indexer) throws InterruptedException, ExecutionException,
TimeoutException {
final Set<Image> images = Sets.newHashSet();
holder.logger.debug(">> providing images");
for (final org.jclouds.rimuhosting.miro.domain.Image from : sync.getImageList()) {
OsFamily os = null;
Architecture arch = from.getId().indexOf("64") == -1 ? Architecture.X86_32 : Architecture.X86_64;
String osDescription = "";
String version = "";
osDescription = from.getId();
Matcher matcher = RIMU_PATTERN.matcher(from.getId());
if (matcher.find()) {
try {
os = OsFamily.fromValue(matcher.group(1).toLowerCase());
} catch (IllegalArgumentException e) {
holder.logger.debug("<< didn't match os(%s)", matcher.group(2));
}
} }
images.add(new ImageImpl(from.getId(), from.getDescription(), from.getId(), null, null, ImmutableMap }, locations);
.<String, String> of(), from.getDescription(), version, os, osDescription, arch, new Credentials(
"root", null)));
}
holder.logger.debug("<< images(%d)", images.size());
return images;
} }
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(RimuHostingImageSupplier.class);
}
@Override
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
return injector.getInstance(RimuHostingLocationSupplier.class);
}
@Override
protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(RimuHostingSizeSupplier.class);
}
} }

View File

@ -0,0 +1,114 @@
/**
*
* 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.rimuhosting.miro.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.rimuhosting.miro.domain.Server;
import org.jclouds.rimuhosting.miro.domain.internal.RunningState;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Resource
protected Logger logger = Logger.NULL;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
private final Supplier<Set<? extends Image>> images;
@SuppressWarnings("unused")
private final Supplier<Set<? extends Location>> locations;
private static class FindImageForServer implements Predicate<Image> {
private final Location location;
private final Server instance;
private FindImageForServer(Location location, Server instance) {
this.location = location;
this.instance = instance;
}
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId())
&& (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation()
.equals(location.getParent()));
}
}
@Inject
ServerToNodeMetadata(Function<Server, Iterable<String>> getPublicAddresses,
Map<RunningState, NodeState> runningStateToNodeState, Supplier<Set<? extends Image>> images,
Supplier<Set<? extends Location>> locations) {
this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState");
this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState");
this.images = checkNotNull(images, "images");
this.locations = checkNotNull(locations, "locations");
}
@Override
public NodeMetadata apply(Server from) {
// TODO properly look up location
Location location = new LocationImpl(LocationScope.ZONE, from.getLocation().getId(),
from.getLocation().getName(), null);
String tag = parseTagFromName(from.getName());
Credentials creds = null;
Image image = null;
try {
image = Iterables.find(images.get(), new FindImageForServer(location, from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}
NodeState state = runningStateToNodeState.get(from.getState());
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), tag, image, state, getPublicAddresses.apply(from), ImmutableList.<String> of(),
ImmutableMap.<String, String> of(), creds);
}
}

View File

@ -0,0 +1,75 @@
/**
*
* 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.rimuhosting.miro.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.NewServerResponse;
import org.jclouds.rimuhosting.miro.domain.Server;
import org.jclouds.rimuhosting.miro.domain.internal.RunningState;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final RimuHostingClient client;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
@Inject
protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client,
Function<Server, Iterable<String>> getPublicAddresses, Map<RunningState, NodeState> runningStateToNodeState) {
this.client = client;
this.getPublicAddresses = getPublicAddresses;
this.runningStateToNodeState = runningStateToNodeState;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
NewServerResponse serverResponse = client.createServer(name, checkNotNull(template.getImage().getProviderId(),
"imageId"), checkNotNull(template.getSize().getProviderId(), "sizeId"));
Server server = client.getServer(serverResponse.getServer().getId());
NodeMetadata node = new NodeMetadataImpl(server.getId().toString(), name, server.getId().toString(), template
.getLocation(), null, ImmutableMap.<String, String> of(), tag, template.getImage(),
runningStateToNodeState.get(server.getState()), getPublicAddresses.apply(server), ImmutableList
.<String> of(), ImmutableMap.<String, String> of(), new Credentials("root", serverResponse
.getNewInstanceRequest().getCreateOptions().getPassword()));
return node;
}
}

View File

@ -0,0 +1,52 @@
/**
*
* 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.rimuhosting.miro.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingDestroyNodeStrategy implements DestroyNodeStrategy {
private final RimuHostingClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected RimuHostingDestroyNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Long serverId = Long.parseLong(id);
client.destroyServer(serverId);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,55 @@
/**
*
* 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.rimuhosting.miro.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.Server;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final RimuHostingClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected RimuHostingGetNodeMetadataStrategy(RimuHostingClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
long serverId = Long.parseLong(id);
Server server = client.getServer(serverId);
return server == null ? null : serverToNodeMetadata.apply(server);
}
}

View File

@ -0,0 +1,62 @@
/**
*
* 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.rimuhosting.miro.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.Server;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingListNodesStrategy implements ListNodesStrategy {
private final RimuHostingClient client;
private final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected RimuHostingListNodesStrategy(RimuHostingClient client,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.getServerList(), serverToNodeMetadata), filter);
}
}

View File

@ -0,0 +1,53 @@
/**
*
* 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.rimuhosting.miro.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingRebootNodeStrategy implements RebootNodeStrategy {
private final RimuHostingClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected RimuHostingRebootNodeStrategy(RimuHostingClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
Long serverId = Long.parseLong(id);
// if false server wasn't around in the first place
client.restartServer(serverId).getState();
return getNode.execute(id);
}
}

View File

@ -0,0 +1,90 @@
/**
*
* 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.rimuhosting.miro.compute.suppliers;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingImageSupplier implements Supplier<Set<? extends Image>> {
private RimuHostingClient sync;
public static final Pattern RIMU_PATTERN = Pattern.compile("([^0-9]*)(.*)");
@Inject
RimuHostingImageSupplier(final RimuHostingClient sync) {
this.sync = sync;
}
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Override
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
logger.debug(">> providing images");
for (final org.jclouds.rimuhosting.miro.domain.Image from : sync.getImageList()) {
OsFamily os = null;
Architecture arch = from.getId().indexOf("64") == -1 ? Architecture.X86_32 : Architecture.X86_64;
String osDescription = "";
String version = "";
osDescription = from.getId();
Matcher matcher = RIMU_PATTERN.matcher(from.getId());
if (matcher.find()) {
try {
os = OsFamily.fromValue(matcher.group(1).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
images.add(new ImageImpl(from.getId(), from.getDescription(), from.getId(), null, null, ImmutableMap
.<String, String> of(), from.getDescription(), version, os, osDescription, arch, new Credentials(
"root", null)));
}
logger.debug("<< images(%d)", images.size());
return images;
}
}

View File

@ -0,0 +1,76 @@
/**
*
* 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.rimuhosting.miro.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.rest.annotations.Provider;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.PricingPlan;
import com.google.common.base.Supplier;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingLocationSupplier implements Supplier<Set<? extends Location>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private RimuHostingClient sync;
private String providerName;
@Inject
RimuHostingLocationSupplier(RimuHostingClient sync, @Provider String providerName) {
this.providerName = providerName;
this.sync = sync;
}
@Override
public Set<? extends Location> get() {
final Set<Location> locations = Sets.newHashSet();
logger.debug(">> providing locations");
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
for (final PricingPlan from : sync.getPricingPlanList()) {
try {
locations.add(new LocationImpl(LocationScope.ZONE, from.getDataCenter().getId(), from.getDataCenter()
.getName(), provider));
} catch (NullPointerException e) {
logger.warn("datacenter not present in " + from.getId());
}
}
logger.debug("<< locations(%d)", locations.size());
return locations;
}
}

View File

@ -0,0 +1,87 @@
/**
*
* 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.rimuhosting.miro.compute.suppliers;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.PricingPlan;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class RimuHostingSizeSupplier implements Supplier<Set<? extends Size>> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private RimuHostingClient sync;
private Supplier<Set<? extends Location>> locations;
@Inject
RimuHostingSizeSupplier(RimuHostingClient sync, Supplier<Set<? extends Location>> locations) {
this.sync = sync;
this.locations = locations;
}
@Override
public Set<? extends Size> get() {
final Set<Size> sizes = Sets.newHashSet();
logger.debug(">> providing sizes");
for (final PricingPlan from : sync.getPricingPlanList()) {
try {
final Location location = Iterables.find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(from.getDataCenter().getId());
}
});
sizes.add(new SizeImpl(from.getId(), from.getId(), from.getId(), location, null, ImmutableMap
.<String, String> of(), 1, from.getRam(), from.getDiskSize(), ImagePredicates.any()));
} catch (NullPointerException e) {
logger.warn("datacenter not present in " + from.getId());
}
}
logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
}

View File

@ -19,82 +19,64 @@
package org.jclouds.slicehost.compute.config; package org.jclouds.slicehost.compute.config;
import static com.google.common.base.Preconditions.checkNotNull;
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 java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.config.BaseComputeServiceContextModule;
import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.internal.SizeImpl;
import org.jclouds.compute.internal.BaseComputeService; import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.compute.strategy.DestroyNodeStrategy; 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.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl; import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.logging.Logger;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.annotations.Provider; import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.internal.RestContextImpl;
import org.jclouds.slicehost.SlicehostAsyncClient; import org.jclouds.slicehost.SlicehostAsyncClient;
import org.jclouds.slicehost.SlicehostClient; import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.compute.functions.SliceToNodeMetadata; import org.jclouds.slicehost.compute.functions.SliceToNodeMetadata;
import org.jclouds.slicehost.domain.Flavor; import org.jclouds.slicehost.compute.strategy.SlicehostAddNodeWithTagStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostDestroyNodeStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostGetNodeMetadataStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostListNodesStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostRebootNodeStrategy;
import org.jclouds.slicehost.compute.suppliers.SlicehostImageSupplier;
import org.jclouds.slicehost.compute.suppliers.SlicehostSizeSupplier;
import org.jclouds.slicehost.domain.Slice; import org.jclouds.slicehost.domain.Slice;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
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.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.inject.Injector;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Scopes; import com.google.inject.Scopes;
import com.google.inject.TypeLiteral; import com.google.inject.TypeLiteral;
import com.google.inject.util.Providers; import com.google.inject.util.Providers;
/** /**
* Configures the {@link SlicehostComputeServiceContext}; requires * Configures the {@link SlicehostComputeServiceContext}; requires {@link BaseComputeService} bound.
* {@link BaseComputeService} bound.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class SlicehostComputeServiceContextModule extends AbstractModule { public class SlicehostComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override @Override
protected void configure() { protected void configure() {
@ -115,145 +97,19 @@ public class SlicehostComputeServiceContextModule extends AbstractModule {
bind(DestroyNodeStrategy.class).to(SlicehostDestroyNodeStrategy.class); bind(DestroyNodeStrategy.class).to(SlicehostDestroyNodeStrategy.class);
} }
@Provides @Override
@Named("DEFAULT") protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
protected TemplateBuilder provideTemplate(TemplateBuilder template) {
return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*"); return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*");
} }
@Provides
@Named("NAMING_CONVENTION")
@Singleton
String provideNamingConvention() {
return "%s-%s";
}
@Singleton
public static class SlicehostRebootNodeStrategy implements RebootNodeStrategy {
private final SlicehostClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected SlicehostRebootNodeStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int sliceId = Integer.parseInt(id);
client.hardRebootSlice(sliceId);
return getNode.execute(id);
}
}
@Singleton
public static class SlicehostDestroyNodeStrategy implements DestroyNodeStrategy {
private final SlicehostClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected SlicehostDestroyNodeStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int sliceId = Integer.parseInt(id);
// if false slice wasn't around in the first place
client.destroySlice(sliceId);
return getNode.execute(id);
}
}
@Singleton
public static class SlicehostAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final SlicehostClient client;
@Inject
protected SlicehostAddNodeWithTagStrategy(SlicehostClient client) {
this.client = checkNotNull(client, "client");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Slice slice = client.createSlice(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getSize().getProviderId()));
return new NodeMetadataImpl(slice.getId() + "", name, slice.getId() + "", template.getLocation(), null,
ImmutableMap.<String, String> of(), tag, template.getImage(), NodeState.PENDING, Iterables.filter(slice
.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return !input.startsWith("10.");
}
}), Iterables.filter(slice.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith("10.");
}
}), ImmutableMap.<String, String> of(), new Credentials("root", slice.getRootPassword()));
}
}
@Singleton
public static class SlicehostListNodesStrategy implements ListNodesStrategy {
private final SlicehostClient client;
private final Function<Slice, NodeMetadata> sliceToNodeMetadata;
@Inject
protected SlicehostListNodesStrategy(SlicehostClient client, Function<Slice, NodeMetadata> sliceToNodeMetadata) {
this.client = client;
this.sliceToNodeMetadata = sliceToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listSlices(), sliceToNodeMetadata), filter);
}
}
@Singleton
public static class SlicehostGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final SlicehostClient client;
private final Function<Slice, NodeMetadata> sliceToNodeMetadata;
@Inject
protected SlicehostGetNodeMetadataStrategy(SlicehostClient client,
Function<Slice, NodeMetadata> sliceToNodeMetadata) {
this.client = client;
this.sliceToNodeMetadata = sliceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
int sliceId = Integer.parseInt(id);
Slice slice = client.getSlice(sliceId);
return slice == null ? null : sliceToNodeMetadata.apply(slice);
}
}
@VisibleForTesting @VisibleForTesting
static final Map<Slice.Status, NodeState> sliceStatusToNodeState = ImmutableMap.<Slice.Status, NodeState> builder() static final Map<Slice.Status, NodeState> sliceStatusToNodeState = ImmutableMap.<Slice.Status, NodeState> builder()
.put(Slice.Status.ACTIVE, NodeState.RUNNING)// .put(Slice.Status.ACTIVE, NodeState.RUNNING)//
.put(Slice.Status.BUILD, NodeState.PENDING)// .put(Slice.Status.BUILD, NodeState.PENDING)//
.put(Slice.Status.REBOOT, NodeState.PENDING)// .put(Slice.Status.REBOOT, NodeState.PENDING)//
.put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)//
.put(Slice.Status.TERMINATED, NodeState.TERMINATED)// .put(Slice.Status.TERMINATED, NodeState.TERMINATED)//
.build(); .build();
@Singleton @Singleton
@Provides @Provides
@ -263,43 +119,9 @@ public class SlicehostComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
protected Function<ComputeMetadata, String> indexer() { Location getLocation(@Provider String providerName) {
return new Function<ComputeMetadata, String>() { Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
@Override return new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider);
public String apply(ComputeMetadata from) {
return from.getProviderId();
}
};
}
@Provides
@Singleton
protected Set<? extends Size> provideSizes(SlicehostClient sync, Set<? extends Image> images, Location location,
LogHolder holder, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,
Function<ComputeMetadata, String> indexer) throws InterruptedException, TimeoutException, ExecutionException {
final Set<Size> sizes = Sets.newHashSet();
holder.logger.debug(">> providing sizes");
for (final Flavor from : sync.listFlavors()) {
sizes.add(new SizeImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), from.getRam() / 1024.0, from.getRam(), (from.getRam() * 4) / 1024,
ImagePredicates.any()));
}
holder.logger.debug("<< sizes(%d)", sizes.size());
return sizes;
}
private static class LogHolder {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
}
public static final Pattern SLICEHOST_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Provides
@Singleton
Location getLocation(@Provider String name) {
return new LocationImpl(LocationScope.PROVIDER, name, name, null);
} }
@Provides @Provides
@ -308,32 +130,13 @@ public class SlicehostComputeServiceContextModule extends AbstractModule {
return ImmutableSet.of(location); return ImmutableSet.of(location);
} }
@Provides @Override
@Singleton protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
protected Set<? extends Image> provideImages(final SlicehostClient sync, Location location, LogHolder holder, return injector.getInstance(SlicehostImageSupplier.class);
Function<ComputeMetadata, String> indexer) throws InterruptedException, ExecutionException, TimeoutException { }
final Set<Image> images = Sets.newHashSet();
holder.logger.debug(">> providing images"); @Override
for (final org.jclouds.slicehost.domain.Image from : sync.listImages()) { protected Supplier<Set<? extends Size>> getSourceSizeSupplier(Injector injector) {
OsFamily os = null; return injector.getInstance(SlicehostSizeSupplier.class);
Architecture arch = Architecture.X86_64;
String osDescription = "";
String version = "";
Matcher matcher = SLICEHOST_PATTERN.matcher(from.getName());
osDescription = from.getName();
if (matcher.find()) {
try {
os = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
holder.logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
images
.add(new ImageImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), from.getName(), version, os, osDescription, arch, new Credentials("root",
null)));
}
holder.logger.debug("<< images(%d)", images.size());
return images;
} }
} }

View File

@ -39,6 +39,7 @@ import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -46,9 +47,9 @@ import com.google.common.collect.Iterables;
* @author Adrian Cole * @author Adrian Cole
*/ */
public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> { public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
private final Location location; private final Supplier<Location> location;
private final Map<Slice.Status, NodeState> sliceToNodeState; private final Map<Slice.Status, NodeState> sliceToNodeState;
private final Set<? extends Image> images; private final Supplier<Set<? extends Image>> images;
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
@ -67,8 +68,8 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
} }
@Inject @Inject
SliceToNodeMetadata(Map<Slice.Status, NodeState> sliceStateToNodeState, Set<? extends Image> images, SliceToNodeMetadata(Map<Slice.Status, NodeState> sliceStateToNodeState, Supplier<Set<? extends Image>> images,
Location location) { Supplier<Location> location) {
this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState"); this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location"); this.location = checkNotNull(location, "location");
@ -79,27 +80,27 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
String tag = parseTagFromName(from.getName()); String tag = parseTagFromName(from.getName());
Image image = null; Image image = null;
try { try {
image = Iterables.find(images, new FindImageForSlice(from)); image = Iterables.find(images.get(), new FindImageForSlice(from));
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
logger.warn("could not find a matching image for slice %s in location %s", from, location); logger.warn("could not find a matching image for slice %s in location %s", from, location);
} }
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
.<String, String> of(), tag, image, sliceToNodeState.get(from.getStatus()), Iterables.filter(from ImmutableMap.<String, String> of(), tag, image, sliceToNodeState.get(from.getStatus()), Iterables
.getAddresses(), new Predicate<String>() { .filter(from.getAddresses(), new Predicate<String>() {
@Override @Override
public boolean apply(String input) { public boolean apply(String input) {
return !input.startsWith("10."); return !input.startsWith("10.");
} }
}), Iterables.filter(from.getAddresses(), new Predicate<String>() { }), Iterables.filter(from.getAddresses(), new Predicate<String>() {
@Override @Override
public boolean apply(String input) { public boolean apply(String input) {
return input.startsWith("10."); return input.startsWith("10.");
} }
}), ImmutableMap.<String, String> of(), null); }), ImmutableMap.<String, String> of(), null);
} }
} }

View File

@ -0,0 +1,76 @@
/**
*
* 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.slicehost.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final SlicehostClient client;
@Inject
protected SlicehostAddNodeWithTagStrategy(SlicehostClient client) {
this.client = checkNotNull(client, "client");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Slice slice = client.createSlice(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getSize().getProviderId()));
return new NodeMetadataImpl(slice.getId() + "", name, slice.getId() + "", template.getLocation(), null,
ImmutableMap.<String, String> of(), tag, template.getImage(), NodeState.PENDING, Iterables.filter(slice
.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return !input.startsWith("10.");
}
}), Iterables.filter(slice.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith("10.");
}
}), ImmutableMap.<String, String> of(), new Credentials("root", slice.getRootPassword()));
}
}

View File

@ -0,0 +1,53 @@
/**
*
* 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.slicehost.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.slicehost.SlicehostClient;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostDestroyNodeStrategy implements DestroyNodeStrategy {
private final SlicehostClient client;
private final GetNodeMetadataStrategy getNode;
@Inject
protected SlicehostDestroyNodeStrategy(SlicehostClient client, GetNodeMetadataStrategy getNode) {
this.client = client;
this.getNode = getNode;
}
@Override
public NodeMetadata execute(String id) {
int sliceId = Integer.parseInt(id);
// if false slice wasn't around in the first place
client.destroySlice(sliceId);
return getNode.execute(id);
}
}

View File

@ -0,0 +1,54 @@
/**
*
* 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.slicehost.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostGetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final SlicehostClient client;
private final Function<Slice, NodeMetadata> sliceToNodeMetadata;
@Inject
protected SlicehostGetNodeMetadataStrategy(SlicehostClient client, Function<Slice, NodeMetadata> sliceToNodeMetadata) {
this.client = client;
this.sliceToNodeMetadata = sliceToNodeMetadata;
}
@Override
public NodeMetadata execute(String id) {
int sliceId = Integer.parseInt(id);
Slice slice = client.getSlice(sliceId);
return slice == null ? null : sliceToNodeMetadata.apply(slice);
}
}

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.slicehost.compute.strategy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostListNodesStrategy implements ListNodesStrategy {
private final SlicehostClient client;
private final Function<Slice, NodeMetadata> sliceToNodeMetadata;
@Inject
protected SlicehostListNodesStrategy(SlicehostClient client, Function<Slice, NodeMetadata> sliceToNodeMetadata) {
this.client = client;
this.sliceToNodeMetadata = sliceToNodeMetadata;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(Iterables.transform(client.listSlices(), sliceToNodeMetadata), filter);
}
}

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