refactored compute provider implementation

This commit is contained in:
Adrian Cole 2010-10-17 18:17:24 -07:00
parent 7f02bd8929
commit 49b88183d2
85 changed files with 2623 additions and 1896 deletions

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, AtmosStorageAsyncClient async, AtmosStorageClient sync,
ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,
BlobStoreListOptionsToListOptions container2ContainerListOptions,
@Memoized Supplier<Set<? extends Location>> locations, AtmosStorageAsyncClient async,
AtmosStorageClient sync, ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd,
BlobToObject blob2Object, BlobStoreListOptionsToListOptions container2ContainerListOptions,
DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,
BlobToHttpGetOptions blob2ObjectGetOptions, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, service, defaultLocation, locations);

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, AtmosStorageClient sync, ObjectToBlob object2Blob,
@Memoized Supplier<Set<? extends Location>> locations, AtmosStorageClient sync, ObjectToBlob object2Blob,
ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,
BlobStoreListOptionsToListOptions container2ContainerListOptions,
DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,

View File

@ -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<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
}

View File

@ -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<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> sizes,
Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client,
Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap,
@Named("DELETED") Predicate<PlacementGroup> placementGroupDeleted) {
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client,
Map<RegionAndName, KeyPair> credentialsMap, @Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap,
@Named("DELETED") Predicate<PlacementGroup> 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) {

View File

@ -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<InstanceState, NodeState> instanceToNodeState = ImmutableMap
.<InstanceState, NodeState> 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<InstanceState, NodeState> provideServerToNodeState() {
return instanceToNodeState;
}
@Provides
@Singleton
@Named("PRESENT")
protected Predicate<RunningInstance> instancePresent(InstancePresent present) {
return new RetryablePredicate<RunningInstance>(present, 5000, 200, TimeUnit.MILLISECONDS);
}
@Provides
@Singleton
@Named("AVAILABLE")
protected Predicate<PlacementGroup> placementGroupAvailable(PlacementGroupAvailable available) {
return new RetryablePredicate<PlacementGroup>(available, 60, 1, TimeUnit.SECONDS);
}
@Provides
@Singleton
@Named("DELETED")
protected Predicate<PlacementGroup> placementGroupDeleted(PlacementGroupDeleted deleted) {
return new RetryablePredicate<PlacementGroup>(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<Function<RunningInstance, NodeMetadata>>() {
}).to(RunningInstanceToNodeMetadata.class);
bind(new TypeLiteral<Function<RunningInstance, Credentials>>() {
}).to(CredentialsForInstance.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<EC2Client, EC2AsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<EC2Client, EC2AsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<EC2Client, EC2AsyncClient>>() {
}).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<String> provideSuffix() {
return new Supplier<String>() {
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<RegionAndName, KeyPair> 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<RegionAndName, String> 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<RegionAndName, String> 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<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) {
return new MapMaker().makeComputingMap(regionAndIdToImage);
}
@Provides
@Singleton
protected Supplier<Map<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache(
@Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) {
@Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Map<RegionAndName, ? extends Image>>(
authException, seconds, new Supplier<Map<RegionAndName, ? extends Image>>() {
@Override
public Map<RegionAndName, ? extends Image> get() {
return supplier.get();
}
});
authException, seconds, new Supplier<Map<RegionAndName, ? extends Image>>() {
@Override
public Map<RegionAndName, ? extends Image> get() {
return supplier.get();
}
});
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
Supplier<Map<RegionAndName, ? extends Image>> map = injector.getInstance(Key
.get(new TypeLiteral<Supplier<Map<RegionAndName, ? extends Image>>>() {
}));
return Suppliers.compose(new Function<Map<RegionAndName, ? extends Image>, Set<? extends Image>>() {
@Override
public Set<? extends Image> apply(Map<RegionAndName, ? extends Image> 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<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
return injector.getInstance(EC2LocationSupplier.class);
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EC2RunNodesAndAddToSetStrategy.class;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return null;
}
/**
* not needed, as {@link EC2RunNodesAndAddToSetStrategy} is used and is already set-based.
*/
@Override
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(EC2HardwareSupplier.class);
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return EC2DestroyNodeStrategy.class;
}
@Override
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
return injector.getInstance(DefaultLocationSupplier.class);
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return EC2GetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return EC2HardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return EC2ImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return EC2ListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return EC2RebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return org.jclouds.aws.suppliers.DefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return EC2LocationSupplier.class;
}
}

View File

@ -0,0 +1,198 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.aws.ec2.compute.config;
import 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<InstanceState, NodeState> instanceToNodeState = ImmutableMap
.<InstanceState, NodeState> 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<InstanceState, NodeState> provideServerToNodeState() {
return instanceToNodeState;
}
@Provides
@Singleton
@Named("PRESENT")
protected Predicate<RunningInstance> instancePresent(InstancePresent present) {
return new RetryablePredicate<RunningInstance>(present, 5000, 200, TimeUnit.MILLISECONDS);
}
@Provides
@Singleton
@Named("AVAILABLE")
protected Predicate<PlacementGroup> placementGroupAvailable(PlacementGroupAvailable available) {
return new RetryablePredicate<PlacementGroup>(available, 60, 1, TimeUnit.SECONDS);
}
@Provides
@Singleton
@Named("DELETED")
protected Predicate<PlacementGroup> placementGroupDeleted(PlacementGroupDeleted deleted) {
return new RetryablePredicate<PlacementGroup>(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<Function<RunningInstance, NodeMetadata>>() {
}).to(RunningInstanceToNodeMetadata.class);
bind(new TypeLiteral<Function<RunningInstance, Credentials>>() {
}).to(CredentialsForInstance.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<EC2Client, EC2AsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<EC2Client, EC2AsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<EC2Client, EC2AsyncClient>>() {
}).in(Scopes.SINGLETON);
}
@Provides
@Singleton
Supplier<String> provideSuffix() {
return new Supplier<String>() {
final SecureRandom random = new SecureRandom();
@Override
public String get() {
return random.nextInt(100) + "";
}
};
}
@Provides
@Singleton
protected final Map<RegionAndName, KeyPair> 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<RegionAndName, String> 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<RegionAndName, String> 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<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) {
return new MapMaker().makeComputingMap(regionAndIdToImage);
}
}

View File

