From 49b88183d2c8c75d86f10284fedddf00ad11db19 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sun, 17 Oct 2010 18:17:24 -0700 Subject: [PATCH] refactored compute provider implementation --- .../saas/blobstore/AtmosAsyncBlobStore.java | 7 +- .../saas/blobstore/AtmosBlobStore.java | 3 +- .../config/AtmosBlobStoreContextModule.java | 2 + .../aws/ec2/compute/EC2ComputeService.java | 33 +- .../EC2ComputeServiceContextModule.java | 251 +++------- .../EC2ComputeServiceDependenciesModule.java | 198 ++++++++ .../ec2/compute/functions/ImageParser.java | 16 +- .../RunningInstanceToNodeMetadata.java | 26 +- .../internal/EC2TemplateBuilderImpl.java | 12 +- .../suppliers/EC2HardwareSupplier.java | 9 +- .../compute/suppliers/EC2ImageSupplier.java | 52 ++ .../aws/s3/blobstore/S3AsyncBlobStore.java | 3 +- .../jclouds/aws/s3/blobstore/S3BlobStore.java | 10 +- .../config/S3BlobStoreContextModule.java | 2 + .../functions/BucketToResourceMetadata.java | 3 +- .../suppliers/DefaultLocationSupplier.java | 3 +- .../ec2/compute/EC2ComputeServiceTest.java | 51 +- .../functions/CredentialsForInstanceTest.java | 44 +- .../RunningInstanceToNodeMetadataTest.java | 139 +++--- .../internal/EC2TemplateBuilderImplTest.java | 41 +- .../blob/blobstore/AzureAsyncBlobStore.java | 3 +- .../blob/blobstore/AzureBlobStore.java | 3 +- .../config/AzureBlobStoreContextModule.java | 2 + .../blobstore/TransientAsyncBlobStore.java | 3 +- .../TransientBlobStoreContextModule.java | 2 + .../internal/BaseAsyncBlobStore.java | 4 +- .../blobstore/internal/BaseBlobStore.java | 3 +- .../compute/ComputeServiceContextFactory.java | 49 +- ...andaloneComputeServiceContextBuilder.java} | 44 +- .../BaseComputeServiceContextModule.java | 194 ++++++-- ...StandaloneComputeServiceClientModule.java} | 12 +- ...StandaloneComputeServiceContextModule.java | 40 ++ .../domain/internal/TemplateBuilderImpl.java | 95 ++-- .../compute/internal/BaseComputeService.java | 68 +-- .../StubComputeServiceContextBuilder.java | 14 +- .../StubComputeServiceContextModule.java | 383 ++------------- .../StubComputeServiceDependenciesModule.java | 377 +++++++++++++++ .../ComputeServiceContextFactoryTest.java | 39 ++ .../internal/TemplateBuilderImplTest.java | 91 ++-- .../java/org/jclouds/collect/Memoized.java | 42 ++ core/src/main/resources/rest.properties | 1 - .../filesystem/FilesystemAsyncBlobStore.java | 450 +++++++++--------- .../FilesystemBlobStoreContextModule.java | 22 +- .../GoGridComputeServiceContextModule.java | 147 ++---- ...oGridComputeServiceDependenciesModule.java | 113 +++++ .../functions/ServerToNodeMetadata.java | 13 +- .../GoGridDefaultLocationSupplier.java | 64 +++ .../suppliers/GoGridHardwareSupplier.java | 30 +- .../suppliers/GoGridImageSupplier.java | 2 +- ...GoGridComputeServiceContextModuleTest.java | 2 +- .../blobstore/CloudFilesAsyncBlobStore.java | 3 +- .../blobstore/CloudFilesBlobStore.java | 3 +- .../CloudFilesBlobStoreContextModule.java | 18 +- ...oudServersComputeServiceContextModule.java | 126 ++--- ...rversComputeServiceDependenciesModule.java | 117 +++++ .../functions/ServerToNodeMetadata.java | 4 +- .../suppliers/CloudServersImageSupplier.java | 4 +- ...e.java => RackspaceLocationsSupplier.java} | 19 +- ...erversComputeServiceContextModuleTest.java | 2 +- .../functions/ServerToNodeMetadataTest.java | 150 +++--- ...imuHostingComputeServiceContextModule.java | 130 ++--- ...stingComputeServiceDependenciesModule.java | 95 ++++ .../functions/ServerToNodeMetadata.java | 11 +- .../RimuHostingDefaultLocationSupplier.java | 64 +++ .../RimuHostingHardwareSupplier.java | 14 +- .../suppliers/RimuHostingImageSupplier.java | 4 +- .../RimuHostingLocationSupplier.java | 4 +- ...ostingComputeServiceContextModuleTest.java | 2 +- .../SlicehostComputeServiceContextModule.java | 116 ++--- ...ehostComputeServiceDependenciesModule.java | 97 ++++ .../functions/SliceToNodeMetadata.java | 6 +- .../suppliers/SlicehostImageSupplier.java | 2 +- ...cehostComputeServiceContextModuleTest.java | 2 +- .../functions/SliceToNodeMetadataTest.java | 99 ++-- ...mmonVCloudComputeServiceContextModule.java | 28 +- .../VCloudComputeServiceContextModule.java | 34 +- ...oudExpressComputeServiceContextModule.java | 38 +- .../functions/FindLocationForResource.java | 3 +- .../VCloudExpressVAppToNodeMetadata.java | 9 +- .../internal/VCloudTemplateBuilderImpl.java | 7 +- .../suppliers/StaticHardwareSupplier.java | 5 +- .../TerremarkVCloudComputeService.java | 23 +- ...markVCloudComputeServiceContextModule.java | 56 +-- ...remarkVCloudExpressVAppToNodeMetadata.java | 4 +- .../suppliers/VAppTemplatesInOrgs.java | 3 +- 85 files changed, 2623 insertions(+), 1896 deletions(-) create mode 100644 aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceDependenciesModule.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2ImageSupplier.java rename compute/src/main/java/org/jclouds/compute/{stub/StubComputeServicePropertiesBuilder.java => StandaloneComputeServiceContextBuilder.java} (53%) rename compute/src/main/java/org/jclouds/compute/{stub/config/StubComputeServiceClientModule.java => config/StandaloneComputeServiceClientModule.java} (77%) create mode 100644 compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceContextModule.java create mode 100644 compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java create mode 100644 compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java create mode 100755 core/src/main/java/org/jclouds/collect/Memoized.java create mode 100644 gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceDependenciesModule.java create mode 100644 gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridDefaultLocationSupplier.java create mode 100644 rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceDependenciesModule.java rename rackspace/src/main/java/org/jclouds/rackspace/config/{RackspaceLocationsModule.java => RackspaceLocationsSupplier.java} (79%) create mode 100644 rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java create mode 100644 rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingDefaultLocationSupplier.java create mode 100644 slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceDependenciesModule.java diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosAsyncBlobStore.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosAsyncBlobStore.java index e314ecf9f8..da6e552226 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosAsyncBlobStore.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosAsyncBlobStore.java @@ -53,6 +53,7 @@ import org.jclouds.blobstore.functions.BlobToHttpGetOptions; import org.jclouds.blobstore.internal.BaseAsyncBlobStore; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.concurrent.Futures; import org.jclouds.crypto.Crypto; import org.jclouds.domain.Location; @@ -81,9 +82,9 @@ public class AtmosAsyncBlobStore extends BaseAsyncBlobStore { @Inject AtmosAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations, AtmosStorageAsyncClient async, AtmosStorageClient sync, - ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object, - BlobStoreListOptionsToListOptions container2ContainerListOptions, + @Memoized Supplier> locations, AtmosStorageAsyncClient async, + AtmosStorageClient sync, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, + BlobToObject blob2Object, BlobStoreListOptionsToListOptions container2ContainerListOptions, DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto, BlobToHttpGetOptions blob2ObjectGetOptions, Provider fetchBlobMetadataProvider) { super(context, blobUtils, service, defaultLocation, locations); diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobStore.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobStore.java index 73c29b4568..cb010d850c 100644 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobStore.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/AtmosBlobStore.java @@ -45,6 +45,7 @@ import org.jclouds.blobstore.functions.BlobToHttpGetOptions; import org.jclouds.blobstore.internal.BaseBlobStore; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.crypto.Crypto; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; @@ -68,7 +69,7 @@ public class AtmosBlobStore extends BaseBlobStore { @Inject AtmosBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, - Supplier> locations, AtmosStorageClient sync, ObjectToBlob object2Blob, + @Memoized Supplier> locations, AtmosStorageClient sync, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object, BlobStoreListOptionsToListOptions container2ContainerListOptions, DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto, diff --git a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreContextModule.java b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreContextModule.java index 8183cdadd0..6355e22d96 100755 --- a/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreContextModule.java +++ b/atmos/src/main/java/org/jclouds/atmosonline/saas/blobstore/config/AtmosBlobStoreContextModule.java @@ -37,6 +37,7 @@ import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.internal.BlobStoreContextImpl; import org.jclouds.blobstore.strategy.ContainsValueInListStrategy; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; @@ -72,6 +73,7 @@ public class AtmosBlobStoreContextModule extends AbstractModule { @Provides @Singleton + @Memoized Supplier> provideLocations(Supplier defaultLocation) { return Suppliers.> ofInstance(ImmutableSet.of(defaultLocation.get())); } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java index dcb9619252..cc5bdd1d6d 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java @@ -24,8 +24,8 @@ import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle; import static org.jclouds.util.Utils.checkNotEmpty; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; +import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import javax.inject.Inject; @@ -42,6 +42,7 @@ import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions; import org.jclouds.aws.ec2.domain.KeyPair; import org.jclouds.aws.ec2.domain.PlacementGroup; import org.jclouds.aws.ec2.domain.PlacementGroup.State; +import org.jclouds.collect.Memoized; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; @@ -77,20 +78,20 @@ public class EC2ComputeService extends BaseComputeService { @Inject protected EC2ComputeService(ComputeServiceContext context, Map credentialStore, - Supplier> images, Supplier> sizes, - Supplier> locations, ListNodesStrategy listNodesStrategy, - GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, - RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, - Provider templateBuilderProvider, Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, - Map credentialsMap, @Named("SECURITY") Map securityGroupMap, - @Named("PLACEMENT") Map placementGroupMap, - @Named("DELETED") Predicate placementGroupDeleted) { + @Memoized Supplier> images, @Memoized Supplier> sizes, + @Memoized Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, + Map credentialsMap, @Named("SECURITY") Map securityGroupMap, + @Named("PLACEMENT") Map placementGroupMap, + @Named("DELETED") Predicate placementGroupDeleted) { super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, - runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, - templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); + runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, + templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); this.ec2Client = ec2Client; this.credentialsMap = credentialsMap; this.securityGroupMap = securityGroupMap; @@ -106,8 +107,8 @@ public class EC2ComputeService extends BaseComputeService { logger.debug(">> deleting placementGroup(%s)", group); try { ec2Client.getPlacementGroupServices().deletePlacementGroupInRegion(region, group); - checkState(placementGroupDeleted.apply(new PlacementGroup(region, group, "cluster", State.PENDING)), - String.format("placementGroup region(%s) name(%s) failed to delete", region, group)); + checkState(placementGroupDeleted.apply(new PlacementGroup(region, group, "cluster", State.PENDING)), String + .format("placementGroup region(%s) name(%s) failed to delete", region, group)); placementGroupMap.remove(new RegionAndName(region, tag)); logger.debug("<< deleted placementGroup(%s)", group); } catch (AWSResponseException e) { diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java index ad56c28f01..dd97e5bf22 100755 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java @@ -19,35 +19,19 @@ package org.jclouds.aws.ec2.compute.config; -import static com.google.common.collect.Iterables.toArray; -import static com.google.common.collect.Maps.newLinkedHashMap; import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; -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.compute.domain.OsFamily.AMZN_LINUX; import static org.jclouds.compute.domain.OsFamily.CENTOS; import static org.jclouds.compute.domain.OsFamily.UBUNTU; -import java.security.SecureRandom; import java.util.Map; import java.util.Set; -import java.util.concurrent.TimeUnit; import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.aws.ec2.EC2AsyncClient; -import org.jclouds.aws.ec2.EC2Client; import org.jclouds.aws.ec2.compute.EC2ComputeService; import org.jclouds.aws.ec2.compute.domain.RegionAndName; -import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded; -import org.jclouds.aws.ec2.compute.functions.CreateSecurityGroupIfNeeded; -import org.jclouds.aws.ec2.compute.functions.CreateUniqueKeyPair; -import org.jclouds.aws.ec2.compute.functions.CredentialsForInstance; -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.options.EC2TemplateOptions; import org.jclouds.aws.ec2.compute.strategy.EC2DestroyLoadBalancerStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2DestroyNodeStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2GetNodeMetadataStrategy; @@ -56,27 +40,15 @@ import org.jclouds.aws.ec2.compute.strategy.EC2LoadBalanceNodesStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2RebootNodeStrategy; import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy; import org.jclouds.aws.ec2.compute.suppliers.EC2HardwareSupplier; +import org.jclouds.aws.ec2.compute.suppliers.EC2ImageSupplier; import org.jclouds.aws.ec2.compute.suppliers.EC2LocationSupplier; import org.jclouds.aws.ec2.compute.suppliers.RegionAndNameToImageSupplier; -import org.jclouds.aws.ec2.domain.InstanceState; -import org.jclouds.aws.ec2.domain.KeyPair; -import org.jclouds.aws.ec2.domain.PlacementGroup; -import org.jclouds.aws.ec2.domain.RunningInstance; -import org.jclouds.aws.ec2.predicates.InstancePresent; -import org.jclouds.aws.ec2.predicates.PlacementGroupAvailable; -import org.jclouds.aws.ec2.predicates.PlacementGroupDeleted; -import org.jclouds.aws.suppliers.DefaultLocationSupplier; -import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.ComputeServiceContextImpl; -import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyLoadBalancerStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; @@ -84,27 +56,14 @@ import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.LoadBalanceNodesStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; -import org.jclouds.predicates.RetryablePredicate; -import org.jclouds.rest.RestContext; import org.jclouds.rest.annotations.Provider; -import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.rest.suppliers.RetryOnTimeOutButNotOnAuthorizationExceptionSupplier; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Splitter; import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.MapMaker; -import com.google.common.collect.Sets; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; /** * Configures the {@link ComputeServiceContext}; requires {@link EC2ComputeService} bound. @@ -112,78 +71,10 @@ import com.google.inject.TypeLiteral; * @author Adrian Cole */ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextModule { - - public static final Map instanceToNodeState = ImmutableMap - . builder().put(InstanceState.PENDING, NodeState.PENDING) - .put(InstanceState.RUNNING, NodeState.RUNNING).put(InstanceState.SHUTTING_DOWN, NodeState.PENDING) - .put(InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING) - .put(InstanceState.STOPPED, NodeState.SUSPENDED).put(InstanceState.UNRECOGNIZED, NodeState.UNRECOGNIZED) - .build(); - - @Singleton - @Provides - Map provideServerToNodeState() { - return instanceToNodeState; - } - - @Provides - @Singleton - @Named("PRESENT") - protected Predicate instancePresent(InstancePresent present) { - return new RetryablePredicate(present, 5000, 200, TimeUnit.MILLISECONDS); - } - - @Provides - @Singleton - @Named("AVAILABLE") - protected Predicate placementGroupAvailable(PlacementGroupAvailable available) { - return new RetryablePredicate(available, 60, 1, TimeUnit.SECONDS); - } - - @Provides - @Singleton - @Named("DELETED") - protected Predicate placementGroupDeleted(PlacementGroupDeleted deleted) { - return new RetryablePredicate(deleted, 60, 1, TimeUnit.SECONDS); - } - @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); - bind(TemplateOptions.class).to(EC2TemplateOptions.class); - bind(ComputeService.class).to(EC2ComputeService.class); - bind(new TypeLiteral>() { - }).to(RunningInstanceToNodeMetadata.class); - bind(new TypeLiteral>() { - }).to(CredentialsForInstance.class); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class); - bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class); - bind(RunNodesAndAddToSetStrategy.class).to(EC2RunNodesAndAddToSetStrategy.class); - bind(ListNodesStrategy.class).to(EC2ListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(EC2GetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(EC2RebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(EC2DestroyNodeStrategy.class); - } - - @Provides - @Singleton - Supplier provideSuffix() { - return new Supplier() { - final SecureRandom random = new SecureRandom(); - - @Override - public String get() { - return random.nextInt(100) + ""; - } - }; - + install(new EC2ComputeServiceDependenciesModule()); + super.configure(); } @Override @@ -197,94 +88,82 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod return template.osFamily(AMZN_LINUX).os64Bit(true); } - @Provides - @Singleton - protected final Map credentialsMap(CreateUniqueKeyPair in) { - // doesn't seem to clear when someone issues remove(key) - // return new MapMaker().makeComputingMap(in); - return newLinkedHashMap(); - } - - @Provides - @Singleton - @Named("SECURITY") - protected final Map securityGroupMap(CreateSecurityGroupIfNeeded in) { - // doesn't seem to clear when someone issues remove(key) - // return new MapMaker().makeComputingMap(in); - return newLinkedHashMap(); - } - - @Provides - @Singleton - @Named("PLACEMENT") - protected final Map placementGroupMap(CreatePlacementGroupIfNeeded in) { - // doesn't seem to clear when someone issues remove(key) - // return new MapMaker().makeComputingMap(in); - return newLinkedHashMap(); - } - - @Provides - @Singleton - @Named(PROPERTY_EC2_AMI_OWNERS) - String[] amiOwners(@Named(PROPERTY_EC2_AMI_OWNERS) String amiOwners) { - if (amiOwners.trim().equals("")) - return new String[] {}; - return toArray(Splitter.on(',').split(amiOwners), String.class); - } - - @Provides - @Singleton - @Named(PROPERTY_EC2_CC_AMIs) - String[] ccAmis(@Named(PROPERTY_EC2_CC_AMIs) String ccAmis) { - if (ccAmis.trim().equals("")) - return new String[] {}; - return toArray(Splitter.on(',').split(ccAmis), String.class); - } - - @Provides - @Singleton - protected Map provideImageMap(RegionAndIdToImage regionAndIdToImage) { - return new MapMaker().makeComputingMap(regionAndIdToImage); - } - @Provides @Singleton protected Supplier> provideRegionAndNameToImageSupplierCache( - @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) { + @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) { return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier>( - authException, seconds, new Supplier>() { - @Override - public Map get() { - return supplier.get(); - } - }); + authException, seconds, new Supplier>() { + @Override + public Map get() { + return supplier.get(); + } + }); } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - Supplier> map = injector.getInstance(Key - .get(new TypeLiteral>>() { - })); - return Suppliers.compose(new Function, Set>() { - @Override - public Set apply(Map from) { - return Sets.newLinkedHashSet(from.values()); - } - }, map); + protected void bindLoadBalancerService() { + bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class); + bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class); } @Override - protected Supplier> getSourceLocationSupplier(Injector injector) { - return injector.getInstance(EC2LocationSupplier.class); + protected Class defineRunNodesAndAddToSetStrategy() { + return EC2RunNodesAndAddToSetStrategy.class; + } + + /** + * not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based. + */ + @Override + protected Class defineAddNodeWithTagStrategy() { + return null; + } + + /** + * not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based. + */ + @Override + protected void bindAddNodeWithTagStrategy(Class clazz) { } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(EC2HardwareSupplier.class); + protected Class defineDestroyNodeStrategy() { + return EC2DestroyNodeStrategy.class; } @Override - protected Supplier supplyDefaultLocation(Injector injector, Supplier> locations) { - return injector.getInstance(DefaultLocationSupplier.class); + protected Class defineGetNodeMetadataStrategy() { + return EC2GetNodeMetadataStrategy.class; + } + + @Override + protected Class>> defineHardwareSupplier() { + return EC2HardwareSupplier.class; + } + + @Override + protected Class>> defineImageSupplier() { + return EC2ImageSupplier.class; + } + + @Override + protected Class defineListNodesStrategy() { + return EC2ListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return EC2RebootNodeStrategy.class; + } + + @Override + protected Class> defineDefaultLocationSupplier() { + return org.jclouds.aws.suppliers.DefaultLocationSupplier.class; + } + + @Override + protected Class>> defineLocationSupplier() { + return EC2LocationSupplier.class; } } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceDependenciesModule.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..0438d500fc --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceDependenciesModule.java @@ -0,0 +1,198 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.ec2.compute.config; + +import static com.google.common.collect.Iterables.toArray; +import static com.google.common.collect.Maps.newLinkedHashMap; +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.security.SecureRandom; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.aws.ec2.EC2AsyncClient; +import org.jclouds.aws.ec2.EC2Client; +import org.jclouds.aws.ec2.compute.EC2ComputeService; +import org.jclouds.aws.ec2.compute.domain.RegionAndName; +import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded; +import org.jclouds.aws.ec2.compute.functions.CreateSecurityGroupIfNeeded; +import org.jclouds.aws.ec2.compute.functions.CreateUniqueKeyPair; +import org.jclouds.aws.ec2.compute.functions.CredentialsForInstance; +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.options.EC2TemplateOptions; +import org.jclouds.aws.ec2.domain.InstanceState; +import org.jclouds.aws.ec2.domain.KeyPair; +import org.jclouds.aws.ec2.domain.PlacementGroup; +import org.jclouds.aws.ec2.domain.RunningInstance; +import org.jclouds.aws.ec2.predicates.InstancePresent; +import org.jclouds.aws.ec2.predicates.PlacementGroupAvailable; +import org.jclouds.aws.ec2.predicates.PlacementGroupDeleted; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.domain.Credentials; +import org.jclouds.predicates.RetryablePredicate; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Splitter; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.MapMaker; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +public class EC2ComputeServiceDependenciesModule extends AbstractModule { + + public static final Map instanceToNodeState = ImmutableMap + . builder().put(InstanceState.PENDING, NodeState.PENDING).put( + InstanceState.RUNNING, NodeState.RUNNING).put(InstanceState.SHUTTING_DOWN, NodeState.PENDING).put( + InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING) + .put(InstanceState.STOPPED, NodeState.SUSPENDED).put(InstanceState.UNRECOGNIZED, NodeState.UNRECOGNIZED) + .build(); + + @Singleton + @Provides + Map provideServerToNodeState() { + return instanceToNodeState; + } + + @Provides + @Singleton + @Named("PRESENT") + protected Predicate instancePresent(InstancePresent present) { + return new RetryablePredicate(present, 5000, 200, TimeUnit.MILLISECONDS); + } + + @Provides + @Singleton + @Named("AVAILABLE") + protected Predicate placementGroupAvailable(PlacementGroupAvailable available) { + return new RetryablePredicate(available, 60, 1, TimeUnit.SECONDS); + } + + @Provides + @Singleton + @Named("DELETED") + protected Predicate placementGroupDeleted(PlacementGroupDeleted deleted) { + return new RetryablePredicate(deleted, 60, 1, TimeUnit.SECONDS); + } + + @Override + protected void configure() { + bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); + bind(TemplateOptions.class).to(EC2TemplateOptions.class); + bind(ComputeService.class).to(EC2ComputeService.class); + bind(new TypeLiteral>() { + }).to(RunningInstanceToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(CredentialsForInstance.class); + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + } + + @Provides + @Singleton + Supplier provideSuffix() { + return new Supplier() { + final SecureRandom random = new SecureRandom(); + + @Override + public String get() { + return random.nextInt(100) + ""; + } + }; + + } + + @Provides + @Singleton + protected final Map credentialsMap(CreateUniqueKeyPair in) { + // doesn't seem to clear when someone issues remove(key) + // return new MapMaker().makeComputingMap(in); + return newLinkedHashMap(); + } + + @Provides + @Singleton + @Named("SECURITY") + protected final Map securityGroupMap(CreateSecurityGroupIfNeeded in) { + // doesn't seem to clear when someone issues remove(key) + // return new MapMaker().makeComputingMap(in); + return newLinkedHashMap(); + } + + @Provides + @Singleton + @Named("PLACEMENT") + protected final Map placementGroupMap(CreatePlacementGroupIfNeeded in) { + // doesn't seem to clear when someone issues remove(key) + // return new MapMaker().makeComputingMap(in); + return newLinkedHashMap(); + } + + @Provides + @Singleton + @Named(PROPERTY_EC2_AMI_OWNERS) + String[] amiOwners(@Named(PROPERTY_EC2_AMI_OWNERS) String amiOwners) { + if (amiOwners.trim().equals("")) + return new String[] {}; + return toArray(Splitter.on(',').split(amiOwners), String.class); + } + + @Provides + @Singleton + @Named(PROPERTY_EC2_CC_AMIs) + String[] ccAmis(@Named(PROPERTY_EC2_CC_AMIs) String ccAmis) { + if (ccAmis.trim().equals("")) + return new String[] {}; + return toArray(Splitter.on(',').split(ccAmis), String.class); + } + + @Provides + @Singleton + protected Map provideImageMap(RegionAndIdToImage regionAndIdToImage) { + return new MapMaker().makeComputingMap(regionAndIdToImage); + } + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java index d39f6d0d5f..e25b15d4b6 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java @@ -35,6 +35,7 @@ import javax.inject.Singleton; import org.jclouds.aws.ec2.domain.Image.Architecture; import org.jclouds.aws.ec2.domain.Image.ImageType; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; @@ -71,17 +72,17 @@ public class ImageParser implements Function> locations; @@ -91,7 +92,8 @@ public class ImageParser implements Function> locations, Supplier defaultLocation, @Provider String provider) { + @Memoized Supplier> locations, Supplier defaultLocation, + @Provider String provider) { this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider"); this.locations = checkNotNull(locations, "locations"); this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation"); @@ -109,7 +111,7 @@ public class ImageParser implements Function of("owner", from.getImageOwnerId(), "rootDeviceType", from - .getRootDeviceType().toString())); + .getRootDeviceType().toString())); OsFamily osFamily = parseOsFamilyOrNull(provider, from.getImageLocation()); String osName = null; @@ -150,7 +152,7 @@ public class ImageParser implements Function instanceToNodeState, - Map credentialStore, Map instanceToImage, - Supplier> locations, Supplier> hardware) { + Map credentialStore, Map instanceToImage, + @Memoized Supplier> locations, @Memoized Supplier> hardware) { this.locations = checkNotNull(locations, "locations"); this.hardware = checkNotNull(hardware, "hardware"); this.instanceToImage = checkNotNull(instanceToImage, "instanceToImage"); @@ -119,14 +120,15 @@ public class RunningInstanceToNodeMetadata implements Function addEBS(final RunningInstance instance, Iterable volumes) { Iterable ebsVolumes = Iterables.transform(instance.getEbsBlockDevices().entrySet(), - new Function, Volume>() { + new Function, Volume>() { - @Override - public Volume apply(Entry from) { - return new VolumeImpl(from.getValue().getVolumeId(), Volume.Type.SAN, null, from.getKey(), instance - .getRootDeviceName() != null && instance.getRootDeviceName().equals(from.getKey()), true); - } - }); + @Override + public Volume apply(Entry from) { + return new VolumeImpl(from.getValue().getVolumeId(), Volume.Type.SAN, null, from.getKey(), + instance.getRootDeviceName() != null + && instance.getRootDeviceName().equals(from.getKey()), true); + } + }); if (instance.getRootDeviceType() == RootDeviceType.EBS) { volumes = Iterables.filter(volumes, new Predicate() { @@ -158,7 +160,9 @@ public class RunningInstanceToNodeMetadata implements Function imageMap; @Inject - protected EC2TemplateBuilderImpl(Supplier> locations, Supplier> images, - Supplier> sizes, Supplier defaultLocation, - Provider optionsProvider, - @Named("DEFAULT") Provider defaultTemplateProvider, Map imageMap) { + protected EC2TemplateBuilderImpl(@Memoized Supplier> locations, + @Memoized Supplier> images, @Memoized Supplier> sizes, + Supplier defaultLocation, Provider optionsProvider, + @Named("DEFAULT") Provider defaultTemplateProvider, Map imageMap) { super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider); this.imageMap = imageMap; } @@ -86,7 +87,8 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl { if (imageId != null) { String[] regionName = imageId.split("/"); checkArgument(regionName.length == 2, - "amazon image ids must include the region ( ex. us-east-1/ami-7ea24a17 ) you specified: " + imageId); + "amazon image ids must include the region ( ex. us-east-1/ami-7ea24a17 ) you specified: " + + imageId); RegionAndName key = new RegionAndName(regionName[0], regionName[1]); try { return imageMap.get(key); diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java index 8bdf4e6615..36dc9d2552 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java @@ -41,6 +41,7 @@ import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Location; @@ -66,8 +67,8 @@ public class EC2HardwareSupplier implements Supplier> { private final String providerName; @Inject - EC2HardwareSupplier(Supplier> locations, @Provider String providerName, - @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) { + EC2HardwareSupplier(@Memoized Supplier> locations, @Provider String providerName, + @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) { this.locations = locations; this.ccAmis = ccAmis; this.providerName = providerName; @@ -89,8 +90,8 @@ public class EC2HardwareSupplier implements Supplier> { sizes.add(cc1_4xlarge().location(location).supportsImageIds(ccAmi).build()); } sizes.addAll(ImmutableSet. of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large() - .build(), "nova".equals(providerName) ? m1_small().supportsImage(any()).build() : m1_small().build(), - m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(), m2_4xlarge().build())); + .build(), "nova".equals(providerName) ? m1_small().supportsImage(any()).build() : m1_small().build(), + m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(), m2_4xlarge().build())); return sizes; } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2ImageSupplier.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2ImageSupplier.java new file mode 100644 index 0000000000..ee6fe4c0bd --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2ImageSupplier.java @@ -0,0 +1,52 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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 java.util.Map; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.aws.ec2.compute.domain.RegionAndName; +import org.jclouds.compute.domain.Image; + +import com.google.common.base.Supplier; +import com.google.common.collect.Sets; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class EC2ImageSupplier implements Supplier> { + private final Supplier> map; + + @Inject + EC2ImageSupplier(Supplier> map) { + this.map = map; + } + + @Override + public Set get() { + return Sets.newLinkedHashSet(map.get().values()); + } + +} \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3AsyncBlobStore.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3AsyncBlobStore.java index 066657a7d5..fad2caa18b 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3AsyncBlobStore.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3AsyncBlobStore.java @@ -55,6 +55,7 @@ import org.jclouds.blobstore.internal.BaseAsyncBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.concurrent.Futures; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; @@ -85,7 +86,7 @@ public class S3AsyncBlobStore extends BaseAsyncBlobStore { @Inject S3AsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations, S3AsyncClient async, S3Client sync, + @Memoized Supplier> locations, S3AsyncClient async, S3Client sync, BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java index 930e9b47b8..369eeaf758 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/S3BlobStore.java @@ -49,6 +49,7 @@ import org.jclouds.blobstore.internal.BaseBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; import org.jclouds.util.Utils; @@ -75,10 +76,11 @@ public class S3BlobStore extends BaseBlobStore { @Inject S3BlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, - Supplier> locations, S3Client sync, BucketToResourceMetadata bucket2ResourceMd, - ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList, - ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, - ObjectToBlobMetadata object2BlobMd, Provider fetchBlobMetadataProvider) { + @Memoized Supplier> locations, S3Client sync, + BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions, + BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob, + BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, + Provider fetchBlobMetadataProvider) { super(context, blobUtils, defaultLocation, locations); this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions"); this.sync = checkNotNull(sync, "sync"); diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java index 076cf69b61..9ca1d87698 100755 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/config/S3BlobStoreContextModule.java @@ -37,6 +37,7 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.internal.BlobStoreContextImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; @@ -73,6 +74,7 @@ public class S3BlobStoreContextModule extends AbstractModule { @Provides @Singleton + @Memoized Supplier> provideLocations(@Region Set regions, @Provider String providerName) { Set locations = Sets.newHashSet(); Location s3 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java index 59c38be173..1a91201aff 100644 --- a/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java +++ b/aws/core/src/main/java/org/jclouds/aws/s3/blobstore/functions/BucketToResourceMetadata.java @@ -33,6 +33,7 @@ import org.jclouds.blobstore.domain.MutableStorageMetadata; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -54,7 +55,7 @@ public class BucketToResourceMetadata implements Function> locations) { + BucketToResourceMetadata(S3Client client, @Memoized Supplier> locations) { this.client = client; this.onlyLocation = locations.get().size() == 1 ? Iterables.get(locations.get(), 0) : null; this.locations = locations; diff --git a/aws/core/src/main/java/org/jclouds/aws/suppliers/DefaultLocationSupplier.java b/aws/core/src/main/java/org/jclouds/aws/suppliers/DefaultLocationSupplier.java index 5ea529cf6d..cec0d37e21 100644 --- a/aws/core/src/main/java/org/jclouds/aws/suppliers/DefaultLocationSupplier.java +++ b/aws/core/src/main/java/org/jclouds/aws/suppliers/DefaultLocationSupplier.java @@ -26,6 +26,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.aws.Region; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; @@ -42,7 +43,7 @@ public class DefaultLocationSupplier implements Supplier { private final Supplier> set; @Inject - DefaultLocationSupplier(@Region final String region, Supplier> set) { + DefaultLocationSupplier(@Region final String region, @Memoized Supplier> set) { this.region = region; this.set = set; } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java index e865f9c6e4..3ebb28664d 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java @@ -33,6 +33,7 @@ import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m2_2xlarge; import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m2_4xlarge; import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m2_xlarge; import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.t1_micro; +import static org.testng.Assert.assertEquals; import java.util.Set; @@ -58,7 +59,6 @@ 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 static org.testng.Assert.assertEquals; /** * Tests compute service specifically to EC2. @@ -74,7 +74,7 @@ public class EC2ComputeServiceTest { private static final Location location = new LocationImpl(LocationScope.REGION, "us-east-1", "us east", null); public static final Hardware CC1_4XLARGE = cc1_4xlarge().location(location).supportsImageIds("us-east-1/cc-image") - .build(); + .build(); /** * Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based @@ -87,10 +87,10 @@ public class EC2ComputeServiceTest { Template template = newTemplateBuilder().os64Bit(true).hardwareId("m2.xlarge").locationId("us-east-1").build(); assert template != null : "The returned template was null, but it should have a value."; -// assert m2_xlarge().build().equals(template.getHardware()) : format( -// "Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", -// String.valueOf(template.getHardware())); - assertEquals( m2_xlarge().build(), template.getHardware()); + // assert m2_xlarge().build().equals(template.getHardware()) : format( + // "Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", + // String.valueOf(template.getHardware())); + assertEquals(m2_xlarge().build(), template.getHardware()); } @Test @@ -99,8 +99,8 @@ public class EC2ComputeServiceTest { assert template != null : "The returned template was null, but it should have a value."; assert CC1_4XLARGE.equals(template.getHardware()) : format( - "Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE.getId(), - String.valueOf(template.getHardware())); + "Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE.getId(), String + .valueOf(template.getHardware())); } /** @@ -111,13 +111,13 @@ public class EC2ComputeServiceTest { */ @Test public void testTemplateChoiceForInstanceByAttributes() throws Exception { - Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.5).smallest() - .locationId("us-east-1").build(); + Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.5).smallest().locationId( + "us-east-1").build(); assert template != null : "The returned template was null, but it should have a value."; assert CC1_4XLARGE.equals(template.getHardware()) : format( - "Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE, - String.valueOf(template.getHardware())); + "Incorrect image determined by the template. Expected: %s. Found: %s.", CC1_4XLARGE, String + .valueOf(template.getHardware())); } /** @@ -130,13 +130,13 @@ public class EC2ComputeServiceTest { */ @Test public void testNegativeTemplateChoiceForInstanceByAttributes() throws Exception { - Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.7).smallest() - .locationId("us-east-1").build(); + Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.7).smallest().locationId( + "us-east-1").build(); assert template != null : "The returned template was null, but it should have a value."; assert !m2_xlarge().build().equals(template.getHardware()) : format( - "Incorrect image determined by the template. Expected: not %s. Found: %s.", "m2.xlarge", - String.valueOf(template.getHardware())); + "Incorrect image determined by the template. Expected: not %s. Found: %s.", "m2.xlarge", String + .valueOf(template.getHardware())); } @SuppressWarnings("unchecked") @@ -148,23 +148,22 @@ public class EC2ComputeServiceTest { expect(optionsProvider.get()).andReturn(defaultOptions); - Image image = new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image") - .location(location) - .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", null, "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new Credentials("root", null)).build(); + Image image = new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) + .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", null, "ubuntu", true)).description( + "description").version("1.0").defaultCredentials(new Credentials("root", null)).build(); replay(optionsProvider); replay(templateBuilderProvider); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); + . of(image)); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(), m1_small() - .build(), m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(), m2_4xlarge().build(), - CC1_4XLARGE)); + . of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(), + m1_small().build(), m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(), + m2_4xlarge().build(), CC1_4XLARGE)); return new TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(location), optionsProvider, - templateBuilderProvider) { + templateBuilderProvider) { }; } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java index 28664cde04..37f4ba9c91 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java @@ -85,7 +85,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -97,7 +97,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1d", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // @@ -180,7 +180,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -192,7 +192,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // @@ -264,7 +264,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -276,7 +276,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // @@ -339,7 +339,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -350,7 +350,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // @@ -426,9 +426,9 @@ public class CredentialsForInstanceTest { // ConcurrentMap imageMap = createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -487,9 +487,9 @@ public class CredentialsForInstanceTest { // ConcurrentMap imageMap = createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -549,9 +549,9 @@ public class CredentialsForInstanceTest { // ConcurrentMap imageMap = createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -616,9 +616,9 @@ public class CredentialsForInstanceTest { // ConcurrentMap imageMap = createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -677,9 +677,9 @@ public class CredentialsForInstanceTest { // ConcurrentMap imageMap = createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -736,7 +736,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -748,7 +748,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // @@ -810,7 +810,7 @@ public class CredentialsForInstanceTest { // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = createMock(ConcurrentMap.class); -// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); // RunningInstance instance = createMock(RunningInstance.class); @@ -822,7 +822,7 @@ public class CredentialsForInstanceTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); -// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// @Memoized Supplier> locations = Suppliers.> ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); // diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index 8ddf849bf5..b1ecab6ad0 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -26,7 +26,7 @@ import java.net.UnknownHostException; import java.util.Map; import java.util.Set; -import org.jclouds.aws.ec2.compute.config.EC2ComputeServiceContextModule; +import org.jclouds.aws.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.aws.ec2.compute.domain.RegionAndName; import org.jclouds.aws.ec2.domain.InstanceState; import org.jclouds.aws.ec2.domain.RunningInstance; @@ -61,7 +61,7 @@ public class RunningInstanceToNodeMetadataTest { public void testAllStatesCovered() { for (InstanceState state : InstanceState.values()) { - assert EC2ComputeServiceContextModule.instanceToNodeState.containsKey(state) : state; + assert EC2ComputeServiceDependenciesModule.instanceToNodeState.containsKey(state) : state; } } @@ -70,101 +70,86 @@ public class RunningInstanceToNodeMetadataTest { @Test public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound() - throws UnknownHostException { + throws UnknownHostException { Credentials creds = new Credentials("root", "abdce"); - RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), - ImmutableSet. of(), ImmutableSet. of(), - ImmutableMap. of("us-east-1/i-9slweygo", creds)); + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet + . of(), ImmutableSet. of(), ImmutableMap. of( + "us-east-1/i-9slweygo", creds)); RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); - assertEquals(parser.apply(server), - new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses(ImmutableSet. of()) - .privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").credentials(creds) - .imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo").providerId("i-9slweygo").build()); + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses( + ImmutableSet. of()).privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo") + .credentials(creds).imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo") + .providerId("i-9slweygo").build()); } @Test public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFound() throws UnknownHostException { - RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), - ImmutableSet. of(), ImmutableSet. of(), ImmutableMap. of()); + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet + . of(), ImmutableSet. of(), ImmutableMap. of()); RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); - assertEquals( - parser.apply(server), - new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses(ImmutableSet. of()) - .privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo") - .imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo").providerId("i-9slweygo").build()); + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses( + ImmutableSet. of()).privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo") + .imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo").providerId("i-9slweygo").build()); } @Test public void testApplyWhereTagDoesntMatchAndLocationFoundAndImageAndHardwareNotFound() throws UnknownHostException { RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet.of(provider), - ImmutableSet. of(), ImmutableMap. of()); + ImmutableSet. of(), ImmutableMap. of()); RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); - assertEquals( - parser.apply(server), - new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses(ImmutableSet.of("10.128.207.5")) - .tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo") - .providerId("i-9slweygo").location(provider).build()); + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses( + ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213").id( + "us-east-1/i-9slweygo").providerId("i-9slweygo").location(provider).build()); } @Test public void testApplyWhereTagDoesntMatchAndImageAndLocationFoundAndHardwareNotFound() throws UnknownHostException { RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet.of(provider), - ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap. of()); + ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap. of()); RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); - assertEquals( - parser.apply(server), - new NodeMetadataBuilder() - .state(NodeState.TERMINATED) - .privateAddresses(ImmutableSet.of("10.128.207.5")) - .tag("NOTAG-i-9slweygo") - .imageId("us-east-1/ami-25CB1213") - .operatingSystem( + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses( + ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213") + .operatingSystem( new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("9.10").arch("paravirtual") - .description("nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo") - .providerId("i-9slweygo").location(provider).build()); + .description("nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo") + .providerId("i-9slweygo").location(provider).build()); } @Test public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationFound() throws UnknownHostException { - RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), - ImmutableSet.of(provider), ImageParserTest.convertImages("/ec2/nova_images.xml"), - ImmutableMap. of()); + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet + .of(provider), ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap + . of()); RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); - assertEquals( - parser.apply(server), - new NodeMetadataBuilder() - .state(NodeState.TERMINATED) - .privateAddresses(ImmutableSet.of("10.128.207.5")) - .tag("NOTAG-i-9slweygo") - .imageId("us-east-1/ami-25CB1213") - .hardware(m1_small().build()) - .operatingSystem( - new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("9.10").arch("paravirtual") - .description("nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo") - .providerId("i-9slweygo").location(provider).build()); + assertEquals(parser.apply(server), new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses( + ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213").hardware( + m1_small().build()).operatingSystem( + new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("9.10").arch("paravirtual").description( + "nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo").providerId( + "i-9slweygo").location(provider).build()); } protected RunningInstance firstInstanceFromResource(String resource) { - RunningInstance server = Iterables.get( - Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0); + RunningInstance server = Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest + .parseRunningInstances(resource), 0), 0); return server; } protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, - final ImmutableSet locations, Set images, - Map credentialStore) { - Map instanceToNodeState = EC2ComputeServiceContextModule.instanceToNodeState; + final ImmutableSet locations, Set images, + Map credentialStore) { + Map instanceToNodeState = EC2ComputeServiceDependenciesModule.instanceToNodeState; Map instanceToImage = Maps.uniqueIndex(images, new Function() { @@ -191,7 +176,7 @@ public class RunningInstanceToNodeMetadataTest { }; RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(instanceToNodeState, credentialStore, - instanceToImage, locationSupplier, hardwareSupplier); + instanceToImage, locationSupplier, hardwareSupplier); return parser; } @@ -207,7 +192,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -221,7 +206,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1d", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -313,7 +298,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -327,7 +312,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -406,7 +391,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -420,7 +405,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -489,7 +474,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m1_small().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -502,7 +487,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location region = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(region)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -585,10 +570,10 @@ public class RunningInstanceToNodeMetadataTest { // createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -651,10 +636,10 @@ public class RunningInstanceToNodeMetadataTest { // createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -719,10 +704,10 @@ public class RunningInstanceToNodeMetadataTest { // createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -794,10 +779,10 @@ public class RunningInstanceToNodeMetadataTest { // createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -861,10 +846,10 @@ public class RunningInstanceToNodeMetadataTest { // createMock(ConcurrentMap.class); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -926,7 +911,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -940,7 +925,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -1006,7 +991,7 @@ public class RunningInstanceToNodeMetadataTest { // Map credentialsMap = createMock(Map.class); // ConcurrentMap imageMap = // createMock(ConcurrentMap.class); - // Supplier> hardwares = Suppliers.> + // @Memoized Supplier> hardwares = Suppliers.> // ofInstance(ImmutableSet // . of(m2_4xlarge().build())); // PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = @@ -1021,7 +1006,7 @@ public class RunningInstanceToNodeMetadataTest { // expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING); // // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - // Supplier> locations = Suppliers.> + // @Memoized Supplier> locations = Suppliers.> // ofInstance(ImmutableSet // . of(location)); // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java index 72b4598821..fc1cdaa1cd 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java @@ -34,6 +34,7 @@ import javax.inject.Provider; import org.jclouds.aws.ec2.compute.domain.RegionAndName; import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OperatingSystem; @@ -67,22 +68,22 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { @Override protected EC2TemplateBuilderImpl createTemplateBuilder(final Image knownImage, - Supplier> locations, Supplier> images, - Supplier> sizes, Location defaultLocation, Provider optionsProvider, - Provider templateBuilderProvider) { + @Memoized Supplier> locations, @Memoized Supplier> images, + @Memoized Supplier> sizes, Location defaultLocation, + Provider optionsProvider, Provider templateBuilderProvider) { final RegionAndName knownRegionAndName = new RegionAndName("region", "ami"); ConcurrentMap imageMap = new MapMaker() - .makeComputingMap(new Function() { - @Override - public Image apply(RegionAndName from) { - return from.equals(knownRegionAndName) ? knownImage : null; - } + .makeComputingMap(new Function() { + @Override + public Image apply(RegionAndName from) { + return from.equals(knownRegionAndName) ? knownImage : null; + } - }); + }); return new EC2TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(defaultLocation), - optionsProvider, templateBuilderProvider, imageMap); + optionsProvider, templateBuilderProvider, imageMap); } @SuppressWarnings("unchecked") @@ -91,11 +92,11 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(Sets - . newLinkedHashSet()); + . newLinkedHashSet()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(c1_medium().build())); + . of(c1_medium().build())); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -127,7 +128,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, location, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); assertEquals(template.imageId("region/ami").build().getImage(), knownImage); @@ -144,10 +145,10 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(c1_medium().build())); + . of(c1_medium().build())); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -162,7 +163,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, location, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("ami").build(); assert false; @@ -181,10 +182,10 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(c1_medium().build())); + . of(c1_medium().build())); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); @@ -202,7 +203,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); assertEquals(template.imageId("region/bad").build().getImage(), knownImage); diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureAsyncBlobStore.java b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureAsyncBlobStore.java index deff8df23d..5fbc2b3b1f 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureAsyncBlobStore.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureAsyncBlobStore.java @@ -53,6 +53,7 @@ import org.jclouds.blobstore.functions.BlobToHttpGetOptions; import org.jclouds.blobstore.internal.BaseAsyncBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.concurrent.Futures; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; @@ -79,7 +80,7 @@ public class AzureAsyncBlobStore extends BaseAsyncBlobStore { @Inject AzureAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations, AzureBlobAsyncClient async, + @Memoized Supplier> locations, AzureBlobAsyncClient async, ContainerToResourceMetadata container2ResourceMd, ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions, ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob, diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobStore.java b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobStore.java index f88ff553ad..7a70b8c66f 100644 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobStore.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/AzureBlobStore.java @@ -47,6 +47,7 @@ import org.jclouds.blobstore.functions.BlobToHttpGetOptions; import org.jclouds.blobstore.internal.BaseBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; @@ -70,7 +71,7 @@ public class AzureBlobStore extends BaseBlobStore { @Inject AzureBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, - Supplier> locations, AzureBlobClient sync, + @Memoized Supplier> locations, AzureBlobClient sync, ContainerToResourceMetadata container2ResourceMd, ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions, ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob, diff --git a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreContextModule.java b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreContextModule.java index b2559f613d..da5e50669b 100755 --- a/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreContextModule.java +++ b/azure/src/main/java/org/jclouds/azure/storage/blob/blobstore/config/AzureBlobStoreContextModule.java @@ -37,6 +37,7 @@ import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.internal.BlobStoreContextImpl; import org.jclouds.blobstore.strategy.ContainsValueInListStrategy; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; @@ -71,6 +72,7 @@ public class AzureBlobStoreContextModule extends AbstractModule { @Provides @Singleton + @Memoized Supplier> provideLocations(Supplier defaultLocation) { return Suppliers.> ofInstance(ImmutableSet.of(defaultLocation.get())); } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java index 8fc18d1b17..5b2bae075b 100755 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/TransientAsyncBlobStore.java @@ -78,6 +78,7 @@ import org.jclouds.blobstore.options.GetOptions; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.IfDirectoryReturnNameStrategy; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.crypto.Crypto; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.DateService; @@ -127,7 +128,7 @@ public class TransientAsyncBlobStore extends BaseAsyncBlobStore { HttpGetOptionsListToGetOptions httpGetOptionsConverter, IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations) { + @Memoized Supplier> locations) { super(context, blobUtils, service, defaultLocation, locations); this.blobFactory = blobFactory; this.dateService = dateService; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java b/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java index 0c827ed4c7..7c76b8b6d1 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java @@ -34,6 +34,7 @@ import org.jclouds.blobstore.TransientBlobRequestSigner; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.internal.BlobStoreContextImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; @@ -81,6 +82,7 @@ public class TransientBlobStoreContextModule extends AbstractModule { @Provides @Singleton + @Memoized Supplier> provideLocations(Supplier defaultLocation) { return Suppliers.> ofInstance(ImmutableSet.of(defaultLocation.get())); } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java index 2583a0648e..7f9cea4159 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseAsyncBlobStore.java @@ -39,6 +39,7 @@ import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.blobstore.util.internal.BlobUtilsImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.util.Utils; @@ -61,7 +62,7 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore { @Inject protected BaseAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations) { + @Memoized Supplier> locations) { this.context = checkNotNull(context, "context"); this.blobUtils = checkNotNull(blobUtils, "blobUtils"); this.service = checkNotNull(service, "service"); @@ -267,5 +268,4 @@ public abstract class BaseAsyncBlobStore implements AsyncBlobStore { protected abstract boolean deleteAndVerifyContainerGone(String container); - } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java index 3929a63b81..736b8c56f9 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java @@ -35,6 +35,7 @@ import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.blobstore.util.internal.BlobUtilsImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.util.Utils; @@ -53,7 +54,7 @@ public abstract class BaseBlobStore implements BlobStore { @Inject protected BaseBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, - Supplier> locations) { + @Memoized Supplier> locations) { this.context = checkNotNull(context, "context"); this.blobUtils = checkNotNull(blobUtils, "blobUtils"); this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation"); diff --git a/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java b/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java index bbca09154b..41987094b9 100644 --- a/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java +++ b/compute/src/main/java/org/jclouds/compute/ComputeServiceContextFactory.java @@ -26,9 +26,12 @@ import java.util.Properties; import javax.annotation.Nullable; +import org.jclouds.PropertiesBuilder; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory.ContextSpec; +import com.google.common.collect.ImmutableSet; import com.google.inject.Module; /** @@ -41,8 +44,8 @@ public class ComputeServiceContextFactory { private final RestContextFactory contextFactory; /** - * Initializes with the default properties built-in to jclouds. This is - * typically stored in the classpath resource {@code rest.properties} + * Initializes with the default properties built-in to jclouds. This is typically stored in the + * classpath resource {@code rest.properties} * * @see RestContextFactory#getPropertiesFromResource */ @@ -59,15 +62,14 @@ public class ComputeServiceContextFactory { /** * - * Uses the supplied RestContextFactory to create - * {@link ComputeServiceContext}s + * Uses the supplied RestContextFactory to create {@link ComputeServiceContext}s */ public ComputeServiceContextFactory(RestContextFactory restContextFactory) { this.contextFactory = restContextFactory; } public static ComputeServiceContext buildContextUnwrappingExceptions( - ComputeServiceContextBuilder builder) { + ComputeServiceContextBuilder builder) { try { return builder.buildComputeServiceContext(); } catch (Exception e) { @@ -80,7 +82,7 @@ public class ComputeServiceContextFactory { */ public ComputeServiceContext createContext(String provider, String identity, String credential) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(contextFactory - .createContextBuilder(provider, identity, credential)); + .createContextBuilder(provider, identity, credential)); return buildContextUnwrappingExceptions(builder); } @@ -89,7 +91,7 @@ public class ComputeServiceContextFactory { */ public ComputeServiceContext createContext(String provider, Properties overrides) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(contextFactory - .createContextBuilder(provider, overrides)); + .createContextBuilder(provider, overrides)); return buildContextUnwrappingExceptions(builder); } @@ -98,30 +100,28 @@ public class ComputeServiceContextFactory { */ public ComputeServiceContext createContext(String provider, Iterable modules, Properties overrides) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(contextFactory - .createContextBuilder(provider, modules, overrides)); + .createContextBuilder(provider, modules, overrides)); return buildContextUnwrappingExceptions(builder); } /** - * @see RestContextFactory#createContextBuilder(String, String,String, - * Iterable) + * @see RestContextFactory#createContextBuilder(String, String,String, Iterable) */ public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential, - Iterable modules) { + Iterable modules) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(contextFactory - .createContextBuilder(provider, identity, credential, modules)); + .createContextBuilder(provider, identity, credential, modules)); return buildContextUnwrappingExceptions(builder); } /** - * @see RestContextFactory#createContextBuilder(String, String,String, - * Iterable, Properties) + * @see RestContextFactory#createContextBuilder(String, String,String, Iterable, Properties) */ public ComputeServiceContext createContext(String provider, @Nullable String identity, @Nullable String credential, - Iterable modules, Properties overrides) { + Iterable modules, Properties overrides) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(contextFactory - .createContextBuilder(provider, identity, credential, modules, overrides)); + .createContextBuilder(provider, identity, credential, modules, overrides)); return buildContextUnwrappingExceptions(builder); } @@ -130,7 +130,7 @@ public class ComputeServiceContextFactory { */ public ComputeServiceContext createContext(ContextSpec contextSpec) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class - .cast(createContextBuilder(contextSpec)); + .cast(createContextBuilder(contextSpec)); return buildContextUnwrappingExceptions(builder); } @@ -140,8 +140,21 @@ public class ComputeServiceContextFactory { */ public ComputeServiceContext createContext(ContextSpec contextSpec, Properties overrides) { ComputeServiceContextBuilder builder = ComputeServiceContextBuilder.class.cast(createContextBuilder( - contextSpec, overrides)); + contextSpec, overrides)); return buildContextUnwrappingExceptions(builder); } + public static ComputeServiceContext createStandaloneContext(StandaloneComputeServiceContextModule contextModule) { + return createStandaloneContext(contextModule, ImmutableSet. of()); + } + + @SuppressWarnings("unchecked") + public static ComputeServiceContext createStandaloneContext(StandaloneComputeServiceContextModule contextModule, + Iterable modules) { + return new ComputeServiceContextFactory().createContext(RestContextFactory + . contextSpec("standalone", "standalone", "1", "standalone", null, + (Class) null, (Class) null, PropertiesBuilder.class, + (Class) StandaloneComputeServiceContextBuilder.class, ImmutableSet. builder().add( + contextModule).addAll(modules).build())); + } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServicePropertiesBuilder.java b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java similarity index 53% rename from compute/src/main/java/org/jclouds/compute/stub/StubComputeServicePropertiesBuilder.java rename to compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java index babaa8066d..5c4f8041b2 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServicePropertiesBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/StandaloneComputeServiceContextBuilder.java @@ -17,41 +17,39 @@ * ==================================================================== */ -package org.jclouds.compute.stub; +package org.jclouds.compute; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.Constants.PROPERTY_ENDPOINT; import static org.jclouds.Constants.PROPERTY_IDENTITY; -import java.net.URI; +import java.util.List; import java.util.Properties; -import org.jclouds.PropertiesBuilder; +import org.jclouds.compute.config.StandaloneComputeServiceClientModule; + +import com.google.inject.Module; /** - * Builds properties used in stub compute services * * @author Adrian Cole */ -public class StubComputeServicePropertiesBuilder extends PropertiesBuilder { +public class StandaloneComputeServiceContextBuilder extends + ComputeServiceContextBuilder { + + public StandaloneComputeServiceContextBuilder(Properties props) { + super(ComputeService.class, ComputeService.class, props); + if (!properties.containsKey(PROPERTY_ENDPOINT)) + properties.setProperty(PROPERTY_ENDPOINT, "standalone"); + if (!properties.containsKey(PROPERTY_API_VERSION)) + properties.setProperty(PROPERTY_API_VERSION, "1"); + if (!properties.containsKey(PROPERTY_IDENTITY)) + properties.setProperty(PROPERTY_IDENTITY, System.getProperty("user.name")); + } + @Override - protected Properties defaultProperties() { - Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_ENDPOINT, "http://localhost/stub"); - properties.setProperty(PROPERTY_API_VERSION, "1"); - properties.setProperty(PROPERTY_IDENTITY, System.getProperty("user.name")); - return properties; + protected void addClientModule(List modules) { + modules.add(new StandaloneComputeServiceClientModule()); } - public StubComputeServicePropertiesBuilder(Properties properties) { - super(properties); - } - - public StubComputeServicePropertiesBuilder withCredentials(String id, String secret) { - return this; - } - - public StubComputeServicePropertiesBuilder withEndpoint(URI endpoint) { - return this; - } -} +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java index 5cd64924c7..47bd722d32 100644 --- a/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java @@ -26,13 +26,23 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; +import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.domain.ComputeMetadata; -import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.strategy.AddNodeWithTagStrategy; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; +import org.jclouds.compute.strategy.impl.EncodeTagIntoNameRunNodesAndAddToSetStrategy; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.rest.AuthorizationException; @@ -46,27 +56,152 @@ 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.Scopes; import com.google.inject.TypeLiteral; +import com.google.inject.util.Providers; /** * * @author Adrian Cole */ public abstract class BaseComputeServiceContextModule extends AbstractModule { + @Override + protected void configure() { + install(new ComputeServiceTimeoutsModule()); + bindRunNodesAndAddToSetStrategy(defineRunNodesAndAddToSetStrategy()); + bindAddNodeWithTagStrategy(defineAddNodeWithTagStrategy()); + bindListNodesStrategy(defineListNodesStrategy()); + bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy()); + bindRebootNodeStrategy(defineRebootNodeStrategy()); + bindDestroyNodeStrategy(defineDestroyNodeStrategy()); + bindImageSupplier(defineImageSupplier()); + bindLocationSupplier(defineLocationSupplier()); + bindHardwareSupplier(defineHardwareSupplier()); + bindDefaultLocationSupplier(defineDefaultLocationSupplier()); + bindLoadBalancerService(); + } - protected abstract Supplier> getSourceImageSupplier(Injector injector); + protected Class defineRunNodesAndAddToSetStrategy() { + return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class; + } - protected abstract Supplier> getSourceSizeSupplier(Injector injector); + /** + * needed, if {@link RunNodesAndAddToSetStrategy} requires it + */ + protected abstract Class defineAddNodeWithTagStrategy(); + + protected abstract Class defineDestroyNodeStrategy(); + + protected abstract Class defineRebootNodeStrategy(); + + protected abstract Class defineGetNodeMetadataStrategy(); + + protected abstract Class defineListNodesStrategy(); + + protected abstract Class>> defineImageSupplier(); + + protected abstract Class>> defineHardwareSupplier(); + + protected Class>> defineLocationSupplier() { + return LocationSupplier.class; + } + + protected Class> defineDefaultLocationSupplier() { + return DefaultLocationSupplier.class; + } + + protected void bindLoadBalancerService() { + bind(LoadBalancerService.class).toProvider(Providers. of(null)).in(Scopes.SINGLETON); + } + + protected void bindRunNodesAndAddToSetStrategy(Class clazz) { + bind(RunNodesAndAddToSetStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + /** + * needed, if {@link RunNodesAndAddToSetStrategy} requires it + */ + protected void bindAddNodeWithTagStrategy(Class clazz) { + bind(AddNodeWithTagStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindDestroyNodeStrategy(Class clazz) { + bind(DestroyNodeStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindRebootNodeStrategy(Class clazz) { + bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindGetNodeMetadataStrategy(Class clazz) { + bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindListNodesStrategy(Class clazz) { + bind(ListNodesStrategy.class).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindImageSupplier(Class>> clazz) { + bind(new TypeLiteral>>() { + }).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindLocationSupplier(Class>> clazz) { + bind(new TypeLiteral>>() { + }).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindDefaultLocationSupplier(Class> clazz) { + bind(new TypeLiteral>() { + }).to(clazz).in(Scopes.SINGLETON); + } + + protected void bindHardwareSupplier(Class>> clazz) { + bind(new TypeLiteral>>() { + }).to(clazz).in(Scopes.SINGLETON); + } /** * By default allows you to use a static set of locations bound to Set */ - protected Supplier> getSourceLocationSupplier(Injector injector) { - Set locations = injector.getInstance(Key.get(new TypeLiteral>() { - })); - return Suppliers.> ofInstance(locations); + @Singleton + public static class LocationSupplier implements Supplier> { + private final Set locations; + + @Inject + LocationSupplier(Set locations) { + this.locations = locations; + } + + @Override + public Set get() { + return locations; + } + + } + + @Singleton + public static class DefaultLocationSupplier implements Supplier { + private final Supplier> locations; + + @Inject + DefaultLocationSupplier(@Memoized Supplier> locations) { + this.locations = locations; + } + + @Override + public Location get() { + return Iterables.find(locations.get(), new Predicate() { + + @Override + public boolean apply(Location input) { + return input.getScope() == LocationScope.ZONE; + } + + }); + } + } @Provides @@ -86,7 +221,7 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { @Provides @Singleton - protected Supplier> provideImageMap(Supplier> images) { + protected Supplier> provideImageMap(@Memoized Supplier> images) { return Suppliers.compose(new Function, Map>() { @Override @@ -106,20 +241,22 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { @Provides @Singleton + @Memoized protected Supplier> supplyImageCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, - final Injector injector) { + final Supplier> imageSupplier) { return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier>(authException, seconds, new Supplier>() { @Override public Set get() { - return getSourceImageSupplier(injector).get(); + return imageSupplier.get(); } }); } @Provides @Singleton - protected Supplier> provideLocationMap(Supplier> locations) { + protected Supplier> provideLocationMap( + @Memoized Supplier> locations) { return Suppliers.compose(new Function, Map>() { @Override @@ -139,20 +276,21 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { @Provides @Singleton + @Memoized protected Supplier> supplyLocationCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, - final Injector injector) { + final Supplier> locationSupplier) { return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier>(authException, seconds, new Supplier>() { @Override public Set get() { - return getSourceLocationSupplier(injector).get(); + return locationSupplier.get(); } }); } @Provides @Singleton - protected Supplier> provideSizeMap(Supplier> sizes) { + protected Supplier> provideSizeMap(@Memoized Supplier> sizes) { return Suppliers.compose(new Function, Map>() { @Override @@ -172,13 +310,14 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { @Provides @Singleton + @Memoized protected Supplier> supplySizeCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds, - final Injector injector) { + final Supplier> hardwareSupplier) { return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier>(authException, seconds, new Supplier>() { @Override public Set get() { - return getSourceSizeSupplier(injector).get(); + return hardwareSupplier.get(); } }); } @@ -194,25 +333,4 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { }; } - @Provides - @Singleton - protected Supplier supplyDefaultLocation(Injector injector, Supplier> locations) { - return Suppliers.compose(new Function, Location>() { - - @Override - public Location apply(Set from) { - return Iterables.find(from, new Predicate() { - - @Override - public boolean apply(Location input) { - return input.getScope() == LocationScope.ZONE; - } - - }); - } - - }, locations); - - } - } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceClientModule.java b/compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceClientModule.java similarity index 77% rename from compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceClientModule.java rename to compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceClientModule.java index 7b856d6a48..75378ae0c3 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceClientModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceClientModule.java @@ -17,21 +17,19 @@ * ==================================================================== */ -package org.jclouds.compute.stub.config; - -import java.util.concurrent.ConcurrentMap; +package org.jclouds.compute.config; +import org.jclouds.compute.ComputeService; import org.jclouds.http.RequiresHttp; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.config.RestClientModule; -@SuppressWarnings("unchecked") @ConfiguresRestClient @RequiresHttp -public class StubComputeServiceClientModule extends RestClientModule { +public class StandaloneComputeServiceClientModule extends RestClientModule { - public StubComputeServiceClientModule() { - super(ConcurrentMap.class, ConcurrentMap.class); + public StandaloneComputeServiceClientModule() { + super(ComputeService.class, ComputeService.class); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceContextModule.java new file mode 100644 index 0000000000..96ecb1c05d --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/config/StandaloneComputeServiceContextModule.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.config; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.internal.ComputeServiceContextImpl; + +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; +/** + * + * @author Adrian Cole + */ +public abstract class StandaloneComputeServiceContextModule extends BaseComputeServiceContextModule { + @Override + protected void configure() { + super.configure(); + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + } +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java index e872baf83e..5d81b7ae83 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java @@ -38,6 +38,7 @@ import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; @@ -114,9 +115,10 @@ public class TemplateBuilderImpl implements TemplateBuilder { protected TemplateOptions options; @Inject - protected TemplateBuilderImpl(Supplier> locations, Supplier> images, - Supplier> hardwares, Supplier defaultLocation2, - Provider optionsProvider, @Named("DEFAULT") Provider defaultTemplateProvider) { + protected TemplateBuilderImpl(@Memoized Supplier> locations, + @Memoized Supplier> images, @Memoized Supplier> hardwares, + Supplier defaultLocation2, Provider optionsProvider, + @Named("DEFAULT") Provider defaultTemplateProvider) { this.locations = locations; this.images = images; this.hardwares = hardwares; @@ -126,13 +128,11 @@ public class TemplateBuilderImpl implements TemplateBuilder { } /** - * If the current location id is null, then we don't care where to launch a - * node. + * If the current location id is null, then we don't care where to launch a node. * * If the input location is null, then the data isn't location sensitive * - * If the input location is a parent of the specified location, then we are - * ok. + * If the input location is a parent of the specified location, then we are ok. */ private final Predicate locationPredicate = new Predicate() { @Override @@ -140,7 +140,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { boolean returnVal = true; if (location != null && input.getLocation() != null) returnVal = location.equals(input.getLocation()) || location.getParent() != null - && location.getParent().equals(input.getLocation()); + && location.getParent().equals(input.getLocation()); return returnVal; } @@ -210,7 +210,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { returnVal = false; else returnVal = input.getDescription().contains(osDescription) - || input.getDescription().matches(osDescription); + || input.getDescription().matches(osDescription); } return returnVal; } @@ -324,8 +324,8 @@ public class TemplateBuilderImpl implements TemplateBuilder { returnVal = false; else returnVal = input.getDescription().equals(imageDescription) - || input.getDescription().contains(imageDescription) - || input.getDescription().matches(imageDescription); + || input.getDescription().contains(imageDescription) + || input.getDescription().matches(imageDescription); } return returnVal; } @@ -380,12 +380,12 @@ public class TemplateBuilderImpl implements TemplateBuilder { } }; private final Predicate hardwarePredicate = and(hardwareIdPredicate, locationPredicate, - hardwareCoresPredicate, hardwareRamPredicate); + hardwareCoresPredicate, hardwareRamPredicate); static final Ordering DEFAULT_SIZE_ORDERING = new Ordering() { public int compare(Hardware left, Hardware right) { return ComparisonChain.start().compare(getCores(left), getCores(right)).compare(left.getRam(), right.getRam()) - .compare(getSpace(left), getSpace(right)).result(); + .compare(getSpace(left), getSpace(right)).result(); } }; static final Ordering BY_CORES_ORDERING = new Ordering() { @@ -395,16 +395,16 @@ public class TemplateBuilderImpl implements TemplateBuilder { }; static final Ordering DEFAULT_IMAGE_ORDERING = new Ordering() { public int compare(Image left, Image right) { - return ComparisonChain.start() - .compare(left.getName(), right.getName(), Ordering. natural().nullsLast()) - .compare(left.getVersion(), right.getVersion(), Ordering. natural().nullsLast()) - .compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(),// - Ordering. natural().nullsLast()) - .compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(),// - Ordering. natural().nullsLast()) - .compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(),// - Ordering. natural().nullsLast()) - .compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch()).result(); + return ComparisonChain.start().compare(left.getName(), right.getName(), + Ordering. natural().nullsLast()).compare(left.getVersion(), right.getVersion(), + Ordering. natural().nullsLast()).compare(left.getOperatingSystem().getName(), + right.getOperatingSystem().getName(),// + Ordering. natural().nullsLast()).compare(left.getOperatingSystem().getVersion(), + right.getOperatingSystem().getVersion(),// + Ordering. natural().nullsLast()).compare(left.getOperatingSystem().getDescription(), + right.getOperatingSystem().getDescription(),// + Ordering. natural().nullsLast()).compare(left.getOperatingSystem().getArch(), + right.getOperatingSystem().getArch()).result(); } }; @@ -535,7 +535,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { Iterable supportedImages = filter(images, buildImagePredicate()); if (Iterables.size(supportedImages) == 0) throw new NoSuchElementException(String.format( - "no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images)); + "no image matched predicate %s images that didn't match below:\n%s", imagePredicate, images)); Hardware hardware = resolveSize(hardwareSorter(), supportedImages); Image image = resolveImage(hardware, supportedImages); logger.debug("<< matched image(%s)", image); @@ -548,29 +548,29 @@ public class TemplateBuilderImpl implements TemplateBuilder { Hardware hardware; try { Iterable hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl, - new Predicate() { - @Override - public boolean apply(final Hardware hardware) { - return Iterables.any(images, new Predicate() { + new Predicate() { + @Override + public boolean apply(final Hardware hardware) { + return Iterables.any(images, new Predicate() { - @Override - public boolean apply(Image input) { - return hardware.supportsImage().apply(input); - } + @Override + public boolean apply(Image input) { + return hardware.supportsImage().apply(input); + } - @Override - public String toString() { - return "hardware(" + hardware + ").supportsImage()"; - } + @Override + public String toString() { + return "hardware(" + hardware + ").supportsImage()"; + } - }); + }); - } - }); + } + }); hardware = hardwareOrdering.max(filter(hardwaresThatAreCompatibleWithOurImages, hardwarePredicate)); } catch (NoSuchElementException exception) { throw new NoSuchElementException("hardwares don't support any images: " + toString() + "\n" + hardwaresl - + "\n" + images); + + "\n" + images); } logger.debug("<< matched hardware(%s)", hardware); return hardware; @@ -678,7 +678,7 @@ public class TemplateBuilderImpl implements TemplateBuilder { // looks verbose, but explicit type needed for this to compile // properly Predicate imagePredicate = predicates.size() == 1 ? Iterables.> get(predicates, 0) - : Predicates. and(predicates); + : Predicates. and(predicates); return imagePredicate; } @@ -826,8 +826,9 @@ public class TemplateBuilderImpl implements TemplateBuilder { @VisibleForTesting boolean nothingChangedExceptOptions() { return osFamily == null && location == null && imageId == null && hardwareId == null && osName == null - && osDescription == null && imageVersion == null && osVersion == null && osArch == null && os64Bit == null - && imageName == null && imageDescription == null && minCores == 0 && minRam == 0 && !biggest && !fastest; + && osDescription == null && imageVersion == null && osVersion == null && osArch == null + && os64Bit == null && imageName == null && imageDescription == null && minCores == 0 && minRam == 0 + && !biggest && !fastest; } /** @@ -841,10 +842,10 @@ public class TemplateBuilderImpl implements TemplateBuilder { @Override public String toString() { return "[biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName + ", imageDescription=" - + imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location=" + location - + ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName=" + osName - + ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch + ", os64Bit=" - + os64Bit + ", hardwareId=" + hardwareId + "]"; + + imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion + ", location=" + + location + ", minCores=" + minCores + ", minRam=" + minRam + ", osFamily=" + osFamily + ", osName=" + + osName + ", osDescription=" + osDescription + ", osVersion=" + osVersion + ", osArch=" + osArch + + ", os64Bit=" + os64Bit + ", hardwareId=" + hardwareId + "]"; } @Override diff --git a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java index 63092898da..e148f0ccef 100755 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java @@ -54,6 +54,7 @@ import javax.inject.Provider; import javax.inject.Singleton; import org.jclouds.Constants; +import org.jclouds.collect.Memoized; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.RunNodesException; @@ -120,14 +121,15 @@ public class BaseComputeService implements ComputeService { @Inject protected BaseComputeService(ComputeServiceContext context, Map credentialStore, - Supplier> images, Supplier> hardwareProfiles, - Supplier> locations, ListNodesStrategy listNodesStrategy, - GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, - RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, - Provider templateBuilderProvider, Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { + @Memoized Supplier> images, + @Memoized Supplier> hardwareProfiles, + @Memoized Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { this.context = checkNotNull(context, "context"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); @@ -160,15 +162,15 @@ public class BaseComputeService implements ComputeService { */ @Override public Set runNodesWithTag(String tag, int count, Template template) - throws RunNodesException { + throws RunNodesException { checkArgument(tag.indexOf('-') == -1, "tag cannot contain hyphens"); checkNotNull(template.getLocation(), "location"); if (template.getOptions().getTaskName() == null && template.getOptions().getRunScript() != null - && !(template.getOptions().getRunScript() instanceof InitBuilder)) + && !(template.getOptions().getRunScript() instanceof InitBuilder)) template.getOptions().nameTask("bootstrap"); logger.debug(">> running %d node%s tag(%s) location(%s) image(%s) hardwareProfile(%s) options(%s)", count, - count > 1 ? "s" : "", tag, template.getLocation().getId(), template.getImage().getId(), template - .getHardware().getId(), template.getOptions()); + count > 1 ? "s" : "", tag, template.getLocation().getId(), template.getImage().getId(), template + .getHardware().getId(), template.getOptions()); Set nodes = newHashSet(); Map badNodes = newLinkedHashMap(); Map> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes); @@ -187,7 +189,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Set runNodesWithTag(String tag, int count, TemplateOptions templateOptions) - throws RunNodesException { + throws RunNodesException { return runNodesWithTag(tag, count, templateBuilder().any().options(templateOptions).build()); } @@ -236,23 +238,23 @@ public class BaseComputeService implements ComputeService { public Set destroyNodesMatching(Predicate filter) { logger.debug(">> destroying nodes matching(%s)", filter); Set set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter), - new Function>() { + new Function>() { - // TODO make an async interface instead of re-wrapping - @Override - public Future apply(final NodeMetadata from) { - return executor.submit(new Callable() { + // TODO make an async interface instead of re-wrapping + @Override + public Future apply(final NodeMetadata from) { + return executor.submit(new Callable() { - @Override - public NodeMetadata call() throws Exception { - destroyNode(from.getId()); - return from; - } + @Override + public NodeMetadata call() throws Exception { + destroyNode(from.getId()); + return from; + } - }); - } + }); + } - }, executor, null, logger, "destroying nodes")); + }, executor, null, logger, "destroying nodes")); logger.debug("<< destroyed(%d)", set.size()); return set; } @@ -360,7 +362,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, Payload runScript) - throws RunScriptOnNodesException { + throws RunScriptOnNodesException { return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE); } @@ -369,7 +371,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, - final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException { + final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException { checkNotNull(filter, "Filter must be provided"); checkNotNull(runScript, "runScript"); @@ -390,8 +392,8 @@ public class BaseComputeService implements ComputeService { @Override public Void call() throws Exception { try { - ExecResponse response = utils.runScriptOnNode(node, - Statements.exec(Utils.toStringAndClose(runScript.getInput())), options); + ExecResponse response = utils.runScriptOnNode(node, Statements.exec(Utils.toStringAndClose(runScript + .getInput())), options); if (response != null) execs.put(node, response); } catch (Exception e) { @@ -413,7 +415,7 @@ public class BaseComputeService implements ComputeService { } private Iterable filterNodesWhoCanRunScripts(Iterable nodes, - final Map badNodes, final @Nullable Credentials overridingCredentials) { + final Map badNodes, final @Nullable Credentials overridingCredentials) { nodes = filter(transform(nodes, new Function() { @Override @@ -425,9 +427,9 @@ public class BaseComputeService implements ComputeService { } else { 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 " - + "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 " - + "specified. Try passing RunScriptOptions with new credentials"); + + "specified. Try passing RunScriptOptions with new credentials"); } return node; } catch (Exception e) { diff --git a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java b/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java index bf71988c23..d9b614c3cd 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/stub/StubComputeServiceContextBuilder.java @@ -21,10 +21,8 @@ package org.jclouds.compute.stub; import java.util.List; import java.util.Properties; -import java.util.concurrent.ConcurrentMap; -import org.jclouds.compute.ComputeServiceContextBuilder; -import org.jclouds.compute.stub.config.StubComputeServiceClientModule; +import org.jclouds.compute.StandaloneComputeServiceContextBuilder; import org.jclouds.compute.stub.config.StubComputeServiceContextModule; import com.google.inject.Module; @@ -33,11 +31,10 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@SuppressWarnings("unchecked") -public class StubComputeServiceContextBuilder extends ComputeServiceContextBuilder { +public class StubComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder { public StubComputeServiceContextBuilder(Properties props) { - super(ConcurrentMap.class, ConcurrentMap.class, props); + super(props); } @Override @@ -45,9 +42,4 @@ public class StubComputeServiceContextBuilder extends ComputeServiceContextBuild modules.add(new StubComputeServiceContextModule()); } - @Override - protected void addClientModule(List modules) { - modules.add(new StubComputeServiceClientModule()); - } - } diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java index 1e52db74a3..c8192f5dc9 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java @@ -19,381 +19,72 @@ package org.jclouds.compute.stub.config; -import static com.google.common.base.Preconditions.checkArgument; - -import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Provider; -import javax.inject.Singleton; - -import org.jclouds.Constants; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.LoadBalancerService; -import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; -import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.config.StandaloneComputeServiceContextModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.internal.VolumeImpl; -import org.jclouds.compute.internal.ComputeServiceContextImpl; -import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubAddNodeWithTagStrategy; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubDestroyNodeStrategy; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubGetNodeMetadataStrategy; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubHardwareSupplier; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubImageSupplier; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubListNodesStrategy; +import org.jclouds.compute.stub.config.StubComputeServiceDependenciesModule.StubRebootNodeStrategy; import org.jclouds.concurrent.SingleThreaded; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationScope; -import org.jclouds.domain.internal.LocationImpl; -import org.jclouds.net.IPSocket; -import org.jclouds.predicates.SocketOpen; -import org.jclouds.rest.ResourceNotFoundException; -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.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; -import com.google.inject.util.Providers; /** * * @author Adrian Cole */ @SingleThreaded -public class StubComputeServiceContextModule extends BaseComputeServiceContextModule { - // STUB STUFF STATIC SO MULTIPLE CONTEXTS CAN SEE IT - private static final AtomicInteger nodeIds = new AtomicInteger(0); - private static final ConcurrentMap nodes = new ConcurrentHashMap(); - private static final ExecutorService service = Executors.newCachedThreadPool(); - - @Provides - @Singleton - ConcurrentMap provideNodes() { - return nodes; - } - - @Provides - @Named("NODE_ID") - Integer provideNodeId() { - return nodeIds.incrementAndGet(); - } - - @Singleton - @Provides - @Named("PUBLIC_IP_PREFIX") - String publicIpPrefix() { - return "144.175.1."; - } - - @Singleton - @Provides - @Named("PRIVATE_IP_PREFIX") - String privateIpPrefix() { - return "10.1.1."; - } - - @Singleton - @Provides - @Named("PASSWORD_PREFIX") - String passwordPrefix() { - return "password"; - } - - @Singleton - @Provides - SocketOpen socketOpen(StubSocketOpen in) { - return in; - } - - @Singleton - public static class StubSocketOpen implements SocketOpen { - private final ConcurrentMap nodes; - private final String publicIpPrefix; - - @Inject - public StubSocketOpen(ConcurrentMap nodes, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix) { - this.nodes = nodes; - this.publicIpPrefix = publicIpPrefix; - } - - @Override - public boolean apply(IPSocket input) { - if (input.getAddress().indexOf(publicIpPrefix) == -1) - return false; - String id = input.getAddress().replace(publicIpPrefix, ""); - NodeMetadata node = nodes.get(id); - return node != null && node.getState() == NodeState.RUNNING; - } - - } - - @SuppressWarnings("unchecked") +public class StubComputeServiceContextModule extends StandaloneComputeServiceContextModule { @Override protected void configure() { - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - install(new ComputeServiceTimeoutsModule()); - bind(ConcurrentMap.class).toInstance(nodes); - bind(AddNodeWithTagStrategy.class).to(StubAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(StubListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(StubGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(StubRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(StubDestroyNodeStrategy.class); - bind(LoadBalancerService.class).toProvider(Providers. of(null)); - } - - @Singleton - public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy { - private final Supplier location; - private final ConcurrentMap nodes; - private final Provider idProvider; - private final String publicIpPrefix; - private final String privateIpPrefix; - private final String passwordPrefix; - private final Map credentialStore; - - @Inject - public StubAddNodeWithTagStrategy(ConcurrentMap nodes, Supplier location, - @Named("NODE_ID") Provider idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, - @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix, - Map credentialStore) { - this.nodes = nodes; - this.location = location; - this.idProvider = idProvider; - this.publicIpPrefix = publicIpPrefix; - this.privateIpPrefix = privateIpPrefix; - this.passwordPrefix = passwordPrefix; - this.credentialStore = credentialStore; - } - - @Override - public NodeMetadata execute(String tag, String name, Template template) { - checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation()); - NodeMetadataBuilder builder = new NodeMetadataBuilder(); - String id = idProvider.get() + ""; - builder.ids(id); - builder.name(name); - builder.tag(tag); - builder.location(location.get()); - builder.imageId(template.getImage().getId()); - builder.operatingSystem(template.getImage().getOperatingSystem()); - builder.state(NodeState.PENDING); - builder.publicAddresses(ImmutableSet. of(publicIpPrefix + id)); - builder.privateAddresses(ImmutableSet. of(privateIpPrefix + id)); - builder.credentials(new Credentials("root", passwordPrefix + id)); - NodeMetadata node = builder.build(); - nodes.put(node.getId(), node); - credentialStore.put(node.getId(), node.getCredentials()); - setState(node, NodeState.RUNNING, 100); - return node; - } - } - - protected static void nodeWithState(NodeMetadata node, NodeState state) { - nodes.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build()); - } - - public static void setState(final NodeMetadata node, final NodeState state, final long millis) { - if (millis == 0l) - nodeWithState(node, state); - else - service.execute(new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - Throwables.propagate(e); - } - nodeWithState(node, state); - } - - }); - } - - @Singleton - public static class StubGetNodeMetadataStrategy implements GetNodeMetadataStrategy { - private final ConcurrentMap nodes; - - @Inject - protected StubGetNodeMetadataStrategy(ConcurrentMap nodes) { - this.nodes = nodes; - } - - @Override - public NodeMetadata execute(String id) { - return nodes.get(id); - } - } - - @Singleton - public static class StubListNodesStrategy implements ListNodesStrategy { - private final ConcurrentMap nodes; - - @Inject - protected StubListNodesStrategy(ConcurrentMap nodes) { - this.nodes = nodes; - } - - @Override - public Iterable list() { - return listDetailsOnNodesMatching(NodePredicates.all()); - } - - @Override - public Iterable listDetailsOnNodesMatching(Predicate filter) { - return Iterables.filter(nodes.values(), filter); - } - } - - @Singleton - public static class StubRebootNodeStrategy implements RebootNodeStrategy { - private final ConcurrentMap nodes; - - @Inject - protected StubRebootNodeStrategy(ConcurrentMap nodes) { - this.nodes = nodes; - } - - @Override - public NodeMetadata execute(String id) { - NodeMetadata node = nodes.get(id); - if (node == null) - throw new ResourceNotFoundException("node not found: " + id); - setState(node, NodeState.PENDING, 0); - setState(node, NodeState.RUNNING, 50); - return node; - } - } - - @Singleton - public static class StubDestroyNodeStrategy implements DestroyNodeStrategy { - private final ConcurrentMap nodes; - private final ExecutorService service; - - @Inject - protected StubDestroyNodeStrategy(ConcurrentMap nodes, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) { - this.nodes = nodes; - this.service = service; - } - - @Override - public NodeMetadata execute(final String id) { - NodeMetadata node = nodes.get(id); - if (node == null) - return node; - setState(node, NodeState.PENDING, 0); - setState(node, NodeState.TERMINATED, 50); - service.execute(new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(200); - } catch (InterruptedException e) { - Throwables.propagate(e); - } finally { - nodes.remove(id); - } - } - - }); - return node; - } + install(new StubComputeServiceDependenciesModule()); + super.configure(); } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - Supplier defaultLocation = injector.getInstance(Key.get(new TypeLiteral>() { - })); - Location zone = defaultLocation.get().getParent(); - String parentId = zone.getId(); - Credentials defaultCredentials = new Credentials("root", null); - return Suppliers - .> ofInstance(ImmutableSet. of( - // - new ImageBuilder() - .providerId("1") - .name(OsFamily.UBUNTU.name()) - .id(parentId + "/1") - .location(zone) - .operatingSystem( - new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false)) - .description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), // - new ImageBuilder() - .providerId("2") - .name(OsFamily.UBUNTU.name()) - .id(parentId + "/2") - .location(zone) - .operatingSystem( - new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true)) - .description("stub ubuntu 64").defaultCredentials(defaultCredentials).build(), // - new ImageBuilder() - .providerId("3") - .name(OsFamily.CENTOS.name()) - .id(parentId + "/3") - .location(zone) - .operatingSystem( - new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true)) - .description("stub centos 64").defaultCredentials(defaultCredentials).build() // - - )); - } - - @Provides - @Singleton - protected Set provideLocations(@org.jclouds.rest.annotations.Provider String providerName) { - Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); - Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region", - provider); - return ImmutableSet - .of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region)); + protected Class defineAddNodeWithTagStrategy() { + return StubAddNodeWithTagStrategy.class; } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return Suppliers.> ofInstance(ImmutableSet. of( - StubHardware.stub("small", 1, 1740, 160), StubHardware.stub("medium", 4, 7680, 850), - StubHardware.stub("large", 8, 15360, 1690))); + protected Class defineDestroyNodeStrategy() { + return StubDestroyNodeStrategy.class; } - private static class StubHardware { + @Override + protected Class defineGetNodeMetadataStrategy() { + return StubGetNodeMetadataStrategy.class; + } - static Hardware stub(String type, int cores, int ram, float disk) { - return new org.jclouds.compute.domain.HardwareBuilder().id(type).providerId(type).name(type) - .processors(ImmutableList.of(new Processor(cores, 1.0))).ram(ram) - .volumes(ImmutableList. of(new VolumeImpl(disk, true, false))).build(); - } + @Override + protected Class defineListNodesStrategy() { + return StubListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return StubRebootNodeStrategy.class; + } + + @Override + protected Class>> defineHardwareSupplier() { + return StubHardwareSupplier.class; + } + + @Override + protected Class>> defineImageSupplier() { + return StubImageSupplier.class; } } diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..1ff03e1270 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java @@ -0,0 +1,377 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.stub.config; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Provider; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.internal.VolumeImpl; +import org.jclouds.compute.predicates.NodePredicates; +import org.jclouds.compute.strategy.AddNodeWithTagStrategy; +import org.jclouds.compute.strategy.DestroyNodeStrategy; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.jclouds.compute.strategy.ListNodesStrategy; +import org.jclouds.compute.strategy.RebootNodeStrategy; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.domain.internal.LocationImpl; +import org.jclouds.net.IPSocket; +import org.jclouds.predicates.SocketOpen; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; + +/** + * + * @author Adrian Cole + */ +public class StubComputeServiceDependenciesModule extends AbstractModule { + + @Override + protected void configure() { + + } + + protected static final ConcurrentMap backing = new ConcurrentHashMap(); + + // implementation details below + @Provides + @Singleton + ConcurrentMap provideNodes() { + return backing; + } + + // STUB STUFF STATIC SO MULTIPLE CONTEXTS CAN SEE IT + private static final AtomicInteger nodeIds = new AtomicInteger(0); + private static final ExecutorService service = Executors.newCachedThreadPool(); + + @Provides + @Named("NODE_ID") + Integer provideNodeId() { + return nodeIds.incrementAndGet(); + } + + @Singleton + @Provides + @Named("PUBLIC_IP_PREFIX") + String publicIpPrefix() { + return "144.175.1."; + } + + @Singleton + @Provides + @Named("PRIVATE_IP_PREFIX") + String privateIpPrefix() { + return "10.1.1."; + } + + @Singleton + @Provides + @Named("PASSWORD_PREFIX") + String passwordPrefix() { + return "password"; + } + + @Singleton + @Provides + SocketOpen socketOpen(StubSocketOpen in) { + return in; + } + + @Singleton + public static class StubSocketOpen implements SocketOpen { + private final ConcurrentMap nodes; + private final String publicIpPrefix; + + @Inject + public StubSocketOpen(ConcurrentMap nodes, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix) { + this.nodes = nodes; + this.publicIpPrefix = publicIpPrefix; + } + + @Override + public boolean apply(IPSocket input) { + if (input.getAddress().indexOf(publicIpPrefix) == -1) + return false; + String id = input.getAddress().replace(publicIpPrefix, ""); + NodeMetadata node = nodes.get(id); + return node != null && node.getState() == NodeState.RUNNING; + } + + } + + @Singleton + public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy { + private final Supplier location; + private final ConcurrentMap nodes; + private final Provider idProvider; + private final String publicIpPrefix; + private final String privateIpPrefix; + private final String passwordPrefix; + private final Map credentialStore; + + @Inject + public StubAddNodeWithTagStrategy(ConcurrentMap nodes, Supplier location, + @Named("NODE_ID") Provider idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, + @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix, + Map credentialStore) { + this.nodes = nodes; + this.location = location; + this.idProvider = idProvider; + this.publicIpPrefix = publicIpPrefix; + this.privateIpPrefix = privateIpPrefix; + this.passwordPrefix = passwordPrefix; + this.credentialStore = credentialStore; + } + + @Override + public NodeMetadata execute(String tag, String name, Template template) { + checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation()); + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + String id = idProvider.get() + ""; + builder.ids(id); + builder.name(name); + builder.tag(tag); + builder.location(location.get()); + builder.imageId(template.getImage().getId()); + builder.operatingSystem(template.getImage().getOperatingSystem()); + builder.state(NodeState.PENDING); + builder.publicAddresses(ImmutableSet. of(publicIpPrefix + id)); + builder.privateAddresses(ImmutableSet. of(privateIpPrefix + id)); + builder.credentials(new Credentials("root", passwordPrefix + id)); + NodeMetadata node = builder.build(); + nodes.put(node.getId(), node); + credentialStore.put(node.getId(), node.getCredentials()); + setState(node, NodeState.RUNNING, 100); + return node; + } + } + + protected static void nodeWithState(NodeMetadata node, NodeState state) { + backing.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build()); + } + + public static void setState(final NodeMetadata node, final NodeState state, final long millis) { + if (millis == 0l) + nodeWithState(node, state); + else + service.execute(new Runnable() { + + @Override + public void run() { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Throwables.propagate(e); + } + nodeWithState(node, state); + } + + }); + } + + @Singleton + public static class StubGetNodeMetadataStrategy implements GetNodeMetadataStrategy { + private final ConcurrentMap nodes; + + @Inject + protected StubGetNodeMetadataStrategy(ConcurrentMap nodes) { + this.nodes = nodes; + } + + @Override + public NodeMetadata execute(String id) { + return nodes.get(id); + } + } + + @Singleton + public static class StubListNodesStrategy implements ListNodesStrategy { + private final ConcurrentMap nodes; + + @Inject + protected StubListNodesStrategy(ConcurrentMap nodes) { + this.nodes = nodes; + } + + @Override + public Iterable list() { + return listDetailsOnNodesMatching(NodePredicates.all()); + } + + @Override + public Iterable listDetailsOnNodesMatching(Predicate filter) { + return Iterables.filter(nodes.values(), filter); + } + } + + @Singleton + public static class StubRebootNodeStrategy implements RebootNodeStrategy { + private final ConcurrentMap nodes; + + @Inject + protected StubRebootNodeStrategy(ConcurrentMap nodes) { + this.nodes = nodes; + } + + @Override + public NodeMetadata execute(String id) { + NodeMetadata node = nodes.get(id); + if (node == null) + throw new ResourceNotFoundException("node not found: " + id); + setState(node, NodeState.PENDING, 0); + setState(node, NodeState.RUNNING, 50); + return node; + } + } + + @Singleton + public static class StubDestroyNodeStrategy implements DestroyNodeStrategy { + private final ConcurrentMap nodes; + private final ExecutorService service; + + @Inject + protected StubDestroyNodeStrategy(ConcurrentMap nodes, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) { + this.nodes = nodes; + this.service = service; + } + + @Override + public NodeMetadata execute(final String id) { + NodeMetadata node = nodes.get(id); + if (node == null) + return node; + setState(node, NodeState.PENDING, 0); + setState(node, NodeState.TERMINATED, 50); + service.execute(new Runnable() { + + @Override + public void run() { + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Throwables.propagate(e); + } finally { + nodes.remove(id); + } + } + + }); + return node; + } + } + + @Singleton + static class StubImageSupplier implements Supplier> { + private final Supplier defaultLocation; + + @Inject + StubImageSupplier(Supplier defaultLocation) { + this.defaultLocation = defaultLocation; + } + + @Override + public Set get() { + Location zone = defaultLocation.get().getParent(); + String parentId = zone.getId(); + Credentials defaultCredentials = new Credentials("root", null); + return ImmutableSet + . of(new ImageBuilder().providerId("1").name(OsFamily.UBUNTU.name()).id(parentId + "/1") + .location(zone).operatingSystem( + new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", + false)).description("stub ubuntu 32").defaultCredentials( + defaultCredentials).build(), // + new ImageBuilder().providerId("2").name(OsFamily.UBUNTU.name()).id(parentId + "/2") + .location(zone).operatingSystem( + new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", + "ubuntu 64", true)).description("stub ubuntu 64") + .defaultCredentials(defaultCredentials).build(), // + new ImageBuilder().providerId("3").name(OsFamily.CENTOS.name()).id(parentId + "/3") + .location(zone).operatingSystem( + new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", + "centos 64", true)).description("stub centos 64") + .defaultCredentials(defaultCredentials).build() // + + ); + } + + } + + @Provides + @Singleton + protected Set provideLocations(@org.jclouds.rest.annotations.Provider String providerName) { + Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); + Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region", + provider); + return ImmutableSet + .of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region)); + } + + @Singleton + static class StubHardwareSupplier implements Supplier> { + + static Hardware stub(String type, int cores, int ram, float disk) { + return new org.jclouds.compute.domain.HardwareBuilder().id(type).providerId(type).name(type).processors( + ImmutableList.of(new Processor(cores, 1.0))).ram(ram).volumes( + ImmutableList. of(new VolumeImpl(disk, true, false))).build(); + } + + @Override + public Set get() { + return ImmutableSet. of(stub("small", 1, 1740, 160), stub("medium", 4, 7680, 850), stub("large", 8, + 15360, 1690)); + } + } + +} diff --git a/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java b/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java new file mode 100644 index 0000000000..729b7e9693 --- /dev/null +++ b/compute/src/test/java/org/jclouds/compute/ComputeServiceContextFactoryTest.java @@ -0,0 +1,39 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute; + +import org.jclouds.compute.stub.config.StubComputeServiceContextModule; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + * + */ +@Test(groups = "unit") +public class ComputeServiceContextFactoryTest { + + @Test + public void testStandalone() { + ComputeServiceContext context = ComputeServiceContextFactory.createStandaloneContext(new StubComputeServiceContextModule()); + context.getComputeService().listNodes(); + } + +} diff --git a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java index a3f7c58059..f2253a1243 100644 --- a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java +++ b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java @@ -64,11 +64,11 @@ public class TemplateBuilderImplTest { Hardware hardware = new HardwareBuilder().id("hardwareId").build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of( - image, image2)); + image, image2)); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(hardware)); + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -98,7 +98,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); assertEquals(template.resolveImage(hardware, images.get()), image2); @@ -124,11 +124,11 @@ public class TemplateBuilderImplTest { Hardware hardware = new HardwareBuilder().id("hardwareId").build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of( - image, image2)); + image, image2)); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(hardware)); + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -153,7 +153,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); assertEquals(template.smallest().osArchMatches("X86_32").build().getImage(), image); @@ -174,15 +174,15 @@ public class TemplateBuilderImplTest { Image image = createMock(Image.class); OperatingSystem os = createMock(OperatingSystem.class); - Hardware hardware = new HardwareBuilder().id("hardwareId") - .supportsImage(ImagePredicates.idEquals("imageId")).build(); + Hardware hardware = new HardwareBuilder().id("hardwareId").supportsImage(ImagePredicates.idEquals("imageId")) + .build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); + . of(image)); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(hardware)); + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -210,7 +210,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); template.imageId("imageId").build(); @@ -229,15 +229,15 @@ public class TemplateBuilderImplTest { Image image = createMock(Image.class); OperatingSystem os = createMock(OperatingSystem.class); - Hardware hardware = new HardwareBuilder().id("hardwareId") - .supportsImage(ImagePredicates.idEquals("imageId")).build(); + Hardware hardware = new HardwareBuilder().id("hardwareId").supportsImage(ImagePredicates.idEquals("imageId")) + .build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); + . of(image)); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(hardware)); + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); @@ -265,7 +265,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(image, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("notImageId").build(); assert false; @@ -286,10 +286,10 @@ public class TemplateBuilderImplTest { TemplateOptions from = provideTemplateOptions(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -306,7 +306,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); template.options(options).build(); @@ -321,10 +321,10 @@ public class TemplateBuilderImplTest { public void testNothingUsesDefaultTemplateBuilder() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); @@ -340,7 +340,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); template.build(); @@ -351,10 +351,11 @@ public class TemplateBuilderImplTest { } protected TemplateBuilderImpl createTemplateBuilder(Image knownImage, Supplier> locations, - Supplier> images, Supplier> hardwares, Location defaultLocation, - Provider optionsProvider, Provider templateBuilderProvider) { - TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, hardwares, - Suppliers.ofInstance(defaultLocation), optionsProvider, templateBuilderProvider); + Supplier> images, Supplier> hardwares, + Location defaultLocation, Provider optionsProvider, + Provider templateBuilderProvider) { + TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, hardwares, Suppliers + .ofInstance(defaultLocation), optionsProvider, templateBuilderProvider); return template; } @@ -362,10 +363,10 @@ public class TemplateBuilderImplTest { @Test public void testSuppliedLocationWithNoOptions() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -377,7 +378,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("foo").locationId("location").build(); @@ -398,10 +399,10 @@ public class TemplateBuilderImplTest { TemplateOptions from = provideTemplateOptions(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -413,7 +414,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("foo").options(provideTemplateOptions()).locationId("location").build(); @@ -431,10 +432,10 @@ public class TemplateBuilderImplTest { @Test public void testDefaultLocationWithNoOptionsNoSuchElement() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -448,7 +449,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("region/ami").build(); @@ -471,10 +472,10 @@ public class TemplateBuilderImplTest { @Test public void testDefaultLocationWithOptions() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); TemplateOptions from = provideTemplateOptions(); @@ -489,7 +490,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); try { template.imageId("region/ami").options(provideTemplateOptions()).build(); @@ -507,10 +508,10 @@ public class TemplateBuilderImplTest { @Test public void testImageIdNullsEverythingElse() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider templateBuilderProvider = createMock(Provider.class); @@ -520,7 +521,7 @@ public class TemplateBuilderImplTest { replay(templateBuilderProvider); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, - optionsProvider, templateBuilderProvider); + optionsProvider, templateBuilderProvider); template.imageDescriptionMatches("imageDescriptionMatches"); template.imageNameMatches("imageNameMatches"); diff --git a/core/src/main/java/org/jclouds/collect/Memoized.java b/core/src/main/java/org/jclouds/collect/Memoized.java new file mode 100755 index 0000000000..efe20ce57e --- /dev/null +++ b/core/src/main/java/org/jclouds/collect/Memoized.java @@ -0,0 +1,42 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.collect; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.inject.Qualifier; + +/** + * Designates that this object is going to return cached results + * + * @author Adrian Cole + */ +@Target( { TYPE, METHOD, PARAMETER }) +@Retention(RUNTIME) +@Qualifier +public @interface Memoized { + +} diff --git a/core/src/main/resources/rest.properties b/core/src/main/resources/rest.properties index d1f83c0aa7..32844739b3 100644 --- a/core/src/main/resources/rest.properties +++ b/core/src/main/resources/rest.properties @@ -92,7 +92,6 @@ gogrid.contextbuilder=org.jclouds.gogrid.GoGridContextBuilder ibmdev.propertiesbuilder=org.jclouds.ibmdev.IBMDeveloperCloudPropertiesBuilder ibmdev.contextbuilder=org.jclouds.ibmdev.IBMDeveloperCloudContextBuilder -stub.propertiesbuilder=org.jclouds.compute.stub.StubComputeServicePropertiesBuilder stub.contextbuilder=org.jclouds.compute.stub.StubComputeServiceContextBuilder # example of where to change your endpoint # bluelock.endpoint=https://express3.bluelock.com/api diff --git a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java index 7a7821ecd6..3ffde30ddf 100644 --- a/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java +++ b/filesystem/src/main/java/org/jclouds/filesystem/FilesystemAsyncBlobStore.java @@ -38,12 +38,12 @@ import static com.google.common.util.concurrent.Futures.immediateFuture; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; -import java.io.File; import java.net.URI; import java.util.Collection; import java.util.Date; @@ -55,10 +55,16 @@ import java.util.TreeSet; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; +import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; import org.jclouds.Constants; +import org.jclouds.blobstore.BlobStoreContext; +import org.jclouds.blobstore.ContainerNotFoundException; +import org.jclouds.blobstore.KeyNotFoundException; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.MutableBlobMetadata; @@ -67,6 +73,7 @@ import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.StorageMetadata; import org.jclouds.blobstore.domain.StorageType; import org.jclouds.blobstore.domain.Blob.Factory; +import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; import org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl; import org.jclouds.blobstore.domain.internal.PageSetImpl; import org.jclouds.blobstore.functions.HttpGetOptionsListToGetOptions; @@ -75,17 +82,23 @@ import org.jclouds.blobstore.options.GetOptions; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.IfDirectoryReturnNameStrategy; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.crypto.Crypto; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.DateService; import org.jclouds.domain.Location; +import org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator; import org.jclouds.filesystem.strategy.FilesystemStorageStrategy; import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.http.options.HttpRequestOptions; +import org.jclouds.io.Payload; import org.jclouds.io.Payloads; +import org.jclouds.io.payloads.FilePayload; +import org.jclouds.logging.Logger; +import org.jclouds.rest.annotations.ParamValidators; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -95,24 +108,11 @@ import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.internal.Nullable; -import javax.annotation.Resource; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.ContainerNotFoundException; -import org.jclouds.blobstore.KeyNotFoundException; -import org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl; -import org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator; -import org.jclouds.io.Payload; -import org.jclouds.io.payloads.FilePayload; -import org.jclouds.logging.Logger; -import org.jclouds.rest.annotations.ParamValidators; /** - * - * Preconditions: - * Blob name cannot start with / char (or \ under windows) - * + * + * Preconditions: Blob name cannot start with / char (or \ under windows) + * * @author Alfredo "Rainbowbreeze" Morresi */ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { @@ -127,17 +127,14 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { protected final Factory blobFactory; protected final FilesystemStorageStrategy storageStrategy; - @Inject protected FilesystemAsyncBlobStore(BlobStoreContext context, DateService dateService, Crypto crypto, HttpGetOptionsListToGetOptions httpGetOptionsConverter, IfDirectoryReturnNameStrategy ifDirectoryReturnName, Blob.Factory blobFactory, BlobUtils blobUtils, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, - Supplier defaultLocation, - Supplier> locations, - FilesystemStorageStrategy storageStrategy) { + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, + @Memoized Supplier> locations, FilesystemStorageStrategy storageStrategy) { super(context, blobUtils, service, defaultLocation, locations); - //super(context, blobUtils, service, null, null); + // super(context, blobUtils, service, null, null); this.blobFactory = blobFactory; this.dateService = dateService; this.crypto = crypto; @@ -156,23 +153,20 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { if (!containerExistsSyncImpl(container)) { return immediateFailedFuture(cnfe(container)); } - + // Loading blobs from container Iterable blobBelongingToContainer = null; try { - blobBelongingToContainer = storageStrategy.getBlobKeysInsideContainer(container); - } catch(IOException e) { - logger.error(e, - "An error occurred loading blobs contained into container %s", - container); - Throwables.propagate(e); - } - + blobBelongingToContainer = storageStrategy.getBlobKeysInsideContainer(container); + } catch (IOException e) { + logger.error(e, "An error occurred loading blobs contained into container %s", container); + Throwables.propagate(e); + } SortedSet contents = newTreeSet(transform(blobBelongingToContainer, - new Function() { - public StorageMetadata apply(String key) { - Blob oldBlob = loadFileBlob(container, key); + new Function() { + public StorageMetadata apply(String key) { + Blob oldBlob = loadFileBlob(container, key); checkState(oldBlob != null, "blob " + key + " is not present although it was in the list of " + container); @@ -188,65 +182,66 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { })); String marker = null; - if(options!=null) { - if (options.getMarker() != null) { - final String finalMarker = options.getMarker(); - StorageMetadata lastMarkerMetadata = find(contents, new Predicate() { - public boolean apply(StorageMetadata metadata) { - return metadata.getName().equals(finalMarker); - } - }); - contents = contents.tailSet(lastMarkerMetadata); - contents.remove(lastMarkerMetadata); - } + if (options != null) { + if (options.getMarker() != null) { + final String finalMarker = options.getMarker(); + StorageMetadata lastMarkerMetadata = find(contents, new Predicate() { + public boolean apply(StorageMetadata metadata) { + return metadata.getName().equals(finalMarker); + } + }); + contents = contents.tailSet(lastMarkerMetadata); + contents.remove(lastMarkerMetadata); + } - final String prefix = options.getDir(); - if (prefix != null) { - contents = newTreeSet(filter(contents, new Predicate() { - public boolean apply(StorageMetadata o) { - return (o != null && o.getName().startsWith(prefix) && !o.getName().equals(prefix)); - } - })); - } + final String prefix = options.getDir(); + if (prefix != null) { + contents = newTreeSet(filter(contents, new Predicate() { + public boolean apply(StorageMetadata o) { + return (o != null && o.getName().startsWith(prefix) && !o.getName().equals(prefix)); + } + })); + } - Integer maxResults = options.getMaxResults() != null ? options.getMaxResults() : 1000; - if (contents.size() > 0) { - SortedSet contentsSlice = firstSliceOfSize(contents, maxResults); - if (!contentsSlice.contains(contents.last())) { - // Partial listing - marker = contentsSlice.last().getName(); - } else { - marker = null; - } - contents = contentsSlice; - } + Integer maxResults = options.getMaxResults() != null ? options.getMaxResults() : 1000; + if (contents.size() > 0) { + SortedSet contentsSlice = firstSliceOfSize(contents, maxResults); + if (!contentsSlice.contains(contents.last())) { + // Partial listing + marker = contentsSlice.last().getName(); + } else { + marker = null; + } + contents = contentsSlice; + } - final String delimiter = options.isRecursive() ? null : File.separator; - if (delimiter != null) { - SortedSet commonPrefixes = null; - Iterable iterable = transform(contents, new CommonPrefixes(prefix != null ? prefix : null, delimiter)); - commonPrefixes = iterable != null ? newTreeSet(iterable) : new TreeSet(); - commonPrefixes.remove(CommonPrefixes.NO_PREFIX); + final String delimiter = options.isRecursive() ? null : File.separator; + if (delimiter != null) { + SortedSet commonPrefixes = null; + Iterable iterable = transform(contents, new CommonPrefixes(prefix != null ? prefix : null, + delimiter)); + commonPrefixes = iterable != null ? newTreeSet(iterable) : new TreeSet(); + commonPrefixes.remove(CommonPrefixes.NO_PREFIX); - contents = newTreeSet(filter(contents, new DelimiterFilter(prefix != null ? prefix : null, delimiter))); + contents = newTreeSet(filter(contents, new DelimiterFilter(prefix != null ? prefix : null, delimiter))); - Iterables. addAll(contents, transform(commonPrefixes, - new Function() { - public StorageMetadata apply(String o) { - MutableStorageMetadata md = new MutableStorageMetadataImpl(); - md.setType(StorageType.RELATIVE_PATH); - md.setName(o); - return md; - } - })); - } + Iterables. addAll(contents, transform(commonPrefixes, + new Function() { + public StorageMetadata apply(String o) { + MutableStorageMetadata md = new MutableStorageMetadataImpl(); + md.setType(StorageType.RELATIVE_PATH); + md.setName(o); + return md; + } + })); + } - // trim metadata, if the response isn't supposed to be detailed. - if (!options.isDetailed()) { - for (StorageMetadata md : contents) { - md.getUserMetadata().clear(); - } - } + // trim metadata, if the response isn't supposed to be detailed. + if (!options.isDetailed()) { + for (StorageMetadata md : contents) { + md.getUserMetadata().clear(); + } + } } return Futures.> immediateFuture(new PageSetImpl(contents, @@ -254,7 +249,6 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { } - private ContainerNotFoundException cnfe(final String name) { return new ContainerNotFoundException(name, String.format("container %s not in filesystem", name)); } @@ -295,37 +289,36 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { */ @Override public ListenableFuture removeBlob(final String container, final String key) { - storageStrategy.removeBlob(container, key); - return immediateFuture(null); + storageStrategy.removeBlob(container, key); + return immediateFuture(null); } - /** * {@inheritDoc} */ @Override public ListenableFuture containerExists(final String containerName) { - boolean exists = containerExistsSyncImpl(containerName); - return immediateFuture(exists); + boolean exists = containerExistsSyncImpl(containerName); + return immediateFuture(exists); } - /** + /** * {@inheritDoc} */ - @Override - public ListenableFuture> list() { - Iterable containers = storageStrategy.getAllContainerNames(); + @Override + public ListenableFuture> list() { + Iterable containers = storageStrategy.getAllContainerNames(); - return Futures.> immediateFuture(new PageSetImpl(transform( - containers, new Function() { - public StorageMetadata apply(String name) { - MutableStorageMetadata cmd = create(); - cmd.setName(name); - cmd.setType(StorageType.CONTAINER); - return cmd; - } - }), null)); - } + return Futures.> immediateFuture(new PageSetImpl(transform( + containers, new Function() { + public StorageMetadata apply(String name) { + MutableStorageMetadata cmd = create(); + cmd.setName(name); + cmd.setType(StorageType.CONTAINER); + return cmd; + } + }), null)); + } protected MutableStorageMetadata create() { return new MutableStorageMetadataImpl(); @@ -336,11 +329,10 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { */ @Path("{container}") @Override - public ListenableFuture createContainerInLocation( - final Location location, - @PathParam("container") @ParamValidators( { FilesystemContainerNameValidator.class }) String name) { - boolean result = storageStrategy.createContainer(name); - return immediateFuture(result); + public ListenableFuture createContainerInLocation(final Location location, + @PathParam("container") @ParamValidators( { FilesystemContainerNameValidator.class }) String name) { + boolean result = storageStrategy.createContainer(name); + return immediateFuture(result); } public String getFirstQueryOrNull(String string, @Nullable HttpRequestOptions options) { @@ -350,44 +342,44 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { return (values != null && values.size() >= 1) ? values.iterator().next() : null; } - /** - * Load the blob with the given key belonging to the container with the given - * name. There must exist a resource on the file system whose complete name - * is given concatenating the container name and the key - * - * @param container it's the name of the container the blob belongs to - * @param key it's the key of the blob - * - * @return the blob belonging to the given container with the given key - */ - private Blob loadFileBlob(final String container, final String key) { - logger.debug("Opening blob in container: %s - %s", container, key); - File blobPayload = storageStrategy.getFileForBlobKey(container, key); - - Payload payload = new FilePayload(blobPayload); - // Loading object metadata - MutableBlobMetadata metadata = new MutableBlobMetadataImpl(); - metadata.setName(key); - metadata.setLastModified(new Date(blobPayload.lastModified())); - metadata.getContentMetadata().setContentLength(blobPayload.length()); - // TODO What about the MD5? are we supposed to calculate it each time we load - //the file? - try { - payload = Payloads.calculateMD5(payload); - } catch (IOException e) { - logger.error("An error occurred calculating MD5 for blob %s from container ", key, container); - Throwables.propagateIfPossible(e); - } - metadata.getContentMetadata().setContentType(""); - String eTag = CryptoStreams.hex(payload.getContentMetadata().getContentMD5()); - metadata.setETag(eTag); - // Creating new blob object - Blob blob = blobFactory.create(metadata); - blob.setPayload(blobPayload); - return blob; - } - + /** + * Load the blob with the given key belonging to the container with the given name. There must + * exist a resource on the file system whose complete name is given concatenating the container + * name and the key + * + * @param container + * it's the name of the container the blob belongs to + * @param key + * it's the key of the blob + * + * @return the blob belonging to the given container with the given key + */ + private Blob loadFileBlob(final String container, final String key) { + logger.debug("Opening blob in container: %s - %s", container, key); + File blobPayload = storageStrategy.getFileForBlobKey(container, key); + Payload payload = new FilePayload(blobPayload); + // Loading object metadata + MutableBlobMetadata metadata = new MutableBlobMetadataImpl(); + metadata.setName(key); + metadata.setLastModified(new Date(blobPayload.lastModified())); + metadata.getContentMetadata().setContentLength(blobPayload.length()); + // TODO What about the MD5? are we supposed to calculate it each time we load + // the file? + try { + payload = Payloads.calculateMD5(payload); + } catch (IOException e) { + logger.error("An error occurred calculating MD5 for blob %s from container ", key, container); + Throwables.propagateIfPossible(e); + } + metadata.getContentMetadata().setContentType(""); + String eTag = CryptoStreams.hex(payload.getContentMetadata().getContentMD5()); + metadata.setETag(eTag); + // Creating new blob object + Blob blob = blobFactory.create(metadata); + blob.setPayload(blobPayload); + return blob; + } protected static class DelimiterFilter implements Predicate { private final String prefix; @@ -496,14 +488,13 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { logger.debug("Put object with key [%s] to container [%s]", blobKey, containerName); String eTag = getEtag(object); try { - //TODO - //must override existing file? + // TODO + // must override existing file? storageStrategy.writePayloadOnFile(containerName, blobKey, object.getPayload()); } catch (IOException e) { - logger.error(e, "An error occurred storing the new object with name [%s] to container [%s].", - blobKey, - containerName); + logger.error(e, "An error occurred storing the new object with name [%s] to container [%s].", blobKey, + containerName); Throwables.propagate(e); } return immediateFuture(eTag); @@ -522,9 +513,9 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { */ @Override public ListenableFuture getBlob(final String containerName, final String key, GetOptions options) { - logger.debug("Retrieving blob with key %s from container %s", key,containerName); + logger.debug("Retrieving blob with key %s from container %s", key, containerName); // If the container doesn't exist, an exception is thrown - if(!containerExistsSyncImpl(containerName)) { + if (!containerExistsSyncImpl(containerName)) { logger.debug("Container %s does not exist", containerName); return immediateFailedFuture(cnfe(containerName)); } @@ -536,63 +527,63 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { Blob blob = loadFileBlob(containerName, key); - if(options!=null) { - if (options.getIfMatch() != null) { - if (!blob.getMetadata().getETag().equals(options.getIfMatch())) - return immediateFailedFuture(returnResponseException(412)); - } - if (options.getIfNoneMatch() != null) { - if (blob.getMetadata().getETag().equals(options.getIfNoneMatch())) - return immediateFailedFuture(returnResponseException(304)); - } - if (options.getIfModifiedSince() != null) { - Date modifiedSince = options.getIfModifiedSince(); + if (options != null) { + if (options.getIfMatch() != null) { + if (!blob.getMetadata().getETag().equals(options.getIfMatch())) + return immediateFailedFuture(returnResponseException(412)); + } + if (options.getIfNoneMatch() != null) { + if (blob.getMetadata().getETag().equals(options.getIfNoneMatch())) + return immediateFailedFuture(returnResponseException(304)); + } + if (options.getIfModifiedSince() != null) { + Date modifiedSince = options.getIfModifiedSince(); if (blob.getMetadata().getLastModified().before(modifiedSince)) { - HttpResponse response = new HttpResponse(304, null, null); - return immediateFailedFuture(new HttpResponseException(String.format("%1$s is before %2$s", blob - .getMetadata().getLastModified(), modifiedSince), null, response)); + HttpResponse response = new HttpResponse(304, null, null); + return immediateFailedFuture(new HttpResponseException(String.format("%1$s is before %2$s", blob + .getMetadata().getLastModified(), modifiedSince), null, response)); } - } - if (options.getIfUnmodifiedSince() != null) { - Date unmodifiedSince = options.getIfUnmodifiedSince(); - if (blob.getMetadata().getLastModified().after(unmodifiedSince)) { - HttpResponse response = new HttpResponse(412, null, null); - return immediateFailedFuture(new HttpResponseException(String.format("%1$s is after %2$s", blob - .getMetadata().getLastModified(), unmodifiedSince), null, response)); - } - } + } + if (options.getIfUnmodifiedSince() != null) { + Date unmodifiedSince = options.getIfUnmodifiedSince(); + if (blob.getMetadata().getLastModified().after(unmodifiedSince)) { + HttpResponse response = new HttpResponse(412, null, null); + return immediateFailedFuture(new HttpResponseException(String.format("%1$s is after %2$s", blob + .getMetadata().getLastModified(), unmodifiedSince), null, response)); + } + } - if (options.getRanges() != null && options.getRanges().size() > 0) { - byte[] data; - try { - data = toByteArray(blob.getPayload().getInput()); - } catch (IOException e) { - return immediateFailedFuture(new RuntimeException(e)); - } - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (String s : options.getRanges()) { - if (s.startsWith("-")) { - int length = Integer.parseInt(s.substring(1)); - out.write(data, data.length - length, length); - } else if (s.endsWith("-")) { - int offset = Integer.parseInt(s.substring(0, s.length() - 1)); - out.write(data, offset, data.length - offset); - } else if (s.contains("-")) { - String[] firstLast = s.split("\\-"); - int offset = Integer.parseInt(firstLast[0]); - int last = Integer.parseInt(firstLast[1]); - int length = (last < data.length) ? last + 1 : data.length - offset; - out.write(data, offset, length); - } else { - return immediateFailedFuture(new IllegalArgumentException("first and last were null!")); - } + if (options.getRanges() != null && options.getRanges().size() > 0) { + byte[] data; + try { + data = toByteArray(blob.getPayload().getInput()); + } catch (IOException e) { + return immediateFailedFuture(new RuntimeException(e)); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (String s : options.getRanges()) { + if (s.startsWith("-")) { + int length = Integer.parseInt(s.substring(1)); + out.write(data, data.length - length, length); + } else if (s.endsWith("-")) { + int offset = Integer.parseInt(s.substring(0, s.length() - 1)); + out.write(data, offset, data.length - offset); + } else if (s.contains("-")) { + String[] firstLast = s.split("\\-"); + int offset = Integer.parseInt(firstLast[0]); + int last = Integer.parseInt(firstLast[1]); + int length = (last < data.length) ? last + 1 : data.length - offset; + out.write(data, offset, length); + } else { + return immediateFailedFuture(new IllegalArgumentException("first and last were null!")); + } - } - blob.setPayload(out.toByteArray()); - blob.getMetadata().getContentMetadata().setContentLength(new Long(data.length)); - } - } + } + blob.setPayload(out.toByteArray()); + blob.getMetadata().getContentMetadata().setContentLength(new Long(data.length)); + } + } checkNotNull(blob.getPayload(), "payload " + blob); return immediateFuture(blob); } @@ -618,11 +609,10 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { return containerExistsSyncImpl(container); } - /** - * Override parent method because it uses strange futures and listenables - * that creates problem in the test if more than one test that deletes the - * container is executed + * Override parent method because it uses strange futures and listenables that creates problem in + * the test if more than one test that deletes the container is executed + * * @param container * @return */ @@ -632,35 +622,33 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore { return immediateFuture(null); } - /** - * Each container is a directory, so in order to check if a container exists - * the corresponding directory must exists. Synchronous implementation + * Each container is a directory, so in order to check if a container exists the corresponding + * directory must exists. Synchronous implementation + * * @param containerName * @return */ private boolean containerExistsSyncImpl(String containerName) { - return storageStrategy.containerExists(containerName); + return storageStrategy.containerExists(containerName); } - - /** - * + * * Calculates the object MD5 and returns it as eTag + * * @param object * @return */ - private String getEtag(Blob object) { - try { - Payloads.calculateMD5(object, crypto.md5()); - } catch (IOException ex) { - logger.error(ex, "An error occurred calculating MD5 for object with name %s.", - object.getMetadata().getName()); - Throwables.propagate(ex); - } + private String getEtag(Blob object) { + try { + Payloads.calculateMD5(object, crypto.md5()); + } catch (IOException ex) { + logger.error(ex, "An error occurred calculating MD5 for object with name %s.", object.getMetadata().getName()); + Throwables.propagate(ex); + } - String eTag = CryptoStreams.hex(object.getPayload().getContentMetadata().getContentMD5()); - return eTag; - } + String eTag = CryptoStreams.hex(object.getPayload().getContentMetadata().getContentMD5()); + return eTag; + } } diff --git a/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java b/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java index 0f6ce99731..548c216374 100644 --- a/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java +++ b/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java @@ -19,15 +19,8 @@ package org.jclouds.filesystem.config; -import com.google.common.base.Supplier; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableSet; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.Singleton; -import com.google.inject.TypeLiteral; import java.util.Set; + import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.BlobStoreContext; @@ -36,6 +29,7 @@ import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.config.BlobStoreObjectModule; import org.jclouds.blobstore.internal.BlobStoreContextImpl; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; @@ -48,8 +42,17 @@ import org.jclouds.filesystem.strategy.FilesystemStorageStrategy; import org.jclouds.filesystem.strategy.internal.FilesystemStorageStrategyImpl; import org.jclouds.filesystem.util.internal.FileSystemBlobUtilsImpl; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableSet; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.Singleton; +import com.google.inject.TypeLiteral; + /** - * + * * @author Alfredo "Rainbowbreeze" Morresi */ public class FilesystemBlobStoreContextModule extends AbstractModule { @@ -76,6 +79,7 @@ public class FilesystemBlobStoreContextModule extends AbstractModule { @Provides @Singleton + @Memoized Supplier> provideLocations(Supplier defaultLocation) { return Suppliers.> ofInstance(ImmutableSet.of(defaultLocation.get())); } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java index 449e74e266..c1ddef2233 100755 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java @@ -20,61 +20,32 @@ package org.jclouds.gogrid.compute.config; import static org.jclouds.compute.domain.OsFamily.CENTOS; -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.compute.util.ComputeServiceUtils.getSpace; -import static org.jclouds.gogrid.reference.GoGridConstants.PROPERTY_GOGRID_DEFAULT_DC; -import java.util.Map; import java.util.Set; -import javax.inject.Singleton; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.domain.Location; -import org.jclouds.gogrid.GoGridAsyncClient; -import org.jclouds.gogrid.GoGridClient; -import org.jclouds.gogrid.compute.functions.ServerToNodeMetadata; import org.jclouds.gogrid.compute.strategy.GoGridAddNodeWithTagStrategy; import org.jclouds.gogrid.compute.strategy.GoGridDestroyNodeStrategy; import org.jclouds.gogrid.compute.strategy.GoGridGetNodeMetadataStrategy; import org.jclouds.gogrid.compute.strategy.GoGridListNodesStrategy; import org.jclouds.gogrid.compute.strategy.GoGridRebootNodeStrategy; +import org.jclouds.gogrid.compute.suppliers.GoGridDefaultLocationSupplier; import org.jclouds.gogrid.compute.suppliers.GoGridHardwareSupplier; import org.jclouds.gogrid.compute.suppliers.GoGridImageSupplier; import org.jclouds.gogrid.compute.suppliers.GoGridLocationSupplier; -import org.jclouds.gogrid.domain.Server; -import org.jclouds.gogrid.domain.ServerState; -import org.jclouds.rest.RestContext; -import org.jclouds.rest.internal.RestContextImpl; -import com.google.common.annotations.VisibleForTesting; -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.ImmutableMap; -import com.google.common.collect.Iterables; import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.util.Providers; /** * @author Oleksiy Yarmula @@ -84,21 +55,8 @@ public class GoGridComputeServiceContextModule extends BaseComputeServiceContext @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - bind(new TypeLiteral>() { - }).to(ServerToNodeMetadata.class); - bind(LoadBalancerService.class).toProvider(Providers. of(null)); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(AddNodeWithTagStrategy.class).to(GoGridAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(GoGridListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(GoGridGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(GoGridRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(GoGridDestroyNodeStrategy.class); + install(new GoGridComputeServiceDependenciesModule()); + super.configure(); } @Override @@ -106,85 +64,48 @@ public class GoGridComputeServiceContextModule extends BaseComputeServiceContext return template.osFamily(CENTOS).imageNameMatches(".*w/ None.*"); } - @VisibleForTesting - static final Map serverStateToNodeState = ImmutableMap. builder() - .put(ServerState.ON, NodeState.RUNNING)// - .put(ServerState.STARTING, NodeState.PENDING)// - .put(ServerState.OFF, NodeState.SUSPENDED)// - .put(ServerState.STOPPING, NodeState.PENDING)// - .put(ServerState.RESTARTING, NodeState.PENDING)// - .put(ServerState.SAVING, NodeState.PENDING)// - .put(ServerState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// - .put(ServerState.RESTORING, NodeState.PENDING)// - .put(ServerState.UPDATING, NodeState.PENDING).build(); - - @Singleton - @Provides - Map provideServerToNodeState() { - return serverStateToNodeState; - } - - /** - * Finds matches to required configurations. GoGrid's documentation only specifies how much RAM - * one can get with different instance types. The # of cores and disk sizes are purely empyrical - * and aren't guaranteed. However, these are the matches found: Ram: 512MB, CPU: 1 core, HDD: 28 - * GB Ram: 1GB, CPU: 1 core, HDD: 57 GB Ram: 2GB, CPU: 1 core, HDD: 113 GB Ram: 4GB, CPU: 3 - * cores, HDD: 233 GB Ram: 8GB, CPU: 6 cores, HDD: 462 GB (as of March 2010) - * - * @return matched size - */ - @Singleton - @Provides - Function provideSizeToRam() { - return new Function() { - @Override - public String apply(Hardware hardware) { - if (hardware.getRam() >= 8 * 1024 || getCores(hardware) >= 6 || getSpace(hardware) >= 450) - return "8GB"; - if (hardware.getRam() >= 4 * 1024 || getCores(hardware) >= 3 || getSpace(hardware) >= 230) - return "4GB"; - if (hardware.getRam() >= 2 * 1024 || getSpace(hardware) >= 110) - return "2GB"; - if (hardware.getRam() >= 1024 || getSpace(hardware) >= 55) - return "1GB"; - return "512MB"; /* smallest */ - } - }; + @Override + protected Class defineAddNodeWithTagStrategy() { + return GoGridAddNodeWithTagStrategy.class; } @Override - protected Supplier supplyDefaultLocation(Injector injector, Supplier> locations) { - final String defaultDC = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_GOGRID_DEFAULT_DC))); - return Suppliers.compose(new Function, Location>() { - - @Override - public Location apply(Set from) { - return Iterables.find(from, new Predicate() { - - @Override - public boolean apply(Location input) { - return input.getId().equals(defaultDC); - } - - }); - } - - }, locations); - + protected Class defineDestroyNodeStrategy() { + return GoGridDestroyNodeStrategy.class; } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(GoGridImageSupplier.class); + protected Class defineGetNodeMetadataStrategy() { + return GoGridGetNodeMetadataStrategy.class; } @Override - protected Supplier> getSourceLocationSupplier(Injector injector) { - return injector.getInstance(GoGridLocationSupplier.class); + protected Class>> defineHardwareSupplier() { + return GoGridHardwareSupplier.class; } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(GoGridHardwareSupplier.class); + protected Class>> defineImageSupplier() { + return GoGridImageSupplier.class; + } + + @Override + protected Class defineListNodesStrategy() { + return GoGridListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return GoGridRebootNodeStrategy.class; + } + + @Override + protected Class> defineDefaultLocationSupplier() { + return GoGridDefaultLocationSupplier.class; + } + + @Override + protected Class>> defineLocationSupplier() { + return GoGridLocationSupplier.class; } } diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceDependenciesModule.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..097aa4ca62 --- /dev/null +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceDependenciesModule.java @@ -0,0 +1,113 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.gogrid.compute.config; + +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.compute.util.ComputeServiceUtils.getSpace; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.gogrid.GoGridAsyncClient; +import org.jclouds.gogrid.GoGridClient; +import org.jclouds.gogrid.compute.functions.ServerToNodeMetadata; +import org.jclouds.gogrid.domain.Server; +import org.jclouds.gogrid.domain.ServerState; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * @author Oleksiy Yarmula + * @author Adrian Cole + */ +public class GoGridComputeServiceDependenciesModule extends AbstractModule { + + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).to(ServerToNodeMetadata.class); + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + } + + @VisibleForTesting + static final Map serverStateToNodeState = ImmutableMap. builder() + .put(ServerState.ON, NodeState.RUNNING)// + .put(ServerState.STARTING, NodeState.PENDING)// + .put(ServerState.OFF, NodeState.SUSPENDED)// + .put(ServerState.STOPPING, NodeState.PENDING)// + .put(ServerState.RESTARTING, NodeState.PENDING)// + .put(ServerState.SAVING, NodeState.PENDING)// + .put(ServerState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + .put(ServerState.RESTORING, NodeState.PENDING)// + .put(ServerState.UPDATING, NodeState.PENDING).build(); + + @Singleton + @Provides + Map provideServerToNodeState() { + return serverStateToNodeState; + } + + /** + * Finds matches to required configurations. GoGrid's documentation only specifies how much RAM + * one can get with different instance types. The # of cores and disk sizes are purely empyrical + * and aren't guaranteed. However, these are the matches found: Ram: 512MB, CPU: 1 core, HDD: 28 + * GB Ram: 1GB, CPU: 1 core, HDD: 57 GB Ram: 2GB, CPU: 1 core, HDD: 113 GB Ram: 4GB, CPU: 3 + * cores, HDD: 233 GB Ram: 8GB, CPU: 6 cores, HDD: 462 GB (as of March 2010) + * + * @return matched size + */ + @Singleton + @Provides + Function provideSizeToRam() { + return new Function() { + @Override + public String apply(Hardware hardware) { + if (hardware.getRam() >= 8 * 1024 || getCores(hardware) >= 6 || getSpace(hardware) >= 450) + return "8GB"; + if (hardware.getRam() >= 4 * 1024 || getCores(hardware) >= 3 || getSpace(hardware) >= 230) + return "4GB"; + if (hardware.getRam() >= 2 * 1024 || getSpace(hardware) >= 110) + return "2GB"; + if (hardware.getRam() >= 1024 || getSpace(hardware) >= 55) + return "1GB"; + return "512MB"; /* smallest */ + } + }; + } +} diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java index 1967083cd6..28670853c2 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java @@ -30,6 +30,7 @@ import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -72,8 +73,8 @@ public class ServerToNodeMetadata implements Function { @Override public boolean apply(Image input) { return input.getProviderId().equals(instance.getImage().getId() + "") - && (input.getLocation() == null || input.getLocation().getId() - .equals(instance.getDatacenter().getId() + "")); + && (input.getLocation() == null || input.getLocation().getId().equals( + instance.getDatacenter().getId() + "")); } } @@ -93,8 +94,8 @@ public class ServerToNodeMetadata implements Function { @Inject ServerToNodeMetadata(Map serverStateToNodeState, GoGridClient client, - Supplier> images, Supplier> hardwares, - Supplier> locations) { + @Memoized Supplier> images, @Memoized Supplier> hardwares, + Supplier> locations) { this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.client = checkNotNull(client, "client"); this.images = checkNotNull(images, "images"); @@ -111,11 +112,11 @@ public class ServerToNodeMetadata implements Function { builder.tag(parseTagFromName(from.getName())); builder.hardware(parseHardware(from)); builder.imageId(from.getImage().getId() + ""); - + Image image = parseImage(from); if (image != null) builder.operatingSystem(image.getOperatingSystem()); - + builder.state(serverStateToNodeState.get(from.getState())); builder.publicAddresses(ImmutableSet.of(from.getIp().getIp())); builder.credentials(client.getServerServices().getServerCredentialsList().get(from.getName())); diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridDefaultLocationSupplier.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridDefaultLocationSupplier.java new file mode 100644 index 0000000000..63d1067ebe --- /dev/null +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridDefaultLocationSupplier.java @@ -0,0 +1,64 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.gogrid.reference.GoGridConstants.PROPERTY_GOGRID_DEFAULT_DC; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.collect.Memoized; +import org.jclouds.domain.Location; + +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class GoGridDefaultLocationSupplier implements Supplier { + private final Supplier> locations; + private final String defaultDC; + + @Inject + GoGridDefaultLocationSupplier(@Memoized Supplier> locations, + @Named(PROPERTY_GOGRID_DEFAULT_DC) String defaultDC) { + this.locations = locations; + this.defaultDC = defaultDC; + } + + @Override + public Location get() { + return Iterables.find(locations.get(), new Predicate() { + + @Override + public boolean apply(Location input) { + return input.getId().equals(defaultDC); + } + + }); + } +} \ No newline at end of file diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java index ae8ee11f1b..72ed1e9eab 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java @@ -40,21 +40,21 @@ import com.google.common.collect.ImmutableSet; @Singleton public class GoGridHardwareSupplier implements Supplier> { - public static final Hardware H8192 = new HardwareBuilder().ids("5").ram(8192) - .processors(ImmutableList.of(new Processor(8, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(480.0f, true, true))).build(); - public static final Hardware H4096 = new HardwareBuilder().ids("4").ram(4096) - .processors(ImmutableList.of(new Processor(4, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(240.0f, true, true))).build(); - public static final Hardware H2048 = new HardwareBuilder().ids("3").ram(2048) - .processors(ImmutableList.of(new Processor(2, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(120.0f, true, true))).build(); - public static final Hardware H1024 = new HardwareBuilder().ids("2").ram(1024) - .processors(ImmutableList.of(new Processor(1, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(60.0f, true, true))).build(); - public static final Hardware H512 = new HardwareBuilder().ids("1").ram(512) - .processors(ImmutableList.of(new Processor(0.5, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(30.0f, true, true))).build(); + public static final Hardware H8192 = new HardwareBuilder().ids("5").ram(8192).processors( + ImmutableList.of(new Processor(8, 1.0))).volumes( + ImmutableList. of(new VolumeImpl(480.0f, true, true))).build(); + public static final Hardware H4096 = new HardwareBuilder().ids("4").ram(4096).processors( + ImmutableList.of(new Processor(4, 1.0))).volumes( + ImmutableList. of(new VolumeImpl(240.0f, true, true))).build(); + public static final Hardware H2048 = new HardwareBuilder().ids("3").ram(2048).processors( + ImmutableList.of(new Processor(2, 1.0))).volumes( + ImmutableList. of(new VolumeImpl(120.0f, true, true))).build(); + public static final Hardware H1024 = new HardwareBuilder().ids("2").ram(1024).processors( + ImmutableList.of(new Processor(1, 1.0))).volumes( + ImmutableList. of(new VolumeImpl(60.0f, true, true))).build(); + public static final Hardware H512 = new HardwareBuilder().ids("1").ram(512).processors( + ImmutableList.of(new Processor(0.5, 1.0))).volumes( + ImmutableList. of(new VolumeImpl(30.0f, true, true))).build(); public static final ImmutableSet H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192); diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java index 142600faca..ee17337bb5 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java @@ -69,7 +69,7 @@ public class GoGridImageSupplier implements Supplier> { Set allImages = sync.getImageServices().getImageList(); for (ServerImage from : allImages) { ImageBuilder builder = new ImageBuilder(); - builder.ids(from.getId()+""); + builder.ids(from.getId() + ""); builder.name(from.getFriendlyName()); builder.description(from.getDescription()); builder.defaultCredentials(authenticator.execute(from)); diff --git a/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java b/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java index ff390a12e7..dc5478829d 100644 --- a/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java +++ b/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java @@ -31,7 +31,7 @@ public class GoGridComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerState state : ServerState.values()) { - assert GoGridComputeServiceContextModule.serverStateToNodeState.containsKey(state) : state; + assert GoGridComputeServiceDependenciesModule.serverStateToNodeState.containsKey(state) : state; } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesAsyncBlobStore.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesAsyncBlobStore.java index 16d889f13e..21618464ec 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesAsyncBlobStore.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesAsyncBlobStore.java @@ -42,6 +42,7 @@ import org.jclouds.blobstore.internal.BaseAsyncBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.concurrent.Futures; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; @@ -83,7 +84,7 @@ public class CloudFilesAsyncBlobStore extends BaseAsyncBlobStore { @Inject CloudFilesAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - Supplier> locations, CloudFilesClient sync, CloudFilesAsyncClient async, + @Memoized Supplier> locations, CloudFilesClient sync, CloudFilesAsyncClient async, ContainerToResourceMetadata container2ResourceMd, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object, diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobStore.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobStore.java index 18181226d6..d25c2bff5d 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobStore.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/CloudFilesBlobStore.java @@ -39,6 +39,7 @@ import org.jclouds.blobstore.internal.BaseBlobStore; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.http.options.GetOptions; import org.jclouds.rackspace.cloudfiles.CloudFilesClient; @@ -72,7 +73,7 @@ public class CloudFilesBlobStore extends BaseBlobStore { @Inject CloudFilesBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, - Supplier> locations, CloudFilesClient sync, + @Memoized Supplier> locations, CloudFilesClient sync, ContainerToResourceMetadata container2ResourceMd, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object, diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java index d60368d013..ac8fabd248 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java @@ -30,13 +30,14 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.internal.BlobStoreContextImpl; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.rackspace.cloudfiles.CloudFilesAsyncClient; import org.jclouds.rackspace.cloudfiles.CloudFilesClient; import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesAsyncBlobStore; import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesBlobRequestSigner; import org.jclouds.rackspace.cloudfiles.blobstore.CloudFilesBlobStore; -import org.jclouds.rackspace.config.RackspaceLocationsModule; +import org.jclouds.rackspace.config.RackspaceLocationsSupplier; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; @@ -56,8 +57,11 @@ public class CloudFilesBlobStoreContextModule extends AbstractModule { @Override protected void configure() { - install(new RackspaceLocationsModule()); install(new BlobStoreMapModule()); + bind(new TypeLiteral>>() { + }).annotatedWith(Memoized.class).to(new TypeLiteral() { + }); + bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(AsyncBlobStore.class).to(CloudFilesAsyncBlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(CloudFilesBlobStore.class).in(Scopes.SINGLETON); @@ -68,14 +72,8 @@ public class CloudFilesBlobStoreContextModule extends AbstractModule { @Provides @Singleton - protected Supplier> getSourceLocationSupplier(Set locations) { - return Suppliers.> ofInstance(locations); - } - - @Provides - @Singleton - protected Supplier getLocation(Set locations) { - return Suppliers. ofInstance(Iterables.get(locations, 0)); + protected Supplier getLocation(@Memoized Supplier> locations) { + return Suppliers. ofInstance(Iterables.get(locations.get(), 0)); } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java index e1aeeb9ed1..8f54b6431c 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java @@ -21,34 +21,19 @@ package org.jclouds.rackspace.cloudservers.compute.config; import static org.jclouds.compute.domain.OsFamily.UBUNTU; -import java.util.Map; import java.util.Set; -import javax.inject.Singleton; - -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.internal.BaseComputeService; -import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy; -import org.jclouds.rackspace.cloudservers.CloudServersAsyncClient; -import org.jclouds.rackspace.cloudservers.CloudServersClient; -import org.jclouds.rackspace.cloudservers.compute.functions.CloudServersImageToImage; -import org.jclouds.rackspace.cloudservers.compute.functions.CloudServersImageToOperatingSystem; -import org.jclouds.rackspace.cloudservers.compute.functions.FlavorToHardware; -import org.jclouds.rackspace.cloudservers.compute.functions.ServerToNodeMetadata; +import org.jclouds.domain.Location; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersAddNodeWithTagStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersDestroyNodeStrategy; import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy; @@ -56,22 +41,10 @@ import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersListNodes import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersRebootNodeStrategy; import org.jclouds.rackspace.cloudservers.compute.suppliers.CloudServersHardwareSupplier; import org.jclouds.rackspace.cloudservers.compute.suppliers.CloudServersImageSupplier; -import org.jclouds.rackspace.cloudservers.domain.Flavor; -import org.jclouds.rackspace.cloudservers.domain.Server; -import org.jclouds.rackspace.cloudservers.domain.ServerStatus; -import org.jclouds.rackspace.config.RackspaceLocationsModule; -import org.jclouds.rest.RestContext; -import org.jclouds.rest.internal.RestContextImpl; +import org.jclouds.rackspace.config.RackspaceLocationsSupplier; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; import com.google.inject.Injector; -import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; -import com.google.inject.util.Providers; /** * Configures the {@link CloudServersComputeServiceContext}; requires {@link BaseComputeService} @@ -83,32 +56,8 @@ public class CloudServersComputeServiceContextModule extends BaseComputeServiceC @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - install(new RackspaceLocationsModule()); - bind(new TypeLiteral>() { - }).to(ServerToNodeMetadata.class); - - bind(new TypeLiteral>() { - }).to(CloudServersImageToImage.class); - - bind(new TypeLiteral>() { - }).to(CloudServersImageToOperatingSystem.class); - - bind(new TypeLiteral>() { - }).to(FlavorToHardware.class); - - bind(LoadBalancerService.class).toProvider(Providers. of(null)); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(AddNodeWithTagStrategy.class).to(CloudServersAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(CloudServersListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(CloudServersGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(CloudServersRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(CloudServersDestroyNodeStrategy.class); + install(new CloudServersComputeServiceDependenciesModule()); + super.configure(); } @Override @@ -116,46 +65,43 @@ public class CloudServersComputeServiceContextModule extends BaseComputeServiceC return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*"); } - @VisibleForTesting - public static final Map serverToNodeState = ImmutableMap - . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// - .put(ServerStatus.DELETED, NodeState.TERMINATED)// - .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// - .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// - .put(ServerStatus.RESIZE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// - .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// - .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// - .put(ServerStatus.MOVE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// - .put(ServerStatus.RESCUE, NodeState.PENDING)// - .put(ServerStatus.ERROR, NodeState.ERROR)// - .put(ServerStatus.BUILD, NodeState.PENDING)// - .put(ServerStatus.RESTORING, NodeState.PENDING)// - .put(ServerStatus.PASSWORD, NodeState.PENDING)// - .put(ServerStatus.REBUILD, NodeState.PENDING)// - .put(ServerStatus.DELETE_IP, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP, NodeState.PENDING)// - .put(ServerStatus.REBOOT, NodeState.PENDING)// - .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// - .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); - - @Singleton - @Provides - Map provideServerToNodeState() { - return serverToNodeState; + @Override + protected Class defineAddNodeWithTagStrategy() { + return CloudServersAddNodeWithTagStrategy.class; } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(CloudServersImageSupplier.class); + protected Class defineDestroyNodeStrategy() { + return CloudServersDestroyNodeStrategy.class; } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(CloudServersHardwareSupplier.class); + protected Class defineGetNodeMetadataStrategy() { + return CloudServersGetNodeMetadataStrategy.class; + } + + @Override + protected Class>> defineHardwareSupplier() { + return CloudServersHardwareSupplier.class; + } + + @Override + protected Class>> defineImageSupplier() { + return CloudServersImageSupplier.class; + } + + @Override + protected Class defineListNodesStrategy() { + return CloudServersListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return CloudServersRebootNodeStrategy.class; + } + + @Override + protected Class>> defineLocationSupplier() { + return RackspaceLocationsSupplier.class; } } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceDependenciesModule.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..9f71b4ac50 --- /dev/null +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceDependenciesModule.java @@ -0,0 +1,117 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.config; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.rackspace.cloudservers.CloudServersAsyncClient; +import org.jclouds.rackspace.cloudservers.CloudServersClient; +import org.jclouds.rackspace.cloudservers.compute.functions.CloudServersImageToImage; +import org.jclouds.rackspace.cloudservers.compute.functions.CloudServersImageToOperatingSystem; +import org.jclouds.rackspace.cloudservers.compute.functions.FlavorToHardware; +import org.jclouds.rackspace.cloudservers.compute.functions.ServerToNodeMetadata; +import org.jclouds.rackspace.cloudservers.domain.Flavor; +import org.jclouds.rackspace.cloudservers.domain.Server; +import org.jclouds.rackspace.cloudservers.domain.ServerStatus; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * Configures the {@link CloudServersComputeServiceContext}; requires {@link BaseComputeService} + * bound. + * + * @author Adrian Cole + */ +public class CloudServersComputeServiceDependenciesModule extends AbstractModule { + + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).to(ServerToNodeMetadata.class); + + bind(new TypeLiteral>() { + }).to(CloudServersImageToImage.class); + + bind(new TypeLiteral>() { + }).to(CloudServersImageToOperatingSystem.class); + + bind(new TypeLiteral>() { + }).to(FlavorToHardware.class); + + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + } + + @VisibleForTesting + public static final Map serverToNodeState = ImmutableMap + . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// + .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// + .put(ServerStatus.DELETED, NodeState.TERMINATED)// + .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// + .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// + .put(ServerStatus.RESIZE, NodeState.PENDING)// + .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// + .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// + .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// + .put(ServerStatus.MOVE, NodeState.PENDING)// + .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// + .put(ServerStatus.RESCUE, NodeState.PENDING)// + .put(ServerStatus.ERROR, NodeState.ERROR)// + .put(ServerStatus.BUILD, NodeState.PENDING)// + .put(ServerStatus.RESTORING, NodeState.PENDING)// + .put(ServerStatus.PASSWORD, NodeState.PENDING)// + .put(ServerStatus.REBUILD, NodeState.PENDING)// + .put(ServerStatus.DELETE_IP, NodeState.PENDING)// + .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// + .put(ServerStatus.SHARE_IP, NodeState.PENDING)// + .put(ServerStatus.REBOOT, NodeState.PENDING)// + .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// + .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// + .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + + @Singleton + @Provides + Map provideServerToNodeState() { + return serverToNodeState; + } + +} diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java index fecc700a45..9135be4549 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java @@ -30,6 +30,7 @@ import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -91,7 +92,8 @@ public class ServerToNodeMetadata implements Function { @Inject ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, - Supplier> images, Supplier location, Supplier> hardwares) { + @Memoized Supplier> images, Supplier location, + @Memoized Supplier> hardwares) { this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java index 8ac4b63a1d..f1b7b1dd79 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java @@ -54,7 +54,7 @@ public class CloudServersImageSupplier implements Supplier> @Inject CloudServersImageSupplier(CloudServersClient sync, - Function cloudServersImageToImage) { + Function cloudServersImageToImage) { this.sync = sync; this.cloudServersImageToImage = cloudServersImageToImage; } @@ -64,7 +64,7 @@ public class CloudServersImageSupplier implements Supplier> Set images; logger.debug(">> providing images"); images = Sets. newLinkedHashSet(Iterables.transform(sync.listImages(withDetails()), - cloudServersImageToImage)); + cloudServersImageToImage)); logger.debug("<< images(%d)", images.size()); return images; } diff --git a/rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsModule.java b/rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsSupplier.java similarity index 79% rename from rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsModule.java rename to rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsSupplier.java index 6c303181eb..533c053ea0 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsModule.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/config/RackspaceLocationsSupplier.java @@ -21,31 +21,32 @@ package org.jclouds.rackspace.config; import java.util.Set; -import javax.inject.Singleton; +import javax.inject.Inject; 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.Supplier; import com.google.common.collect.ImmutableSet; -import com.google.inject.AbstractModule; -import com.google.inject.Provides; /** * Configures the locations used in Rackspace services * * @author Adrian Cole */ -public class RackspaceLocationsModule extends AbstractModule { +public class RackspaceLocationsSupplier implements Supplier> { - @Override - protected void configure() { + private final String providerName; + + @Inject + RackspaceLocationsSupplier(@Provider String providerName) { + this.providerName = providerName; } - @Provides - @Singleton - Set provideLocations(@Provider String providerName) { + @Override + public Set get() { Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); return ImmutableSet.of(new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider)); } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java index 763e101c54..ea4e0f0d0f 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModuleTest.java @@ -31,7 +31,7 @@ public class CloudServersComputeServiceContextModuleTest { public void testAllStatusCovered() { for (ServerStatus state : ServerStatus.values()) { - assert CloudServersComputeServiceContextModule.serverToNodeState.containsKey(state) : state; + assert CloudServersComputeServiceDependenciesModule.serverToNodeState.containsKey(state) : state; } } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java index 5a863b1bba..51b0288450 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java @@ -40,7 +40,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; -import org.jclouds.rackspace.cloudservers.compute.config.CloudServersComputeServiceContextModule; +import org.jclouds.rackspace.cloudservers.compute.config.CloudServersComputeServiceDependenciesModule; import org.jclouds.rackspace.cloudservers.domain.Server; import org.jclouds.rackspace.cloudservers.domain.ServerStatus; import org.jclouds.rackspace.cloudservers.functions.ParseServerFromJsonResponseTest; @@ -59,148 +59,104 @@ public class ServerToNodeMetadataTest { Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null); @Test - public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() - throws UnknownHostException { + public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException { Credentials creds = new Credentials("root", "abdce"); - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, - ImmutableMap. of("1234", creds), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + . of("1234", creds), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) - .privateAddresses(ImmutableSet.of("10.176.42.16")) - .tag("NOTAG-sample-server") - .imageId("2") - .id("1234") - .providerId("1234") - .name("sample-server") - .credentials(creds) - .location( - new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", - "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", - "description", null))) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")).tag( + "NOTAG-sample-server").imageId("2").id("1234").providerId("1234").name("sample-server").credentials( + creds).location( + new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", + "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", + "description", null))).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) - .privateAddresses(ImmutableSet.of("10.176.42.16")) - .tag("NOTAG-sample-server") - .imageId("2") - .id("1234") - .providerId("1234") - .name("sample-server") - .location( - new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", - "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", - "description", null))) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")).tag( + "NOTAG-sample-server").imageId("2").id("1234").providerId("1234").name("sample-server").location( + new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", + "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", + "description", null))).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState; org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) - .privateAddresses(ImmutableSet.of("10.176.42.16")) - .tag("NOTAG-sample-server") - .imageId("2") - .operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true) - .build()) - .id("1234") - .providerId("1234") - .name("sample-server") - .location( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")).tag( + "NOTAG-sample-server").imageId("2").operatingSystem( + new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true).build()) + .id("1234").providerId("1234").name("sample-server").location( new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", - "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", - "description", null))) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", + "description", null))).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageAndHardwareFound() throws UnknownHostException { - Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Map serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState; Set images = ImmutableSet.of(CloudServersImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "67.23.10.131")) - .privateAddresses(ImmutableSet.of("10.176.42.16")) - .tag("NOTAG-sample-server") - .imageId("2") - .hardware( - new HardwareBuilder() - .ids("1") - .name("256 MB Server") - .processors(ImmutableList.of(new Processor(1.0, 1.0))) - .ram(256) - .volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f) - .durable(true).bootDevice(true).build())).build()) - .operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true) - .build()) - .id("1234") - .providerId("1234") - .name("sample-server") - .location( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")).tag( + "NOTAG-sample-server").imageId("2").hardware( + new HardwareBuilder().ids("1").name("256 MB Server").processors( + ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( + ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) + .bootDevice(true).build())).build()).operatingSystem( + new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true).build()) + .id("1234").providerId("1234").name("sample-server").location( new LocationImpl(LocationScope.HOST, "e4d909c290d0fb1ca068ffaddf22cbd0", - "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", - "description", null))) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + "e4d909c290d0fb1ca068ffaddf22cbd0", new LocationImpl(LocationScope.ZONE, "dallas", + "description", null))).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } } \ No newline at end of file diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModule.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModule.java index 791ecf3878..9784d12970 100755 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModule.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceContextModule.java @@ -20,61 +20,31 @@ package org.jclouds.rimuhosting.miro.compute.config; import static org.jclouds.compute.domain.OsFamily.UBUNTU; -import static org.jclouds.rimuhosting.miro.reference.RimuHostingConstants.PROPERTY_RIMUHOSTING_DEFAULT_DC; -import java.util.Map; import java.util.Set; -import javax.inject.Singleton; - -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.domain.Location; -import org.jclouds.rest.RestContext; -import org.jclouds.rest.internal.RestContextImpl; -import org.jclouds.rimuhosting.miro.RimuHostingAsyncClient; -import org.jclouds.rimuhosting.miro.RimuHostingClient; -import org.jclouds.rimuhosting.miro.compute.functions.ServerToNodeMetadata; 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.RimuHostingDefaultLocationSupplier; import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingHardwareSupplier; import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingImageSupplier; import org.jclouds.rimuhosting.miro.compute.suppliers.RimuHostingLocationSupplier; -import org.jclouds.rimuhosting.miro.domain.Server; -import org.jclouds.rimuhosting.miro.domain.internal.RunningState; -import com.google.common.annotations.VisibleForTesting; -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.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Provides; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.util.Providers; /** * Configures the {@link RimuHostingComputeServiceContext}; requires @@ -86,23 +56,8 @@ public class RimuHostingComputeServiceContextModule extends BaseComputeServiceCo @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - bind(new TypeLiteral>() { - }).to(ServerToNodeMetadata.class); - bind(LoadBalancerService.class).toProvider(Providers. of(null)); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>>() { - }).to(ServerToPublicAddresses.class); - bind(AddNodeWithTagStrategy.class).to(RimuHostingAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(RimuHostingListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(RimuHostingGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(RimuHostingRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(RimuHostingDestroyNodeStrategy.class); + install(new RimuHostingComputeServiceDependenciesModule()); + super.configure(); } @Override @@ -110,64 +65,49 @@ public class RimuHostingComputeServiceContextModule extends BaseComputeServiceCo return template.hardwareId("MIRO1B").osFamily(UBUNTU).os64Bit(false).imageNameMatches(".*10\\.?04.*"); } - @VisibleForTesting - static final Map runningStateToNodeState = ImmutableMap. builder() - .put(RunningState.RUNNING, NodeState.RUNNING)// - .put(RunningState.NOTRUNNING, NodeState.SUSPENDED)// - .put(RunningState.POWERCYCLING, NodeState.PENDING)// - .put(RunningState.RESTARTING, NodeState.PENDING)// - .put(RunningState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// - .build(); - - @Singleton - @Provides - Map provideServerToNodeState() { - return runningStateToNodeState; - } - - @Singleton - private static class ServerToPublicAddresses implements Function> { - @Override - public Iterable apply(Server server) { - return server.getIpAddresses() == null ? ImmutableSet. of() : Iterables.concat(ImmutableList.of(server - .getIpAddresses().getPrimaryIp()), server.getIpAddresses().getSecondaryIps()); - } + @Override + protected Class defineAddNodeWithTagStrategy() { + return RimuHostingAddNodeWithTagStrategy.class; } @Override - protected Supplier supplyDefaultLocation(Injector injector, Supplier> locations) { - final String defaultDC = injector - .getInstance(Key.get(String.class, Names.named(PROPERTY_RIMUHOSTING_DEFAULT_DC))); - return Suppliers.compose(new Function, Location>() { - - @Override - public Location apply(Set from) { - return Iterables.find(from, new Predicate() { - - @Override - public boolean apply(Location input) { - return input.getId().equals(defaultDC); - } - - }); - } - - }, locations); - + protected Class defineDestroyNodeStrategy() { + return RimuHostingDestroyNodeStrategy.class; } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(RimuHostingImageSupplier.class); + protected Class defineGetNodeMetadataStrategy() { + return RimuHostingGetNodeMetadataStrategy.class; } @Override - protected Supplier> getSourceLocationSupplier(Injector injector) { - return injector.getInstance(RimuHostingLocationSupplier.class); + protected Class>> defineHardwareSupplier() { + return RimuHostingHardwareSupplier.class; } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(RimuHostingHardwareSupplier.class); + protected Class>> defineImageSupplier() { + return RimuHostingImageSupplier.class; } + + @Override + protected Class defineListNodesStrategy() { + return RimuHostingListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return RimuHostingRebootNodeStrategy.class; + } + + @Override + protected Class>> defineLocationSupplier() { + return RimuHostingLocationSupplier.class; + } + + @Override + protected Class> defineDefaultLocationSupplier() { + return RimuHostingDefaultLocationSupplier.class; + } + } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..37aa1276b5 --- /dev/null +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/config/RimuHostingComputeServiceDependenciesModule.java @@ -0,0 +1,95 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.config; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; +import org.jclouds.rimuhosting.miro.RimuHostingAsyncClient; +import org.jclouds.rimuhosting.miro.RimuHostingClient; +import org.jclouds.rimuhosting.miro.compute.functions.ServerToNodeMetadata; +import org.jclouds.rimuhosting.miro.domain.Server; +import org.jclouds.rimuhosting.miro.domain.internal.RunningState; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * Configures the {@link RimuHostingComputeServiceContext}; requires + * {@link RimuHostingComputeService} bound. + * + * @author Adrian Cole + */ +public class RimuHostingComputeServiceDependenciesModule extends AbstractModule { + + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).to(ServerToNodeMetadata.class); + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>>() { + }).to(ServerToPublicAddresses.class); + + } + + @VisibleForTesting + static final Map runningStateToNodeState = ImmutableMap. builder() + .put(RunningState.RUNNING, NodeState.RUNNING)// + .put(RunningState.NOTRUNNING, NodeState.SUSPENDED)// + .put(RunningState.POWERCYCLING, NodeState.PENDING)// + .put(RunningState.RESTARTING, NodeState.PENDING)// + .put(RunningState.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + .build(); + + @Singleton + @Provides + Map provideServerToNodeState() { + return runningStateToNodeState; + } + + @Singleton + private static class ServerToPublicAddresses implements Function> { + @Override + public Iterable apply(Server server) { + return server.getIpAddresses() == null ? ImmutableSet. of() : Iterables.concat(ImmutableList.of(server + .getIpAddresses().getPrimaryIp()), server.getIpAddresses().getSecondaryIps()); + } + } +} diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java index 54d4d77cf6..810b7bf65e 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java @@ -30,6 +30,7 @@ import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; @@ -74,15 +75,15 @@ public class ServerToNodeMetadata implements Function { @Override public boolean apply(Image input) { return input.getProviderId().equals(instance.getImageId()) - && (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation().equals( - location.getParent())); + && (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation() + .equals(location.getParent())); } } @Inject ServerToNodeMetadata(Function> getPublicAddresses, - Map credentialStore, Map runningStateToNodeState, - Supplier> images) { + Map credentialStore, Map runningStateToNodeState, + @Memoized Supplier> images) { this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState"); @@ -96,7 +97,7 @@ public class ServerToNodeMetadata implements Function { builder.name(from.getName()); // TODO properly look up location LocationImpl location = new LocationImpl(LocationScope.ZONE, from.getLocation().getId(), from.getLocation() - .getName(), null); + .getName(), null); builder.location(location); builder.tag(parseTagFromName(from.getName())); builder.imageId(from.getImageId() + ""); diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingDefaultLocationSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingDefaultLocationSupplier.java new file mode 100644 index 0000000000..020a40d5c4 --- /dev/null +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingDefaultLocationSupplier.java @@ -0,0 +1,64 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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 static org.jclouds.rimuhosting.miro.reference.RimuHostingConstants.PROPERTY_RIMUHOSTING_DEFAULT_DC; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.collect.Memoized; +import org.jclouds.domain.Location; + +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class RimuHostingDefaultLocationSupplier implements Supplier { + private final Supplier> locations; + private final String defaultDC; + + @Inject + RimuHostingDefaultLocationSupplier(@Memoized Supplier> locations, + @Named(PROPERTY_RIMUHOSTING_DEFAULT_DC) String defaultDC) { + this.locations = locations; + this.defaultDC = defaultDC; + } + + @Override + public Location get() { + return Iterables.find(locations.get(), new Predicate() { + + @Override + public boolean apply(Location input) { + return input.getId().equals(defaultDC); + } + + }); + } +} \ No newline at end of file diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java index 288331c82c..dec0108649 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java @@ -26,6 +26,7 @@ import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.HardwareBuilder; import org.jclouds.compute.domain.Processor; @@ -53,11 +54,12 @@ public class RimuHostingHardwareSupplier implements Supplier> locations; + + private final RimuHostingClient sync; + private final Supplier> locations; @Inject - RimuHostingHardwareSupplier(RimuHostingClient sync, Supplier> locations) { + RimuHostingHardwareSupplier(RimuHostingClient sync, @Memoized Supplier> locations) { this.sync = sync; this.locations = locations; } @@ -77,9 +79,9 @@ public class RimuHostingHardwareSupplier implements Supplier of(new VolumeImpl((float) from.getDiskSize(), true, true))).build()); + sizes.add(new HardwareBuilder().ids(from.getId()).location(location).processors( + ImmutableList.of(new Processor(1, 1.0))).ram(from.getRam()).volumes( + ImmutableList. of(new VolumeImpl((float) from.getDiskSize(), true, true))).build()); } catch (NullPointerException e) { logger.warn("datacenter not present in " + from.getId()); } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java index 7d584ca2e2..05b9d9104b 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java @@ -46,11 +46,11 @@ import com.google.common.collect.Sets; */ @Singleton public class RimuHostingImageSupplier implements Supplier> { - private RimuHostingClient sync; public static final Pattern RIMU_PATTERN = Pattern.compile("([^0-9]*)(.*)"); + private final RimuHostingClient sync; @Inject - RimuHostingImageSupplier(final RimuHostingClient sync) { + RimuHostingImageSupplier(RimuHostingClient sync) { this.sync = sync; } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingLocationSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingLocationSupplier.java index 3e7e90e153..3fd843c570 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingLocationSupplier.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingLocationSupplier.java @@ -48,8 +48,8 @@ public class RimuHostingLocationSupplier implements Supplier>() { - }).to(SliceToNodeMetadata.class); - - bind(new TypeLiteral>() { - }).to(SlicehostImageToImage.class); - - bind(new TypeLiteral>() { - }).to(SlicehostImageToOperatingSystem.class); - bind(new TypeLiteral>() { - }).to(FlavorToHardware.class); - - bind(LoadBalancerService.class).toProvider(Providers. of(null)); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(new TypeLiteral>() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - bind(AddNodeWithTagStrategy.class).to(SlicehostAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(SlicehostListNodesStrategy.class); - bind(GetNodeMetadataStrategy.class).to(SlicehostGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(SlicehostRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(SlicehostDestroyNodeStrategy.class); - } - - @Override - protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) { - return template.osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*"); - } - - @VisibleForTesting - public static final Map sliceStatusToNodeState = ImmutableMap - . builder().put(Slice.Status.ACTIVE, NodeState.RUNNING)// - .put(Slice.Status.BUILD, NodeState.PENDING)// - .put(Slice.Status.REBOOT, NodeState.PENDING)// - .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// - .put(Slice.Status.TERMINATED, NodeState.TERMINATED)// - .put(Slice.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// - .build(); - - @Singleton - @Provides - Map provideSliceToNodeState() { - return sliceStatusToNodeState; - } - @Provides @Singleton Location getLocation(@Provider String providerName) { @@ -146,12 +69,43 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(SlicehostImageSupplier.class); + protected void configure() { + install(new SlicehostComputeServiceDependenciesModule()); + super.configure(); } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(SlicehostHardwareSupplier.class); + protected Class defineAddNodeWithTagStrategy() { + return SlicehostAddNodeWithTagStrategy.class; + } + + @Override + protected Class defineDestroyNodeStrategy() { + return SlicehostDestroyNodeStrategy.class; + } + + @Override + protected Class defineGetNodeMetadataStrategy() { + return SlicehostGetNodeMetadataStrategy.class; + } + + @Override + protected Class>> defineHardwareSupplier() { + return SlicehostHardwareSupplier.class; + } + + @Override + protected Class>> defineImageSupplier() { + return SlicehostImageSupplier.class; + } + + @Override + protected Class defineListNodesStrategy() { + return SlicehostListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return SlicehostRebootNodeStrategy.class; } } diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceDependenciesModule.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceDependenciesModule.java new file mode 100644 index 0000000000..7e178543e8 --- /dev/null +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceDependenciesModule.java @@ -0,0 +1,97 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.config; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.internal.BaseComputeService; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; +import org.jclouds.slicehost.SlicehostAsyncClient; +import org.jclouds.slicehost.SlicehostClient; +import org.jclouds.slicehost.compute.functions.FlavorToHardware; +import org.jclouds.slicehost.compute.functions.SliceToNodeMetadata; +import org.jclouds.slicehost.compute.functions.SlicehostImageToImage; +import org.jclouds.slicehost.compute.functions.SlicehostImageToOperatingSystem; +import org.jclouds.slicehost.domain.Flavor; +import org.jclouds.slicehost.domain.Slice; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * Configures the {@link SlicehostComputeServiceContext}; requires {@link BaseComputeService} bound. + * + * @author Adrian Cole + */ +public class SlicehostComputeServiceDependenciesModule extends AbstractModule { + + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).to(SliceToNodeMetadata.class); + + bind(new TypeLiteral>() { + }).to(SlicehostImageToImage.class); + + bind(new TypeLiteral>() { + }).to(SlicehostImageToOperatingSystem.class); + bind(new TypeLiteral>() { + }).to(FlavorToHardware.class); + + bind(new TypeLiteral() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + bind(new TypeLiteral>() { + }).to(new TypeLiteral>() { + }).in(Scopes.SINGLETON); + + } + + @VisibleForTesting + public static final Map sliceStatusToNodeState = ImmutableMap + . builder().put(Slice.Status.ACTIVE, NodeState.RUNNING)// + .put(Slice.Status.BUILD, NodeState.PENDING)// + .put(Slice.Status.REBOOT, NodeState.PENDING)// + .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// + .put(Slice.Status.TERMINATED, NodeState.TERMINATED)// + .put(Slice.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + .build(); + + @Singleton + @Provides + Map provideSliceToNodeState() { + return sliceStatusToNodeState; + } +} diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java index 5b6a86fbbd..cc678cc0b6 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java @@ -28,7 +28,9 @@ import java.util.Set; import javax.annotation.Resource; import javax.inject.Inject; +import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; @@ -48,6 +50,7 @@ import com.google.common.collect.Iterables; /** * @author Adrian Cole */ +@Singleton public class SliceToNodeMetadata implements Function { protected final Supplier location; protected final Map sliceToNodeState; @@ -86,7 +89,8 @@ public class SliceToNodeMetadata implements Function { @Inject SliceToNodeMetadata(Map sliceStateToNodeState, Map credentialStore, - Supplier> images, Supplier location, Supplier> hardwares) { + @Memoized Supplier> images, Supplier location, + @Memoized Supplier> hardwares) { this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java index 02ed757134..5ed2b710a0 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java @@ -52,7 +52,7 @@ public class SlicehostImageSupplier implements Supplier> { @Inject SlicehostImageSupplier(SlicehostClient sync, - Function slicehostImageToImage) { + Function slicehostImageToImage) { this.sync = sync; this.slicehostImageToImage = slicehostImageToImage; } diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java index b615744dfe..9bd52ef52b 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModuleTest.java @@ -31,7 +31,7 @@ public class SlicehostComputeServiceContextModuleTest { public void testAllStatusCovered() { for (Slice.Status state : Slice.Status.values()) { - assert SlicehostComputeServiceContextModule.sliceStatusToNodeState.containsKey(state) : state; + assert SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState.containsKey(state) : state; } } diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java index fe0bafd649..d03c26a7c2 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java @@ -40,7 +40,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.domain.internal.LocationImpl; -import org.jclouds.slicehost.compute.config.SlicehostComputeServiceContextModule; +import org.jclouds.slicehost.compute.config.SlicehostComputeServiceDependenciesModule; import org.jclouds.slicehost.domain.Slice; import org.jclouds.slicehost.xml.SliceHandlerTest; import org.testng.annotations.Test; @@ -60,105 +60,84 @@ public class SliceToNodeMetadataTest { @Test public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException { Credentials creds = new Credentials("root", "abdce"); - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, - ImmutableMap. of("1", creds), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap + . of("1", creds), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(slice); - assertEquals( - metadata, - new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses(ImmutableSet.of("174.143.212.229")) - .privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds").imageId("2").id("1") - .providerId("1").name("jclouds-foo").location(provider).credentials(creds) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds") + .imageId("2").id("1").providerId("1").name("jclouds-foo").location(provider).credentials(creds) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(slice); - assertEquals( - metadata, - new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses(ImmutableSet.of("174.143.212.229")) - .privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds").imageId("2").id("1") - .providerId("1").name("jclouds-foo").location(provider) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds") + .imageId("2").id("1").providerId("1").name("jclouds-foo").location(provider).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState; org.jclouds.compute.domain.Image jcImage = SlicehostImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); Set hardwares = ImmutableSet.of(); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(slice); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("174.143.212.229")) - .privateAddresses(ImmutableSet.of("10.176.164.199")) - .tag("jclouds") - .imageId("2") - .operatingSystem( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds") + .imageId("2").operatingSystem( new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true) - .build()).id("1").providerId("1").name("jclouds-foo").location(provider) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + .build()).id("1").providerId("1").name("jclouds-foo").location(provider).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } @Test public void testApplyWhereImageAndHardwareFound() throws UnknownHostException { - Map sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Map sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState; Set images = ImmutableSet.of(SlicehostImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Slice slice = SliceHandlerTest.parseSlice(); - SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, - ImmutableMap. of(), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap + . of(), Suppliers.> ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(slice); - assertEquals( - metadata, - new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("174.143.212.229")) - .privateAddresses(ImmutableSet.of("10.176.164.199")) - .tag("jclouds") - .imageId("2") - .hardware( - new HardwareBuilder() - .ids("1") - .name("256 slice") - .processors(ImmutableList.of(new Processor(0.25, 1.0))) - .ram(256) - .volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(1.0f) - .durable(true).bootDevice(true).build())).build()) - .operatingSystem( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("174.143.212.229")).privateAddresses(ImmutableSet.of("10.176.164.199")).tag("jclouds") + .imageId("2").hardware( + new HardwareBuilder().ids("1").name("256 slice").processors( + ImmutableList.of(new Processor(0.25, 1.0))).ram(256).volumes( + ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(1.0f).durable(true) + .bootDevice(true).build())).build()).operatingSystem( new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true) - .build()).id("1").providerId("1").name("jclouds-foo").location(provider) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + .build()).id("1").providerId("1").name("jclouds-foo").location(provider).userMetadata( + ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/CommonVCloudComputeServiceContextModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/CommonVCloudComputeServiceContextModule.java index 22d655f667..551a27d8ce 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/CommonVCloudComputeServiceContextModule.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/CommonVCloudComputeServiceContextModule.java @@ -24,9 +24,7 @@ import java.util.Set; import javax.inject.Singleton; -import org.jclouds.compute.LoadBalancerService; import org.jclouds.compute.config.BaseComputeServiceContextModule; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeState; @@ -41,9 +39,7 @@ import org.jclouds.vcloud.domain.Status; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; -import com.google.inject.Injector; import com.google.inject.Provides; -import com.google.inject.util.Providers; /** * Configures the {@link VCloudComputeServiceContext}; requires {@link VCloudComputeClientImpl} @@ -70,28 +66,26 @@ public abstract class CommonVCloudComputeServiceContextModule extends BaseComput @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - bind(RunNodesAndAddToSetStrategy.class).to(EncodeTagIntoNameRunNodesAndAddToSetStrategy.class); - bindLoadBalancer(); - } - - protected void bindLoadBalancer() { - bind(LoadBalancerService.class).toProvider(Providers. of(null)); + super.configure(); } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(StaticHardwareSupplier.class); + protected Class defineRunNodesAndAddToSetStrategy() { + return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class; } @Override - protected Supplier> getSourceLocationSupplier(Injector injector) { - return injector.getInstance(OrgAndVDCToLocationSupplier.class); + protected Class>> defineHardwareSupplier() { + return StaticHardwareSupplier.class; } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(VCloudImageSupplier.class); + protected Class>> defineImageSupplier() { + return VCloudImageSupplier.class; } + @Override + protected Class>> defineLocationSupplier() { + return OrgAndVDCToLocationSupplier.class; + } } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java index a8c4805a93..798c631ef1 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java @@ -55,7 +55,6 @@ import org.jclouds.vcloud.domain.VApp; import com.google.common.base.Function; import com.google.common.base.Supplier; -import com.google.inject.Injector; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; @@ -74,11 +73,9 @@ public class VCloudComputeServiceContextModule extends CommonVCloudComputeServic }).to(VAppToNodeMetadata.class); bind(TemplateOptions.class).to(VCloudTemplateOptions.class); bind(TemplateBuilder.class).to(VCloudTemplateBuilderImpl.class); - bind(RebootNodeStrategy.class).to(VCloudRebootNodeStrategy.class); bind(new TypeLiteral>() { }).to(new TypeLiteral() { }); - bind(GetNodeMetadataStrategy.class).to(VCloudGetNodeMetadataStrategy.class); bind(new TypeLiteral() { }).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); @@ -91,15 +88,36 @@ public class VCloudComputeServiceContextModule extends CommonVCloudComputeServic bind(new TypeLiteral>>() { }).to(new TypeLiteral() { }); - bind(AddNodeWithTagStrategy.class).to(VCloudAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(VCloudListNodesStrategy.class); bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to(GetLoginCredentialsFromGuestConfiguration.class); - bind(DestroyNodeStrategy.class).to(VCloudDestroyNodeStrategy.class); } @Override - protected Supplier> getSourceSizeSupplier(Injector injector) { - return injector.getInstance(VCloudHardwareSupplier.class); + protected Class>> defineHardwareSupplier() { + return VCloudHardwareSupplier.class; } + @Override + protected Class defineAddNodeWithTagStrategy() { + return VCloudAddNodeWithTagStrategy.class; + } + + @Override + protected Class defineDestroyNodeStrategy() { + return VCloudDestroyNodeStrategy.class; + } + + @Override + protected Class defineGetNodeMetadataStrategy() { + return VCloudGetNodeMetadataStrategy.class; + } + + @Override + protected Class defineListNodesStrategy() { + return VCloudListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return VCloudRebootNodeStrategy.class; + } } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java index e02b1a1a14..19d6b905f6 100755 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java @@ -62,10 +62,7 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput @Override protected void configure() { super.configure(); - bind(RebootNodeStrategy.class).to(VCloudExpressRebootNodeStrategy.class); - bind(GetNodeMetadataStrategy.class).to(VCloudExpressGetNodeMetadataStrategy.class); - bind(new TypeLiteral>() { - }).to(VCloudExpressVAppToNodeMetadata.class); + bindVAppConverter(); bind(new TypeLiteral() { }).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); @@ -75,9 +72,11 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput bind(new TypeLiteral>>() { }).to(new TypeLiteral() { }); - bind(AddNodeWithTagStrategy.class).to(VCloudExpressAddNodeWithTagStrategy.class); - bind(ListNodesStrategy.class).to(VCloudExpressListNodesStrategy.class); - bind(DestroyNodeStrategy.class).to(VCloudExpressDestroyNodeStrategy.class); + } + + protected void bindVAppConverter() { + bind(new TypeLiteral>() { + }).to(VCloudExpressVAppToNodeMetadata.class); } @Provides @@ -85,4 +84,29 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput CommonVCloudComputeClient provideCommonVCloudComputeClient(VCloudExpressComputeClient in) { return in; } + + @Override + protected Class defineAddNodeWithTagStrategy() { + return VCloudExpressAddNodeWithTagStrategy.class; + } + + @Override + protected Class defineDestroyNodeStrategy() { + return VCloudExpressDestroyNodeStrategy.class; + } + + @Override + protected Class defineGetNodeMetadataStrategy() { + return VCloudExpressGetNodeMetadataStrategy.class; + } + + @Override + protected Class defineListNodesStrategy() { + return VCloudExpressListNodesStrategy.class; + } + + @Override + protected Class defineRebootNodeStrategy() { + return VCloudExpressRebootNodeStrategy.class; + } } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/FindLocationForResource.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/FindLocationForResource.java index 8df6a3d21e..24eb90e943 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/FindLocationForResource.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/FindLocationForResource.java @@ -27,6 +27,7 @@ import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; import org.jclouds.vcloud.domain.ReferenceType; @@ -45,7 +46,7 @@ public class FindLocationForResource { final Supplier> locations; @Inject - public FindLocationForResource(Supplier> locations) { + public FindLocationForResource(@Memoized Supplier> locations) { this.locations = locations; } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java index 9a0dd8f77b..49d0b4a250 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java @@ -28,6 +28,7 @@ import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; @@ -56,9 +57,9 @@ public class VCloudExpressVAppToNodeMetadata implements Function credentialStore, Map vAppStatusToNodeState, - HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, - FindLocationForResource findLocationForResourceInVDC, Supplier> images) { + Map credentialStore, Map vAppStatusToNodeState, + HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, + FindLocationForResource findLocationForResourceInVDC, @Memoized Supplier> images) { this.images = checkNotNull(images, "images"); this.hardwareForVCloudExpressVApp = checkNotNull(hardwareForVCloudExpressVApp, "hardwareForVCloudExpressVApp"); this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); @@ -76,7 +77,7 @@ public class VCloudExpressVAppToNodeMetadata implements Function> locations, - Supplier> images, Supplier> sizes, + protected VCloudTemplateBuilderImpl(@Memoized Supplier> locations, + @Memoized Supplier> images, @Memoized Supplier> sizes, Supplier defaultLocation, Provider optionsProvider, @Named("DEFAULT") Provider defaultTemplateProvider) { super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java index a0a9e5a4b2..7f69a98e19 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java @@ -45,9 +45,8 @@ public class StaticHardwareSupplier implements Supplier> for (int cpus : new int[] { 1, 2, 4, 8 }) for (int ram : new int[] { 512, 1024, 2048, 4096, 8192, 16384 }) { String id = String.format("cpu=%d,ram=%s,disk=%d", cpus, ram, 10); - hardware.add(new HardwareBuilder().ids(id).ram(ram) - .processors(ImmutableList.of(new Processor(cpus, 1.0))) - .volumes(ImmutableList. of(new VolumeImpl(10f, true, true))).build()); + hardware.add(new HardwareBuilder().ids(id).ram(ram).processors(ImmutableList.of(new Processor(cpus, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(10f, true, true))).build()); } return hardware; } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java index e14a0db1fb..243a542b53 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java @@ -30,6 +30,7 @@ import javax.inject.Provider; import javax.inject.Singleton; import org.jclouds.Constants; +import org.jclouds.collect.Memoized; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Image; @@ -64,18 +65,18 @@ public class TerremarkVCloudComputeService extends BaseComputeService { @Inject protected TerremarkVCloudComputeService(ComputeServiceContext context, Map credentialStore, - Supplier> images, Supplier> sizes, - Supplier> locations, ListNodesStrategy listNodesStrategy, - GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, - RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, - Provider templateBuilderProvider, Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys, - ConcurrentMap credentialsMap, NodeMetadataToOrgAndName nodeToOrgAndName) { + @Memoized Supplier> images, @Memoized Supplier> sizes, + @Memoized Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys, + ConcurrentMap credentialsMap, NodeMetadataToOrgAndName nodeToOrgAndName) { super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, - runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, - templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); + runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, + templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); this.cleanupOrphanKeys = cleanupOrphanKeys; } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java index 6ceb5d2aed..dffc0a5464 100755 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java @@ -28,27 +28,14 @@ import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; -import org.jclouds.compute.strategy.DestroyNodeStrategy; -import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.compute.strategy.ListNodesStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; -import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy; -import org.jclouds.vcloud.VCloudExpressAsyncClient; -import org.jclouds.vcloud.VCloudExpressClient; import org.jclouds.vcloud.compute.VCloudExpressComputeClient; import org.jclouds.vcloud.compute.config.VCloudExpressComputeServiceContextModule; -import org.jclouds.vcloud.compute.strategy.VCloudExpressDestroyNodeStrategy; -import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy; -import org.jclouds.vcloud.compute.strategy.VCloudExpressListNodesStrategy; -import org.jclouds.vcloud.compute.strategy.VCloudExpressRebootNodeStrategy; import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeClient; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeService; @@ -64,9 +51,7 @@ import org.jclouds.vcloud.terremark.compute.suppliers.VAppTemplatesInOrgs; import com.google.common.base.Function; import com.google.common.base.Supplier; -import com.google.inject.Injector; import com.google.inject.Provides; -import com.google.inject.Scopes; import com.google.inject.TypeLiteral; /** @@ -91,23 +76,7 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom @Override protected void configure() { - install(new ComputeServiceTimeoutsModule()); - // NOTE - bind(AddNodeWithTagStrategy.class).to(TerremarkVCloudAddNodeWithTagStrategy.class); - bind(new TypeLiteral() { - }).to(new TypeLiteral>() { - }).in(Scopes.SINGLETON); - // NOTE - bind(RunNodesAndAddToSetStrategy.class).to(TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy.class); - bind(ListNodesStrategy.class).to(VCloudExpressListNodesStrategy.class); - // NOTE - bind(new TypeLiteral>() { - }).to(TerremarkVCloudExpressVAppToNodeMetadata.class); - bind(GetNodeMetadataStrategy.class).to(VCloudExpressGetNodeMetadataStrategy.class); - bind(RebootNodeStrategy.class).to(VCloudExpressRebootNodeStrategy.class); - bind(DestroyNodeStrategy.class).to(VCloudExpressDestroyNodeStrategy.class); - bindLoadBalancer(); - // MORE specifics... + super.configure(); bind(new TypeLiteral>() { }).to(new TypeLiteral() { }); @@ -115,10 +84,26 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom bind(ComputeService.class).to(TerremarkVCloudComputeService.class); bind(VCloudExpressComputeClient.class).to(TerremarkVCloudComputeClient.class); bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to( - ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); + ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); bind(SecureRandom.class).toInstance(new SecureRandom()); } + @Override + protected void bindVAppConverter() { + bind(new TypeLiteral>() { + }).to(TerremarkVCloudExpressVAppToNodeMetadata.class); + } + + @Override + protected Class defineRunNodesAndAddToSetStrategy() { + return TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy.class; + } + + @Override + protected Class defineAddNodeWithTagStrategy() { + return TerremarkVCloudAddNodeWithTagStrategy.class; + } + @Provides @Singleton ConcurrentMap credentialsMap() { @@ -140,8 +125,7 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom } @Override - protected Supplier> getSourceImageSupplier(Injector injector) { - return injector.getInstance(VAppTemplatesInOrgs.class); + protected Class>> defineImageSupplier() { + return VAppTemplatesInOrgs.class; } - } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java index c7aea007c5..517dfda86a 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java @@ -29,6 +29,7 @@ import java.util.concurrent.ConcurrentMap; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; @@ -56,12 +57,11 @@ public class TerremarkVCloudExpressVAppToNodeMetadata extends VCloudExpressVAppT public TerremarkVCloudExpressVAppToNodeMetadata(VCloudExpressComputeClient computeClient, Map credentialStore, Map vAppStatusToNodeState, HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, - FindLocationForResource findLocationForResourceInVDC, Supplier> images, + FindLocationForResource findLocationForResourceInVDC, @Memoized Supplier> images, ConcurrentMap credentialsMap) { super(computeClient, credentialStore, vAppStatusToNodeState, hardwareForVCloudExpressVApp, findLocationForResourceInVDC, images); this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); - ; } @Override diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgs.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgs.java index b971b3b57c..fb439c8a2a 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgs.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/suppliers/VAppTemplatesInOrgs.java @@ -28,6 +28,7 @@ import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; +import org.jclouds.collect.Memoized; import org.jclouds.compute.domain.Image; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Location; @@ -54,7 +55,7 @@ public class VAppTemplatesInOrgs implements Supplier> { private final ImagesInVCloudExpressOrg imagesInOrg; @Inject - VAppTemplatesInOrgs(Supplier> locations, + VAppTemplatesInOrgs(@Memoized Supplier> locations, Function, Iterable> organizatonsForLocations, ImagesInVCloudExpressOrg imagesInOrg) { this.locations = locations;