@ -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<org.jclouds.aws.ec2.domain.Image, I
// amzn-ami-us-east-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml
// amzn-ami-us-east-1/amzn-ami-0.9.7-beta.i386.manifest.xml
public static final Pattern AMZN_PATTERN = Pattern
.compile(".*/amzn-ami-(.*)\\.(i386|x86_64)(-ebs|\\.manifest.xml)?");
.compile(".*/amzn-ami-(.*)\\.(i386|x86_64)(-ebs|\\.manifest.xml)?");
public static final Pattern CANONICAL_PATTERN = Pattern.compile(".*/([^-]*)-([^-]*)-.*-(.*)(\\.manifest.xml)?");
// ex rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml
public static final Pattern RIGHTSCALE_PATTERN = Pattern
.compile("[^/]*/([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?");
.compile("[^/]*/([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?");
// ex 411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha
public static final Pattern RIGHTIMAGE_PATTERN = Pattern
.compile("[^/]*/RightImage_([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?");
.compile("[^/]*/RightImage_([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\.manifest.xml)?");
private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;
private final Supplier<Set<? extends Location>> locations;
@ -91,7 +92,8 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
@Inject
ImageParser(PopulateDefaultLoginCredentialsForImageStrategy credentialProvider,
Supplier<Set<? extends Location>> locations, Supplier<Location> defaultLocation, @Provider String provider) {
@Memoized Supplier<Set<? extends Location>> locations, Supplier<Location> 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<org.jclouds.aws.ec2.domain.Image, I
builder.id(from.getRegion() + "/" + from.getId());
builder.description(from.getDescription() != null ? from.getDescription() : from.getImageLocation());
builder.userMetadata(ImmutableMap.<String, String> 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<org.jclouds.aws.ec2.domain.Image, I
} catch (NoSuchElementException e) {
System.err.printf("unknown region %s for image %s; not in %s", from.getRegion(), from.getId(), locations);
builder.location(new LocationImpl(LocationScope.REGION, from.getRegion(), from.getRegion(), defaultLocation
.get().getParent()));
.get().getParent()));
}
builder.operatingSystem(new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit));
return builder.build();
@ -163,7 +165,7 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
*/
private Matcher getMatcherAndFind(String manifest) {
for (Pattern pattern : new Pattern[] { AMZN_PATTERN, NEBULA_PATTERN, CANONICAL_PATTERN, RIGHTIMAGE_PATTERN,
RIGHTSCALE_PATTERN }) {
RIGHTSCALE_PATTERN }) {
Matcher matcher = pattern.matcher(manifest);
if (matcher.find())
return matcher;

View File

@ -24,9 +24,9 @@ import static org.jclouds.util.Utils.nullSafeSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Map.Entry;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -37,6 +37,7 @@ import org.jclouds.aws.ec2.domain.InstanceState;
import org.jclouds.aws.ec2.domain.RootDeviceType;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.aws.ec2.domain.RunningInstance.EbsBlockDevice;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
@ -73,8 +74,8 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@Inject
RunningInstanceToNodeMetadata(Map<InstanceState, NodeState> instanceToNodeState,
Map<String, Credentials> credentialStore, Map<RegionAndName, Image> instanceToImage,
Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Hardware>> hardware) {
Map<String, Credentials> credentialStore, Map<RegionAndName, Image> instanceToImage,
@Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Hardware>> 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<RunningInstance,
@VisibleForTesting
static List<Volume> addEBS(final RunningInstance instance, Iterable<? extends Volume> volumes) {
Iterable<Volume> ebsVolumes = Iterables.transform(instance.getEbsBlockDevices().entrySet(),
new Function<Entry<String, EbsBlockDevice>, Volume>() {
new Function<Entry<String, EbsBlockDevice>, Volume>() {
@Override
public Volume apply(Entry<String, EbsBlockDevice> 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<String, EbsBlockDevice> 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<Volume>() {
@ -158,7 +160,9 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
} catch (NoSuchElementException e) {
logger.debug("no tag parsed from %s's groups: %s", instance.getId(), instance.getGroupIds());
} catch (IllegalArgumentException e) {
logger.debug("too many groups match %s; %s's groups: %s", "jclouds#", instance.getId(), instance.getGroupIds());
logger
.debug("too many groups match %s; %s's groups: %s", "jclouds#", instance.getId(), instance
.getGroupIds());
}
return tag;
}

View File

@ -31,6 +31,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.TemplateBuilder;
@ -50,10 +51,10 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
private final Map<RegionAndName, Image> imageMap;
@Inject
protected EC2TemplateBuilderImpl(Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Supplier<Set<? extends Hardware>> sizes, Supplier<Location> defaultLocation,
Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider, Map<RegionAndName, Image> imageMap) {
protected EC2TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
Supplier<Location> defaultLocation, Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider, Map<RegionAndName, Image> 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);

View File

@ -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<Set<? extends Hardware>> {
private final String providerName;
@Inject
EC2HardwareSupplier(Supplier<Set<? extends Location>> locations, @Provider String providerName,
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
EC2HardwareSupplier(@Memoized Supplier<Set<? extends Location>> 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<Set<? extends Hardware>> {
sizes.add(cc1_4xlarge().location(location).supportsImageIds(ccAmi).build());
}
sizes.addAll(ImmutableSet.<Hardware> 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;
}
}

View File

@ -0,0 +1,52 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.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<Set<? extends Image>> {
private final Supplier<Map<RegionAndName, ? extends Image>> map;
@Inject
EC2ImageSupplier(Supplier<Map<RegionAndName, ? extends Image>> map) {
this.map = map;
}
@Override
public Set<? extends Image> get() {
return Sets.newLinkedHashSet(map.get().values());
}
}

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, S3AsyncClient async, S3Client sync,
@Memoized Supplier<Set<? extends Location>> locations, S3AsyncClient async, S3Client sync,
BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions,
BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob,
BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd,

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, S3Client sync, BucketToResourceMetadata bucket2ResourceMd,
ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList,
ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object,
ObjectToBlobMetadata object2BlobMd, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
@Memoized Supplier<Set<? extends Location>> locations, S3Client sync,
BucketToResourceMetadata bucket2ResourceMd, ContainerToBucketListOptions container2BucketListOptions,
BucketToResourceList bucket2ResourceList, ObjectToBlob object2Blob,
BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd,
Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {
super(context, blobUtils, defaultLocation, locations);
this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, "blob2ObjectGetOptions");
this.sync = checkNotNull(sync, "sync");

View File

@ -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<Set<? extends Location>> provideLocations(@Region Set<String> regions, @Provider String providerName) {
Set<Location> locations = Sets.newHashSet();
Location s3 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);

View File

@ -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<BucketMetadata, Storag
protected Logger logger = Logger.NULL;
@Inject
BucketToResourceMetadata(S3Client client, Supplier<Set<? extends Location>> locations) {
BucketToResourceMetadata(S3Client client, @Memoized Supplier<Set<? extends Location>> locations) {
this.client = client;
this.onlyLocation = locations.get().size() == 1 ? Iterables.get(locations.get(), 0) : null;
this.locations = locations;

View File

@ -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<Location> {
private final Supplier<Set<? extends Location>> set;
@Inject
DefaultLocationSupplier(@Region final String region, Supplier<Set<? extends Location>> set) {
DefaultLocationSupplier(@Region final String region, @Memoized Supplier<Set<? extends Location>> set) {
this.region = region;
this.set = set;
}

View File

@ -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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
.<Location> of(location));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(image));
.<Image> of(image));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> 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));
.<Hardware> 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) {
};
}

View File

@ -85,7 +85,7 @@ public class CredentialsForInstanceTest {
// expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce();
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
@ -180,7 +180,7 @@ public class CredentialsForInstanceTest {
// expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce();
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> 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<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> 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<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
@ -426,9 +426,9 @@ public class CredentialsForInstanceTest {
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
//
// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
// Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
@ -487,9 +487,9 @@ public class CredentialsForInstanceTest {
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
//
// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
// Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
@ -549,9 +549,9 @@ public class CredentialsForInstanceTest {
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
//
// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
// Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
@ -616,9 +616,9 @@ public class CredentialsForInstanceTest {
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
//
// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
// Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
@ -677,9 +677,9 @@ public class CredentialsForInstanceTest {
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
//
// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null);
// Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
@ -810,7 +810,7 @@ public class CredentialsForInstanceTest {
// expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce();
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap = createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//

View File

@ -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.<Hardware> of(),
ImmutableSet.<Location> of(), ImmutableSet.<Image> of(),
ImmutableMap.<String, Credentials> of("us-east-1/i-9slweygo", creds));
RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet
.<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> 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.<String> 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.<String> 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.<Hardware> of(),
ImmutableSet.<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());
RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet
.<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());
RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml");
assertEquals(
parser.apply(server),
new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses(ImmutableSet.<String> 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.<String> 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.<Hardware> of(), ImmutableSet.of(provider),
ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());
ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> 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.<Hardware> of(), ImmutableSet.of(provider),
ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap.<String, Credentials> of());
ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap.<String, Credentials> 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.<String, Credentials> of());
RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet
.of(provider), ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap
.<String, Credentials> 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> hardware,
final ImmutableSet<Location> locations, Set<org.jclouds.compute.domain.Image> images,
Map<String, Credentials> credentialStore) {
Map<InstanceState, NodeState> instanceToNodeState = EC2ComputeServiceContextModule.instanceToNodeState;
final ImmutableSet<Location> locations, Set<org.jclouds.compute.domain.Image> images,
Map<String, Credentials> credentialStore) {
Map<InstanceState, NodeState> instanceToNodeState = EC2ComputeServiceDependenciesModule.instanceToNodeState;
Map<RegionAndName, Image> instanceToImage = Maps.uniqueIndex(images, new Function<Image, RegionAndName>() {
@ -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<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
@ -313,7 +298,7 @@ public class RunningInstanceToNodeMetadataTest {
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
@ -406,7 +391,7 @@ public class RunningInstanceToNodeMetadataTest {
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
@ -489,7 +474,7 @@ public class RunningInstanceToNodeMetadataTest {
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider =
@ -926,7 +911,7 @@ public class RunningInstanceToNodeMetadataTest {
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
@ -1006,7 +991,7 @@ public class RunningInstanceToNodeMetadataTest {
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// ConcurrentMap<RegionAndName, org.jclouds.compute.domain.Image> imageMap =
// createMock(ConcurrentMap.class);
// Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// @Memoized Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>
// ofInstance(ImmutableSet
// .<Hardware> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// @Memoized Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>
// ofInstance(ImmutableSet
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);

View File

@ -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<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Supplier<Set<? extends Hardware>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider,
Provider<TemplateBuilder> templateBuilderProvider) {
@Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Image>> images,
@Memoized Supplier<Set<? extends Hardware>> sizes, Location defaultLocation,
Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
final RegionAndName knownRegionAndName = new RegionAndName("region", "ami");
ConcurrentMap<RegionAndName, Image> imageMap = new MapMaker()
.makeComputingMap(new Function<RegionAndName, Image>() {
@Override
public Image apply(RegionAndName from) {
return from.equals(knownRegionAndName) ? knownImage : null;
}
.makeComputingMap(new Function<RegionAndName, Image>() {
@Override
public Image apply(RegionAndName from) {
return from.equals(knownRegionAndName) ? knownImage : null;
}
});
});
return new EC2TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(defaultLocation),
optionsProvider, templateBuilderProvider, imageMap);
optionsProvider, templateBuilderProvider, imageMap);
}
@SuppressWarnings("unchecked")
@ -91,11 +92,11 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
.<Location> of(location));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(Sets
.<Image> newLinkedHashSet());
.<Image> newLinkedHashSet());
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(c1_medium().build()));
.<Hardware> of(c1_medium().build()));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
.<Location> of(location));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(c1_medium().build()));
.<Hardware> of(c1_medium().build()));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(location));
.<Location> of(location));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(c1_medium().build()));
.<Hardware> of(c1_medium().build()));
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> 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);

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, AzureBlobAsyncClient async,
@Memoized Supplier<Set<? extends Location>> locations, AzureBlobAsyncClient async,
ContainerToResourceMetadata container2ResourceMd,
ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions,
ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob,

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, AzureBlobClient sync,
@Memoized Supplier<Set<? extends Location>> locations, AzureBlobClient sync,
ContainerToResourceMetadata container2ResourceMd,
ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions,
ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob,

View File

@ -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<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
}

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations) {
@Memoized Supplier<Set<? extends Location>> locations) {
super(context, blobUtils, service, defaultLocation, locations);
this.blobFactory = blobFactory;
this.dateService = dateService;

View File

@ -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<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
}

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations) {
@Memoized Supplier<Set<? extends Location>> 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);
}

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations) {
@Memoized Supplier<Set<? extends Location>> locations) {
this.context = checkNotNull(context, "context");
this.blobUtils = checkNotNull(blobUtils, "blobUtils");
this.defaultLocation = checkNotNull(defaultLocation, "defaultLocation");

View File

@ -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 <S, A> ComputeServiceContext buildContextUnwrappingExceptions(
ComputeServiceContextBuilder<S, A> builder) {
ComputeServiceContextBuilder<S, A> 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<? extends Module> 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<? extends Module> modules) {
Iterable<? extends Module> 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<? extends Module> modules, Properties overrides) {
Iterable<? extends Module> 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 <S, A> ComputeServiceContext createContext(ContextSpec<S, A> contextSpec) {
ComputeServiceContextBuilder<?, ?> builder = ComputeServiceContextBuilder.class
.cast(createContextBuilder(contextSpec));
.cast(createContextBuilder(contextSpec));
return buildContextUnwrappingExceptions(builder);
}
@ -140,8 +140,21 @@ public class ComputeServiceContextFactory {
*/
public <S, A> ComputeServiceContext createContext(ContextSpec<S, A> 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.<Module> of());
}
@SuppressWarnings("unchecked")
public static ComputeServiceContext createStandaloneContext(StandaloneComputeServiceContextModule contextModule,
Iterable<Module> modules) {
return new ComputeServiceContextFactory().createContext(RestContextFactory
.<ComputeService, ComputeService> contextSpec("standalone", "standalone", "1", "standalone", null,
(Class) null, (Class) null, PropertiesBuilder.class,
(Class) StandaloneComputeServiceContextBuilder.class, ImmutableSet.<Module> builder().add(
contextModule).addAll(modules).build()));
}
}

View File

@ -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<ComputeService, ComputeService> {
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<Module> 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;
}
}

View File

@ -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<Set<? extends Image>> getSourceImageSupplier(Injector injector);
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class;
}
protected abstract Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector);
/**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it
*/
protected abstract Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy();
protected abstract Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy();
protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy();
protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();
protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();
protected abstract Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier();
protected abstract Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier();
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return LocationSupplier.class;
}
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return DefaultLocationSupplier.class;
}
protected void bindLoadBalancerService() {
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null)).in(Scopes.SINGLETON);
}
protected void bindRunNodesAndAddToSetStrategy(Class<? extends RunNodesAndAddToSetStrategy> clazz) {
bind(RunNodesAndAddToSetStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
/**
* needed, if {@link RunNodesAndAddToSetStrategy} requires it
*/
protected void bindAddNodeWithTagStrategy(Class<? extends AddNodeWithTagStrategy> clazz) {
bind(AddNodeWithTagStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDestroyNodeStrategy(Class<? extends DestroyNodeStrategy> clazz) {
bind(DestroyNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindRebootNodeStrategy(Class<? extends RebootNodeStrategy> clazz) {
bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) {
bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindListNodesStrategy(Class<? extends ListNodesStrategy> clazz) {
bind(ListNodesStrategy.class).to(clazz).in(Scopes.SINGLETON);
}
protected void bindImageSupplier(Class<? extends Supplier<Set<? extends Image>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Image>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindLocationSupplier(Class<? extends Supplier<Set<? extends Location>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Location>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindDefaultLocationSupplier(Class<? extends Supplier<Location>> clazz) {
bind(new TypeLiteral<Supplier<Location>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
protected void bindHardwareSupplier(Class<? extends Supplier<Set<? extends Hardware>>> clazz) {
bind(new TypeLiteral<Supplier<Set<? extends Hardware>>>() {
}).to(clazz).in(Scopes.SINGLETON);
}
/**
* By default allows you to use a static set of locations bound to Set<? extends Location>
*/
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
Set<? extends Location> locations = injector.getInstance(Key.get(new TypeLiteral<Set<? extends Location>>() {
}));
return Suppliers.<Set<? extends Location>> ofInstance(locations);
@Singleton
public static class LocationSupplier implements Supplier<Set<? extends Location>> {
private final Set<? extends Location> locations;
@Inject
LocationSupplier(Set<? extends Location> locations) {
this.locations = locations;
}
@Override
public Set<? extends Location> get() {
return locations;
}
}
@Singleton
public static class DefaultLocationSupplier implements Supplier<Location> {
private final Supplier<Set<? extends Location>> locations;
@Inject
DefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> locations) {
this.locations = locations;
}
@Override
public Location get() {
return Iterables.find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
});
}
}
@Provides
@ -86,7 +221,7 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Provides
@Singleton
protected Supplier<Map<String, ? extends Image>> provideImageMap(Supplier<Set<? extends Image>> images) {
protected Supplier<Map<String, ? extends Image>> provideImageMap(@Memoized Supplier<Set<? extends Image>> images) {
return Suppliers.compose(new Function<Set<? extends Image>, Map<String, ? extends Image>>() {
@Override
@ -106,20 +241,22 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Provides
@Singleton
@Memoized
protected Supplier<Set<? extends Image>> supplyImageCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
final Supplier<Set<? extends Image>> imageSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Image>>(authException, seconds,
new Supplier<Set<? extends Image>>() {
@Override
public Set<? extends Image> get() {
return getSourceImageSupplier(injector).get();
return imageSupplier.get();
}
});
}
@Provides
@Singleton
protected Supplier<Map<String, ? extends Location>> provideLocationMap(Supplier<Set<? extends Location>> locations) {
protected Supplier<Map<String, ? extends Location>> provideLocationMap(
@Memoized Supplier<Set<? extends Location>> locations) {
return Suppliers.compose(new Function<Set<? extends Location>, Map<String, ? extends Location>>() {
@Override
@ -139,20 +276,21 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Provides
@Singleton
@Memoized
protected Supplier<Set<? extends Location>> supplyLocationCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
final Supplier<Set<? extends Location>> locationSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Location>>(authException, seconds,
new Supplier<Set<? extends Location>>() {
@Override
public Set<? extends Location> get() {
return getSourceLocationSupplier(injector).get();
return locationSupplier.get();
}
});
}
@Provides
@Singleton
protected Supplier<Map<String, ? extends Hardware>> provideSizeMap(Supplier<Set<? extends Hardware>> sizes) {
protected Supplier<Map<String, ? extends Hardware>> provideSizeMap(@Memoized Supplier<Set<? extends Hardware>> sizes) {
return Suppliers.compose(new Function<Set<? extends Hardware>, Map<String, ? extends Hardware>>() {
@Override
@ -172,13 +310,14 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
@Provides
@Singleton
@Memoized
protected Supplier<Set<? extends Hardware>> supplySizeCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,
final Injector injector) {
final Supplier<Set<? extends Hardware>> hardwareSupplier) {
return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier<Set<? extends Hardware>>(authException, seconds,
new Supplier<Set<? extends Hardware>>() {
@Override
public Set<? extends Hardware> get() {
return getSourceSizeSupplier(injector).get();
return hardwareSupplier.get();
}
});
}
@ -194,25 +333,4 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
};
}
@Provides
@Singleton
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
@Override
public Location apply(Set<? extends Location> from) {
return Iterables.find(from, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getScope() == LocationScope.ZONE;
}
});
}
}, locations);
}
}

View File

@ -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<ConcurrentMap, ConcurrentMap> {
public class StandaloneComputeServiceClientModule extends RestClientModule<ComputeService, ComputeService> {
public StubComputeServiceClientModule() {
super(ConcurrentMap.class, ConcurrentMap.class);
public StandaloneComputeServiceClientModule() {
super(ComputeService.class, ComputeService.class);
}
@Override

View File

@ -0,0 +1,40 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute.config;
import org.jclouds.compute.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<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<ComputeService, ComputeService>>() {
}).in(Scopes.SINGLETON);
}
}

View File

@ -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<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
Supplier<Set<? extends Hardware>> hardwares, Supplier<Location> defaultLocation2,
Provider<TemplateOptions> optionsProvider, @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
Supplier<Location> defaultLocation2, Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> 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<ComputeMetadata> locationPredicate = new Predicate<ComputeMetadata>() {
@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<Hardware> hardwarePredicate = and(hardwareIdPredicate, locationPredicate,
hardwareCoresPredicate, hardwareRamPredicate);
hardwareCoresPredicate, hardwareRamPredicate);
static final Ordering<Hardware> DEFAULT_SIZE_ORDERING = new Ordering<Hardware>() {
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<Hardware> BY_CORES_ORDERING = new Ordering<Hardware>() {
@ -395,16 +395,16 @@ public class TemplateBuilderImpl implements TemplateBuilder {
};
static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() {
public int compare(Image left, Image right) {
return ComparisonChain.start()
.compare(left.getName(), right.getName(), Ordering.<String> natural().nullsLast())
.compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsLast())
.compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(),//
Ordering.<String> natural().nullsLast())
.compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(),//
Ordering.<String> natural().nullsLast())
.compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(),//
Ordering.<String> natural().nullsLast())
.compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch()).result();
return ComparisonChain.start().compare(left.getName(), right.getName(),
Ordering.<String> natural().nullsLast()).compare(left.getVersion(), right.getVersion(),
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getName(),
right.getOperatingSystem().getName(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getVersion(),
right.getOperatingSystem().getVersion(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getDescription(),
right.getOperatingSystem().getDescription(),//
Ordering.<String> natural().nullsLast()).compare(left.getOperatingSystem().getArch(),
right.getOperatingSystem().getArch()).result();
}
};
@ -535,7 +535,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
Iterable<? extends Image> 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<? extends Hardware> hardwaresThatAreCompatibleWithOurImages = filter(hardwaresl,
new Predicate<Hardware>() {
@Override
public boolean apply(final Hardware hardware) {
return Iterables.any(images, new Predicate<Image>() {
new Predicate<Hardware>() {
@Override
public boolean apply(final Hardware hardware) {
return Iterables.any(images, new Predicate<Image>() {
@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 <Image> type needed for this to compile
// properly
Predicate<Image> imagePredicate = predicates.size() == 1 ? Iterables.<Predicate<Image>> get(predicates, 0)
: Predicates.<Image> and(predicates);
: Predicates.<Image> 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

View File

@ -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<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> hardwareProfiles,
Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
@Memoized Supplier<Set<? extends Image>> images,
@Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> 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<? extends NodeMetadata> 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<NodeMetadata> nodes = newHashSet();
Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();
Map<?, Future<Void>> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes);
@ -187,7 +189,7 @@ public class BaseComputeService implements ComputeService {
*/
@Override
public Set<? extends NodeMetadata> 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<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> destroying nodes matching(%s)", filter);
Set<NodeMetadata> set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter),
new Function<NodeMetadata, Future<NodeMetadata>>() {
new Function<NodeMetadata, Future<NodeMetadata>>() {
// TODO make an async interface instead of re-wrapping
@Override
public Future<NodeMetadata> apply(final NodeMetadata from) {
return executor.submit(new Callable<NodeMetadata>() {
// TODO make an async interface instead of re-wrapping
@Override
public Future<NodeMetadata> apply(final NodeMetadata from) {
return executor.submit(new Callable<NodeMetadata>() {
@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<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> 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<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> 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<? extends NodeMetadata> filterNodesWhoCanRunScripts(Iterable<? extends NodeMetadata> nodes,
final Map<NodeMetadata, Exception> badNodes, final @Nullable Credentials overridingCredentials) {
final Map<NodeMetadata, Exception> badNodes, final @Nullable Credentials overridingCredentials) {
nodes = filter(transform(nodes, new Function<NodeMetadata, NodeMetadata>() {
@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) {

View File

@ -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<ConcurrentMap, ConcurrentMap> {
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<Module> modules) {
modules.add(new StubComputeServiceClientModule());
}
}

View File

@ -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<String, NodeMetadata> nodes = new ConcurrentHashMap<String, NodeMetadata>();
private static final ExecutorService service = Executors.newCachedThreadPool();
@Provides
@Singleton
ConcurrentMap<String, NodeMetadata> 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<String, NodeMetadata> nodes;
private final String publicIpPrefix;
@Inject
public StubSocketOpen(ConcurrentMap<String, NodeMetadata> 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<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<ConcurrentMap, ConcurrentMap>>() {
}).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.<LoadBalancerService> of(null));
}
@Singleton
public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final Supplier<Location> location;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final Provider<Integer> idProvider;
private final String publicIpPrefix;
private final String privateIpPrefix;
private final String passwordPrefix;
private final Map<String, Credentials> credentialStore;
@Inject
public StubAddNodeWithTagStrategy(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
Map<String, Credentials> credentialStore) {
this.nodes = nodes;
this.location = location;
this.idProvider = idProvider;
this.publicIpPrefix = publicIpPrefix;
this.privateIpPrefix = privateIpPrefix;
this.passwordPrefix = passwordPrefix;
this.credentialStore = credentialStore;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation());
NodeMetadataBuilder builder = new NodeMetadataBuilder();
String id = idProvider.get() + "";
builder.ids(id);
builder.name(name);
builder.tag(tag);
builder.location(location.get());
builder.imageId(template.getImage().getId());
builder.operatingSystem(template.getImage().getOperatingSystem());
builder.state(NodeState.PENDING);
builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
builder.credentials(new Credentials("root", passwordPrefix + id));
NodeMetadata node = builder.build();
nodes.put(node.getId(), node);
credentialStore.put(node.getId(), node.getCredentials());
setState(node, NodeState.RUNNING, 100);
return node;
}
}
protected static void nodeWithState(NodeMetadata node, NodeState state) {
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<String, NodeMetadata> nodes;
@Inject
protected StubGetNodeMetadataStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
return nodes.get(id);
}
}
@Singleton
public static class StubListNodesStrategy implements ListNodesStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubListNodesStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(nodes.values(), filter);
}
}
@Singleton
public static class StubRebootNodeStrategy implements RebootNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubRebootNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.RUNNING, 50);
return node;
}
}
@Singleton
public static class StubDestroyNodeStrategy implements DestroyNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
private final ExecutorService service;
@Inject
protected StubDestroyNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) {
this.nodes = nodes;
this.service = service;
}
@Override
public NodeMetadata execute(final String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
return node;
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.TERMINATED, 50);
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Throwables.propagate(e);
} finally {
nodes.remove(id);
}
}
});
return node;
}
install(new StubComputeServiceDependenciesModule());
super.configure();
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
Supplier<Location> defaultLocation = injector.getInstance(Key.get(new TypeLiteral<Supplier<Location>>() {
}));
Location zone = defaultLocation.get().getParent();
String parentId = zone.getId();
Credentials defaultCredentials = new Credentials("root", null);
return Suppliers
.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
//
new ImageBuilder()
.providerId("1")
.name(OsFamily.UBUNTU.name())
.id(parentId + "/1")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false))
.description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), //
new ImageBuilder()
.providerId("2")
.name(OsFamily.UBUNTU.name())
.id(parentId + "/2")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true))
.description("stub ubuntu 64").defaultCredentials(defaultCredentials).build(), //
new ImageBuilder()
.providerId("3")
.name(OsFamily.CENTOS.name())
.id(parentId + "/3")
.location(zone)
.operatingSystem(
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true))
.description("stub centos 64").defaultCredentials(defaultCredentials).build() //
));
}
@Provides
@Singleton
protected Set<? extends Location> provideLocations(@org.jclouds.rest.annotations.Provider String providerName) {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
provider);
return ImmutableSet
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return StubAddNodeWithTagStrategy.class;
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of(
StubHardware.stub("small", 1, 1740, 160), StubHardware.stub("medium", 4, 7680, 850),
StubHardware.stub("large", 8, 15360, 1690)));
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return StubDestroyNodeStrategy.class;
}
private static class StubHardware {
@Override
protected Class<? extends GetNodeMetadataStrategy> 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.<Volume> of(new VolumeImpl(disk, true, false))).build();
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return StubListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return StubRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return StubHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return StubImageSupplier.class;
}
}

View File

@ -0,0 +1,377 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute.stub.config;
import 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<String, NodeMetadata> backing = new ConcurrentHashMap<String, NodeMetadata>();
// implementation details below
@Provides
@Singleton
ConcurrentMap<String, NodeMetadata> 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<String, NodeMetadata> nodes;
private final String publicIpPrefix;
@Inject
public StubSocketOpen(ConcurrentMap<String, NodeMetadata> 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> location;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final Provider<Integer> idProvider;
private final String publicIpPrefix;
private final String privateIpPrefix;
private final String passwordPrefix;
private final Map<String, Credentials> credentialStore;
@Inject
public StubAddNodeWithTagStrategy(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
Map<String, Credentials> credentialStore) {
this.nodes = nodes;
this.location = location;
this.idProvider = idProvider;
this.publicIpPrefix = publicIpPrefix;
this.privateIpPrefix = privateIpPrefix;
this.passwordPrefix = passwordPrefix;
this.credentialStore = credentialStore;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
checkArgument(location.get().equals(template.getLocation()), "invalid location: " + template.getLocation());
NodeMetadataBuilder builder = new NodeMetadataBuilder();
String id = idProvider.get() + "";
builder.ids(id);
builder.name(name);
builder.tag(tag);
builder.location(location.get());
builder.imageId(template.getImage().getId());
builder.operatingSystem(template.getImage().getOperatingSystem());
builder.state(NodeState.PENDING);
builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
builder.credentials(new Credentials("root", passwordPrefix + id));
NodeMetadata node = builder.build();
nodes.put(node.getId(), node);
credentialStore.put(node.getId(), node.getCredentials());
setState(node, NodeState.RUNNING, 100);
return node;
}
}
protected static void nodeWithState(NodeMetadata node, NodeState state) {
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<String, NodeMetadata> nodes;
@Inject
protected StubGetNodeMetadataStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
return nodes.get(id);
}
}
@Singleton
public static class StubListNodesStrategy implements ListNodesStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubListNodesStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public Iterable<? extends ComputeMetadata> list() {
return listDetailsOnNodesMatching(NodePredicates.all());
}
@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
return Iterables.filter(nodes.values(), filter);
}
}
@Singleton
public static class StubRebootNodeStrategy implements RebootNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubRebootNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.RUNNING, 50);
return node;
}
}
@Singleton
public static class StubDestroyNodeStrategy implements DestroyNodeStrategy {
private final ConcurrentMap<String, NodeMetadata> nodes;
private final ExecutorService service;
@Inject
protected StubDestroyNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) {
this.nodes = nodes;
this.service = service;
}
@Override
public NodeMetadata execute(final String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
return node;
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.TERMINATED, 50);
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Throwables.propagate(e);
} finally {
nodes.remove(id);
}
}
});
return node;
}
}
@Singleton
static class StubImageSupplier implements Supplier<Set<? extends Image>> {
private final Supplier<Location> defaultLocation;
@Inject
StubImageSupplier(Supplier<Location> defaultLocation) {
this.defaultLocation = defaultLocation;
}
@Override
public Set<? extends Image> get() {
Location zone = defaultLocation.get().getParent();
String parentId = zone.getId();
Credentials defaultCredentials = new Credentials("root", null);
return ImmutableSet
.<Image> of(new ImageBuilder().providerId("1").name(OsFamily.UBUNTU.name()).id(parentId + "/1")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32",
false)).description("stub ubuntu 32").defaultCredentials(
defaultCredentials).build(), //
new ImageBuilder().providerId("2").name(OsFamily.UBUNTU.name()).id(parentId + "/2")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64",
"ubuntu 64", true)).description("stub ubuntu 64")
.defaultCredentials(defaultCredentials).build(), //
new ImageBuilder().providerId("3").name(OsFamily.CENTOS.name()).id(parentId + "/3")
.location(zone).operatingSystem(
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64",
"centos 64", true)).description("stub centos 64")
.defaultCredentials(defaultCredentials).build() //
);
}
}
@Provides
@Singleton
protected Set<? extends Location> provideLocations(@org.jclouds.rest.annotations.Provider String providerName) {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region",
provider);
return ImmutableSet
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
}
@Singleton
static class StubHardwareSupplier implements Supplier<Set<? extends Hardware>> {
static Hardware stub(String type, int cores, int ram, float disk) {
return new org.jclouds.compute.domain.HardwareBuilder().id(type).providerId(type).name(type).processors(
ImmutableList.of(new Processor(cores, 1.0))).ram(ram).volumes(
ImmutableList.<Volume> of(new VolumeImpl(disk, true, false))).build();
}
@Override
public Set<? extends Hardware> get() {
return ImmutableSet.<Hardware> of(stub("small", 1, 1740, 160), stub("medium", 4, 7680, 850), stub("large", 8,
15360, 1690));
}
}
}

View File

@ -0,0 +1,39 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute;
import org.jclouds.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();
}
}

View File

@ -64,11 +64,11 @@ public class TemplateBuilderImplTest {
Hardware hardware = new HardwareBuilder().id("hardwareId").build();
Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation));
.<Location> of(defaultLocation));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
image, image2));
image, image2));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation));
.<Location> of(defaultLocation));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
image, image2));
image, image2));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation));
.<Location> of(defaultLocation));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(image));
.<Image> of(image));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(defaultLocation));
.<Location> of(defaultLocation));
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(image));
.<Image> of(image));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> 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<Set<? extends Location>> locations,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> hardwares, Location defaultLocation,
Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, hardwares,
Suppliers.ofInstance(defaultLocation), optionsProvider, templateBuilderProvider);
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> hardwares,
Location defaultLocation, Provider<TemplateOptions> optionsProvider,
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> 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<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of());
.<Location> of());
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> 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");

View File

@ -0,0 +1,42 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.collect;
import static 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 {
}

View File

@ -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

View File

@ -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,23 +108,10 @@ 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
*/
@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations,
FilesystemStorageStrategy storageStrategy) {
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier<Location> defaultLocation,
@Memoized Supplier<Set<? extends Location>> 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;
@ -160,19 +157,16 @@ public class FilesystemAsyncBlobStore extends BaseAsyncBlobStore {
// Loading blobs from container
Iterable<String> 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<StorageMetadata> contents = newTreeSet(transform(blobBelongingToContainer,
new Function<String, StorageMetadata>() {
public StorageMetadata apply(String key) {
Blob oldBlob = loadFileBlob(container, key);
new Function<String, StorageMetadata>() {
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<StorageMetadata>() {
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<StorageMetadata>() {
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<StorageMetadata>() {
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<StorageMetadata>() {
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<StorageMetadata> 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<StorageMetadata> 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<String> commonPrefixes = null;
Iterable<String> iterable = transform(contents, new CommonPrefixes(prefix != null ? prefix : null, delimiter));
commonPrefixes = iterable != null ? newTreeSet(iterable) : new TreeSet<String>();
commonPrefixes.remove(CommonPrefixes.NO_PREFIX);
final String delimiter = options.isRecursive() ? null : File.separator;
if (delimiter != null) {
SortedSet<String> commonPrefixes = null;
Iterable<String> iterable = transform(contents, new CommonPrefixes(prefix != null ? prefix : null,
delimiter));
commonPrefixes = iterable != null ? newTreeSet(iterable) : new TreeSet<String>();
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.<StorageMetadata> addAll(contents, transform(commonPrefixes,
new Function<String, StorageMetadata>() {
public StorageMetadata apply(String o) {
MutableStorageMetadata md = new MutableStorageMetadataImpl();
md.setType(StorageType.RELATIVE_PATH);
md.setName(o);
return md;
}
}));
}
Iterables.<StorageMetadata> addAll(contents, transform(commonPrefixes,
new Function<String, StorageMetadata>() {
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.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(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<Void> 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<Boolean> containerExists(final String containerName) {
boolean exists = containerExistsSyncImpl(containerName);
return immediateFuture(exists);
boolean exists = containerExistsSyncImpl(containerName);
return immediateFuture(exists);
}
/**
/**
* {@inheritDoc}
*/
@Override
public ListenableFuture<PageSet<? extends StorageMetadata>> list() {
Iterable<String> containers = storageStrategy.getAllContainerNames();
@Override
public ListenableFuture<PageSet<? extends StorageMetadata>> list() {
Iterable<String> containers = storageStrategy.getAllContainerNames();
return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(transform(
containers, new Function<String, StorageMetadata>() {
public StorageMetadata apply(String name) {
MutableStorageMetadata cmd = create();
cmd.setName(name);
cmd.setType(StorageType.CONTAINER);
return cmd;
}
}), null));
}
return Futures.<PageSet<? extends StorageMetadata>> immediateFuture(new PageSetImpl<StorageMetadata>(transform(
containers, new Function<String, StorageMetadata>() {
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<Boolean> createContainerInLocation(
final Location location,
@PathParam("container") @ParamValidators( { FilesystemContainerNameValidator.class }) String name) {
boolean result = storageStrategy.createContainer(name);
return immediateFuture(result);
public ListenableFuture<Boolean> 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<StorageMetadata> {
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<Blob> 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;
}
}

View File

@ -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,6 +42,15 @@ 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
@ -76,6 +79,7 @@ public class FilesystemBlobStoreContextModule extends AbstractModule {
@Provides
@Singleton
@Memoized
Supplier<Set<? extends Location>> provideLocations(Supplier<Location> defaultLocation) {
return Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(defaultLocation.get()));
}

View File

@ -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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<GoGridClient, GoGridAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<GoGridClient, GoGridAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<GoGridClient, GoGridAsyncClient>>() {
}).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<ServerState, NodeState> serverStateToNodeState = ImmutableMap.<ServerState, NodeState> 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<ServerState, NodeState> 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<Hardware, String> provideSizeToRam() {
return new Function<Hardware, String>() {
@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<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return GoGridAddNodeWithTagStrategy.class;
}
@Override
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
final String defaultDC = injector.getInstance(Key.get(String.class, Names.named(PROPERTY_GOGRID_DEFAULT_DC)));
return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
@Override
public Location apply(Set<? extends Location> from) {
return Iterables.find(from, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultDC);
}
});
}
}, locations);
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return GoGridDestroyNodeStrategy.class;
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(GoGridImageSupplier.class);
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return GoGridGetNodeMetadataStrategy.class;
}
@Override
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
return injector.getInstance(GoGridLocationSupplier.class);
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return GoGridHardwareSupplier.class;
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(GoGridHardwareSupplier.class);
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return GoGridImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return GoGridListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return GoGridRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return GoGridDefaultLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return GoGridLocationSupplier.class;
}
}

View File

@ -0,0 +1,113 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.gogrid.compute.config;
import 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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<GoGridClient, GoGridAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<GoGridClient, GoGridAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<GoGridClient, GoGridAsyncClient>>() {
}).in(Scopes.SINGLETON);
}
@VisibleForTesting
static final Map<ServerState, NodeState> serverStateToNodeState = ImmutableMap.<ServerState, NodeState> 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<ServerState, NodeState> 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<Hardware, String> provideSizeToRam() {
return new Function<Hardware, String>() {
@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 */
}
};
}
}

View File

@ -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<Server, NodeMetadata> {
@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<Server, NodeMetadata> {
@Inject
ServerToNodeMetadata(Map<ServerState, NodeState> serverStateToNodeState, GoGridClient client,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> hardwares,
Supplier<Map<String, ? extends Location>> locations) {
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,
Supplier<Map<String, ? extends Location>> locations) {
this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.client = checkNotNull(client, "client");
this.images = checkNotNull(images, "images");

View File

@ -0,0 +1,64 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.gogrid.compute.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<Location> {
private final Supplier<Set<? extends Location>> locations;
private final String defaultDC;
@Inject
GoGridDefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> 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<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultDC);
}
});
}
}

View File

@ -40,21 +40,21 @@ import com.google.common.collect.ImmutableSet;
@Singleton
public class GoGridHardwareSupplier implements Supplier<Set<? extends Hardware>> {
public static final Hardware H8192 = new HardwareBuilder().ids("5").ram(8192)
.processors(ImmutableList.of(new Processor(8, 1.0)))
.volumes(ImmutableList.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> 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.<Volume> of(new VolumeImpl(30.0f, true, true))).build();
public static final ImmutableSet<Hardware> H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192);

View File

@ -69,7 +69,7 @@ public class GoGridImageSupplier implements Supplier<Set<? extends Image>> {
Set<ServerImage> 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));

View File

@ -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;
}
}

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, CloudFilesClient sync, CloudFilesAsyncClient async,
@Memoized Supplier<Set<? extends Location>> locations, CloudFilesClient sync, CloudFilesAsyncClient async,
ContainerToResourceMetadata container2ResourceMd,
BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions,
ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object,

View File

@ -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<Location> defaultLocation,
Supplier<Set<? extends Location>> locations, CloudFilesClient sync,
@Memoized Supplier<Set<? extends Location>> locations, CloudFilesClient sync,
ContainerToResourceMetadata container2ResourceMd,
BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions,
ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object,

View File

@ -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<Supplier<Set<? extends Location>>>() {
}).annotatedWith(Memoized.class).to(new TypeLiteral<RackspaceLocationsSupplier>() {
});
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<Set<? extends Location>> getSourceLocationSupplier(Set<? extends Location> locations) {
return Suppliers.<Set<? extends Location>> ofInstance(locations);
}
@Provides
@Singleton
protected Supplier<Location> getLocation(Set<? extends Location> locations) {
return Suppliers.<Location> ofInstance(Iterables.get(locations, 0));
protected Supplier<Location> getLocation(@Memoized Supplier<Set<? extends Location>> locations) {
return Suppliers.<Location> ofInstance(Iterables.get(locations.get(), 0));
}
}

View File

@ -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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.rackspace.cloudservers.domain.Image, Image>>() {
}).to(CloudServersImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem>>() {
}).to(CloudServersImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<CloudServersClient, CloudServersAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<CloudServersClient, CloudServersAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<CloudServersClient, CloudServersAsyncClient>>() {
}).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<ServerStatus, NodeState> serverToNodeState = ImmutableMap
.<ServerStatus, NodeState> 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<ServerStatus, NodeState> provideServerToNodeState() {
return serverToNodeState;
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return CloudServersAddNodeWithTagStrategy.class;
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(CloudServersImageSupplier.class);
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return CloudServersDestroyNodeStrategy.class;
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(CloudServersHardwareSupplier.class);
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return CloudServersGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return CloudServersHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return CloudServersImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return CloudServersListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return CloudServersRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return RackspaceLocationsSupplier.class;
}
}

View File

@ -0,0 +1,117 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rackspace.cloudservers.compute.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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.rackspace.cloudservers.domain.Image, Image>>() {
}).to(CloudServersImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem>>() {
}).to(CloudServersImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<CloudServersClient, CloudServersAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<CloudServersClient, CloudServersAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<CloudServersClient, CloudServersAsyncClient>>() {
}).in(Scopes.SINGLETON);
}
@VisibleForTesting
public static final Map<ServerStatus, NodeState> serverToNodeState = ImmutableMap
.<ServerStatus, NodeState> 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<ServerStatus, NodeState> provideServerToNodeState() {
return serverToNodeState;
}
}

View File

@ -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<Server, NodeMetadata> {
@Inject
ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Map<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
@Memoized Supplier<Set<? extends Image>> images, Supplier<Location> location,
@Memoized Supplier<Set<? extends Hardware>> hardwares) {
this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");

View File

@ -54,7 +54,7 @@ public class CloudServersImageSupplier implements Supplier<Set<? extends Image>>
@Inject
CloudServersImageSupplier(CloudServersClient sync,
Function<org.jclouds.rackspace.cloudservers.domain.Image, Image> cloudServersImageToImage) {
Function<org.jclouds.rackspace.cloudservers.domain.Image, Image> cloudServersImageToImage) {
this.sync = sync;
this.cloudServersImageToImage = cloudServersImageToImage;
}
@ -64,7 +64,7 @@ public class CloudServersImageSupplier implements Supplier<Set<? extends Image>>
Set<Image> images;
logger.debug(">> providing images");
images = Sets.<Image> newLinkedHashSet(Iterables.transform(sync.listImages(withDetails()),
cloudServersImageToImage));
cloudServersImageToImage));
logger.debug("<< images(%d)", images.size());
return images;
}

View File

@ -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<Set<? extends Location>> {
@Override
protected void configure() {
private final String providerName;
@Inject
RackspaceLocationsSupplier(@Provider String providerName) {
this.providerName = providerName;
}
@Provides
@Singleton
Set<? extends Location> provideLocations(@Provider String providerName) {
@Override
public Set<? extends Location> get() {
Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
return ImmutableSet.of(new LocationImpl(LocationScope.ZONE, "DFW1", "Dallas, TX", provider));
}

View File

@ -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;
}
}

View File

@ -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<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
ImmutableMap.<String, Credentials> of("1234", creds), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials> of("1234", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState;
org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState;
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(CloudServersImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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());
}
}

View File

@ -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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<RimuHostingClient, RimuHostingAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<RimuHostingClient, RimuHostingAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<RimuHostingClient, RimuHostingAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<Function<Server, Iterable<String>>>() {
}).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<RunningState, NodeState> runningStateToNodeState = ImmutableMap.<RunningState, NodeState> 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<RunningState, NodeState> provideServerToNodeState() {
return runningStateToNodeState;
}
@Singleton
private static class ServerToPublicAddresses implements Function<Server, Iterable<String>> {
@Override
public Iterable<String> apply(Server server) {
return server.getIpAddresses() == null ? ImmutableSet.<String> of() : Iterables.concat(ImmutableList.of(server
.getIpAddresses().getPrimaryIp()), server.getIpAddresses().getSecondaryIps());
}
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return RimuHostingAddNodeWithTagStrategy.class;
}
@Override
protected Supplier<Location> supplyDefaultLocation(Injector injector, Supplier<Set<? extends Location>> locations) {
final String defaultDC = injector
.getInstance(Key.get(String.class, Names.named(PROPERTY_RIMUHOSTING_DEFAULT_DC)));
return Suppliers.compose(new Function<Set<? extends Location>, Location>() {
@Override
public Location apply(Set<? extends Location> from) {
return Iterables.find(from, new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultDC);
}
});
}
}, locations);
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return RimuHostingDestroyNodeStrategy.class;
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(RimuHostingImageSupplier.class);
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return RimuHostingGetNodeMetadataStrategy.class;
}
@Override
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
return injector.getInstance(RimuHostingLocationSupplier.class);
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return RimuHostingHardwareSupplier.class;
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(RimuHostingHardwareSupplier.class);
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return RimuHostingImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return RimuHostingListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return RimuHostingRebootNodeStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return RimuHostingLocationSupplier.class;
}
@Override
protected Class<? extends Supplier<Location>> defineDefaultLocationSupplier() {
return RimuHostingDefaultLocationSupplier.class;
}
}

View File

@ -0,0 +1,95 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rimuhosting.miro.compute.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<Function<Server, NodeMetadata>>() {
}).to(ServerToNodeMetadata.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<RimuHostingClient, RimuHostingAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<RimuHostingClient, RimuHostingAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<RimuHostingClient, RimuHostingAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<Function<Server, Iterable<String>>>() {
}).to(ServerToPublicAddresses.class);
}
@VisibleForTesting
static final Map<RunningState, NodeState> runningStateToNodeState = ImmutableMap.<RunningState, NodeState> 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<RunningState, NodeState> provideServerToNodeState() {
return runningStateToNodeState;
}
@Singleton
private static class ServerToPublicAddresses implements Function<Server, Iterable<String>> {
@Override
public Iterable<String> apply(Server server) {
return server.getIpAddresses() == null ? ImmutableSet.<String> of() : Iterables.concat(ImmutableList.of(server
.getIpAddresses().getPrimaryIp()), server.getIpAddresses().getSecondaryIps());
}
}
}

View File

@ -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<Server, NodeMetadata> {
@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<Server, Iterable<String>> getPublicAddresses,
Map<String, Credentials> credentialStore, Map<RunningState, NodeState> runningStateToNodeState,
Supplier<Set<? extends Image>> images) {
Map<String, Credentials> credentialStore, Map<RunningState, NodeState> runningStateToNodeState,
@Memoized Supplier<Set<? extends Image>> 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<Server, NodeMetadata> {
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() + "");

View File

@ -0,0 +1,64 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.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<Location> {
private final Supplier<Set<? extends Location>> locations;
private final String defaultDC;
@Inject
RimuHostingDefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> 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<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(defaultDC);
}
});
}
}

View File

@ -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<Set<? extends Hardw
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private RimuHostingClient sync;
private Supplier<Set<? extends Location>> locations;
private final RimuHostingClient sync;
private final Supplier<Set<? extends Location>> locations;
@Inject
RimuHostingHardwareSupplier(RimuHostingClient sync, Supplier<Set<? extends Location>> locations) {
RimuHostingHardwareSupplier(RimuHostingClient sync, @Memoized Supplier<Set<? extends Location>> locations) {
this.sync = sync;
this.locations = locations;
}
@ -77,9 +79,9 @@ public class RimuHostingHardwareSupplier implements Supplier<Set<? extends Hardw
}
});
sizes.add(new HardwareBuilder().ids(from.getId()).location(location)
.processors(ImmutableList.of(new Processor(1, 1.0))).ram(from.getRam())
.volumes(ImmutableList.<Volume> 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.<Volume> of(new VolumeImpl((float) from.getDiskSize(), true, true))).build());
} catch (NullPointerException e) {
logger.warn("datacenter not present in " + from.getId());
}

View File

@ -46,11 +46,11 @@ import com.google.common.collect.Sets;
*/
@Singleton
public class RimuHostingImageSupplier implements Supplier<Set<? extends Image>> {
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;
}

View File

@ -48,8 +48,8 @@ public class RimuHostingLocationSupplier implements Supplier<Set<? extends Locat
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private RimuHostingClient sync;
private String providerName;
private final RimuHostingClient sync;
private final String providerName;
@Inject
RimuHostingLocationSupplier(RimuHostingClient sync, @Provider String providerName) {

View File

@ -31,7 +31,7 @@ public class RimuHostingComputeServiceContextModuleTest {
public void testAllStatusCovered() {
for (RunningState state : RunningState.values()) {
assert RimuHostingComputeServiceContextModule.runningStateToNodeState.containsKey(state) : state;
assert RimuHostingComputeServiceDependenciesModule.runningStateToNodeState.containsKey(state) : state;
}
}

View File

@ -19,25 +19,14 @@
package org.jclouds.slicehost.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;
@ -46,15 +35,7 @@ import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rest.RestContext;
import org.jclouds.rest.annotations.Provider;
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.compute.strategy.SlicehostAddNodeWithTagStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostDestroyNodeStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostGetNodeMetadataStrategy;
@ -62,19 +43,10 @@ import org.jclouds.slicehost.compute.strategy.SlicehostListNodesStrategy;
import org.jclouds.slicehost.compute.strategy.SlicehostRebootNodeStrategy;
import org.jclouds.slicehost.compute.suppliers.SlicehostHardwareSupplier;
import org.jclouds.slicehost.compute.suppliers.SlicehostImageSupplier;
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.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
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 SlicehostComputeServiceContext}; requires {@link BaseComputeService} bound.
@ -83,55 +55,6 @@ import com.google.inject.util.Providers;
*/
public class SlicehostComputeServiceContextModule extends BaseComputeServiceContextModule {
@Override
protected void configure() {
install(new ComputeServiceTimeoutsModule());
bind(new TypeLiteral<Function<Slice, NodeMetadata>>() {
}).to(SliceToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.slicehost.domain.Image, Image>>() {
}).to(SlicehostImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.slicehost.domain.Image, OperatingSystem>>() {
}).to(SlicehostImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<SlicehostClient, SlicehostAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<SlicehostClient, SlicehostAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<SlicehostClient, SlicehostAsyncClient>>() {
}).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<Slice.Status, NodeState> sliceStatusToNodeState = ImmutableMap
.<Slice.Status, NodeState> 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<Slice.Status, NodeState> provideSliceToNodeState() {
return sliceStatusToNodeState;
}
@Provides
@Singleton
Location getLocation(@Provider String providerName) {
@ -146,12 +69,43 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(SlicehostImageSupplier.class);
protected void configure() {
install(new SlicehostComputeServiceDependenciesModule());
super.configure();
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(SlicehostHardwareSupplier.class);
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return SlicehostAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return SlicehostDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return SlicehostGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return SlicehostHardwareSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return SlicehostImageSupplier.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return SlicehostListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return SlicehostRebootNodeStrategy.class;
}
}

View File

@ -0,0 +1,97 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.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<Function<Slice, NodeMetadata>>() {
}).to(SliceToNodeMetadata.class);
bind(new TypeLiteral<Function<org.jclouds.slicehost.domain.Image, Image>>() {
}).to(SlicehostImageToImage.class);
bind(new TypeLiteral<Function<org.jclouds.slicehost.domain.Image, OperatingSystem>>() {
}).to(SlicehostImageToOperatingSystem.class);
bind(new TypeLiteral<Function<Flavor, Hardware>>() {
}).to(FlavorToHardware.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<SlicehostClient, SlicehostAsyncClient>>() {
}).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<SlicehostClient, SlicehostAsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<SlicehostClient, SlicehostAsyncClient>>() {
}).in(Scopes.SINGLETON);
}
@VisibleForTesting
public static final Map<Slice.Status, NodeState> sliceStatusToNodeState = ImmutableMap
.<Slice.Status, NodeState> 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<Slice.Status, NodeState> provideSliceToNodeState() {
return sliceStatusToNodeState;
}
}

View File

@ -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<Slice, NodeMetadata> {
protected final Supplier<Location> location;
protected final Map<Slice.Status, NodeState> sliceToNodeState;
@ -86,7 +89,8 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
@Inject
SliceToNodeMetadata(Map<Slice.Status, NodeState> sliceStateToNodeState, Map<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
@Memoized Supplier<Set<? extends Image>> images, Supplier<Location> location,
@Memoized Supplier<Set<? extends Hardware>> hardwares) {
this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");

View File

@ -52,7 +52,7 @@ public class SlicehostImageSupplier implements Supplier<Set<? extends Image>> {
@Inject
SlicehostImageSupplier(SlicehostClient sync,
Function<org.jclouds.slicehost.domain.Image, Image> slicehostImageToImage) {
Function<org.jclouds.slicehost.domain.Image, Image> slicehostImageToImage) {
this.sync = sync;
this.slicehostImageToImage = slicehostImageToImage;
}

View File

@ -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;
}
}

View File

@ -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<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState;
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Slice slice = SliceHandlerTest.parseSlice();
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState,
ImmutableMap.<String, Credentials> of("1", creds), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap
.<String, Credentials> of("1", creds), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState;
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Slice slice = SliceHandlerTest.parseSlice();
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState;
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState;
org.jclouds.compute.domain.Image jcImage = SlicehostImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Slice slice = SliceHandlerTest.parseSlice();
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState;
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(SlicehostImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Slice slice = SliceHandlerTest.parseSlice();
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState,
ImmutableMap.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, ImmutableMap
.<String, Credentials> of(), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>> 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());
}
}

View File

@ -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.<LoadBalancerService> of(null));
super.configure();
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(StaticHardwareSupplier.class);
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return EncodeTagIntoNameRunNodesAndAddToSetStrategy.class;
}
@Override
protected Supplier<Set<? extends Location>> getSourceLocationSupplier(Injector injector) {
return injector.getInstance(OrgAndVDCToLocationSupplier.class);
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return StaticHardwareSupplier.class;
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(VCloudImageSupplier.class);
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return VCloudImageSupplier.class;
}
@Override
protected Class<? extends Supplier<Set<? extends Location>>> defineLocationSupplier() {
return OrgAndVDCToLocationSupplier.class;
}
}

View File

@ -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<Function<VApp, Hardware>>() {
}).to(new TypeLiteral<HardwareForVApp>() {
});
bind(GetNodeMetadataStrategy.class).to(VCloudGetNodeMetadataStrategy.class);
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<VCloudClient, VCloudClient>>() {
}).in(Scopes.SINGLETON);
@ -91,15 +88,36 @@ public class VCloudComputeServiceContextModule extends CommonVCloudComputeServic
bind(new TypeLiteral<Function<Org, Iterable<? extends Hardware>>>() {
}).to(new TypeLiteral<HardwareInOrg>() {
});
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<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return injector.getInstance(VCloudHardwareSupplier.class);
protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {
return VCloudHardwareSupplier.class;
}
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return VCloudAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return VCloudDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return VCloudGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return VCloudListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return VCloudRebootNodeStrategy.class;
}
}

View File

@ -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<Function<VCloudExpressVApp, NodeMetadata>>() {
}).to(VCloudExpressVAppToNodeMetadata.class);
bindVAppConverter();
bind(new TypeLiteral<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<VCloudExpressClient, VCloudExpressClient>>() {
}).in(Scopes.SINGLETON);
@ -75,9 +72,11 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput
bind(new TypeLiteral<Function<Org, Iterable<? extends Image>>>() {
}).to(new TypeLiteral<ImagesInVCloudExpressOrg>() {
});
bind(AddNodeWithTagStrategy.class).to(VCloudExpressAddNodeWithTagStrategy.class);
bind(ListNodesStrategy.class).to(VCloudExpressListNodesStrategy.class);
bind(DestroyNodeStrategy.class).to(VCloudExpressDestroyNodeStrategy.class);
}
protected void bindVAppConverter() {
bind(new TypeLiteral<Function<VCloudExpressVApp, NodeMetadata>>() {
}).to(VCloudExpressVAppToNodeMetadata.class);
}
@Provides
@ -85,4 +84,29 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput
CommonVCloudComputeClient provideCommonVCloudComputeClient(VCloudExpressComputeClient in) {
return in;
}
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return VCloudExpressAddNodeWithTagStrategy.class;
}
@Override
protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {
return VCloudExpressDestroyNodeStrategy.class;
}
@Override
protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {
return VCloudExpressGetNodeMetadataStrategy.class;
}
@Override
protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {
return VCloudExpressListNodesStrategy.class;
}
@Override
protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {
return VCloudExpressRebootNodeStrategy.class;
}
}

View File

@ -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<Set<? extends Location>> locations;
@Inject
public FindLocationForResource(Supplier<Set<? extends Location>> locations) {
public FindLocationForResource(@Memoized Supplier<Set<? extends Location>> locations) {
this.locations = locations;
}

View File

@ -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<VCloudExpressVA
@Inject
protected VCloudExpressVAppToNodeMetadata(VCloudExpressComputeClient computeClient,
Map<String, Credentials> credentialStore, Map<Status, NodeState> vAppStatusToNodeState,
HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp,
FindLocationForResource findLocationForResourceInVDC, Supplier<Set<? extends Image>> images) {
Map<String, Credentials> credentialStore, Map<Status, NodeState> vAppStatusToNodeState,
HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp,
FindLocationForResource findLocationForResourceInVDC, @Memoized Supplier<Set<? extends Image>> 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<VCloudExpressVA
builder.location(findLocationForResourceInVDC.apply(from.getVDC()));
builder.tag(parseTagFromName(from.getName()));
builder.operatingSystem(from.getOsType() != null ? new CIMOperatingSystem(CIMOperatingSystem.OSType
.fromValue(from.getOsType()), null, null, from.getOperatingSystemDescription()) : null);
.fromValue(from.getOsType()), null, null, from.getOperatingSystemDescription()) : null);
builder.hardware(hardwareForVCloudExpressVApp.apply(from));
builder.state(vAppStatusToNodeState.get(from.getStatus()));
builder.publicAddresses(computeClient.getPublicAddresses(from.getHref()));

View File

@ -25,8 +25,9 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import org.jclouds.compute.domain.Image;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.TemplateBuilderImpl;
import org.jclouds.compute.options.TemplateOptions;
@ -42,8 +43,8 @@ import com.google.common.base.Supplier;
public class VCloudTemplateBuilderImpl extends TemplateBuilderImpl {
@Inject
protected VCloudTemplateBuilderImpl(Supplier<Set<? extends Location>> locations,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> sizes,
protected VCloudTemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
Supplier<Location> defaultLocation, Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider);

View File

@ -45,9 +45,8 @@ public class StaticHardwareSupplier implements Supplier<Set<? extends Hardware>>
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.<Volume> 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.<Volume> of(new VolumeImpl(10f, true, true))).build());
}
return hardware;
}

View File

@ -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<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> sizes,
Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys,
ConcurrentMap<OrgAndName, KeyPairCredentials> credentialsMap, NodeMetadataToOrgAndName nodeToOrgAndName) {
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, ComputeUtils utils, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys,
ConcurrentMap<OrgAndName, KeyPairCredentials> 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;
}

View File

@ -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<ComputeServiceContext>() {
}).to(new TypeLiteral<ComputeServiceContextImpl<VCloudExpressClient, VCloudExpressAsyncClient>>() {
}).in(Scopes.SINGLETON);
// NOTE
bind(RunNodesAndAddToSetStrategy.class).to(TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy.class);
bind(ListNodesStrategy.class).to(VCloudExpressListNodesStrategy.class);
// NOTE
bind(new TypeLiteral<Function<VCloudExpressVApp, NodeMetadata>>() {
}).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<Function<NodeMetadata, OrgAndName>>() {
}).to(new TypeLiteral<NodeMetadataToOrgAndName>() {
});
@ -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<Function<VCloudExpressVApp, NodeMetadata>>() {
}).to(TerremarkVCloudExpressVAppToNodeMetadata.class);
}
@Override
protected Class<? extends RunNodesAndAddToSetStrategy> defineRunNodesAndAddToSetStrategy() {
return TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy.class;
}
@Override
protected Class<? extends AddNodeWithTagStrategy> defineAddNodeWithTagStrategy() {
return TerremarkVCloudAddNodeWithTagStrategy.class;
}
@Provides
@Singleton
ConcurrentMap<OrgAndName, KeyPairCredentials> credentialsMap() {
@ -140,8 +125,7 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom
}
@Override
protected Supplier<Set<? extends Image>> getSourceImageSupplier(Injector injector) {
return injector.getInstance(VAppTemplatesInOrgs.class);
protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {
return VAppTemplatesInOrgs.class;
}
}

View File

@ -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<String, Credentials> credentialStore, Map<Status, NodeState> vAppStatusToNodeState,
HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp,
FindLocationForResource findLocationForResourceInVDC, Supplier<Set<? extends Image>> images,
FindLocationForResource findLocationForResourceInVDC, @Memoized Supplier<Set<? extends Image>> images,
ConcurrentMap<OrgAndName, KeyPairCredentials> credentialsMap) {
super(computeClient, credentialStore, vAppStatusToNodeState, hardwareForVCloudExpressVApp,
findLocationForResourceInVDC, images);
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
;
}
@Override

View File

@ -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<Set<? extends Image>> {
private final ImagesInVCloudExpressOrg imagesInOrg;
@Inject
VAppTemplatesInOrgs(Supplier<Set<? extends Location>> locations,
VAppTemplatesInOrgs(@Memoized Supplier<Set<? extends Location>> locations,
Function<Iterable<? extends Location>, Iterable<? extends Org>> organizatonsForLocations,
ImagesInVCloudExpressOrg imagesInOrg) {
this.locations = locations;