Issue 377: refactored value classes and tests so that we could test and implement credential storage

This commit is contained in:
Adrian Cole 2010-10-16 22:24:22 -07:00
parent 1a63d627b1
commit a9de959146
129 changed files with 6918 additions and 3518 deletions

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.Set;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
@ -56,6 +56,7 @@ import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.annotations.VisibleForTesting;
@ -75,21 +76,21 @@ public class EC2ComputeService extends BaseComputeService {
private final Predicate<PlacementGroup> placementGroupDeleted;
@Inject
protected EC2ComputeService(ComputeServiceContext context, 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) {
super(context, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, runNodesAndAddToSetStrategy,
rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,
nodeTerminated, utils, timeouts, executor);
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) {
super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy,
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider,
templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor);
this.ec2Client = ec2Client;
this.credentialsMap = credentialsMap;
this.securityGroupMap = securityGroupMap;
@ -105,8 +106,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

@ -31,7 +31,6 @@ import static org.jclouds.compute.domain.OsFamily.UBUNTU;
import java.security.SecureRandom;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.inject.Named;
@ -44,7 +43,9 @@ 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;
@ -57,6 +58,7 @@ import org.jclouds.aws.ec2.compute.strategy.EC2RunNodesAndAddToSetStrategy;
import org.jclouds.aws.ec2.compute.suppliers.EC2HardwareSupplier;
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;
@ -70,6 +72,8 @@ 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;
@ -80,6 +84,7 @@ 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;
@ -92,6 +97,7 @@ 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;
@ -107,6 +113,19 @@ import com.google.inject.TypeLiteral;
*/
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")
@ -134,6 +153,10 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod
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);
@ -220,28 +243,28 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod
@Provides
@Singleton
protected ConcurrentMap<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) {
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>>>() {
}));
.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) {

View File

@ -1,197 +0,0 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.not;
import static org.jclouds.compute.predicates.ImagePredicates.any;
import static org.jclouds.compute.predicates.ImagePredicates.idIn;
import static org.jclouds.compute.predicates.ImagePredicates.is64Bit;
import java.util.Arrays;
import org.jclouds.aws.ec2.domain.InstanceType;
import org.jclouds.aws.ec2.domain.RootDeviceType;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.domain.Location;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
*
* @author Adrian Cole
* @see <a
* href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instance-types.html"
* />
*/
public class EC2Hardware extends HardwareImpl {
/** The serialVersionUID */
private static final long serialVersionUID = 8605688733788974797L;
private final String instanceType;
/**
* evaluates true if the Image has the following rootDeviceType
*
* @param type
* rootDeviceType of the image
* @return predicate
*/
public static Predicate<Image> hasRootDeviceType(final RootDeviceType type) {
checkNotNull(type, "type must be defined");
return new Predicate<Image>() {
@Override
public boolean apply(Image image) {
return type.toString().equals(image.getUserMetadata().get("rootDeviceType"));
}
@Override
public String toString() {
return "hasRootDeviceType(" + type + ")";
}
};
}
EC2Hardware(String instanceType, Iterable<? extends Processor> processors, Integer ram,
Iterable<? extends Volume> volumes, RootDeviceType rootDeviceType) {
this(null, instanceType, processors, ram, volumes, hasRootDeviceType(rootDeviceType));
}
EC2Hardware(Location location, String instanceType, Iterable<? extends Processor> processors, Integer ram,
Iterable<? extends Volume> volumes, Predicate<Image> supportsImage) {
super(instanceType, instanceType, instanceType, location, null, ImmutableMap.<String, String> of(), processors,
ram, volumes, supportsImage);
this.instanceType = instanceType;
}
EC2Hardware(String instanceType, Iterable<? extends Processor> processors, Integer ram,
Iterable<? extends Volume> volumes, boolean is64Bit) {
this(null, instanceType, processors, ram, volumes, is64Bit ? is64Bit() : not(is64Bit()));
}
public EC2Hardware(Location location, String instanceType, Iterable<? extends Processor> processors, Integer ram,
Iterable<? extends Volume> volumes, String[] ids) {
this(location, instanceType, processors, ram, volumes, (ids.length == 0 ? is64Bit() : idIn(Arrays.asList(ids))));
}
/**
* Returns the EC2 InstanceType associated with this size.
*/
public String getInstanceType() {
return instanceType;
}
/**
* @see InstanceType#M1_SMALL
*/
public static final EC2Hardware M1_SMALL = new EC2Hardware(InstanceType.M1_SMALL, ImmutableList.of(new Processor(
1.0, 1.0)), 1740, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(150.0f,
"/dev/sda2", false, false)), false);
/**
* In Nova, m1.small can run 64bit images.
*
* @see InstanceType#M1_SMALL
*/
public static final EC2Hardware M1_SMALL_NOVA = new EC2Hardware(null, InstanceType.M1_SMALL, ImmutableList
.of(new Processor(1.0, 1.0)), 1740, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false),
new VolumeImpl(150.0f, "/dev/sda2", false, false)), any());
/**
* @see InstanceType#T1_MICRO
*/
public static final EC2Hardware T1_MICRO = new EC2Hardware(InstanceType.T1_MICRO, ImmutableList.of(new Processor(
1.0, 1.0)), 630, ImmutableList.<Volume> of(), RootDeviceType.EBS);
/**
* @see InstanceType#M1_LARGE
*/
public static final EC2Hardware M1_LARGE = new EC2Hardware(InstanceType.M1_LARGE, ImmutableList.of(new Processor(
2.0, 2.0)), 7680, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false)), true);
/**
* @see InstanceType#M1_XLARGE
*/
public static final EC2Hardware M1_XLARGE = new EC2Hardware(InstanceType.M1_XLARGE, ImmutableList.of(new Processor(
4.0, 2.0)), 15360, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false), new VolumeImpl(420.0f,
"/dev/sdd", false, false), new VolumeImpl(420.0f, "/dev/sde", false, false)), true);
/**
* @see InstanceType#M2_XLARGE
*/
public static final EC2Hardware M2_XLARGE = new EC2Hardware(InstanceType.M2_XLARGE, ImmutableList.of(new Processor(
2.0, 3.25)), 17510, ImmutableList.of(new VolumeImpl(420.0f, "/dev/sda1", true, false)), true);
/**
* @see InstanceType#M2_2XLARGE
*/
public static final EC2Hardware M2_2XLARGE = new EC2Hardware(InstanceType.M2_2XLARGE, ImmutableList
.of(new Processor(4.0, 3.25)), 35020, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false),
new VolumeImpl(840.0f, "/dev/sdb", false, false)), true);
/**
* @see InstanceType#M2_4XLARGE
*/
public static final EC2Hardware M2_4XLARGE = new EC2Hardware(InstanceType.M2_4XLARGE, ImmutableList
.of(new Processor(8.0, 3.25)), 70041, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false),
new VolumeImpl(840.0f, "/dev/sdb", false, false), new VolumeImpl(840.0f, "/dev/sdc", false, false)), true);
/**
* @see InstanceType#C1_MEDIUM
*/
public static final EC2Hardware C1_MEDIUM = new EC2Hardware(InstanceType.C1_MEDIUM, ImmutableList.of(new Processor(
2.0, 2.5)), 1740, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(340.0f,
"/dev/sda2", false, false)), false);
/**
* @see InstanceType#C1_XLARGE
*/
public static final EC2Hardware C1_XLARGE = new EC2Hardware(InstanceType.C1_XLARGE, ImmutableList.of(new Processor(
8.0, 2.5)), 7168, ImmutableList.of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false), new VolumeImpl(420.0f,
"/dev/sdd", false, false), new VolumeImpl(420.0f, "/dev/sde", false, false)), true);
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((instanceType == null) ? 0 : instanceType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
EC2Hardware other = (EC2Hardware) obj;
if (instanceType == null) {
if (other.instanceType != null)
return false;
} else if (!instanceType.equals(other.instanceType))
return false;
return true;
}
}

View File

@ -0,0 +1,262 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.predicates.ImagePredicates.idIn;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.jclouds.aws.ec2.domain.InstanceType;
import org.jclouds.aws.ec2.domain.RootDeviceType;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.domain.Location;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
/**
*
* @author Adrian Cole
* @see <a
* href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instance-types.html"
* />
*/
public class EC2HardwareBuilder extends HardwareBuilder {
/**
* evaluates true if the Image has the following rootDeviceType
*
* @param type
* rootDeviceType of the image
* @return predicate
*/
public static class HasRootDeviceType implements Predicate<Image> {
final RootDeviceType type;
public HasRootDeviceType(final RootDeviceType type) {
this.type = checkNotNull(type, "type must be defined");
}
@Override
public boolean apply(Image image) {
return type.toString().equals(image.getUserMetadata().get("rootDeviceType"));
}
@Override
public String toString() {
return "hasRootDeviceType(" + type + ")";
}
}
public EC2HardwareBuilder(String instanceType) {
super();
ids(instanceType);
}
public EC2HardwareBuilder rootDeviceType(RootDeviceType rootDeviceType) {
supportsImage(new HasRootDeviceType(rootDeviceType));
return this;
}
public EC2HardwareBuilder supportsImageIds(String... ids) {
checkArgument(ids != null && ids.length > 0, "ids must be specified");
supportsImage(idIn(Arrays.asList(ids)));
return this;
}
public EC2HardwareBuilder ids(String id) {
return EC2HardwareBuilder.class.cast(super.ids(id));
}
public EC2HardwareBuilder ram(int ram) {
return EC2HardwareBuilder.class.cast(super.ram(ram));
}
public EC2HardwareBuilder processors(List<Processor> processors) {
return EC2HardwareBuilder.class.cast(super.processors(processors));
}
public EC2HardwareBuilder volumes(List<Volume> volumes) {
return EC2HardwareBuilder.class.cast(super.volumes(volumes));
}
public EC2HardwareBuilder supportsImage(Predicate<Image> supportsImage) {
return EC2HardwareBuilder.class.cast(super.supportsImage(supportsImage));
}
public EC2HardwareBuilder is64Bit(boolean is64Bit) {
return EC2HardwareBuilder.class.cast(super.is64Bit(is64Bit));
}
public EC2HardwareBuilder id(String id) {
return EC2HardwareBuilder.class.cast(super.id(id));
}
@Override
public EC2HardwareBuilder providerId(String providerId) {
return EC2HardwareBuilder.class.cast(super.providerId(providerId));
}
@Override
public EC2HardwareBuilder name(String name) {
return EC2HardwareBuilder.class.cast(super.name(name));
}
@Override
public EC2HardwareBuilder location(Location location) {
return EC2HardwareBuilder.class.cast(super.location(location));
}
@Override
public EC2HardwareBuilder uri(URI uri) {
return EC2HardwareBuilder.class.cast(super.uri(uri));
}
@Override
public EC2HardwareBuilder userMetadata(Map<String, String> userMetadata) {
return EC2HardwareBuilder.class.cast(super.userMetadata(userMetadata));
}
/**
* @see InstanceType#M1_SMALL
*/
public static EC2HardwareBuilder m1_small() {
return new EC2HardwareBuilder(InstanceType.M1_SMALL)
.ram(1740)
.processors(ImmutableList.of(new Processor(1.0, 1.0)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(150.0f,
"/dev/sda2", false, false))).is64Bit(false);
}
/**
* @see InstanceType#T1_MICRO
*/
public static EC2HardwareBuilder t1_micro() {
return new EC2HardwareBuilder(InstanceType.T1_MICRO).ram(630)
.processors(ImmutableList.of(new Processor(1.0, 1.0))).rootDeviceType(RootDeviceType.EBS);
}
/**
* @see InstanceType#M1_LARGE
*/
public static EC2HardwareBuilder m1_large() {
return new EC2HardwareBuilder(InstanceType.M1_LARGE)
.ram(7680)
.processors(ImmutableList.of(new Processor(2.0, 2.0)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false))).is64Bit(true);
}
/**
* @see InstanceType#M1_XLARGE
*/
public static EC2HardwareBuilder m1_xlarge() {
return new EC2HardwareBuilder(InstanceType.M1_XLARGE)
.ram(15360)
.processors(ImmutableList.of(new Processor(4.0, 2.0)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false), new VolumeImpl(
420.0f, "/dev/sdd", false, false), new VolumeImpl(420.0f, "/dev/sde", false, false)))
.is64Bit(true);
}
/**
* @see InstanceType#M2_XLARGE
*/
public static EC2HardwareBuilder m2_xlarge() {
return new EC2HardwareBuilder(InstanceType.M2_XLARGE).ram(17510)
.processors(ImmutableList.of(new Processor(2.0, 3.25)))
.volumes(ImmutableList.<Volume> of(new VolumeImpl(420.0f, "/dev/sda1", true, false))).is64Bit(true);
}
/**
* @see InstanceType#M2_2XLARGE
*/
public static EC2HardwareBuilder m2_2xlarge() {
return new EC2HardwareBuilder(InstanceType.M2_2XLARGE)
.ram(35020)
.processors(ImmutableList.of(new Processor(4.0, 3.25)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(840.0f,
"/dev/sdb", false, false))).is64Bit(true);
}
/**
* @see InstanceType#M2_4XLARGE
*/
public static EC2HardwareBuilder m2_4xlarge() {
return new EC2HardwareBuilder(InstanceType.M2_4XLARGE)
.ram(70041)
.processors(ImmutableList.of(new Processor(8.0, 3.25)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(840.0f,
"/dev/sdb", false, false), new VolumeImpl(840.0f, "/dev/sdc", false, false))).is64Bit(true);
}
/**
* @see InstanceType#C1_MEDIUM
*/
public static EC2HardwareBuilder c1_medium() {
return new EC2HardwareBuilder(InstanceType.C1_MEDIUM)
.ram(1740)
.processors(ImmutableList.of(new Processor(2.0, 2.5)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(340.0f,
"/dev/sda2", false, false))).is64Bit(false);
}
/**
* @see InstanceType#C1_XLARGE
*/
public static EC2HardwareBuilder c1_xlarge() {
return new EC2HardwareBuilder(InstanceType.C1_XLARGE)
.ram(7168)
.processors(ImmutableList.of(new Processor(8.0, 2.5)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(420.0f,
"/dev/sdb", false, false), new VolumeImpl(420.0f, "/dev/sdc", false, false), new VolumeImpl(
420.0f, "/dev/sdd", false, false), new VolumeImpl(420.0f, "/dev/sde", false, false)))
.is64Bit(true);
}
public static EC2HardwareBuilder cc1_4xlarge() {
return new EC2HardwareBuilder(InstanceType.CC1_4XLARGE)
.ram(23 * 1024)
.processors(ImmutableList.of(new Processor(4.0, 4.0), new Processor(4.0, 4.0)))
.volumes(
ImmutableList.<Volume> of(new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(840.0f,
"/dev/sdb", false, false), new VolumeImpl(840.0f, "/dev/sdc", false, false)));
}
}

View File

@ -0,0 +1,79 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.aws.ec2.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.domain.KeyPair;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class CredentialsForInstance implements Function<RunningInstance, Credentials> {
private final Map<RegionAndName, KeyPair> credentialsMap;
private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;
private final Map<RegionAndName, Image> imageForInstance;
@Inject
CredentialsForInstance(Map<RegionAndName, KeyPair> credentialsMap,
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, Map<RegionAndName, Image> imageForInstance) {
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider");
this.imageForInstance = imageForInstance;
}
@Override
public Credentials apply(RunningInstance instance) {
Credentials credentials = null;// default if no keypair exists
if (instance.getKeyName() != null) {
credentials = new Credentials(getLoginAccountFor(instance), getPrivateKeyOrNull(instance));
}
return credentials;
}
@VisibleForTesting
String getPrivateKeyOrNull(RunningInstance instance) {
KeyPair keyPair = credentialsMap.get(new RegionAndName(instance.getRegion(), instance.getKeyName()));
return keyPair != null ? keyPair.getKeyMaterial() : null;
}
@VisibleForTesting
String getLoginAccountFor(RunningInstance from) {
return checkNotNull(
credentialProvider.execute(imageForInstance.get(new RegionAndName(from.getRegion(), from.getImageId()))),
"login from image: " + from.getImageId()).identity;
}
}

View File

@ -36,12 +36,11 @@ import javax.inject.Singleton;
import org.jclouds.aws.ec2.domain.Image.Architecture;
import org.jclouds.aws.ec2.domain.Image.ImageType;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
@ -72,17 +71,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;
@ -92,7 +91,7 @@ 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) {
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");
@ -105,9 +104,12 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
logger.trace("skipping as not a machine image(%s)", from.getId());
return null;
}
String name = null;
String description = from.getDescription() != null ? from.getDescription() : from.getImageLocation();
String version = null;
ImageBuilder builder = new ImageBuilder();
builder.providerId(from.getId());
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()));
OsFamily osFamily = parseOsFamilyOrNull(provider, from.getImageLocation());
String osName = null;
@ -119,13 +121,14 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
Matcher matcher = getMatcherAndFind(from.getImageLocation());
if (matcher.pattern() == AMZN_PATTERN) {
osFamily = OsFamily.AMZN_LINUX;
version = osVersion = matcher.group(1);
osVersion = matcher.group(1);
builder.version(osVersion);
} else if (matcher.pattern() == NEBULA_PATTERN) {
osVersion = parseVersionOrReturnEmptyString(osFamily, matcher.group(2));
} else {
osFamily = OsFamily.fromValue(matcher.group(1));
osVersion = parseVersionOrReturnEmptyString(osFamily, matcher.group(2));
version = matcher.group(3).replace(".manifest.xml", "");
builder.version(matcher.group(3).replace(".manifest.xml", ""));
}
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", from.getImageLocation());
@ -133,28 +136,24 @@ public class ImageParser implements Function<org.jclouds.aws.ec2.domain.Image, I
logger.debug("<< didn't match at all(%s)", from.getImageLocation());
}
Credentials defaultCredentials = credentialProvider.execute(from);
builder.defaultCredentials(credentialProvider.execute(from));
Location location = null;
try {
location = Iterables.find(locations.get(), new Predicate<Location>() {
builder.location(Iterables.find(locations.get(), new Predicate<Location>() {
@Override
public boolean apply(Location input) {
return input.getId().equals(from.getRegion());
}
});
}));
} catch (NoSuchElementException e) {
System.err.printf("unknown region %s for image %s; not in %s", from.getRegion(), from.getId(), locations);
location = new LocationImpl(LocationScope.REGION, from.getRegion(), from.getRegion(), defaultLocation.get()
.getParent());
builder.location(new LocationImpl(LocationScope.REGION, from.getRegion(), from.getRegion(), defaultLocation
.get().getParent()));
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
return new ImageImpl(from.getId(), name, from.getRegion() + "/" + from.getId(), location, null, ImmutableMap
.<String, String> of("owner", from.getImageOwnerId(), "rootDeviceType", from.getRootDeviceType()
.toString()), os, description, version, defaultCredentials);
builder.operatingSystem(new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit));
return builder.build();
}
/**
@ -164,7 +163,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

@ -22,34 +22,29 @@ package org.jclouds.aws.ec2.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.Utils.nullSafeSet;
import java.net.URI;
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 java.util.concurrent.ConcurrentMap;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.domain.InstanceState;
import org.jclouds.aws.ec2.domain.KeyPair;
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.aws.ec2.options.DescribeImagesOptions;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.compute.util.ComputeServiceUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
@ -58,9 +53,8 @@ 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.collect.ComputationException;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
/**
* @author Adrian Cole
@ -71,79 +65,68 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
@Resource
protected Logger logger = Logger.NULL;
@VisibleForTesting
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();
private final EC2Client client;
private final Map<RegionAndName, KeyPair> credentialsMap;
private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;
private final Supplier<Set<? extends Location>> locations;
private final Supplier<Set<? extends Hardware>> hardware;
private final ConcurrentMap<RegionAndName, Image> imageMap;
protected final Supplier<Set<? extends Location>> locations;
protected final Supplier<Set<? extends Hardware>> hardware;
protected final Map<RegionAndName, Image> instanceToImage;
protected final Map<String, Credentials> credentialStore;
protected final Map<InstanceState, NodeState> instanceToNodeState;
@Inject
RunningInstanceToNodeMetadata(EC2Client client, Map<RegionAndName, KeyPair> credentialsMap,
PopulateDefaultLoginCredentialsForImageStrategy credentialProvider,
ConcurrentMap<RegionAndName, Image> imageMap, Supplier<Set<? extends Location>> locations,
Supplier<Set<? extends Hardware>> hardware) {
this.client = checkNotNull(client, "client");
this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap");
this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider");
RunningInstanceToNodeMetadata(Map<InstanceState, NodeState> instanceToNodeState,
Map<String, Credentials> credentialStore, Map<RegionAndName, Image> instanceToImage,
Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Hardware>> hardware) {
this.locations = checkNotNull(locations, "locations");
this.hardware = checkNotNull(hardware, "hardware");
this.imageMap = checkNotNull(imageMap, "imageMap");
this.instanceToImage = checkNotNull(instanceToImage, "instanceToImage");
this.instanceToNodeState = checkNotNull(instanceToNodeState, "instanceToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
}
@Override
public NodeMetadata apply(final RunningInstance instance) {
String id = checkNotNull(instance, "instance").getId();
String name = null; // user doesn't determine a node name;
URI uri = null; // no uri to get rest access to host info
public NodeMetadata apply(RunningInstance instance) {
NodeMetadataBuilder builder = new NodeMetadataBuilder();
String providerId = checkNotNull(instance, "instance").getId();
builder.providerId(providerId);
builder.id(instance.getRegion() + "/" + providerId);
String tag = getTagForInstance(instance);
builder.tag(tag);
builder.credentials(credentialStore.get(instance.getRegion() + "/" + providerId));
builder.state(instanceToNodeState.get(instance.getInstanceState()));
builder.publicAddresses(nullSafeSet(instance.getIpAddress()));
builder.privateAddresses(nullSafeSet(instance.getPrivateIpAddress()));
builder.hardware(parseHardware(instance));
Location location = getLocationForAvailabilityZoneOrRegion(instance);
builder.location(location);
builder.imageId(instance.getRegion() + "/" + instance.getImageId());
Credentials credentials = getCredentialsForInstanceWithTag(instance, tag);
// extract the operating system from the image
Image image = instanceToImage.get(new RegionAndName(instance.getRegion(), instance.getImageId()));
if (image != null)
builder.operatingSystem(image.getOperatingSystem());
Map<String, String> userMetadata = ImmutableMap.<String, String> of();
NodeState state = instanceToNodeState.get(instance.getInstanceState());
Set<String> publicAddresses = nullSafeSet(instance.getIpAddress());
Set<String> privateAddresses = nullSafeSet(instance.getPrivateIpAddress());
return builder.build();
}
protected Hardware parseHardware(final RunningInstance instance) {
Hardware hardware = getHardwareForInstance(instance);
if (hardware != null) {
hardware = ComputeServiceUtils.replacesVolumes(hardware, addEBS(instance, hardware.getVolumes()));
hardware = HardwareBuilder.fromHardware(hardware).volumes(addEBS(instance, hardware.getVolumes())).build();
}
Location location = getLocationForAvailabilityZoneOrRegion(instance);
Image image = resolveImageForInstanceInLocation(instance, location);
return new NodeMetadataImpl(id, name, instance.getRegion() + "/" + instance.getId(), location, uri, userMetadata,
tag, hardware, instance.getRegion() + "/" + instance.getImageId(), image != null ? image
.getOperatingSystem() : null, state, publicAddresses, privateAddresses, credentials);
return hardware;
}
@VisibleForTesting
static Iterable<? extends Volume> addEBS(final RunningInstance instance, Iterable<? extends Volume> volumes) {
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>() {
@ -156,19 +139,10 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
});
}
return Iterables.concat(volumes, ebsVolumes);
return Lists.newArrayList(Iterables.concat(volumes, ebsVolumes));
}
private Credentials getCredentialsForInstanceWithTag(final RunningInstance instance, String tag) {
Credentials credentials = null;// default if no keypair exists
if (instance.getKeyName() != null) {
credentials = new Credentials(getLoginAccountFor(instance), getPrivateKeyOrNull(instance, tag));
}
return credentials;
}
@VisibleForTesting
String getTagForInstance(final RunningInstance instance) {
String tag = String.format("NOTAG-%s", instance.getId());// default
@ -184,9 +158,7 @@ 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;
}
@ -233,36 +205,4 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
}
}
@VisibleForTesting
Image resolveImageForInstanceInLocation(final RunningInstance instance, final Location location) {
Image image = null;
RegionAndName key = new RegionAndName(instance.getRegion(), instance.getImageId());
try {
image = imageMap.get(key);
} catch (NullPointerException nex) {
logger.debug("could not find a matching image for instance %s in location %s", instance, location);
} catch (ComputationException nex) {
logger.debug("could not find a matching image for instance %s in location %s", instance, location);
}
return image;
}
@VisibleForTesting
String getPrivateKeyOrNull(RunningInstance instance, String tag) {
KeyPair keyPair = credentialsMap.get(new RegionAndName(instance.getRegion(), instance.getKeyName()));
return keyPair != null ? keyPair.getKeyMaterial() : null;
}
@VisibleForTesting
String getLoginAccountFor(RunningInstance from) {
org.jclouds.aws.ec2.domain.Image image = null;
try {
image = Iterables.getOnlyElement(client.getAMIServices().describeImagesInRegion(from.getRegion(),
DescribeImagesOptions.Builder.imageIds(from.getImageId())));
} catch (NoSuchElementException e) {
logger.debug("couldn't find image %s/%s", from.getRegion(), from.getImageId());
}
return checkNotNull(credentialProvider.execute(image), "login from image: " + from.getImageId()).identity;
}
}

View File

@ -21,9 +21,9 @@ package org.jclouds.aws.ec2.compute.internal;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import javax.inject.Inject;
import javax.inject.Named;
@ -47,14 +47,13 @@ import com.google.common.collect.ComputationException;
*/
public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
private final ConcurrentMap<RegionAndName, Image> imageMap;
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,
ConcurrentMap<RegionAndName, Image> imageMap) {
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;
}
@ -87,8 +86,7 @@ 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

@ -19,7 +19,6 @@
package org.jclouds.aws.ec2.compute.strategy;
import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.aws.ec2.options.RunInstancesOptions.Builder.asType;
import java.util.Map;
@ -30,7 +29,6 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.compute.domain.EC2Hardware;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.compute.domain.RegionNameAndIngressRules;
import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded;
@ -66,10 +64,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
@Inject
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions(Map<RegionAndName, KeyPair> credentialsMap,
@Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap, CreateUniqueKeyPair createUniqueKeyPair,
CreateSecurityGroupIfNeeded createSecurityGroupIfNeeded,
CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded) {
@Named("SECURITY") Map<RegionAndName, String> securityGroupMap,
@Named("PLACEMENT") Map<RegionAndName, String> placementGroupMap, CreateUniqueKeyPair createUniqueKeyPair,
CreateSecurityGroupIfNeeded createSecurityGroupIfNeeded,
CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded) {
this.credentialsMap = credentialsMap;
this.securityGroupMap = securityGroupMap;
this.placementGroupMap = placementGroupMap;
@ -79,17 +77,13 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
}
public RunInstancesOptions execute(String region, String tag, Template template) {
checkArgument(template.getHardware() instanceof EC2Hardware, "unexpected image type. should be EC2Size, was: "
+ template.getHardware().getClass());
EC2Hardware ec2Size = EC2Hardware.class.cast(template.getHardware());
RunInstancesOptions instanceOptions = asType(ec2Size.getInstanceType()).withAdditionalInfo(tag);
RunInstancesOptions instanceOptions = asType(template.getHardware().getId()).withAdditionalInfo(tag);
String keyPairName = createNewKeyPairUnlessUserSpecifiedOtherwise(region, tag, template.getOptions());
String placementGroupName = ec2Size.getId().startsWith("cc") ? createNewPlacementGroupUnlessUserSpecifiedOtherwise(
region, tag, template.getOptions())
: null;
String placementGroupName = template.getHardware().getId().startsWith("cc") ? createNewPlacementGroupUnlessUserSpecifiedOtherwise(
region, tag, template.getOptions()) : null;
String subnetId = EC2TemplateOptions.class.cast(template.getOptions()).getSubnetId();
@ -122,7 +116,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
keyPairName = EC2TemplateOptions.class.cast(options).getKeyPair();
if (keyPairName == null)
shouldAutomaticallyCreateKeyPair = EC2TemplateOptions.class.cast(options)
.shouldAutomaticallyCreateKeyPair();
.shouldAutomaticallyCreateKeyPair();
}
if (keyPairName == null && shouldAutomaticallyCreateKeyPair) {
RegionAndName regionAndName = new RegionAndName(region, tag);
@ -147,7 +141,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
placementGroupName = EC2TemplateOptions.class.cast(options).getPlacementGroup();
if (placementGroupName == null)
shouldAutomaticallyCreatePlacementGroup = EC2TemplateOptions.class.cast(options)
.shouldAutomaticallyCreatePlacementGroup();
.shouldAutomaticallyCreatePlacementGroup();
}
if (placementGroupName == null && shouldAutomaticallyCreatePlacementGroup) {
placementGroupName = String.format("jclouds#%s#%s", tag, region);
@ -171,17 +165,17 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions
if (options instanceof EC2TemplateOptions && EC2TemplateOptions.class.cast(options).getGroupIds().size() > 0) {
regionNameAndIngessRulesForMarkerGroup = new RegionNameAndIngressRules(region, markerGroup, new int[] {},
false);
false);
groups.addAll(EC2TemplateOptions.class.cast(options).getGroupIds());
} else {
regionNameAndIngessRulesForMarkerGroup = new RegionNameAndIngressRules(region, markerGroup, options
.getInboundPorts(), true);
regionNameAndIngessRulesForMarkerGroup = new RegionNameAndIngressRules(region, markerGroup,
options.getInboundPorts(), true);
}
if (!securityGroupMap.containsKey(regionNameAndIngessRulesForMarkerGroup)) {
securityGroupMap.put(regionNameAndIngessRulesForMarkerGroup, createSecurityGroupIfNeeded
.apply(regionNameAndIngessRulesForMarkerGroup));
securityGroupMap.put(regionNameAndIngessRulesForMarkerGroup,
createSecurityGroupIfNeeded.apply(regionNameAndIngessRulesForMarkerGroup));
}
}
return groups;

View File

@ -29,11 +29,12 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
@ -42,10 +43,11 @@ import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
public class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
private final EC2Client client;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
private final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;
@Inject
protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) {
protected EC2GetNodeMetadataStrategy(EC2Client client,
Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata) {
this.client = client;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
}
@ -57,7 +59,7 @@ public class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
String instanceId = parts[1];
try {
RunningInstance runningInstance = getOnlyElement(getAllRunningInstancesInRegion(client.getInstanceServices(),
region, instanceId));
region, instanceId));
return runningInstanceToNodeMetadata.apply(runningInstance);
} catch (NoSuchElementException e) {
return null;

View File

@ -39,7 +39,6 @@ import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.EC2AsyncClient;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.domain.Reservation;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.compute.domain.ComputeMetadata;
@ -64,13 +63,13 @@ public class EC2ListNodesStrategy implements ListNodesStrategy {
private final EC2AsyncClient client;
private final Map<String, URI> regionMap;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
private final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;
private final ExecutorService executor;
@Inject
protected EC2ListNodesStrategy(EC2AsyncClient client, @Region Map<String, URI> regionMap,
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.client = client;
this.regionMap = regionMap;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
@ -84,15 +83,15 @@ public class EC2ListNodesStrategy implements ListNodesStrategy {
@Override
public Set<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
Iterable<Set<? extends Reservation<? extends RunningInstance>>> reservations = transformParallel(regionMap
.keySet(), new Function<String, Future<Set<? extends Reservation<? extends RunningInstance>>>>() {
Iterable<Set<? extends Reservation<? extends RunningInstance>>> reservations = transformParallel(
regionMap.keySet(), new Function<String, Future<Set<? extends Reservation<? extends RunningInstance>>>>() {
@Override
public Future<Set<? extends Reservation<? extends RunningInstance>>> apply(String from) {
return client.getInstanceServices().describeInstancesInRegion(from);
}
@Override
public Future<Set<? extends Reservation<? extends RunningInstance>>> apply(String from) {
return client.getInstanceServices().describeInstancesInRegion(from);
}
}, executor, null, logger, "reservations");
}, executor, null, logger, "reservations");
Iterable<? extends RunningInstance> instances = concat(concat(reservations));
Iterable<? extends NodeMetadata> nodes = filter(transform(instances, runningInstanceToNodeMetadata), filter);

View File

@ -32,19 +32,24 @@ import org.jclouds.domain.Credentials;
*/
@Singleton
public class EC2PopulateDefaultLoginCredentialsForImageStrategy implements
PopulateDefaultLoginCredentialsForImageStrategy {
PopulateDefaultLoginCredentialsForImageStrategy {
@Override
public Credentials execute(Object resourceToAuthenticate) {
Credentials credentials = new Credentials("root", null);
if (resourceToAuthenticate != null) {
checkArgument(resourceToAuthenticate instanceof Image, "Resource must be an image (for EC2)");
Image image = (Image) resourceToAuthenticate;
String owner = null;
if (resourceToAuthenticate instanceof Image) {
owner = Image.class.cast(resourceToAuthenticate).getImageOwnerId();
} else if (resourceToAuthenticate instanceof org.jclouds.compute.domain.Image) {
owner = org.jclouds.compute.domain.Image.class.cast(resourceToAuthenticate).getUserMetadata().get("owner");
}
checkArgument(owner != null, "Resource must be an image (for EC2)");
// canonical/alestic images use the ubuntu user to login
if (image.getImageOwnerId().matches("063491364108|099720109477")) {
if (owner.matches("063491364108|099720109477")) {
credentials = new Credentials("ubuntu", null);
// http://aws.typepad.com/aws/2010/09/introducing-amazon-linux-ami.html
} else if (image.getImageOwnerId().equals("137112412989")) {
} else if (owner.equals("137112412989")) {
credentials = new Credentials("ec2-user", null);
}
}

View File

@ -35,7 +35,6 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.aws.ec2.domain.Reservation;
import org.jclouds.aws.ec2.domain.RunningInstance;
@ -45,11 +44,14 @@ import org.jclouds.compute.domain.Template;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.RunNodesAndAddToSetStrategy;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* creates futures that correlate to
@ -68,62 +70,77 @@ public class EC2RunNodesAndAddToSetStrategy implements RunNodesAndAddToSetStrate
@VisibleForTesting
final CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;
@VisibleForTesting
final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;
@VisibleForTesting
final ComputeUtils utils;
final Predicate<RunningInstance> instancePresent;
final Function<RunningInstance, Credentials> instanceToCredentials;
final Map<String, Credentials> credentialStore;
@Inject
EC2RunNodesAndAddToSetStrategy(
EC2Client client,
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
@Named("PRESENT") Predicate<RunningInstance> instancePresent,
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata, ComputeUtils utils) {
EC2Client client,
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
@Named("PRESENT") Predicate<RunningInstance> instancePresent,
Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,
Function<RunningInstance, Credentials> instanceToCredentials, Map<String, Credentials> credentialStore,
ComputeUtils utils) {
this.client = client;
this.instancePresent = instancePresent;
this.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions = createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
this.instanceToCredentials = instanceToCredentials;
this.credentialStore = credentialStore;
this.utils = utils;
}
@Override
public Map<?, Future<Void>> execute(String tag, int count, Template template, Set<NodeMetadata> goodNodes,
Map<NodeMetadata, Exception> badNodes) {
Map<NodeMetadata, Exception> badNodes) {
Reservation<? extends RunningInstance> reservation = createKeyPairAndSecurityGroupsAsNeededThenRunInstances(tag,
count, template);
count, template);
Iterable<String> ids = transform(reservation, instanceToId);
String idsString = Joiner.on(',').join(ids);
if (Iterables.size(ids) > 0) {
logger.debug("<< started instances(%s)", idsString);
all(reservation, instancePresent);
logger.debug("<< present instances(%s)", idsString);
populateCredentials(reservation);
}
logger.debug("<< started instances(%s)", idsString);
all(reservation, instancePresent);
logger.debug("<< present instances(%s)", idsString);
return utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(template.getOptions(),
transform(reservation, runningInstanceToNodeMetadata), goodNodes, badNodes);
}
return utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(template.getOptions(), transform(
reservation, runningInstanceToNodeMetadata), goodNodes, badNodes);
protected void populateCredentials(Reservation<? extends RunningInstance> reservation) {
RunningInstance instance1 = Iterables.get(reservation, 0);
Credentials credentials = instanceToCredentials.apply(instance1);
if (credentials != null)
for (RunningInstance instance : reservation)
credentialStore.put(instance.getRegion() + "/" + instance.getId(), credentials);
}
@VisibleForTesting
Reservation<? extends RunningInstance> createKeyPairAndSecurityGroupsAsNeededThenRunInstances(String tag, int count,
Template template) {
Template template) {
String region = getRegionFromLocationOrNull(template.getLocation());
String zone = getZoneFromLocationOrNull(template.getLocation());
RunInstancesOptions instanceOptions = createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region,
tag, template);
tag, template);
if (EC2TemplateOptions.class.cast(template.getOptions()).isMonitoringEnabled())
instanceOptions.enableMonitoring();
if (logger.isDebugEnabled())
logger.debug(">> running %d instance region(%s) zone(%s) ami(%s) params(%s)", count, region, zone, template
.getImage().getProviderId(), instanceOptions.buildFormParameters());
.getImage().getProviderId(), instanceOptions.buildFormParameters());
return client.getInstanceServices().runInstancesInRegion(region, zone, template.getImage().getProviderId(), 1,
count, instanceOptions);
count, instanceOptions);
}
}

View File

@ -20,8 +20,19 @@
package org.jclouds.aws.ec2.compute.suppliers;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.c1_medium;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.c1_xlarge;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.cc1_4xlarge;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_large;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_small;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_xlarge;
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.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs;
import static org.jclouds.compute.predicates.ImagePredicates.any;
import java.util.Set;
@ -30,11 +41,7 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.aws.ec2.compute.domain.EC2Hardware;
import org.jclouds.aws.ec2.domain.InstanceType;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
@ -43,7 +50,6 @@ import org.jclouds.rest.annotations.Provider;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
@ -61,7 +67,7 @@ public class EC2HardwareSupplier implements Supplier<Set<? extends Hardware>> {
@Inject
EC2HardwareSupplier(Supplier<Set<? extends Location>> locations, @Provider String providerName,
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
this.locations = locations;
this.ccAmis = ccAmis;
this.providerName = providerName;
@ -69,7 +75,7 @@ public class EC2HardwareSupplier implements Supplier<Set<? extends Hardware>> {
@Override
public Set<? extends Hardware> get() {
Set<Hardware> sizes = newHashSet();
Set<Hardware> sizes = newLinkedHashSet();
for (String ccAmi : ccAmis) {
final String region = ccAmi.split("/")[0];
Location location = find(locations.get(), new Predicate<Location>() {
@ -80,14 +86,11 @@ public class EC2HardwareSupplier implements Supplier<Set<? extends Hardware>> {
}
});
sizes.add(new EC2Hardware(location, InstanceType.CC1_4XLARGE, ImmutableList.of(new Processor(4.0, 4.0),
new Processor(4.0, 4.0)), 23 * 1024, ImmutableList.of(
new VolumeImpl(10.0f, "/dev/sda1", true, false), new VolumeImpl(840.0f, "/dev/sdb", false, false),
new VolumeImpl(840.0f, "/dev/sdc", false, false)), ccAmis));
sizes.add(cc1_4xlarge().location(location).supportsImageIds(ccAmi).build());
}
sizes.addAll(ImmutableSet.<Hardware> of(EC2Hardware.T1_MICRO, EC2Hardware.C1_MEDIUM, EC2Hardware.C1_XLARGE,
EC2Hardware.M1_LARGE, "nova".equals(providerName) ? EC2Hardware.M1_SMALL_NOVA : EC2Hardware.M1_SMALL,
EC2Hardware.M1_XLARGE, EC2Hardware.M2_XLARGE, EC2Hardware.M2_2XLARGE, EC2Hardware.M2_4XLARGE));
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()));
return sizes;
}
}

View File

@ -52,7 +52,6 @@ import static org.jclouds.aws.ec2.reference.EC2Constants.PROPERTY_EC2_CC_AMIs;
import java.net.URI;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -87,12 +86,12 @@ public class RegionAndNameToImageSupplier implements Supplier<Map<RegionAndName,
private final String[] ccAmis;
private final String[] amiOwners;
private final ImageParser parser;
private final ConcurrentMap<RegionAndName, Image> images;
private final Map<RegionAndName, Image> images;
@Inject
RegionAndNameToImageSupplier(@Region Map<String, URI> regionMap, DescribeImagesParallel describer,
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners,
final ImageParser parser, final ConcurrentMap<RegionAndName, Image> images) {
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners,
final ImageParser parser, final Map<RegionAndName, Image> images) {
this.regionMap = regionMap;
this.describer = describer;
this.ccAmis = ccAmis;
@ -108,11 +107,12 @@ public class RegionAndNameToImageSupplier implements Supplier<Map<RegionAndName,
} else {
logger.debug(">> providing images");
Iterable<Entry<String, DescribeImagesOptions>> queries = concat(getDescribeQueriesForOwnersInRegions(
regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis).entrySet());
Iterable<Entry<String, DescribeImagesOptions>> queries = concat(
getDescribeQueriesForOwnersInRegions(regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis)
.entrySet());
Iterable<? extends Image> parsedImages = filter(transform(describer.apply(queries), parser), Predicates
.notNull());
Iterable<? extends Image> parsedImages = filter(transform(describer.apply(queries), parser),
Predicates.notNull());
images.putAll(uniqueIndex(parsedImages, new Function<Image, RegionAndName>() {
@ -137,7 +137,7 @@ public class RegionAndNameToImageSupplier implements Supplier<Map<RegionAndName,
}
private static Map<String, DescribeImagesOptions> getDescribeQueriesForOwnersInRegions(Map<String, URI> regionMap,
final String[] amiOwners) {
final String[] amiOwners) {
final DescribeImagesOptions options = getOptionsForOwners(amiOwners);
return transformValues(regionMap, new Function<URI, DescribeImagesOptions>() {

View File

@ -230,14 +230,14 @@ public abstract class BaseReservationHandler<T> extends HandlerForGeneratedReque
protected void inItem() {
if (inBlockDeviceMapping) {
ebsBlockDevices.put(deviceName, new RunningInstance.EbsBlockDevice(volumeId, attachmentStatus, attachTime,
deleteOnTermination));
deleteOnTermination));
this.deviceName = null;
this.volumeId = null;
this.attachmentStatus = null;
this.attachTime = null;
this.deleteOnTermination = true;
} else if (inInstances && !inProductCodes && !inBlockDeviceMapping) {
String region = EC2Utils.findRegionInArgsOrNull(getRequest());
String region = getRequest() != null ? EC2Utils.findRegionInArgsOrNull(getRequest()) : null;
// Eucalyptus
if (ipAddress == null && dnsName != null && dnsName.matches(".*[0-9]$")) {
@ -252,10 +252,10 @@ public abstract class BaseReservationHandler<T> extends HandlerForGeneratedReque
if (region == null)
region = defaultRegion;
instances.add(new RunningInstance(region, groupIds, amiLaunchIndex, dnsName, imageId, instanceId,
instanceState, instanceType, ipAddress, kernelId, keyName, launchTime, monitoringState,
availabilityZone, placementGroup, virtualizationType, platform, privateDnsName, privateIpAddress,
productCodes, ramdiskId, reason, subnetId, spotInstanceRequestId, vpcId, rootDeviceType,
rootDeviceName, ebsBlockDevices));
instanceState, instanceType, ipAddress, kernelId, keyName, launchTime, monitoringState,
availabilityZone, placementGroup, virtualizationType, platform, privateDnsName, privateIpAddress,
productCodes, ramdiskId, reason, subnetId, spotInstanceRequestId, vpcId, rootDeviceType, rootDeviceName,
ebsBlockDevices));
this.amiLaunchIndex = null;
this.dnsName = null;
this.imageId = null;
@ -290,11 +290,11 @@ public abstract class BaseReservationHandler<T> extends HandlerForGeneratedReque
}
protected Reservation<? extends RunningInstance> newReservation() {
String region = EC2Utils.findRegionInArgsOrNull(getRequest());
String region = getRequest() != null ? EC2Utils.findRegionInArgsOrNull(getRequest()) : null;
if (region == null)
region = defaultRegion;
Reservation<? extends RunningInstance> info = new Reservation<RunningInstance>(region, groupIds, instances,
ownerId, requesterId, reservationId);
ownerId, requesterId, reservationId);
this.groupIds = Sets.newLinkedHashSet();
this.instances = Sets.newLinkedHashSet();
this.ownerId = null;

View File

@ -46,7 +46,8 @@ import com.google.common.collect.Sets;
* DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2010-06-15/"
*
* @author Adrian Cole
* @see <a href="http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html"
* @see <a href=
* "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html"
* />
*/
public class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Set<Image>> {
@ -159,12 +160,12 @@ public class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedR
this.deleteOnTermination = true;
} else if (!inProductCodes) {
try {
String region = EC2Utils.findRegionInArgsOrNull(getRequest());
String region = getRequest() != null ? EC2Utils.findRegionInArgsOrNull(getRequest()) : null;
if (region == null)
region = defaultRegion;
contents.add(new Image(region, architecture, this.name, description, imageId, imageLocation,
imageOwnerId, imageState, imageType, isPublic, productCodes, kernelId, platform, ramdiskId,
rootDeviceType, rootDeviceName, ebsBlockDevices, virtualizationType));
imageOwnerId, imageState, imageType, isPublic, productCodes, kernelId, platform, ramdiskId,
rootDeviceType, rootDeviceName, ebsBlockDevices, virtualizationType));
} catch (NullPointerException e) {
logger.warn(e, "malformed image: %s", imageId);
}

View File

@ -39,6 +39,10 @@ import org.testng.annotations.Test;
/**
* This test helps us understand how we can use the power of blobstores to our favor.
* <p/>
* This test is in aws only because it happens to have both blobstore and compute
*
* TODO create a blobstore and compute integration module
*
* @author Adrian Cole
*/

View File

@ -0,0 +1,102 @@
/**
*
* 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;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.jclouds.blobstore.BlobStoreContext;
import org.jclouds.blobstore.BlobStoreContextFactory;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.domain.Credentials;
import org.jclouds.rest.config.CredentialStoreModule;
import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Tests that credentials stored in the blobstore can be reused across compute contexts.
* <p/>
* This test is in aws only because it happens to have both blobstore and compute
*
* TODO create a blobstore and compute integration module
*
* @author Adrian Cole
*/
@Test(testName = "jclouds.CredentialsStoredInBlobStoreTest")
public class CredentialsStoredInBlobStoreTest {
private BlobStoreContext blobContext;
private Map<String, InputStream> credentialsMap;
@BeforeTest
void setupCredentialContainerAndMap() {
blobContext = new BlobStoreContextFactory().createContext("transient", "foo", "bar");
blobContext.getBlobStore().createContainerInLocation(null, "credentials");
credentialsMap = blobContext.createInputStreamMap("credentials");
}
@Test
public void testWeCanUseBlobStoreToStoreCredentialsAcrossContexts() throws RunNodesException, IOException {
ComputeServiceContext computeContext = new ComputeServiceContextFactory().createContext("stub", "foo", "bar",
ImmutableSet.of(new CredentialStoreModule(credentialsMap)));
Set<? extends NodeMetadata> nodes = computeContext.getComputeService().runNodesWithTag("foo", 10);
verifyCredentialsFromNodesAreInContext(nodes, computeContext);
computeContext.close();
// recreate the compute context with the same map and ensure it still works!
computeContext = new ComputeServiceContextFactory().createContext("stub", "foo", "bar",
Collections.singleton(new CredentialStoreModule(credentialsMap)));
verifyCredentialsFromNodesAreInContext(nodes, computeContext);
}
protected void verifyCredentialsFromNodesAreInContext(Set<? extends NodeMetadata> nodes,
ComputeServiceContext computeContext) throws IOException {
// verify each node's credential is in the map.
assertEquals(computeContext.credentialStore().size(), 10);
for (NodeMetadata node : nodes) {
assertEquals(computeContext.credentialStore().get(node.getId()), node.getCredentials());
}
// verify the credentials are in the backing store and of a known json format
assertEquals(credentialsMap.size(), 10);
for (Entry<String, InputStream> entry : credentialsMap.entrySet()) {
Credentials credentials = computeContext.credentialStore().get(entry.getKey());
assertEquals(Utils.toStringAndClose(entry.getValue()), String.format(
"{\"identity\":\"%s\",\"credential\":\"%s\"}", credentials.identity, credentials.credential));
}
}
}

View File

@ -23,24 +23,30 @@ import static java.lang.String.format;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.c1_medium;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.c1_xlarge;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.cc1_4xlarge;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_large;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_small;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_xlarge;
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 java.util.Set;
import javax.inject.Provider;
import org.jclouds.aws.ec2.compute.domain.EC2Hardware;
import org.jclouds.aws.ec2.domain.InstanceType;
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.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.domain.internal.TemplateBuilderImpl;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
@ -51,9 +57,8 @@ import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import static org.testng.Assert.assertEquals;
/**
* Tests compute service specifically to EC2.
@ -68,10 +73,8 @@ import com.google.common.collect.Maps;
public class EC2ComputeServiceTest {
private static final Location location = new LocationImpl(LocationScope.REGION, "us-east-1", "us east", null);
public static final EC2Hardware CC1_4XLARGE = new EC2Hardware(location, InstanceType.CC1_4XLARGE, ImmutableList.of(
new Processor(4.0, 4.0), new Processor(4.0, 4.0)), 23 * 1024, ImmutableList.of(new VolumeImpl(10.0f,
"/dev/sda1", true, false), new VolumeImpl(840.0f, "/dev/sdb", false, false), new VolumeImpl(840.0f,
"/dev/sdc", false, false)), new String[] { "us-east-1/cc-image" });
public static final Hardware CC1_4XLARGE = cc1_4xlarge().location(location).supportsImageIds("us-east-1/cc-image")
.build();
/**
* Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based
@ -84,9 +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 EC2Hardware.M2_XLARGE.equals(template.getHardware()) : format(
"Incorrect image determined by the template. Expected: %s. Found: %s.", "m2.xlarge", String
.valueOf(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
@ -95,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()));
}
/**
@ -107,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()));
}
/**
@ -126,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 !EC2Hardware.M2_XLARGE.equals(template.getHardware()) : format(
"Incorrect image determined by the template. Expected: not %s. Found: %s.", "m2.xlarge", String
.valueOf(template.getHardware()));
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()));
}
@SuppressWarnings("unchecked")
@ -144,22 +148,23 @@ public class EC2ComputeServiceTest {
expect(optionsProvider.get()).andReturn(defaultOptions);
Image image = new ImageImpl("cc-image", "image", "us-east-1/cc-image", location, null, Maps
.<String, String> newHashMap(), new OperatingSystem(OsFamily.UBUNTU, null, "1.0", null, "ubuntu", true),
"description", "1.0", new Credentials("root", null));
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(EC2Hardware.T1_MICRO, EC2Hardware.C1_MEDIUM, EC2Hardware.C1_XLARGE, EC2Hardware.M1_LARGE,
EC2Hardware.M1_SMALL, EC2Hardware.M1_XLARGE, EC2Hardware.M2_XLARGE, EC2Hardware.M2_2XLARGE,
EC2Hardware.M2_4XLARGE, 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

@ -0,0 +1,879 @@
/**
*
* 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.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_small;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m2_4xlarge;
import static org.jclouds.aws.ec2.options.DescribeImagesOptions.Builder.imageIds;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.domain.Attachment;
import org.jclouds.aws.ec2.domain.AvailabilityZone;
import org.jclouds.aws.ec2.domain.Image;
import org.jclouds.aws.ec2.domain.InstanceState;
import org.jclouds.aws.ec2.domain.InstanceType;
import org.jclouds.aws.ec2.domain.KeyPair;
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.aws.ec2.services.AMIClient;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.date.DateService;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.testng.annotations.Test;
import com.google.common.base.Function;
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.Maps;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ec2.CredentialsForInstanceTest")
public class CredentialsForInstanceTest {
DateService dateService = new SimpleDateFormatDateService();
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyWithEBSWhenBootIsInstanceStoreAndAvailabilityZoneNotFound() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m1_small().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
// Image image = createMock(Image.class);
//
// expect(instance.getId()).andReturn("i-3d640055").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.of("default")).atLeastOnce();
// expect(instance.getKeyName()).andReturn("jclouds#tag#us-east-1#50").atLeastOnce();
// 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
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn("174.129.1.50");
// expect(instance.getPrivateIpAddress()).andReturn("10.202.117.241");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("ami-1515f07c").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "ami-1515f07c"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("ami-1515f07c"))).andReturn(
// (Set) ImmutableSet.<Image> of(image));
//
// expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn(
// new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass"));
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.M1_SMALL).atLeastOnce();
// expect(instance.getEbsBlockDevices()).andReturn(
// ImmutableMap.<String, EbsBlockDevice> of(
// "/dev/sdg",
// new EbsBlockDevice("vol-1f20d376", Attachment.Status.ATTACHED, dateService
// .iso8601DateParse("2009-12-11T16:32:46.000Z"), false),
// "/dev/sdj",
// new EbsBlockDevice("vol-c0eb78aa", Attachment.Status.ATTACHED, dateService
// .iso8601DateParse("2010-06-17T10:43:28.000Z"), false)));
// expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE);
// expect(instance.getRootDeviceName()).andReturn(null).atLeastOnce();
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "NOTAG-i-3d640055");
// assertEquals(metadata.getLocation(), null);
// assertEquals(metadata.getImageId(), "us-east-1/ami-1515f07c");
// assertEquals(metadata.getHardware().getId(), "m1.small");
// assertEquals(metadata.getHardware().getName(), "m1.small");
// assertEquals(metadata.getHardware().getProviderId(), "m1.small");
// assertEquals(metadata.getHardware().getProcessors(), ImmutableList.<Processor> of(new Processor(1.0, 1.0)));
// assertEquals(metadata.getHardware().getRam(), 1740);
// assertEquals(metadata.getHardware().getVolumes(),
// ImmutableList.<Volume> of(new VolumeImpl(null, Volume.Type.LOCAL, 10.0f, "/dev/sda1", true, false),//
// new VolumeImpl(null, Volume.Type.LOCAL, 150.0f, "/dev/sda2", false, false),//
// new VolumeImpl("vol-1f20d376", Volume.Type.SAN, null, "/dev/sdg", false, true),//
// new VolumeImpl("vol-c0eb78aa", Volume.Type.SAN, null, "/dev/sdj", false, true)));
//
// assertEquals(metadata.getCredentials(), new Credentials("user", "pass"));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
//
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyForNovaWhereNullAvailabilityZoneIpAddressNoGroups() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m1_small().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
// Image image = createMock(Image.class);
//
// expect(instance.getId()).andReturn("i-3d640055").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn("nebulatanimislam").atLeastOnce();
// 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
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn(null);
// expect(instance.getPrivateIpAddress()).andReturn("10.202.117.241");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("ami-1515f07c").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "ami-1515f07c"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("ami-1515f07c"))).andReturn(
// (Set) ImmutableSet.<Image> of(image));
//
// expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "nebulatanimislam"))).andReturn(null);
//
// expect(instance.getAvailabilityZone()).andReturn(null).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.M1_SMALL).atLeastOnce();
// expect(instance.getEbsBlockDevices()).andReturn(Maps.<String, EbsBlockDevice> newHashMap());
// expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE);
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "NOTAG-i-3d640055");
// assertEquals(metadata.getLocation(), region);
// assertEquals(metadata.getImageId(), "us-east-1/ami-1515f07c");
// assertEquals(metadata.getHardware().getId(), "m1.small");
// assertEquals(metadata.getHardware().getName(), "m1.small");
// assertEquals(metadata.getHardware().getProviderId(), "m1.small");
// assertEquals(metadata.getHardware().getProcessors(), ImmutableList.<Processor> of(new Processor(1.0, 1.0)));
// assertEquals(metadata.getHardware().getRam(), 1740);
// assertEquals(metadata.getHardware().getVolumes(),
// ImmutableList.<Volume> of(new VolumeImpl(null, Volume.Type.LOCAL, 10.0f, "/dev/sda1", true, false),//
// new VolumeImpl(null, Volume.Type.LOCAL, 150.0f, "/dev/sda2", false, false)));
//
// assertEquals(metadata.getCredentials(), new Credentials("user", null));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
//
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyWhereUnknownInstanceType() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m1_small().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
// Image image = createMock(Image.class);
//
// expect(instance.getId()).andReturn("i-3d640055").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn("nebulatanimislam").atLeastOnce();
// 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
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn(null);
// expect(instance.getPrivateIpAddress()).andReturn("10.202.117.241");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("ami-1515f07c").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "ami-1515f07c"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("ami-1515f07c"))).andReturn(
// (Set) ImmutableSet.<Image> of(image));
//
// expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "nebulatanimislam"))).andReturn(null);
//
// expect(instance.getAvailabilityZone()).andReturn(null).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn("hhttpp").atLeastOnce();
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "NOTAG-i-3d640055");
// assertEquals(metadata.getLocation(), region);
// assertEquals(metadata.getImageId(), "us-east-1/ami-1515f07c");
// assertEquals(metadata.getHardware(), null);
//
// assertEquals(metadata.getCredentials(), new Credentials("user", null));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
//
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyForNovaWhereImageNotFound() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m1_small().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
//
// expect(instance.getId()).andReturn("i-3d640055").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn("nebulatanimislam").atLeastOnce();
// 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
// .<Location> of(region));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn(null);
// expect(instance.getPrivateIpAddress()).andReturn("10.202.117.241");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("ami-1515f07c").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "ami-1515f07c"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("ami-1515f07c"))).andReturn(
// (Set) ImmutableSet.<Image> of());
//
// expect(credentialProvider.execute(null)).andReturn(new Credentials("root", null));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "nebulatanimislam"))).andReturn(null);
//
// expect(instance.getAvailabilityZone()).andReturn(null).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.M1_SMALL).atLeastOnce();
// expect(instance.getEbsBlockDevices()).andReturn(Maps.<String, EbsBlockDevice> newHashMap());
// expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE);
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "NOTAG-i-3d640055");
// assertEquals(metadata.getLocation(), region);
// assertEquals(metadata.getImageId(), "us-east-1/ami-1515f07c");
// assertEquals(metadata.getHardware().getId(), "m1.small");
// assertEquals(metadata.getHardware().getName(), "m1.small");
// assertEquals(metadata.getHardware().getProviderId(), "m1.small");
// assertEquals(metadata.getHardware().getProcessors(), ImmutableList.<Processor> of(new Processor(1.0, 1.0)));
// assertEquals(metadata.getHardware().getRam(), 1740);
// assertEquals(metadata.getHardware().getVolumes(),
// ImmutableList.<Volume> of(new VolumeImpl(null, Volume.Type.LOCAL, 10.0f, "/dev/sda1", true, false),//
// new VolumeImpl(null, Volume.Type.LOCAL, 150.0f, "/dev/sda2", false, false)));
//
// assertEquals(metadata.getCredentials(), new Credentials("root", null));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
//
// @SuppressWarnings("unchecked")
// @Test
// public void testImageNotFoundAndLazyReturnsNull() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
//
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// 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
// .<Location> of(location));
// 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);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn(null).atLeastOnce();
// expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
//
// expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andReturn(null);
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(jcImage);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
// assertEquals(metadata.getLocation(), locations.get().iterator().next());
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
// assertEquals(metadata.getTag(), "NOTAG-id");
// assertEquals(metadata.getCredentials(), null);
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
// }
//
// @SuppressWarnings("unchecked")
// @Test
// public void testImageNotFoundStillSetsImageId() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// 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
// .<Location> of(location));
// 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);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn(null).atLeastOnce();
// expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
//
// expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andThrow(new NullPointerException())
// .atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(jcImage);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
// assertEquals(metadata.getLocation(), locations.get().iterator().next());
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
// assertEquals(metadata.getTag(), "NOTAG-id");
// assertEquals(metadata.getCredentials(), null);
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
// }
//
// @SuppressWarnings("unchecked")
// @Test
// public void testImageNotFoundAndLazySucceeds() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// 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
// .<Location> of(location));
// 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);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn(null).atLeastOnce();
// expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
//
// org.jclouds.compute.domain.Image lateImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(imageMap.get(new RegionAndName("us-east-1", "imageId"))).andReturn(lateImage).atLeastOnce();
// expect(lateImage.getId()).andReturn("us-east-1/imageId").atLeastOnce();
// expect(lateImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(lateImage);
// replay(imageMap);
// replay(jcImage);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
// assertEquals(metadata.getLocation(), locations.get().iterator().next());
// assertEquals(metadata.getImageId(), lateImage.getId());
// assertEquals(metadata.getTag(), "NOTAG-id");
// assertEquals(metadata.getCredentials(), null);
//
// verify(lateImage);
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
// }
//
// @SuppressWarnings("unchecked")
// @Test
// public void testApplyWithNoSecurityGroupCreatesTagOfIdPrefixedByTagAndNullCredentials() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// 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
// .<Location> of(location));
// 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);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.<String> of()).atLeastOnce();
// expect(instance.getKeyName()).andReturn(null).atLeastOnce();
// expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(jcImage);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
// assertEquals(metadata.getLocation(), locations.get().iterator().next());
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
// assertEquals(metadata.getTag(), "NOTAG-id");
// assertEquals(metadata.getCredentials(), null);
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
// }
//
// @SuppressWarnings("unchecked")
// @Test
// public void testApplyWithNoKeyPairCreatesTagOfParsedSecurityGroupAndNullCredentials() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// Map<RegionAndName, KeyPair> credentialsMap = createMock(Map.class);
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
// 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
// .<Location> of(location));
// 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);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getRegion()).andReturn("us-east-1").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.of("jclouds#tag#us-east-1")).atLeastOnce();
// expect(instance.getKeyName()).andReturn(null).atLeastOnce();
// expect(instance.getInstanceState()).andReturn(InstanceState.RUNNING);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(jcImage);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
// assertEquals(metadata.getLocation(), locations.get().iterator().next());
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
// assertEquals(metadata.getTag(), "tag");
// assertEquals(metadata.getCredentials(), null);
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
// }
//
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyWithKeyPairCreatesTagOfParsedSecurityGroupAndCredentialsBasedOnIt() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
// Image image = createMock(Image.class);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.of("jclouds#tag#us-east-1")).atLeastOnce();
// expect(instance.getKeyName()).andReturn("jclouds#tag#us-east-1#50").atLeastOnce();
// 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
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn(
// (Set) ImmutableSet.<Image> of(image));
//
// expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn(
// new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass"));
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "tag");
// assertEquals(metadata.getLocation(), location);
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
//
// assertEquals(metadata.getCredentials(), new Credentials("user", "pass"));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
//
// @SuppressWarnings({ "unchecked" })
// @Test
// public void testApplyWithTwoSecurityGroups() throws UnknownHostException {
// EC2Client client = createMock(EC2Client.class);
// AMIClient amiClient = createMock(AMIClient.class);
// 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
// .<Hardware> of(m2_4xlarge().build()));
// PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class);
// RunningInstance instance = createMock(RunningInstance.class);
// Image image = createMock(Image.class);
//
// expect(instance.getId()).andReturn("id").atLeastOnce();
// expect(instance.getGroupIds()).andReturn(ImmutableSet.of("jclouds1", "jclouds2")).atLeastOnce();
// expect(instance.getKeyName()).andReturn("jclouds#tag#us-east-1#50").atLeastOnce();
// 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
// .<Location> of(location));
// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
//
// expect(instance.getIpAddress()).andReturn("127.0.0.1");
// expect(instance.getPrivateIpAddress()).andReturn("127.0.0.1");
//
// expect(instance.getRegion()).andReturn(Region.US_EAST_1).atLeastOnce();
//
// expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
//
// expect(instance.getImageId()).andReturn("imageId").atLeastOnce();
// expect(imageMap.get(new RegionAndName(Region.US_EAST_1, "imageId"))).andReturn(jcImage);
//
// expect(amiClient.describeImagesInRegion(Region.US_EAST_1, imageIds("imageId"))).andReturn(
// (Set) ImmutableSet.<Image> of(image));
//
// expect(credentialProvider.execute(image)).andReturn(new Credentials("user", "pass"));
//
// expect(credentialsMap.get(new RegionAndName(Region.US_EAST_1, "jclouds#tag#us-east-1#50"))).andReturn(
// new KeyPair(Region.US_EAST_1, "jclouds#tag#us-east-1#50", "keyFingerprint", "pass"));
//
// expect(instance.getAvailabilityZone()).andReturn(AvailabilityZone.US_EAST_1A).atLeastOnce();
//
// expect(instance.getInstanceType()).andReturn(InstanceType.C1_XLARGE).atLeastOnce();
//
// replay(imageMap);
// replay(client);
// replay(amiClient);
// replay(credentialsMap);
// replay(credentialProvider);
// replay(instance);
// replay(jcImage);
//
// Function<RunningInstance, NodeMetadata> parser = new CredentialsForInstance(client, credentialsMap,
// credentialProvider, imageMap, locations, hardwares);
//
// NodeMetadata metadata = parser.apply(instance);
//
// assertEquals(metadata.getTag(), "NOTAG-id");
// assertEquals(metadata.getLocation(), location);
// assertEquals(metadata.getImageId(), "us-east-1/imageId");
//
// assertEquals(metadata.getCredentials(), new Credentials("user", "pass"));
//
// verify(imageMap);
// verify(jcImage);
// verify(client);
// verify(amiClient);
// verify(credentialsMap);
// verify(credentialProvider);
// verify(instance);
//
// }
}

View File

@ -19,648 +19,200 @@
package org.jclouds.aws.ec2.compute.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.util.Set;
import org.jclouds.aws.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.aws.ec2.domain.Image;
import org.jclouds.aws.ec2.xml.BaseEC2HandlerTest;
import org.jclouds.aws.ec2.xml.DescribeImagesResponseHandler;
import org.jclouds.aws.ec2.xml.DescribeImagesResponseHandlerTest;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;
import com.google.common.base.Predicates;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "compute.ImageParserTest")
public class ImageParserTest extends BaseEC2HandlerTest {
public class ImageParserTest {
public void testParseAlesticCanonicalImage() {
InputStream is = getClass().getResourceAsStream("/ec2/alestic_canonical.xml");
Set<Image> result = parseImages(is);
assertEquals(result.size(), 8);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/alestic_canonical.xml");
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables.get(result, 0));
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.UBUNTU).arch("paravirtual").version("8.04")
.description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml")
.is64Bit(false).build())
.description("ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml")
.defaultCredentials(new Credentials("ubuntu", null)).id("us-east-1/ami-7e28ca17")
.providerId("ami-7e28ca17").location(defaultLocation).version("20091130")
.userMetadata(ImmutableMap.of("owner", "099720109477", "rootDeviceType", "instance-store")).build());
assertEquals(ubuntuHardy.getDescription(), "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getId(), "us-east-1/ami-7e28ca17");
assertEquals(ubuntuHardy.getProviderId(), "ami-7e28ca17");
assertEquals(ubuntuHardy.getLocation(), defaultLocation);
assertEquals(ubuntuHardy.getName(), null);
assertEquals(ubuntuHardy.getOperatingSystem().getName(), null);
assertEquals(ubuntuHardy.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuHardy.getOperatingSystem().getVersion(), "8.04");
assertEquals(ubuntuHardy.getOperatingSystem().getArch(), "paravirtual");
assertEquals(ubuntuHardy.getOperatingSystem().getDescription(),
"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getOperatingSystem().is64Bit(), false);
assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477",
"rootDeviceType", "instance-store"));
assertEquals(ubuntuHardy.getVersion(), "20091130");
assertEquals(
Iterables.get(result, 4),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.UBUNTU).arch("paravirtual").version("8.04")
.description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml").is64Bit(false)
.build()).description("alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml")
.defaultCredentials(new Credentials("ubuntu", null)).id("us-east-1/ami-c0fa1ea9")
.providerId("ami-c0fa1ea9").location(defaultLocation).version("20080905")
.userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store")).build());
org.jclouds.compute.domain.Image alesticKarmic = parser.apply(Iterables.get(result, 1));
assertEquals(alesticKarmic.getOperatingSystem().is64Bit(), false);
assertEquals(alesticKarmic.getDescription(), "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
assertEquals(alesticKarmic.getId(), "us-east-1/ami-19a34270");
assertEquals(alesticKarmic.getProviderId(), "ami-19a34270");
assertEquals(alesticKarmic.getLocation(), defaultLocation);
assertEquals(alesticKarmic.getName(), null);
assertEquals(alesticKarmic.getOperatingSystem().getName(), null);
assertEquals(alesticKarmic.getOperatingSystem().getVersion(), "9.10");
assertEquals(alesticKarmic.getOperatingSystem().getArch(), "paravirtual");
assertEquals(alesticKarmic.getOperatingSystem().getDescription(),
"alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
assertEquals(alesticKarmic.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(alesticKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "063491364108",
"rootDeviceType", "instance-store"));
assertEquals(alesticKarmic.getVersion(), "20090623");
org.jclouds.compute.domain.Image ubuntuKarmic = parser.apply(Iterables.get(result, 2));
assertEquals(ubuntuKarmic.getOperatingSystem().is64Bit(), false);
assertEquals(ubuntuKarmic.getDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getId(), "us-east-1/ami-bb709dd2");
assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2");
assertEquals(ubuntuKarmic.getLocation(), defaultLocation);
assertEquals(ubuntuKarmic.getName(), null);
assertEquals(ubuntuKarmic.getOperatingSystem().getName(), null);
assertEquals(ubuntuKarmic.getOperatingSystem().getVersion(), "9.10");
assertEquals(ubuntuKarmic.getOperatingSystem().getArch(), "paravirtual");
assertEquals(ubuntuKarmic.getOperatingSystem().getDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477",
"rootDeviceType", "instance-store"));
assertEquals(ubuntuKarmic.getVersion(), "20100121");
org.jclouds.compute.domain.Image testing = parser.apply(Iterables.get(result, 3));
assertEquals(testing.getOperatingSystem().is64Bit(), true);
assertEquals(testing.getDescription(),
"ubuntu-images-testing-us/ubuntu-lucid-daily-amd64-desktop-20100317.manifest.xml");
assertEquals(testing.getId(), "us-east-1/ami-190fe070");
assertEquals(testing.getProviderId(), "ami-190fe070");
assertEquals(testing.getLocation(), defaultLocation);
assertEquals(testing.getName(), null);
assertEquals(testing.getOperatingSystem().getName(), null);
assertEquals(testing.getOperatingSystem().getVersion(), "10.04");
assertEquals(testing.getOperatingSystem().getArch(), "paravirtual");
assertEquals(testing.getOperatingSystem().getDescription(),
"ubuntu-images-testing-us/ubuntu-lucid-daily-amd64-desktop-20100317.manifest.xml");
assertEquals(testing.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(testing.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477",
"rootDeviceType", "instance-store"));
assertEquals(testing.getVersion(), "20100317");
org.jclouds.compute.domain.Image alesticHardy = parser.apply(Iterables.get(result, 4));
assertEquals(alesticHardy.getOperatingSystem().is64Bit(), false);
assertEquals(alesticHardy.getDescription(), "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
assertEquals(alesticHardy.getId(), "us-east-1/ami-c0fa1ea9");
assertEquals(alesticHardy.getProviderId(), "ami-c0fa1ea9");
assertEquals(alesticHardy.getLocation(), defaultLocation);
assertEquals(alesticHardy.getName(), null);
assertEquals(alesticHardy.getOperatingSystem().getName(), null);
assertEquals(alesticHardy.getOperatingSystem().getVersion(), "8.04");
assertEquals(alesticHardy.getOperatingSystem().getArch(), "paravirtual");
assertEquals(alesticHardy.getOperatingSystem().getDescription(),
"alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
assertEquals(alesticHardy.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(alesticHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "063491364108",
"rootDeviceType", "instance-store"));
assertEquals(alesticHardy.getVersion(), "20080905");
org.jclouds.compute.domain.Image ubuntuLucid = parser.apply(Iterables.get(result, 5));
assertEquals(ubuntuLucid.getOperatingSystem().is64Bit(), false);
assertEquals(ubuntuLucid.getDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getId(), "us-east-1/ami-c597c680");
assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680");
assertEquals(ubuntuLucid.getLocation(), defaultLocation);
assertEquals(ubuntuLucid.getName(), null);
assertEquals(ubuntuLucid.getOperatingSystem().getName(), null);
assertEquals(ubuntuLucid.getOperatingSystem().getVersion(), "10.04");
assertEquals(ubuntuLucid.getOperatingSystem().getArch(), "paravirtual");
assertEquals(ubuntuLucid.getOperatingSystem().getDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477",
"rootDeviceType", "instance-store"));
assertEquals(ubuntuLucid.getVersion(), "20100427.1");
// should skip kernel
assert parser.apply(Iterables.get(result, 6)) == null;
org.jclouds.compute.domain.Image ubuntuEbs = parser.apply(Iterables.get(result, 7));
assertEquals(ubuntuEbs.getOperatingSystem().is64Bit(), false);
assertEquals(ubuntuEbs.getDescription(), "099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827");
assertEquals(ubuntuEbs.getId(), "us-east-1/ami-10f3a255");
assertEquals(ubuntuEbs.getProviderId(), "ami-10f3a255");
assertEquals(ubuntuEbs.getLocation(), defaultLocation);
assertEquals(ubuntuEbs.getName(), null);
assertEquals(ubuntuEbs.getOperatingSystem().getName(), null);
assertEquals(ubuntuEbs.getOperatingSystem().getVersion(), "10.04");
assertEquals(ubuntuEbs.getOperatingSystem().getArch(), "paravirtual");
assertEquals(ubuntuEbs.getOperatingSystem().getDescription(),
"099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827");
assertEquals(ubuntuEbs.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuEbs.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477",
"rootDeviceType", "ebs"));
assertEquals(ubuntuEbs.getVersion(), "20100827");
assertEquals(
Iterables.get(result, 6),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.UBUNTU).arch("paravirtual").version("10.04")
.description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827")
.is64Bit(false).build())
.description("099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827")
.defaultCredentials(new Credentials("ubuntu", null)).id("us-east-1/ami-10f3a255")
.providerId("ami-10f3a255").location(defaultLocation).version("20100827")
.userMetadata(ImmutableMap.of("owner", "099720109477", "rootDeviceType", "ebs")).build());
}
private Location defaultLocation = new LocationImpl(LocationScope.REGION, "us-east-1", "us-east-1", null);
public void testParseVostokImage() {
InputStream is = getClass().getResourceAsStream("/ec2/vostok.xml");
Set<Image> result = parseImages(is);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/vostok.xml");
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), false);
assertEquals(image.getDescription(), "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-870de2ee");
assertEquals(image.getProviderId(), "ami-870de2ee");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(),
"vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UNRECOGNIZED);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "133804938231", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), "5622");
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("")
.description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml")
.is64Bit(false).build())
.description("vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml")
.defaultCredentials(new Credentials("root", null)).id("us-east-1/ami-870de2ee")
.providerId("ami-870de2ee").location(defaultLocation).version("5622")
.userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store")).build());
}
public void testParseCCImage() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_images_cc.xml");
Set<Image> result = parseImages(is);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/describe_images_cc.xml");
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "EC2 CentOS 5.4 HVM AMI");
assertEquals(image.getId(), "us-east-1/ami-7ea24a17");
assertEquals(image.getProviderId(), "ami-7ea24a17");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "5.4");
assertEquals(image.getOperatingSystem().getArch(), "hvm");
assertEquals(image.getOperatingSystem().getDescription(), "amazon/EC2 CentOS 5.4 HVM AMI");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.CENTOS);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "206029621532", "rootDeviceType",
"ebs"));
assertEquals(image.getVersion(), null);
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).arch("hvm").version("5.4")
.description("amazon/EC2 CentOS 5.4 HVM AMI").is64Bit(true).build())
.description("EC2 CentOS 5.4 HVM AMI").defaultCredentials(new Credentials("root", null))
.id("us-east-1/ami-7ea24a17").providerId("ami-7ea24a17").location(defaultLocation)
.userMetadata(ImmutableMap.of("owner", "206029621532", "rootDeviceType", "ebs")).build());
}
public void testParseRightScaleImage() {
InputStream is = getClass().getResourceAsStream("/ec2/rightscale_images.xml");
Set<Image> result = parseImages(is);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/rightscale_images.xml");
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-ccb35ea5");
assertEquals(image.getProviderId(), "ami-ccb35ea5");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "5.4");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(),
"rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.CENTOS);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "411009282317", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), "4.4.10");
image = parser.apply(Iterables.get(result, 1));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
assertEquals(image.getId(), "us-east-1/ami-c19db6b5");
assertEquals(image.getProviderId(), "ami-c19db6b5");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "9.10");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(),
"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "411009282317", "rootDeviceType",
"ebs"));
assertEquals(image.getVersion(), "4.5.3_EBS_Alpha");
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).arch("paravirtual").version("5.4")
.description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml").is64Bit(true)
.build()).description("rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml")
.defaultCredentials(new Credentials("root", null)).id("us-east-1/ami-ccb35ea5")
.providerId("ami-ccb35ea5").location(defaultLocation).version("4.4.10")
.userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store")).build());
assertEquals(
new Gson().toJson(Iterables.get(result, 1)),
"{\"operatingSystem\":{\"family\":\"UBUNTU\",\"arch\":\"paravirtual\",\"version\":\"9.10\",\"description\":\"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"is64Bit\":true},\"version\":\"4.5.3_EBS_Alpha\",\"description\":\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-c19db6b5\",\"type\":\"IMAGE\",\"providerId\":\"ami-c19db6b5\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\"},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\"}}");
}
public void testParseEucalyptusImage() {
InputStream is = getClass().getResourceAsStream("/ec2/eucalyptus_images.xml");
Set<Image> result = parseImages(is);
assertEquals(result.size(), 4);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
assertEquals(image.getId(), "us-east-1/emi-9ACB1363");
assertEquals(image.getProviderId(), "emi-9ACB1363");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "5.3");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.CENTOS);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/eucalyptus_images.xml");
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).arch("paravirtual").version("5.3")
.description("centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml").is64Bit(true)
.build()).description("centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml")
.defaultCredentials(new Credentials("root", null)).id("us-east-1/emi-9ACB1363")
.providerId("emi-9ACB1363").location(defaultLocation)
.userMetadata(ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store")).build());
}
public void testParseAmznmage() {
InputStream is = getClass().getResourceAsStream("/ec2/amzn_images.xml");
public void testParseAmznImage() {
Set<Image> result = parseImages(is);
assertEquals(result.size(), 4);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "ec2");
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/amzn_images.xml");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), false);
assertEquals(image.getDescription(), "Amazon");
assertEquals(image.getId(), "us-east-1/ami-82e4b5c7");
assertEquals(image.getProviderId(), "ami-82e4b5c7");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "0.9.7-beta");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "137112412989/amzn-ami-0.9.7-beta.i386-ebs");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "137112412989", "rootDeviceType",
"ebs"));
assertEquals(image.getVersion(), "0.9.7-beta");
image = parser.apply(Iterables.get(result, 1));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "Amazon");
assertEquals(image.getId(), "us-east-1/ami-8ce4b5c9");
assertEquals(image.getProviderId(), "ami-8ce4b5c9");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "0.9.7-beta");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "137112412989/amzn-ami-0.9.7-beta.x86_64-ebs");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "137112412989", "rootDeviceType",
"ebs"));
assertEquals(image.getVersion(), "0.9.7-beta");
image = parser.apply(Iterables.get(result, 2));
assertEquals(image.getOperatingSystem().is64Bit(), false);
assertEquals(image.getDescription(), "Amazon Linux AMI i386 S3");
assertEquals(image.getId(), "us-east-1/ami-f0e4b5b5");
assertEquals(image.getProviderId(), "ami-f0e4b5b5");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "0.9.7-beta");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(),
"amzn-ami-us-west-1/amzn-ami-0.9.7-beta.i386.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "137112412989", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), "0.9.7-beta");
image = parser.apply(Iterables.get(result, 3));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "Amazon Linux AMI x86_64 S3");
assertEquals(image.getId(), "us-east-1/ami-f2e4b5b7");
assertEquals(image.getProviderId(), "ami-f2e4b5b7");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "0.9.7-beta");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(),
"amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "137112412989", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), "0.9.7-beta");
assertEquals(
Iterables.get(result, 0),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.AMZN_LINUX).arch("paravirtual")
.version("0.9.7-beta").description("137112412989/amzn-ami-0.9.7-beta.i386-ebs")
.is64Bit(false).build()).description("Amazon")
.defaultCredentials(new Credentials("ec2-user", null)).id("us-east-1/ami-82e4b5c7")
.providerId("ami-82e4b5c7").location(defaultLocation).version("0.9.7-beta")
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build());
assertEquals(
Iterables.get(result, 3),
new ImageBuilder()
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.AMZN_LINUX).arch("paravirtual")
.version("0.9.7-beta")
.description("amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml").is64Bit(true)
.build()).description("Amazon Linux AMI x86_64 S3")
.defaultCredentials(new Credentials("ec2-user", null)).id("us-east-1/ami-f2e4b5b7")
.providerId("ami-f2e4b5b7").location(defaultLocation).version("0.9.7-beta")
.userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build());
}
public void testParseNovaImage() {
InputStream is = getClass().getResourceAsStream("/ec2/nova_images.xml");
Set<Image> result = parseImages(is);
assertEquals(result.size(), 19);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers
.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers
.ofInstance(defaultLocation), "nebula");
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nasacms/image.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-h30p5im0");
assertEquals(image.getProviderId(), "ami-h30p5im0");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nasacms/image.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "foo", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
assertEquals(parser.apply(Iterables.get(result, 1)), null);
image = parser.apply(Iterables.get(result, 2));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nebula/tiny");
assertEquals(image.getId(), "us-east-1/ami-tiny");
assertEquals(image.getProviderId(), "ami-tiny");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nebula/tiny");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "vishvananda", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 3));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "demos/mediawiki");
assertEquals(image.getId(), "us-east-1/ami-630A130F");
assertEquals(image.getProviderId(), "ami-630A130F");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "demos/mediawiki");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
assertEquals(parser.apply(Iterables.get(result, 4)), null);
assertEquals(parser.apply(Iterables.get(result, 5)), null);
assertEquals(parser.apply(Iterables.get(result, 6)), null);
image = parser.apply(Iterables.get(result, 7));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "pinglet/instances");
assertEquals(image.getId(), "us-east-1/ami-pinginst");
assertEquals(image.getProviderId(), "ami-pinginst");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "pinglet/instances");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 8));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "bucket/testbuntu.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-alqbihe2");
assertEquals(image.getProviderId(), "ami-alqbihe2");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "bucket/testbuntu.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "rkumar2", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 9));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "gfortran-bucket/gfortran.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-i0aemtfp");
assertEquals(image.getProviderId(), "ami-i0aemtfp");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "gfortran-bucket/gfortran.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "ykliu", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
assertEquals(parser.apply(Iterables.get(result, 10)), null);
image = parser.apply(Iterables.get(result, 11));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "grinder/grinder-analyzer.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-2ig7w1bh");
assertEquals(image.getProviderId(), "ami-2ig7w1bh");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "grinder/grinder-analyzer.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "foo", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
assertEquals(parser.apply(Iterables.get(result, 12)), null);
image = parser.apply(Iterables.get(result, 13));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nebula/lucid");
assertEquals(image.getId(), "us-east-1/ami-lucid");
assertEquals(image.getProviderId(), "ami-lucid");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "10.04");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nebula/lucid");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "vishvananda", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 14));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nebula/karmic-large");
assertEquals(image.getId(), "us-east-1/ami-karmiclg");
assertEquals(image.getProviderId(), "ami-karmiclg");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "9.10");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nebula/karmic-large");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 15));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "jo/qa-grinder.manifest.xml");
assertEquals(image.getId(), "us-east-1/ami-8jen8kdn");
assertEquals(image.getProviderId(), "ami-8jen8kdn");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "jo/qa-grinder.manifest.xml");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "jyothi", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 16));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nebula/lucid-large");
assertEquals(image.getId(), "us-east-1/ami-lucidlg");
assertEquals(image.getProviderId(), "ami-lucidlg");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "10.04");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nebula/lucid-large");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "vishvananda", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 17));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "demos/wordpress");
assertEquals(image.getId(), "us-east-1/ami-6CD61336");
assertEquals(image.getProviderId(), "ami-6CD61336");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "demos/wordpress");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
image = parser.apply(Iterables.get(result, 18));
assertEquals(image.getOperatingSystem().is64Bit(), true);
assertEquals(image.getDescription(), "nebula/ubuntu-karmic");
assertEquals(image.getId(), "us-east-1/ami-25CB1213");
assertEquals(image.getProviderId(), "ami-25CB1213");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), null);
assertEquals(image.getOperatingSystem().getName(), null);
assertEquals(image.getOperatingSystem().getVersion(), "9.10");
assertEquals(image.getOperatingSystem().getArch(), "paravirtual");
assertEquals(image.getOperatingSystem().getDescription(), "nebula/ubuntu-karmic");
assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin", "rootDeviceType",
"instance-store"));
assertEquals(image.getVersion(), null);
Set<org.jclouds.compute.domain.Image> result = convertImages("/ec2/nova_images.xml");
assertEquals(
new Gson().toJson(Iterables.get(result, 0)),
"{\"operatingSystem\":{\"arch\":\"paravirtual\",\"version\":\"\",\"description\":\"nasacms/image.manifest.xml\",\"is64Bit\":true},\"description\":\"nasacms/image.manifest.xml\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-h30p5im0\",\"type\":\"IMAGE\",\"providerId\":\"ami-h30p5im0\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\"},\"userMetadata\":{\"owner\":\"foo\",\"rootDeviceType\":\"instance-store\"}}");
assertEquals(
new Gson().toJson(Iterables.get(result, 1)),
"{\"operatingSystem\":{\"arch\":\"paravirtual\",\"version\":\"\",\"description\":\"nebula/tiny\",\"is64Bit\":true},\"description\":\"nebula/tiny\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-tiny\",\"type\":\"IMAGE\",\"providerId\":\"ami-tiny\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\"},\"userMetadata\":{\"owner\":\"vishvananda\",\"rootDeviceType\":\"instance-store\"}}");
assertEquals(
new Gson().toJson(Iterables.get(result, 2)),
"{\"operatingSystem\":{\"arch\":\"paravirtual\",\"version\":\"\",\"description\":\"demos/mediawiki\",\"is64Bit\":true},\"description\":\"demos/mediawiki\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-630A130F\",\"type\":\"IMAGE\",\"providerId\":\"ami-630A130F\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\"},\"userMetadata\":{\"owner\":\"admin\",\"rootDeviceType\":\"instance-store\"}}");
assertEquals(
new Gson().toJson(Iterables.get(result, 3)),
"{\"operatingSystem\":{\"arch\":\"paravirtual\",\"version\":\"\",\"description\":\"pinglet/instances\",\"is64Bit\":true},\"description\":\"pinglet/instances\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-pinginst\",\"type\":\"IMAGE\",\"providerId\":\"ami-pinginst\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\"},\"userMetadata\":{\"owner\":\"admin\",\"rootDeviceType\":\"instance-store\"}}");
}
private Set<Image> parseImages(InputStream is) {
DescribeImagesResponseHandler handler = injector.getInstance(DescribeImagesResponseHandler.class);
addDefaultRegionToHandler(handler);
Set<Image> result = factory.create(handler).parse(is);
return result;
static Location defaultLocation = new LocationImpl(LocationScope.REGION, "us-east-1", "us-east-1", null);
public static Set<org.jclouds.compute.domain.Image> convertImages(String resource) {
Set<Image> result = DescribeImagesResponseHandlerTest.parseImages(resource);
ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(),
Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)),
Suppliers.ofInstance(defaultLocation), "ec2");
return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull()));
}
private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce();
replay(request);
handler.setContext(request);
}
}

View File

@ -23,6 +23,7 @@ import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.c1_medium;
import static org.testng.Assert.assertEquals;
import java.util.NoSuchElementException;
@ -36,14 +37,10 @@ import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.internal.TemplateBuilderImpl;
import org.jclouds.compute.domain.internal.TemplateBuilderImplTest;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
@ -52,8 +49,6 @@ import org.testng.annotations.Test;
import com.google.common.base.Function;
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.MapMaker;
import com.google.common.collect.Sets;
@ -72,22 +67,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) {
Supplier<Set<? extends Location>> locations, Supplier<Set<? extends Image>> images,
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")
@ -96,13 +91,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(new HardwareImpl("1", "1", "region/1", location, null,
ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList
.<Volume> of(), ImagePredicates.any())));
.<Hardware> of(c1_medium().build()));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -134,7 +127,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);
@ -151,12 +144,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(new HardwareImpl("1", "1", "region/1", location, null,
ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList
.<Volume> of(), ImagePredicates.any())));
.<Hardware> of(c1_medium().build()));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -171,7 +162,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;
@ -190,12 +181,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(new HardwareImpl("1", "1", "region/1", location, null,
ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList
.<Volume> of(), ImagePredicates.any())));
.<Hardware> of(c1_medium().build()));
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
@ -213,7 +202,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

@ -31,7 +31,7 @@ import java.util.Set;
import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.compute.EC2ComputeServiceTest;
import org.jclouds.aws.ec2.compute.domain.EC2Hardware;
import org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder;
import org.jclouds.aws.ec2.compute.domain.RegionAndName;
import org.jclouds.aws.ec2.compute.domain.RegionNameAndIngressRules;
import org.jclouds.aws.ec2.compute.functions.CreatePlacementGroupIfNeeded;
@ -41,6 +41,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.options.RunInstancesOptions;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.encryption.internal.Base64;
@ -59,7 +60,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT
// setup constants
String region = Region.AP_SOUTHEAST_1;
String tag = "tag";
EC2Hardware size = EC2Hardware.M1_SMALL;
Hardware size = EC2HardwareBuilder.m1_small().build();
String systemGeneratedKeyPairName = "systemGeneratedKeyPair";
String generatedGroup = "group";
Set<String> generatedGroups = ImmutableSet.of(generatedGroup);
@ -115,7 +116,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT
// setup constants
String region = Region.US_EAST_1;
String tag = "tag";
EC2Hardware size = EC2ComputeServiceTest.CC1_4XLARGE;
Hardware size = EC2ComputeServiceTest.CC1_4XLARGE;
String systemGeneratedKeyPairName = "systemGeneratedKeyPair";
String generatedGroup = "group";
Set<String> generatedGroups = ImmutableSet.of(generatedGroup);
@ -174,7 +175,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT
// setup constants
String region = Region.US_EAST_1;
String tag = "tag";
EC2Hardware size = EC2ComputeServiceTest.CC1_4XLARGE;
Hardware size = EC2ComputeServiceTest.CC1_4XLARGE;
String systemGeneratedKeyPairName = "systemGeneratedKeyPair";
String generatedGroup = "group";
Set<String> generatedGroups = ImmutableSet.of(generatedGroup);
@ -233,7 +234,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT
// setup constants
String region = Region.AP_SOUTHEAST_1;
String tag = "tag";
EC2Hardware size = EC2Hardware.M1_SMALL;
Hardware size = EC2HardwareBuilder.m1_small().build();
String systemGeneratedKeyPairName = "systemGeneratedKeyPair";
// create mocks
@ -286,7 +287,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT
// setup constants
String region = Region.AP_SOUTHEAST_1;
String tag = "tag";
EC2Hardware size = EC2Hardware.M1_SMALL;
Hardware size = EC2HardwareBuilder.m1_small().build();
String systemGeneratedKeyPairName = "systemGeneratedKeyPair";
String generatedGroup = "group";
Set<String> generatedGroups = ImmutableSet.of(generatedGroup);

View File

@ -32,7 +32,6 @@ import java.util.Set;
import org.easymock.IArgumentMatcher;
import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.EC2Client;
import org.jclouds.aws.ec2.compute.domain.EC2Hardware;
import org.jclouds.aws.ec2.compute.functions.RunningInstanceToNodeMetadata;
import org.jclouds.aws.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.aws.ec2.domain.AvailabilityZone;
@ -40,15 +39,18 @@ import org.jclouds.aws.ec2.domain.Reservation;
import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.aws.ec2.options.RunInstancesOptions;
import org.jclouds.aws.ec2.services.InstanceClient;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@ -90,7 +92,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
return null;
}
@SuppressWarnings({ "unchecked"})
@SuppressWarnings({ "unchecked" })
private void assertRegionAndZoneForLocation(Location location, String region, String zone) {
String imageId = "ami1";
String instanceCreatedId = "instance1";
@ -100,29 +102,36 @@ public class EC2RunNodesAndAddToSetStrategyTest {
InstanceClient instanceClient = createMock(InstanceClient.class);
RunInstancesOptions ec2Options = createMock(RunInstancesOptions.class);
RunningInstance instance = createMock(RunningInstance.class);
Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region, ImmutableSet
.<String> of(), ImmutableSet.<RunningInstance> of(instance), "ownerId", "requesterId", "reservationId");
Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region,
ImmutableSet.<String> of(), ImmutableSet.<RunningInstance> of(instance), "ownerId", "requesterId",
"reservationId");
NodeMetadata nodeMetadata = createMock(NodeMetadata.class);
// setup expectations
expect(strategy.client.getInstanceServices()).andReturn(instanceClient).atLeastOnce();
expect(
strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag,
input.template)).andReturn(ec2Options);
strategy.createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.execute(region, input.tag,
input.template)).andReturn(ec2Options);
expect(input.template.getLocation()).andReturn(input.location).atLeastOnce();
expect(input.template.getImage()).andReturn(input.image).atLeastOnce();
expect(input.image.getProviderId()).andReturn(imageId).atLeastOnce();
expect(instanceClient.runInstancesInRegion(region, zone, imageId, 1, input.count, ec2Options)).andReturn(
(Reservation) reservation);
(Reservation) reservation);
expect(instance.getId()).andReturn(instanceCreatedId).atLeastOnce();
// simulate a lazy credentials fetch
Credentials creds = new Credentials("foo","bar");
expect(strategy.instanceToCredentials.apply(instance)).andReturn(creds);
expect(instance.getRegion()).andReturn(region);
expect(strategy.credentialStore.put(region + "/" + instanceCreatedId, creds)).andReturn(null);
expect(strategy.instancePresent.apply(instance)).andReturn(true);
expect(input.template.getOptions()).andReturn(input.options).atLeastOnce();
expect(input.options.isMonitoringEnabled()).andReturn(false);
expect(strategy.runningInstanceToNodeMetadata.apply(instance)).andReturn(nodeMetadata);
expect(
strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options),
containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null);
strategy.utils.runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(eq(input.options),
containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes))).andReturn(null);
// replay mocks
replay(instanceClient);
@ -145,9 +154,9 @@ public class EC2RunNodesAndAddToSetStrategyTest {
}
private static final Location REGION_AP_SOUTHEAST_1 = new LocationImpl(LocationScope.REGION, Region.AP_SOUTHEAST_1,
Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null));
Region.AP_SOUTHEAST_1, new LocationImpl(LocationScope.PROVIDER, "ec2", "ec2", null));
private static final Location ZONE_AP_SOUTHEAST_1A = new LocationImpl(LocationScope.ZONE,
AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1);
AvailabilityZone.AP_SOUTHEAST_1A, AvailabilityZone.AP_SOUTHEAST_1A, REGION_AP_SOUTHEAST_1);
// /////////////////////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
@ -157,7 +166,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
Template template = createMock(Template.class);
Set<NodeMetadata> nodes = createMock(Set.class);
Map<NodeMetadata, Exception> badNodes = createMock(Map.class);
EC2Hardware size = createMock(EC2Hardware.class);
Hardware hardware = createMock(Hardware.class);
Image image = createMock(Image.class);
final Location location;
EC2TemplateOptions options = createMock(EC2TemplateOptions.class);
@ -168,7 +177,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
void replayMe() {
replay(template);
replay(size);
replay(hardware);
replay(image);
replay(nodes);
replay(badNodes);
@ -177,7 +186,7 @@ public class EC2RunNodesAndAddToSetStrategyTest {
void verifyMe() {
verify(template);
verify(size);
verify(hardware);
verify(image);
verify(nodes);
verify(badNodes);
@ -190,6 +199,8 @@ public class EC2RunNodesAndAddToSetStrategyTest {
verify(strategy.client);
verify(strategy.instancePresent);
verify(strategy.runningInstanceToNodeMetadata);
verify(strategy.instanceToCredentials);
verify(strategy.credentialStore);
verify(strategy.utils);
}
@ -199,9 +210,11 @@ public class EC2RunNodesAndAddToSetStrategyTest {
CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions = createMock(CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class);
Predicate<RunningInstance> instanceStateRunning = createMock(Predicate.class);
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata = createMock(RunningInstanceToNodeMetadata.class);
Function<RunningInstance, Credentials> instanceToCredentials = createMock(Function.class);
Map<String, Credentials> credentialStore = createMock(Map.class);
ComputeUtils utils = createMock(ComputeUtils.class);
return new EC2RunNodesAndAddToSetStrategy(client, createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions,
instanceStateRunning, runningInstanceToNodeMetadata, utils);
instanceStateRunning, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils);
}
private void replayStrategy(EC2RunNodesAndAddToSetStrategy strategy) {
@ -209,6 +222,8 @@ public class EC2RunNodesAndAddToSetStrategyTest {
replay(strategy.client);
replay(strategy.instancePresent);
replay(strategy.runningInstanceToNodeMetadata);
replay(strategy.instanceToCredentials);
replay(strategy.credentialStore);
replay(strategy.utils);
}

View File

@ -19,26 +19,29 @@
package org.jclouds.aws.ec2.xml;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.util.Set;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.compute.functions.ImageParserTest;
import org.jclouds.aws.ec2.domain.Image;
import org.jclouds.aws.ec2.domain.RootDeviceType;
import org.jclouds.aws.ec2.domain.Image.Architecture;
import org.jclouds.aws.ec2.domain.Image.EbsBlockDevice;
import org.jclouds.aws.ec2.domain.Image.ImageState;
import org.jclouds.aws.ec2.domain.Image.ImageType;
import org.jclouds.aws.ec2.domain.RootDeviceType;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.http.functions.config.SaxParserModule;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code DescribeImagesResponseHandler}
@ -46,67 +49,58 @@ import com.google.common.collect.Sets;
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ec2.DescribeImagesResponseHandlerTest")
public class DescribeImagesResponseHandlerTest extends BaseEC2HandlerTest {
public class DescribeImagesResponseHandlerTest {
public void testUNIX() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_images.xml");
Set<Image> contents = Sets.newLinkedHashSet();
Set<Image> contents = ImmutableSet.of(new Image("us-east-1", Architecture.I386, null, null, "ami-be3adfd7",
"ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml", "206029621532", ImageState.AVAILABLE,
ImageType.MACHINE, false, Sets.<String> newHashSet("9961934F"), "aki-4438dd2d", null, "ari-4538dd2c",
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(), "paravirtual"));
contents.add(new Image(defaultRegion, Architecture.I386, null, null, "ami-be3adfd7",
"ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml", "206029621532",
ImageState.AVAILABLE, ImageType.MACHINE, false,
Sets.<String> newHashSet("9961934F"), "aki-4438dd2d", null, "ari-4538dd2c",
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(),"paravirtual"));
Set<Image> result = parseImages(is);
Set<Image> result = parseImages("/ec2/describe_images.xml");
assertEquals(result, contents);
}
public void testWindows() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_images_windows.xml");
Set<Image> contents = Sets.newLinkedHashSet();
Set<Image> contents = ImmutableSet.of(new Image("us-east-1", Architecture.X86_64, null, null, "ami-02eb086b",
"aws-solutions-amis/SqlSvrStd2003r2-x86_64-Win_SFWBasic5.1-v1.0.manifest.xml", "771350841976",
ImageState.AVAILABLE, ImageType.MACHINE, true, Sets.<String> newHashSet("5771E9A6"), null, "windows", null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(), "paravirtual"));
contents.add(new Image(defaultRegion, Architecture.X86_64, null, null, "ami-02eb086b",
"aws-solutions-amis/SqlSvrStd2003r2-x86_64-Win_SFWBasic5.1-v1.0.manifest.xml",
"771350841976", ImageState.AVAILABLE, ImageType.MACHINE, true, Sets
.<String> newHashSet("5771E9A6"), null, "windows", null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(),"paravirtual"));
Set<Image> result = parseImages(is);
Set<Image> result = parseImages("/ec2/describe_images_windows.xml");
assertEquals(result, contents);
}
public void testEBS() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_images_ebs.xml");
Set<Image> contents = Sets.newLinkedHashSet();
Set<Image> contents = ImmutableSet.of(new Image("us-east-1", Architecture.I386, "websrv_2009-12-10",
"Web Server AMI", "ami-246f8d4d", "706093390852/websrv_2009-12-10", "706093390852", ImageState.AVAILABLE,
ImageType.MACHINE, true, Sets.<String> newHashSet(), null, "windows", null, RootDeviceType.EBS,
"/dev/sda1", ImmutableMap.<String, EbsBlockDevice> of("/dev/sda1", new EbsBlockDevice("snap-d01272b9", 30,
true), "xvdf", new EbsBlockDevice("snap-d31272ba", 250, false)), "hvm"));
contents.add(new Image(defaultRegion, Architecture.I386, "websrv_2009-12-10",
"Web Server AMI", "ami-246f8d4d", "706093390852/websrv_2009-12-10", "706093390852",
ImageState.AVAILABLE, ImageType.MACHINE, true, Sets.<String> newHashSet(), null,
"windows", null, RootDeviceType.EBS, "/dev/sda1", ImmutableMap
.<String, EbsBlockDevice> of("/dev/sda1", new EbsBlockDevice(
"snap-d01272b9", 30, true), "xvdf", new EbsBlockDevice(
"snap-d31272ba", 250, false)),"hvm"));
Set<Image> result = parseImages(is);
Set<Image> result = parseImages("/ec2/describe_images_ebs.xml");
assertEquals(result, contents);
}
private Set<Image> parseImages(InputStream is) {
DescribeImagesResponseHandler handler = injector
.getInstance(DescribeImagesResponseHandler.class);
addDefaultRegionToHandler(handler);
Set<Image> result = factory.create(handler).parse(is);
return result;
static ParseSax<Set<Image>> createParser() {
Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Region.class).toInstance("us-east-1");
}
});
ParseSax<Set<Image>> parser = (ParseSax<Set<Image>>) injector.getInstance(ParseSax.Factory.class).create(
injector.getInstance(DescribeImagesResponseHandler.class));
return parser;
}
private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
expect(request.getArgs()).andReturn(new Object[] { null });
replay(request);
handler.setContext(request);
public static Set<Image> parseImages(String resource) {
InputStream is = ImageParserTest.class.getResourceAsStream(resource);
return createParser().parse(is);
}
}

View File

@ -19,15 +19,13 @@
package org.jclouds.aws.ec2.xml;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Set;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.domain.Attachment;
import org.jclouds.aws.ec2.domain.AvailabilityZone;
import org.jclouds.aws.ec2.domain.InstanceState;
@ -39,13 +37,16 @@ import org.jclouds.aws.ec2.domain.RunningInstance;
import org.jclouds.aws.ec2.domain.RunningInstance.EbsBlockDevice;
import org.jclouds.date.DateService;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.http.functions.config.SaxParserModule;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code DescribeInstancesResponseHandler}
@ -67,47 +68,45 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest {
public void testWhenRunning() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/ec2/describe_instances_running.xml");
Set<Reservation<? extends RunningInstance>> contents = Sets.newLinkedHashSet();
contents.add(new Reservation<RunningInstance>(defaultRegion, ImmutableSet.of("adriancole.ec2ingress"),
ImmutableSet.of(new RunningInstance(defaultRegion, ImmutableSet.of("adriancole.ec2ingress"), "0",
"ec2-174-129-81-68.compute-1.amazonaws.com", "ami-1fd73376", "i-0799056f",
InstanceState.RUNNING, InstanceType.M1_SMALL, "174.129.81.68", "aki-a71cf9ce",
"adriancole.ec21", dateService.iso8601DateParse("2009-11-09T03:00:34.000Z"),
MonitoringState.DISABLED, AvailabilityZone.US_EAST_1C, null, "paravirtual", null,
"ip-10-243-42-70.ec2.internal", "10.243.42.70", ImmutableSet.<String> of(), "ari-a51cf9cc",
null, null, null, null, RootDeviceType.INSTANCE_STORE, null, ImmutableMap
.<String, EbsBlockDevice> of())), "993194456877", null, "r-a3c508cb"));
ImmutableSet.of(new RunningInstance(defaultRegion, ImmutableSet.of("adriancole.ec2ingress"), "0",
"ec2-174-129-81-68.compute-1.amazonaws.com", "ami-1fd73376", "i-0799056f", InstanceState.RUNNING,
InstanceType.M1_SMALL, "174.129.81.68", "aki-a71cf9ce", "adriancole.ec21", dateService
.iso8601DateParse("2009-11-09T03:00:34.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1C, null, "paravirtual", null, "ip-10-243-42-70.ec2.internal",
"10.243.42.70", ImmutableSet.<String> of(), "ari-a51cf9cc", null, null, null, null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of())), "993194456877",
null, "r-a3c508cb"));
Set<Reservation<? extends RunningInstance>> result = getReservations(is);
Set<Reservation<? extends RunningInstance>> result = parseRunningInstances("/ec2/describe_instances_running.xml");
assertEquals(result, contents);
}
public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_instances.xml");
Set<Reservation<? extends RunningInstance>> contents = Sets.newLinkedHashSet();
contents.add(new Reservation<RunningInstance>(defaultRegion, ImmutableSet.of("default"), ImmutableSet.of(
new RunningInstance(defaultRegion, ImmutableSet.of("default"), "23",
"ec2-72-44-33-4.compute-1.amazonaws.com", "ami-6ea54007", "i-28a64341", InstanceState.RUNNING,
InstanceType.M1_LARGE, (String) null, "aki-ba3adfd3", "example-key-name", dateService
.iso8601DateParse("2007-08-07T11:54:42.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1B, null, "paravirtual", null, "10-251-50-132.ec2.internal", null,
ImmutableSet.of("774F4FF8"), "ari-badbad00", null, null, null, null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of()),
new RunningInstance(defaultRegion, ImmutableSet.of("default"), "23",
"ec2-72-44-33-6.compute-1.amazonaws.com", "ami-6ea54007", "i-28a64435", InstanceState.RUNNING,
InstanceType.M1_LARGE, (String) null, "aki-ba3adfd3", "example-key-name", dateService
.iso8601DateParse("2007-08-07T11:54:42.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1B, null, "paravirtual", null, "10-251-50-134.ec2.internal", null,
ImmutableSet.of("774F4FF8"), "ari-badbad00", null, null, null, null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of())),
"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", null, "r-44a5402d"));
new RunningInstance(defaultRegion, ImmutableSet.of("default"), "23",
"ec2-72-44-33-4.compute-1.amazonaws.com", "ami-6ea54007", "i-28a64341", InstanceState.RUNNING,
InstanceType.M1_LARGE, (String) null, "aki-ba3adfd3", "example-key-name", dateService
.iso8601DateParse("2007-08-07T11:54:42.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1B, null, "paravirtual", null, "10-251-50-132.ec2.internal", null,
ImmutableSet.of("774F4FF8"), "ari-badbad00", null, null, null, null, RootDeviceType.INSTANCE_STORE,
null, ImmutableMap.<String, EbsBlockDevice> of()),
new RunningInstance(defaultRegion, ImmutableSet.of("default"), "23",
"ec2-72-44-33-6.compute-1.amazonaws.com", "ami-6ea54007", "i-28a64435", InstanceState.RUNNING,
InstanceType.M1_LARGE, (String) null, "aki-ba3adfd3", "example-key-name", dateService
.iso8601DateParse("2007-08-07T11:54:42.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1B, null, "paravirtual", null, "10-251-50-134.ec2.internal", null,
ImmutableSet.of("774F4FF8"), "ari-badbad00", null, null, null, null, RootDeviceType.INSTANCE_STORE,
null, ImmutableMap.<String, EbsBlockDevice> of())), "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", null,
"r-44a5402d"));
Set<Reservation<? extends RunningInstance>> result = getReservations(is);
Set<Reservation<? extends RunningInstance>> result = parseRunningInstances("/ec2/describe_instances.xml");
assertEquals(result, contents);
}
@ -116,73 +115,75 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest {
// TODO not sure why equals fails
public void testApplyInputStreamEuc() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_instances_euc.xml");
Set<Reservation<? extends RunningInstance>> contents = Sets.newLinkedHashSet();
contents.add(new Reservation<RunningInstance>(defaultRegion, ImmutableSet.of("default"), ImmutableSet
.of(new RunningInstance(defaultRegion, ImmutableSet.of("jclouds#euc"), "1", null, "emi-9ACB1363",
"i-3FFA0762", InstanceState.SHUTTING_DOWN, InstanceType.M1_LARGE, null, "eki-6CBD12F2",
"jclouds#euc-17", dateService.iso8601DateParse("2010-06-16T03:06:19.000Z"),
MonitoringState.DISABLED, "open", null, "paravirtual", null, "10.7.0.179", null, ImmutableSet
.<String> of(), "eri-A97113E4", null, null, null, null, RootDeviceType.INSTANCE_STORE,
null, ImmutableMap.<String, EbsBlockDevice> of())), "jclouds", null, "r-4D2A08AD"));
.of(new RunningInstance(defaultRegion, ImmutableSet.of("jclouds#euc"), "1", null, "emi-9ACB1363",
"i-3FFA0762", InstanceState.SHUTTING_DOWN, InstanceType.M1_LARGE, null, "eki-6CBD12F2",
"jclouds#euc-17", dateService.iso8601DateParse("2010-06-16T03:06:19.000Z"), MonitoringState.DISABLED,
"open", null, "paravirtual", null, "10.7.0.179", null, ImmutableSet.<String> of(), "eri-A97113E4",
null, null, null, null, RootDeviceType.INSTANCE_STORE, null, ImmutableMap
.<String, EbsBlockDevice> of())), "jclouds", null, "r-4D2A08AD"));
Set<Reservation<? extends RunningInstance>> result = getReservations(is);
Set<Reservation<? extends RunningInstance>> result = parseRunningInstances("/ec2/describe_instances_euc.xml");
assertEquals(result, contents);
}
public void testApplyInputStreamNovaNoAvailabilityZone() {
InputStream is = getClass().getResourceAsStream("/ec2/describe_instances_nova.xml");
Set<Reservation<? extends RunningInstance>> contents = Sets.newLinkedHashSet();
contents.add(new Reservation<RunningInstance>(defaultRegion, ImmutableSet.of("default"), ImmutableSet
.of(new RunningInstance(defaultRegion, ImmutableSet.<String> of(), "0", null, "ami-h30p5im0",
"i-9slweygo", InstanceState.TERMINATED, InstanceType.M1_SMALL, null, null, "nebulatanimislam",
dateService.iso8601SecondsDateParse("2010-09-09T18:09:42Z"), null, null, null, "paravirtual",
null, null, "10.128.207.5", ImmutableSet.<String> of("None"), null, null, null, null, null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of())), "tislam1",
null, "r-opqeylmj"));
.of(new RunningInstance(defaultRegion, ImmutableSet.<String> of(), "0", null, "ami-25CB1213", "i-9slweygo",
InstanceState.TERMINATED, InstanceType.M1_SMALL, null, null, "nebulatanimislam", dateService
.iso8601SecondsDateParse("2010-09-09T18:09:42Z"), null, null, null, "paravirtual", null, null,
"10.128.207.5", ImmutableSet.<String> of("None"), null, null, null, null, null,
RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of())), "tislam1", null,
"r-opqeylmj"));
Set<Reservation<? extends RunningInstance>> result = getReservations(is);
Set<Reservation<? extends RunningInstance>> result = parseRunningInstances("/ec2/describe_instances_nova.xml");
assertEquals(result, contents);
}
public void testEBS() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/ec2/describe_instances_ebs.xml");
Set<Reservation<? extends RunningInstance>> contents = Sets.newLinkedHashSet();
contents.add(new Reservation<RunningInstance>(defaultRegion, ImmutableSet.of("adriancole.ec2ebsingress"),
ImmutableSet.of(new RunningInstance(defaultRegion, ImmutableSet.of("adriancole.ec2ebsingress"), "0",
"ec2-75-101-203-146.compute-1.amazonaws.com", "ami-849875ed", "i-e564438d",
InstanceState.RUNNING, InstanceType.M1_SMALL, "75.101.203.146", "aki-a71cf9ce",
"adriancole.ec2ebs1", dateService.iso8601DateParse("2009-12-30T04:06:23.000Z"),
MonitoringState.DISABLED, AvailabilityZone.US_EAST_1B, "placement", "hvm", null,
"domU-12-31-39-09-CE-53.compute-1.internal", "10.210.209.157", ImmutableSet.<String> of(),
"ari-a51cf9cc", null, null, null, null, RootDeviceType.EBS, "/dev/sda1", ImmutableMap
.<String, EbsBlockDevice> of("/dev/sda1", new EbsBlockDevice("vol-dc6ca8b5",
Attachment.Status.ATTACHED, dateService
.iso8601DateParse("2009-12-30T04:06:29.000Z"), true)))),
"993194456877", null, "r-596dd731"));
ImmutableSet.of(new RunningInstance(defaultRegion, ImmutableSet.of("adriancole.ec2ebsingress"), "0",
"ec2-75-101-203-146.compute-1.amazonaws.com", "ami-849875ed", "i-e564438d", InstanceState.RUNNING,
InstanceType.M1_SMALL, "75.101.203.146", "aki-a71cf9ce", "adriancole.ec2ebs1", dateService
.iso8601DateParse("2009-12-30T04:06:23.000Z"), MonitoringState.DISABLED,
AvailabilityZone.US_EAST_1B, "placement", "hvm", null, "domU-12-31-39-09-CE-53.compute-1.internal",
"10.210.209.157", ImmutableSet.<String> of(), "ari-a51cf9cc", null, null, null, null,
RootDeviceType.EBS, "/dev/sda1", ImmutableMap.<String, EbsBlockDevice> of(
"/dev/sda1",
new EbsBlockDevice("vol-dc6ca8b5", Attachment.Status.ATTACHED, dateService
.iso8601DateParse("2009-12-30T04:06:29.000Z"), true)))), "993194456877", null,
"r-596dd731"));
Set<Reservation<? extends RunningInstance>> result = getReservations(is);
Set<Reservation<? extends RunningInstance>> result = parseRunningInstances("/ec2/describe_instances_ebs.xml");
assertEquals(result, contents);
}
private Set<Reservation<? extends RunningInstance>> getReservations(InputStream is) {
DescribeInstancesResponseHandler handler = injector.getInstance(DescribeInstancesResponseHandler.class);
addDefaultRegionToHandler(handler);
Set<Reservation<? extends RunningInstance>> result = factory.create(handler).parse(is);
return result;
static ParseSax<Set<Reservation<? extends RunningInstance>>> createParser() {
Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Region.class).toInstance("us-east-1");
}
});
ParseSax<Set<Reservation<? extends RunningInstance>>> parser = (ParseSax<Set<Reservation<? extends RunningInstance>>>) injector
.getInstance(ParseSax.Factory.class).create(injector.getInstance(DescribeInstancesResponseHandler.class));
return parser;
}
private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
expect(request.getArgs()).andReturn(new Object[] { null }).atLeastOnce();
replay(request);
handler.setContext(request);
public static Set<Reservation<? extends RunningInstance>> parseRunningInstances(String resource) {
InputStream is = DescribeInstancesResponseHandlerTest.class.getResourceAsStream(resource);
return createParser().parse(is);
}
}

View File

@ -11,7 +11,7 @@
<dnsName />
<launchTime>2010-09-09T18:09:42Z</launchTime>
<instanceId>i-9slweygo</instanceId>
<imageId>ami-h30p5im0</imageId>
<imageId>ami-25CB1213</imageId>
<instanceState>
<code>1</code>
<name>shutdown</name>

View File

@ -19,6 +19,8 @@
package org.jclouds.blobstore.domain.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable;
import java.net.URI;
import java.util.Date;
@ -47,12 +49,57 @@ public class StorageMetadataImpl extends ResourceMetadataImpl<StorageType> imple
@Nullable
private final Date lastModified;
private final StorageType type;
public StorageMetadataImpl(StorageType type, @Nullable String id, @Nullable String name,
@Nullable Location location, @Nullable URI uri, @Nullable String eTag, @Nullable Date lastModified,
Map<String, String> userMetadata) {
super(type, id, name, location, uri, userMetadata);
@Nullable Location location, @Nullable URI uri, @Nullable String eTag, @Nullable Date lastModified,
Map<String, String> userMetadata) {
super(id, name, location, uri, userMetadata);
this.eTag = eTag;
this.lastModified = lastModified;
this.type = checkNotNull(type, "type");
}
/**
* {@inheritDoc}
*/
@Override
public StorageType getType() {
return type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((eTag == null) ? 0 : eTag.hashCode());
result = prime * result + ((lastModified == null) ? 0 : lastModified.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
StorageMetadataImpl other = (StorageMetadataImpl) obj;
if (eTag == null) {
if (other.eTag != null)
return false;
} else if (!eTag.equals(other.eTag))
return false;
if (lastModified == null) {
if (other.lastModified != null)
return false;
} else if (!lastModified.equals(other.lastModified))
return false;
if (type != other.type)
return false;
return true;
}
/**

View File

@ -19,9 +19,13 @@
package org.jclouds.compute;
import java.util.Map;
import org.jclouds.compute.internal.ComputeServiceContextImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.rest.RestContext;
import com.google.common.annotations.Beta;
import com.google.inject.ImplementedBy;
/**
@ -44,6 +48,18 @@ public interface ComputeServiceContext {
<S, A> RestContext<S, A> getProviderSpecificContext();
/**
* retrieves a list of credentials for resources created within this context, keyed on {@code id}
* of the resource. We are testing this approach for resources such as compute nodes, where you
* could access this externally.
*
*/
@Beta
Map<String, Credentials> getCredentialStore();
@Beta
Map<String, Credentials> credentialStore();
Utils getUtils();
/**

View File

@ -0,0 +1,90 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import org.jclouds.compute.domain.internal.ComputeMetadataImpl;
import org.jclouds.domain.Location;
import org.jclouds.domain.ResourceMetadataBuilder;
/**
*
* @author Adrian Cole
*/
public class ComputeMetadataBuilder extends ResourceMetadataBuilder<ComputeType> {
protected String id;
protected ComputeType type;
public ComputeMetadataBuilder(ComputeType type) {
super();
this.type = checkNotNull(type, "type");
}
public ComputeMetadataBuilder id(String id) {
this.id = id;
return this;
}
/**
* set id and providerId to the same value;
*/
public ComputeMetadataBuilder ids(String id) {
id(id).providerId(id);
return this;
}
@Override
public ComputeMetadataBuilder providerId(String providerId) {
return ComputeMetadataBuilder.class.cast(super.providerId(providerId));
}
@Override
public ComputeMetadataBuilder name(String name) {
return ComputeMetadataBuilder.class.cast(super.name(name));
}
@Override
public ComputeMetadataBuilder location(Location location) {
return ComputeMetadataBuilder.class.cast(super.location(location));
}
@Override
public ComputeMetadataBuilder uri(URI uri) {
return ComputeMetadataBuilder.class.cast(super.uri(uri));
}
@Override
public ComputeMetadataBuilder userMetadata(Map<String, String> userMetadata) {
return ComputeMetadataBuilder.class.cast(super.userMetadata(userMetadata));
}
public ComputeMetadata build() {
return new ComputeMetadataImpl(type, providerId, name, id, location, uri, userMetadata);
}
public static ComputeMetadataBuilder fromComputeMetadata(ComputeMetadata in) {
return new ComputeMetadataBuilder(in.getType()).id(in.getId()).location(in.getLocation()).name(in.getName())
.uri(in.getUri()).userMetadata(in.getUserMetadata());
}
}

View File

@ -0,0 +1,124 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.not;
import static org.jclouds.compute.predicates.ImagePredicates.any;
import java.net.URI;
import java.util.List;
import java.util.Map;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.domain.Location;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
/**
*
* @author Adrian Cole
*/
public class HardwareBuilder extends ComputeMetadataBuilder {
private List<Processor> processors = Lists.newArrayList();
private int ram;
private List<Volume> volumes = Lists.newArrayList();
private Predicate<Image> supportsImage = any();
public HardwareBuilder() {
super(ComputeType.HARDWARE);
}
public HardwareBuilder processors(List<Processor> processors) {
this.processors = checkNotNull(processors, "processors");
return this;
}
public HardwareBuilder ram(int ram) {
this.ram = ram;
return this;
}
public HardwareBuilder volumes(List<Volume> volumes) {
this.volumes = checkNotNull(volumes, "volumes");
return this;
}
public HardwareBuilder supportsImage(Predicate<Image> supportsImage) {
this.supportsImage = checkNotNull(supportsImage, "supportsImage");
return this;
}
public HardwareBuilder is64Bit(boolean is64Bit) {
supportsImage(is64Bit ? ImagePredicates.is64Bit() : not(ImagePredicates.is64Bit()));
return this;
}
@Override
public HardwareBuilder id(String id) {
return HardwareBuilder.class.cast(super.id(id));
}
@Override
public HardwareBuilder ids(String id) {
return HardwareBuilder.class.cast(super.ids(id));
}
@Override
public HardwareBuilder providerId(String providerId) {
return HardwareBuilder.class.cast(super.providerId(providerId));
}
@Override
public HardwareBuilder name(String name) {
return HardwareBuilder.class.cast(super.name(name));
}
@Override
public HardwareBuilder location(Location location) {
return HardwareBuilder.class.cast(super.location(location));
}
@Override
public HardwareBuilder uri(URI uri) {
return HardwareBuilder.class.cast(super.uri(uri));
}
@Override
public HardwareBuilder userMetadata(Map<String, String> userMetadata) {
return HardwareBuilder.class.cast(super.userMetadata(userMetadata));
}
@Override
public Hardware build() {
return new HardwareImpl(providerId, name, id, location, uri, userMetadata, processors, ram, volumes,
supportsImage);
}
@SuppressWarnings("unchecked")
public static HardwareBuilder fromHardware(Hardware in) {
return new HardwareBuilder().id(in.getId()).providerId(in.getProviderId()).location(in.getLocation())
.name(in.getName()).uri(in.getUri()).userMetadata(in.getUserMetadata())
.processors(List.class.cast(in.getProcessors())).ram(in.getRam()).volumes(List.class.cast(in.getVolumes()))
.supportsImage(in.supportsImage());
}
}

View File

@ -0,0 +1,107 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
/**
* @author Adrian Cole
*/
public class ImageBuilder extends ComputeMetadataBuilder {
private OperatingSystem operatingSystem;
private String version;
private String description;
private Credentials defaultCredentials;
public ImageBuilder() {
super(ComputeType.IMAGE);
}
public ImageBuilder operatingSystem(OperatingSystem operatingSystem) {
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
return this;
}
public ImageBuilder version(@Nullable String version) {
this.version = version;
return this;
}
public ImageBuilder description(String description) {
this.description = checkNotNull(description, "description");
return this;
}
public ImageBuilder defaultCredentials(@Nullable Credentials defaultCredentials) {
this.defaultCredentials = defaultCredentials;
return this;
}
@Override
public ImageBuilder id(String id) {
return ImageBuilder.class.cast(super.id(id));
}
@Override
public ImageBuilder ids(String id) {
return ImageBuilder.class.cast(super.ids(id));
}
@Override
public ImageBuilder providerId(String providerId) {
return ImageBuilder.class.cast(super.providerId(providerId));
}
@Override
public ImageBuilder name(String name) {
return ImageBuilder.class.cast(super.name(name));
}
@Override
public ImageBuilder location(Location location) {
return ImageBuilder.class.cast(super.location(location));
}
@Override
public ImageBuilder uri(URI uri) {
return ImageBuilder.class.cast(super.uri(uri));
}
@Override
public ImageBuilder userMetadata(Map<String, String> userMetadata) {
return ImageBuilder.class.cast(super.userMetadata(userMetadata));
}
@Override
public Image build() {
return new ImageImpl(providerId, name, id, location, uri, userMetadata, operatingSystem, description, version,
defaultCredentials);
}
}

View File

@ -0,0 +1,148 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class NodeMetadataBuilder extends ComputeMetadataBuilder {
private NodeState state;
private Set<String> publicAddresses = Sets.newLinkedHashSet();
private Set<String> privateAddresses = Sets.newLinkedHashSet();
@Nullable
private Credentials credentials;
@Nullable
private String tag;
@Nullable
private String imageId;
@Nullable
private Hardware hardware;
@Nullable
private OperatingSystem os;
public NodeMetadataBuilder() {
super(ComputeType.NODE);
}
public NodeMetadataBuilder state(NodeState state) {
this.state = checkNotNull(state, "state");
return this;
}
public NodeMetadataBuilder publicAddresses(Iterable<String> publicAddresses) {
this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses"));
return this;
}
public NodeMetadataBuilder privateAddresses(Iterable<String> privateAddresses) {
this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses"));
return this;
}
public NodeMetadataBuilder credentials(@Nullable Credentials credentials) {
this.credentials = credentials;
return this;
}
public NodeMetadataBuilder tag(@Nullable String tag) {
this.tag = tag;
return this;
}
public NodeMetadataBuilder imageId(@Nullable String imageId) {
this.imageId = imageId;
return this;
}
public NodeMetadataBuilder hardware(@Nullable Hardware hardware) {
this.hardware = hardware;
return this;
}
public NodeMetadataBuilder operatingSystem(@Nullable OperatingSystem os) {
this.os = os;
return this;
}
@Override
public NodeMetadataBuilder id(String id) {
return NodeMetadataBuilder.class.cast(super.id(id));
}
@Override
public NodeMetadataBuilder ids(String id) {
return NodeMetadataBuilder.class.cast(super.ids(id));
}
@Override
public NodeMetadataBuilder providerId(String providerId) {
return NodeMetadataBuilder.class.cast(super.providerId(providerId));
}
@Override
public NodeMetadataBuilder name(String name) {
return NodeMetadataBuilder.class.cast(super.name(name));
}
@Override
public NodeMetadataBuilder location(Location location) {
return NodeMetadataBuilder.class.cast(super.location(location));
}
@Override
public NodeMetadataBuilder uri(URI uri) {
return NodeMetadataBuilder.class.cast(super.uri(uri));
}
@Override
public NodeMetadataBuilder userMetadata(Map<String, String> userMetadata) {
return NodeMetadataBuilder.class.cast(super.userMetadata(userMetadata));
}
@Override
public NodeMetadata build() {
return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tag, hardware, imageId, os, state,
publicAddresses, privateAddresses, credentials);
}
public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) {
return new NodeMetadataBuilder().providerId(node.getProviderId()).name(node.getName()).id(node.getId())
.location(node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tag(node.getTag())
.hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem(node.getOperatingSystem())
.state(node.getState()).publicAddresses(node.getPublicAddresses())
.privateAddresses(node.getPrivateAddresses()).credentials(node.getCredentials());
}
}

View File

@ -0,0 +1,80 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
/**
*
* @author Adrian Cole
*/
public class OperatingSystemBuilder {
@Nullable
private OsFamily family;
@Nullable
private String name;
@Nullable
private String arch;
@Nullable
private String version;
private String description;
private boolean is64Bit;
public OperatingSystemBuilder family(@Nullable OsFamily family) {
this.family = family;
return this;
}
public OperatingSystemBuilder name(@Nullable String name) {
this.name = name;
return this;
}
public OperatingSystemBuilder arch(@Nullable String arch) {
this.arch = arch;
return this;
}
public OperatingSystemBuilder version(@Nullable String version) {
this.version = version;
return this;
}
public OperatingSystemBuilder description(String description) {
this.description = checkNotNull(description, "description");
return this;
}
public OperatingSystemBuilder is64Bit(boolean is64Bit) {
this.is64Bit = is64Bit;
return this;
}
public OperatingSystem build() {
return new OperatingSystem(family, name, version, arch, description, is64Bit);
}
public static OperatingSystem fromOperatingSystem(OperatingSystem in) {
return new OperatingSystem(in.getFamily(), in.getName(), in.getVersion(), in.getArch(), in.getDescription(),
in.is64Bit());
}
}

View File

@ -0,0 +1,80 @@
/**
*
* 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.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.VolumeImpl;
/**
*
* @author Adrian Cole
*/
public class VolumeBuilder {
private Volume.Type type;
private String id;
@Nullable
private Float size;
@Nullable
private String device;
private boolean bootDevice;
private boolean durable;
public VolumeBuilder type(Volume.Type type) {
this.type = checkNotNull(type, "type");
return this;
}
public VolumeBuilder id(String id) {
this.id = checkNotNull(id, "id");
return this;
}
public VolumeBuilder size(@Nullable Float size) {
this.size = size;
return this;
}
public VolumeBuilder device(@Nullable String device) {
this.device = device;
return this;
}
public VolumeBuilder bootDevice(boolean bootDevice) {
this.bootDevice = bootDevice;
return this;
}
public VolumeBuilder durable(boolean durable) {
this.durable = durable;
return this;
}
public Volume build() {
return new VolumeImpl(id, type, size, device, bootDevice, durable);
}
public static Volume fromVolume(Volume in) {
return new VolumeImpl(in.getId(), in.getType(), in.getSize(), in.getDevice(), in.isBootDevice(), in.isDurable());
}
}

View File

@ -33,17 +33,25 @@ import org.jclouds.domain.internal.ResourceMetadataImpl;
* @author Adrian Cole
* @author Ivan Meredith
*/
public class ComputeMetadataImpl extends ResourceMetadataImpl<ComputeType> implements
ComputeMetadata {
public class ComputeMetadataImpl extends ResourceMetadataImpl<ComputeType> implements ComputeMetadata {
/** The serialVersionUID */
private static final long serialVersionUID = 7374704415964898694L;
private final String id;
private final ComputeType type;
public ComputeMetadataImpl(ComputeType type, String providerId, String name, String id,
Location location, URI uri, Map<String, String> userMetadata) {
super(type, providerId, name, location, uri, userMetadata);
public ComputeMetadataImpl(ComputeType type, String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata) {
super(providerId, name, location, uri, userMetadata);
this.id = checkNotNull(id, "id");
this.type = checkNotNull(type, "type");
}
/**
* {@inheritDoc}
*/
@Override
public ComputeType getType() {
return type;
}
/**
@ -59,6 +67,7 @@ public class ComputeMetadataImpl extends ResourceMetadataImpl<ComputeType> imple
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@ -76,6 +85,8 @@ public class ComputeMetadataImpl extends ResourceMetadataImpl<ComputeType> imple
return false;
} else if (!id.equals(other.id))
return false;
if (type != other.type)
return false;
return true;
}

View File

@ -39,28 +39,27 @@ import org.jclouds.domain.ResourceMetadata;
import com.google.common.base.Predicate;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.ImmutableList;
/**
* @author Adrian Cole
*/
public class HardwareImpl extends ComputeMetadataImpl implements Hardware {
/** The serialVersionUID */
private static final long serialVersionUID = 8994255275911717567L;
private final List<Processor> processors = Lists.newArrayList();
private final List<Processor> processors;
private final int ram;
private final List<Volume> volumes = Lists.newArrayList();
private Predicate<Image> supportsImage;
private final List<Volume> volumes;
private final Predicate<Image> supportsImage;
public HardwareImpl(String providerId, String name, String id, @Nullable Location location, URI uri,
Map<String, String> userMetadata, Iterable<? extends Processor> processors, int ram,
Iterable<? extends Volume> volumes, Predicate<Image> supportsImage) {
Map<String, String> userMetadata, Iterable<? extends Processor> processors, int ram,
Iterable<? extends Volume> volumes, Predicate<Image> supportsImage) {
super(ComputeType.HARDWARE, providerId, name, id, location, uri, userMetadata);
Iterables.addAll(this.processors, checkNotNull(processors, "processors"));
this.processors = ImmutableList.copyOf(checkNotNull(processors, "processors"));
this.ram = ram;
Iterables.addAll(this.volumes, checkNotNull(volumes, "volumes"));
this.volumes = ImmutableList.copyOf(checkNotNull(volumes, "volumes"));
this.supportsImage = supportsImage;
}
@ -95,8 +94,8 @@ public class HardwareImpl extends ComputeMetadataImpl implements Hardware {
public int compareTo(ResourceMetadata<ComputeType> that) {
if (that instanceof Hardware) {
Hardware thatHardware = Hardware.class.cast(that);
return ComparisonChain.start().compare(getCoresAndSpeed(this), getCoresAndSpeed(thatHardware)).compare(
this.getRam(), thatHardware.getRam()).compare(getSpace(this), getSpace(thatHardware)).result();
return ComparisonChain.start().compare(getCoresAndSpeed(this), getCoresAndSpeed(thatHardware))
.compare(this.getRam(), thatHardware.getRam()).compare(getSpace(this), getSpace(thatHardware)).result();
} else {
return super.compareTo(that);
}
@ -108,7 +107,7 @@ public class HardwareImpl extends ComputeMetadataImpl implements Hardware {
@Override
public String toString() {
return "[id=" + getId() + ", providerId=" + getProviderId() + ", name=" + getName() + ", processors="
+ processors + ", ram=" + ram + ", volumes=" + volumes + ", supportsImage=" + supportsImage + "]";
+ processors + ", ram=" + ram + ", volumes=" + volumes + ", supportsImage=" + supportsImage + "]";
}
/**

View File

@ -41,14 +41,13 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
private static final long serialVersionUID = 7856744554191025307L;
private final OperatingSystem operatingSystem;
private final String version;
private final String description;
private final Credentials defaultCredentials;
public ImageImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, OperatingSystem operatingSystem, String description,
@Nullable String version, @Nullable Credentials defaultCredentials) {
Map<String, String> userMetadata, OperatingSystem operatingSystem, String description,
@Nullable String version, @Nullable Credentials defaultCredentials) {
super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata);
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
this.version = version;
@ -91,7 +90,9 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
@Override
public String toString() {
return "[id=" + getId() + ", name=" + getName() + ", operatingSystem=" + operatingSystem + ", description="
+ description + ", version=" + version + ", location=" + getLocation() + "]";
+ description + ", version=" + version + ", location=" + getLocation() + ", loginUser="
+ ((defaultCredentials != null) ? defaultCredentials.identity : null) + ", userMetadata="
+ getUserMetadata() + "]";
}
@Override

View File

@ -35,39 +35,43 @@ import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.collect.ImmutableSet;
/**
* @author Adrian Cole
* @author Ivan Meredith
*/
public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadata {
/** The serialVersionUID */
private static final long serialVersionUID = 7924307572338157887L;
private final NodeState state;
private final Set<String> publicAddresses = Sets.newLinkedHashSet();
private final Set<String> privateAddresses = Sets.newLinkedHashSet();
private final Set<String> publicAddresses;
private final Set<String> privateAddresses;
@Nullable
private final Credentials credentials;
@Nullable
private final String tag;
@Nullable
private final String imageId;
@Nullable
private final Hardware hardware;
@Nullable
private final OperatingSystem os;
public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, @Nullable String tag, @Nullable Hardware hardware,
@Nullable String imageId, @Nullable OperatingSystem os, NodeState state, Iterable<String> publicAddresses,
Iterable<String> privateAddresses, @Nullable Credentials credentials) {
Map<String, String> userMetadata, @Nullable String tag, @Nullable Hardware hardware, @Nullable String imageId,
@Nullable OperatingSystem os, NodeState state, Iterable<String> publicAddresses,
Iterable<String> privateAddresses, @Nullable Credentials credentials) {
super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata);
this.tag = tag;
this.hardware = hardware;
this.imageId = imageId;
this.os = os;
this.state = checkNotNull(state, "state");
Iterables.addAll(this.publicAddresses, checkNotNull(publicAddresses, "publicAddresses"));
Iterables.addAll(this.privateAddresses, checkNotNull(privateAddresses, "privateAddresses"));
this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses"));
this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses"));
this.credentials = credentials;
}
@ -138,10 +142,10 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
@Override
public String toString() {
return "[id=" + getId() + ", providerId=" + getProviderId() + ", tag=" + getTag() + ", name=" + getName()
+ ", location=" + getLocation() + ", uri=" + getUri() + ", imageId=" + getImageId() + ", os="
+ getOperatingSystem() + ", userMetadata=" + getUserMetadata() + ", state=" + getState()
+ ", privateAddresses=" + privateAddresses + ", publicAddresses=" + publicAddresses + ", hardware="
+ getHardware() + "]";
+ ", location=" + getLocation() + ", uri=" + getUri() + ", imageId=" + getImageId() + ", os="
+ getOperatingSystem() + ", state=" + getState() + ", privateAddresses=" + privateAddresses
+ ", publicAddresses=" + publicAddresses + ", hardware=" + getHardware() + ", loginUser="
+ ((credentials != null) ? credentials.identity : null) + ", userMetadata=" + getUserMetadata() + "]";
}
@Override
@ -154,6 +158,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());
result = prime * result + ((hardware == null) ? 0 : hardware.hashCode());
result = prime * result + ((os == null) ? 0 : os.hashCode());
result = prime * result + ((credentials == null) ? 0 : credentials.hashCode());
return result;
}
@ -196,6 +201,11 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
return false;
} else if (!os.equals(other.os))
return false;
if (credentials == null) {
if (other.credentials != null)
return false;
} else if (!credentials.equals(other.credentials))
return false;
return true;
}

View File

@ -21,7 +21,20 @@ package org.jclouds.compute.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.installNewCredentials;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.not;
import static com.google.common.base.Predicates.notNull;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newLinkedHashMap;
import static com.google.common.collect.Sets.filter;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
import static org.jclouds.compute.predicates.NodePredicates.all;
import static org.jclouds.concurrent.FutureIterables.awaitCompletion;
import static org.jclouds.concurrent.FutureIterables.transformParallel;
@ -49,11 +62,11 @@ import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
@ -74,12 +87,7 @@ import org.jclouds.util.Utils;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
/**
*
@ -93,6 +101,7 @@ public class BaseComputeService implements ComputeService {
protected Logger logger = Logger.NULL;
protected final ComputeServiceContext context;
protected final Map<String, Credentials> credentialStore;
protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwareProfiles;
protected final Supplier<Set<? extends Location>> locations;
@ -110,16 +119,17 @@ public class BaseComputeService implements ComputeService {
protected final ExecutorService executor;
@Inject
protected BaseComputeService(ComputeServiceContext context, 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) {
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) {
this.context = checkNotNull(context, "context");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");
this.hardwareProfiles = checkNotNull(hardwareProfiles, "hardwareProfiles");
this.locations = checkNotNull(locations, "locations");
@ -150,19 +160,22 @@ 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());
Set<NodeMetadata> nodes = Sets.newHashSet();
Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap();
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);
Map<?, Exception> executionExceptions = awaitCompletion(responses, executor, null, logger, "starting nodes");
for (NodeMetadata node : concat(nodes, badNodes.keySet()))
if (node.getCredentials() != null)
credentialStore.put("node/" + node.getId(), node.getCredentials());
if (executionExceptions.size() > 0 || badNodes.size() > 0) {
throw new RunNodesException(tag, count, template, nodes, executionExceptions, badNodes);
}
@ -174,7 +187,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());
}
@ -211,6 +224,8 @@ public class BaseComputeService implements ComputeService {
}, timeouts.nodeRunning, 1000, TimeUnit.MILLISECONDS);
boolean successful = tester.apply(id) && (node.get() == null || nodeTerminated.apply(node.get()));
if (successful)
credentialStore.remove("node/" + id);
logger.debug("<< destroyed node(%s) success(%s)", id, successful);
}
@ -220,30 +235,30 @@ public class BaseComputeService implements ComputeService {
@Override
public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<NodeMetadata> filter) {
logger.debug(">> destroying nodes matching(%s)", filter);
Set<NodeMetadata> set = Sets.newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter),
new Function<NodeMetadata, Future<NodeMetadata>>() {
Set<NodeMetadata> set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter),
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;
}
private Iterable<? extends NodeMetadata> nodesMatchingFilterAndNotTerminated(Predicate<NodeMetadata> filter) {
return Iterables.filter(detailsOnAllNodes(), Predicates.and(filter, Predicates.not(NodePredicates.TERMINATED)));
return filter(detailsOnAllNodes(), and(filter, not(TERMINATED)));
}
/**
@ -252,7 +267,7 @@ public class BaseComputeService implements ComputeService {
@Override
public Set<ComputeMetadata> listNodes() {
logger.debug(">> listing nodes");
Set<ComputeMetadata> set = Sets.newLinkedHashSet(listNodesStrategy.list());
Set<ComputeMetadata> set = newLinkedHashSet(listNodesStrategy.list());
logger.debug("<< list(%d)", set.size());
return set;
}
@ -264,7 +279,7 @@ public class BaseComputeService implements ComputeService {
public Set<? extends NodeMetadata> listNodesDetailsMatching(Predicate<ComputeMetadata> filter) {
checkNotNull(filter, "filter");
logger.debug(">> listing node details matching(%s)", filter);
Set<NodeMetadata> set = Sets.newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(filter));
Set<NodeMetadata> set = newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(filter));
logger.debug("<< list(%d)", set.size());
return set;
}
@ -333,7 +348,7 @@ public class BaseComputeService implements ComputeService {
@Override
public Future<Void> apply(NodeMetadata from) {
rebootNode(from.getId());
return Futures.immediateFuture(null);
return immediateFuture(null);
}
}, executor, null, logger, "rebooting nodes");
@ -345,7 +360,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);
}
@ -354,7 +369,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");
@ -362,11 +377,11 @@ public class BaseComputeService implements ComputeService {
if (options.getTaskName() == null)
options.nameTask("jclouds-script-" + System.currentTimeMillis());
Iterable<? extends NodeMetadata> nodes = Iterables.filter(detailsOnAllNodes(), filter);
Iterable<? extends NodeMetadata> nodes = filter(detailsOnAllNodes(), filter);
final Map<NodeMetadata, ExecResponse> execs = Maps.newHashMap();
final Map<NodeMetadata, Future<Void>> responses = Maps.newHashMap();
final Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap();
final Map<NodeMetadata, ExecResponse> execs = newHashMap();
final Map<NodeMetadata, Future<Void>> responses = newHashMap();
final Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();
nodes = filterNodesWhoCanRunScripts(nodes, badNodes, options.getOverrideCredentials());
for (final NodeMetadata node : nodes) {
@ -375,8 +390,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) {
@ -398,21 +413,21 @@ public class BaseComputeService implements ComputeService {
}
private Iterable<? extends NodeMetadata> filterNodesWhoCanRunScripts(Iterable<? extends NodeMetadata> nodes,
final Map<NodeMetadata, Exception> badNodes, final @Nullable Credentials overridingCredentials) {
nodes = Iterables.filter(Iterables.transform(nodes, new Function<NodeMetadata, NodeMetadata>() {
final Map<NodeMetadata, Exception> badNodes, final @Nullable Credentials overridingCredentials) {
nodes = filter(transform(nodes, new Function<NodeMetadata, NodeMetadata>() {
@Override
public NodeMetadata apply(NodeMetadata node) {
try {
checkArgument(node.getPublicAddresses().size() > 0, "no public ip addresses on node: " + node);
if (overridingCredentials != null) {
node = installNewCredentials(node, overridingCredentials);
node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(overridingCredentials).build();
} 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) {
@ -420,12 +435,12 @@ public class BaseComputeService implements ComputeService {
return null;
}
}
}), Predicates.notNull());
}), notNull());
return nodes;
}
private Set<? extends NodeMetadata> detailsOnAllNodes() {
return Sets.newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(NodePredicates.all()));
return newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(all()));
}
@Override

View File

@ -21,6 +21,8 @@ package org.jclouds.compute.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -29,6 +31,7 @@ import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.LoadBalancerService;
import org.jclouds.compute.Utils;
import org.jclouds.domain.Credentials;
import org.jclouds.rest.RestContext;
/**
@ -40,11 +43,13 @@ public class ComputeServiceContextImpl<S, A> implements ComputeServiceContext {
private final LoadBalancerService loadBalancerService;
private final RestContext<S, A> providerSpecificContext;
private final Utils utils;
private final Map<String, Credentials> credentialStore;
@SuppressWarnings({ "unchecked" })
@Inject
public ComputeServiceContextImpl(ComputeService computeService, Utils utils,
@Nullable LoadBalancerService loadBalancerService, RestContext providerSpecificContext) {
public ComputeServiceContextImpl(ComputeService computeService, Map<String, Credentials> credentialStore,
Utils utils, @Nullable LoadBalancerService loadBalancerService, RestContext providerSpecificContext) {
this.credentialStore = credentialStore;
this.utils = utils;
this.providerSpecificContext = providerSpecificContext;
this.computeService = checkNotNull(computeService, "computeService");
@ -55,7 +60,7 @@ public class ComputeServiceContextImpl<S, A> implements ComputeServiceContext {
return computeService;
}
@SuppressWarnings( { "unchecked", "hiding" })
@SuppressWarnings({ "unchecked", "hiding" })
@Override
public <S, A> RestContext<S, A> getProviderSpecificContext() {
return (RestContext<S, A>) providerSpecificContext;
@ -94,4 +99,14 @@ public class ComputeServiceContextImpl<S, A> implements ComputeServiceContext {
public boolean equals(Object obj) {
return providerSpecificContext.equals(obj);
}
@Override
public Map<String, Credentials> getCredentialStore() {
return credentialStore;
}
@Override
public Map<String, Credentials> credentialStore() {
return credentialStore;
}
}

View File

@ -23,6 +23,8 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import javax.annotation.Nullable;
import org.jclouds.compute.domain.Image;
import com.google.common.base.Predicate;
@ -38,6 +40,24 @@ import com.google.common.collect.Sets;
* @author Adrian Cole
*/
public class ImagePredicates {
private static final class Is64BitPredicate implements Predicate<Image> {
@Override
public boolean apply(Image image) {
return image.getOperatingSystem().is64Bit();
}
@Override
public String toString() {
return "is64Bit()";
}
@Override
public boolean equals(@Nullable Object obj) {
return (obj instanceof Is64BitPredicate);
}
}
/**
* evaluates true if the Image
*
@ -87,17 +107,7 @@ public class ImagePredicates {
* return true if this is a 64bit image.
*/
public static Predicate<Image> is64Bit() {
return new Predicate<Image>() {
@Override
public boolean apply(Image image) {
return image.getOperatingSystem().is64Bit();
}
@Override
public String toString() {
return "is64Bit()";
}
};
return new Is64BitPredicate();
}
/**

View File

@ -20,9 +20,7 @@
package org.jclouds.compute.stub.config;
import static com.google.common.base.Preconditions.checkArgument;
import static org.jclouds.compute.predicates.ImagePredicates.any;
import java.net.URI;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ -31,7 +29,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
@ -45,14 +42,15 @@ import org.jclouds.compute.config.ComputeServiceTimeoutsModule;
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.internal.ImageImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
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;
@ -75,7 +73,6 @@ 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.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
@ -93,11 +90,12 @@ import com.google.inject.util.Providers;
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<Integer, StubNodeMetadata> nodes = new ConcurrentHashMap<Integer, StubNodeMetadata>();
private static final ConcurrentMap<String, NodeMetadata> nodes = new ConcurrentHashMap<String, NodeMetadata>();
private static final ExecutorService service = Executors.newCachedThreadPool();
@Provides
@Singleton
ConcurrentMap<Integer, StubNodeMetadata> provideNodes() {
ConcurrentMap<String, NodeMetadata> provideNodes() {
return nodes;
}
@ -136,12 +134,11 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
@Singleton
public static class StubSocketOpen implements SocketOpen {
private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final String publicIpPrefix;
@Inject
public StubSocketOpen(ConcurrentMap<Integer, StubNodeMetadata> nodes,
@Named("PUBLIC_IP_PREFIX") String publicIpPrefix) {
public StubSocketOpen(ConcurrentMap<String, NodeMetadata> nodes, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix) {
this.nodes = nodes;
this.publicIpPrefix = publicIpPrefix;
}
@ -151,8 +148,7 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
if (input.getAddress().indexOf(publicIpPrefix) == -1)
return false;
String id = input.getAddress().replace(publicIpPrefix, "");
int intId = Integer.parseInt(id);
StubNodeMetadata node = nodes.get(intId);
NodeMetadata node = nodes.get(id);
return node != null && node.getState() == NodeState.RUNNING;
}
@ -174,109 +170,97 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
bind(LoadBalancerService.class).toProvider(Providers.<LoadBalancerService> of(null));
}
public static class StubNodeMetadata extends NodeMetadataImpl {
/** The serialVersionUID */
private static final long serialVersionUID = 5538798859671465494L;
private NodeState state;
private final ExecutorService service;
public StubNodeMetadata(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, String tag, @Nullable Hardware hardware, String imageId, Image image,
OperatingSystem os, NodeState state, Iterable<String> publicAddresses,
Iterable<String> privateAddresses, Credentials credentials, ExecutorService service) {
super(providerId, name, id, location, uri, userMetadata, tag, hardware, imageId, os, state, publicAddresses,
privateAddresses, credentials);
this.setState(state, 0);
this.service = service;
}
public void setState(final NodeState state, final long millis) {
if (millis == 0l)
this.state = state;
else
service.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Throwables.propagate(e);
}
StubNodeMetadata.this.state = state;
}
});
}
@Override
public NodeState getState() {
return state;
}
}
@Singleton
public static class StubAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final Supplier<Location> location;
private final ExecutorService service;
private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
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<Integer, StubNodeMetadata> nodes, Supplier<Location> location,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix) {
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.service = Executors.newCachedThreadPool();
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());
int id = idProvider.get();
StubNodeMetadata node = new StubNodeMetadata(id + "", name, id + "", location.get(), null, ImmutableMap
.<String, String> of(), tag, null, template.getImage().getId(), template.getImage(), template
.getImage().getOperatingSystem(), NodeState.PENDING, ImmutableSet.<String> of(publicIpPrefix + id),
ImmutableSet.<String> of(privateIpPrefix + id), new Credentials("root", passwordPrefix + id), service);
nodes.put(id, node);
node.setState(NodeState.RUNNING, 100);
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<Integer, StubNodeMetadata> nodes;
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubGetNodeMetadataStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes) {
protected StubGetNodeMetadataStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public NodeMetadata execute(String id) {
return nodes.get(Integer.parseInt(id));
return nodes.get(id);
}
}
@Singleton
public static class StubListNodesStrategy implements ListNodesStrategy {
private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubListNodesStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes) {
protected StubListNodesStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@ -293,44 +277,43 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
@Singleton
public static class StubRebootNodeStrategy implements RebootNodeStrategy {
private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
private final ConcurrentMap<String, NodeMetadata> nodes;
@Inject
protected StubRebootNodeStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes) {
protected StubRebootNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes) {
this.nodes = nodes;
}
@Override
public StubNodeMetadata execute(String id) {
StubNodeMetadata node = nodes.get(Integer.parseInt(id));
public NodeMetadata execute(String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
throw new ResourceNotFoundException("node not found: " + id);
node.setState(NodeState.PENDING, 0);
node.setState(NodeState.RUNNING, 50);
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.RUNNING, 50);
return node;
}
}
@Singleton
public static class StubDestroyNodeStrategy implements DestroyNodeStrategy {
private final ConcurrentMap<Integer, StubNodeMetadata> nodes;
private final ConcurrentMap<String, NodeMetadata> nodes;
private final ExecutorService service;
@Inject
protected StubDestroyNodeStrategy(ConcurrentMap<Integer, StubNodeMetadata> nodes,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) {
protected StubDestroyNodeStrategy(ConcurrentMap<String, NodeMetadata> nodes,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) {
this.nodes = nodes;
this.service = service;
}
@Override
public StubNodeMetadata execute(String id) {
final int nodeId = Integer.parseInt(id);
StubNodeMetadata node = nodes.get(nodeId);
public NodeMetadata execute(final String id) {
NodeMetadata node = nodes.get(id);
if (node == null)
return node;
node.setState(NodeState.PENDING, 0);
node.setState(NodeState.TERMINATED, 50);
setState(node, NodeState.PENDING, 0);
setState(node, NodeState.TERMINATED, 50);
service.execute(new Runnable() {
@Override
@ -340,7 +323,7 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
} catch (InterruptedException e) {
Throwables.propagate(e);
} finally {
nodes.remove(nodeId);
nodes.remove(id);
}
}
@ -355,19 +338,36 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
}));
Location zone = defaultLocation.get().getParent();
String parentId = zone.getId();
return Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(//
new ImageImpl("1", OsFamily.UBUNTU.name(), parentId + "/1", zone, null,
ImmutableMap.<String, String> of(), //
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false),
"stub ubuntu 32", "", new Credentials("root", null)), //
new ImageImpl("2", OsFamily.UBUNTU.name(), parentId + "/2", zone, null,
ImmutableMap.<String, String> of(),//
new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true),
"stub ubuntu 64", "", new Credentials("root", null)),//
new ImageImpl("3", OsFamily.CENTOS.name(), parentId + "/3", zone, null,
ImmutableMap.<String, String> of(), //
new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true),
"stub centos 64", "", new Credentials("root", null))));
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
@ -375,24 +375,24 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo
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);
provider);
return ImmutableSet
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
.of(new LocationImpl(LocationScope.ZONE, providerName + "zone", providerName + "zone", region));
}
@Override
protected Supplier<Set<? extends Hardware>> getSourceSizeSupplier(Injector injector) {
return Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of(new StubHardware("small", 1,
1740, 160), new StubHardware("medium", 4, 7680, 850), new StubHardware("large", 8, 15360, 1690)));
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)));
}
private static class StubHardware extends org.jclouds.compute.domain.internal.HardwareImpl {
/** The serialVersionUID */
private static final long serialVersionUID = -1842135761654973637L;
private static class StubHardware {
StubHardware(String type, int cores, int ram, float disk) {
super(type, type, type, null, null, ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(cores,
1.0)), ram, ImmutableList.of(new VolumeImpl(disk, true, false)), any());
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();
}
}

View File

@ -27,8 +27,8 @@ import static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash
import java.net.URI;
import java.util.Formatter;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -40,9 +40,6 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpRequest;
import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.domain.Statement;
@ -80,7 +77,7 @@ public class ComputeServiceUtils {
*/
public static Statement extractTargzIntoDirectory(HttpRequest targz, String directory) {
return Statements
.extractTargzIntoDirectory(targz.getMethod(), targz.getEndpoint(), targz.getHeaders(), directory);
.extractTargzIntoDirectory(targz.getMethod(), targz.getEndpoint(), targz.getHeaders(), directory);
}
public static Statement extractTargzIntoDirectory(URI targz, String directory) {
@ -93,14 +90,13 @@ public class ComputeServiceUtils {
* @return a shell script that will invoke the http request
*/
public static Statement extractZipIntoDirectory(HttpRequest zip, String directory) {
return Statements
.extractZipIntoDirectory(zip.getMethod(), zip.getEndpoint(), zip.getHeaders(), directory);
return Statements.extractZipIntoDirectory(zip.getMethod(), zip.getEndpoint(), zip.getHeaders(), directory);
}
public static Statement extractZipIntoDirectory(URI zip, String directory) {
return extractZipIntoDirectory(new HttpRequest("GET", zip), directory);
}
public static String parseTagFromName(String from) {
Matcher matcher = DELIMETED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX.matcher(from);
return matcher.find() ? matcher.group(1) : "NOTAG-" + from;
@ -128,14 +124,15 @@ public class ComputeServiceUtils {
}
public static final Map<org.jclouds.compute.domain.OsFamily, Map<String, String>> NAME_VERSION_MAP = ImmutableMap
.<org.jclouds.compute.domain.OsFamily, Map<String, String>> of(org.jclouds.compute.domain.OsFamily.CENTOS,
ImmutableMap.<String, String> builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5")
.build(), org.jclouds.compute.domain.OsFamily.RHEL,
ImmutableMap.<String, String> builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5")
.build(), org.jclouds.compute.domain.OsFamily.UBUNTU, ImmutableMap
.<String, String> builder().put("hardy", "8.04").put("intrepid", "8.10").put("jaunty",
"9.04").put("karmic", "9.10").put("lucid", "10.04").put("maverick", "10.10")
.put("natty", "11.04").build());
.<org.jclouds.compute.domain.OsFamily, Map<String, String>> of(
org.jclouds.compute.domain.OsFamily.CENTOS,
ImmutableMap.<String, String> builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5").build(),
org.jclouds.compute.domain.OsFamily.RHEL,
ImmutableMap.<String, String> builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5").build(),
org.jclouds.compute.domain.OsFamily.UBUNTU,
ImmutableMap.<String, String> builder().put("hardy", "8.04").put("intrepid", "8.10")
.put("jaunty", "9.04").put("karmic", "9.10").put("lucid", "10.04").put("maverick", "10.10")
.put("natty", "11.04").build());
public static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, final String in) {
if (NAME_VERSION_MAP.containsKey(family)) {
@ -170,8 +167,8 @@ public class ComputeServiceUtils {
Formatter fmt = new Formatter().format("Execution failures:%n%n");
int index = 1;
for (Entry<?, Exception> errorMessage : executionExceptions.entrySet()) {
fmt.format("%s) %s on %s:%n%s%n%n", index++, errorMessage.getValue().getClass().getSimpleName(), errorMessage
.getKey(), getStackTraceAsString(errorMessage.getValue()));
fmt.format("%s) %s on %s:%n%s%n%n", index++, errorMessage.getValue().getClass().getSimpleName(),
errorMessage.getKey(), getStackTraceAsString(errorMessage.getValue()));
}
return fmt.format("%s error[s]", executionExceptions.size()).toString();
}
@ -181,13 +178,13 @@ public class ComputeServiceUtils {
int index = 1;
for (Entry<? extends NodeMetadata, ? extends Throwable> errorMessage : failedNodes.entrySet()) {
fmt.format("%s) %s on node %s:%n%s%n%n", index++, errorMessage.getValue().getClass().getSimpleName(),
errorMessage.getKey().getId(), getStackTraceAsString(errorMessage.getValue()));
errorMessage.getKey().getId(), getStackTraceAsString(errorMessage.getValue()));
}
return fmt.format("%s error[s]", failedNodes.size()).toString();
}
public static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes,
final String name) {
final String name) {
return filter(nodes, new Predicate<ComputeMetadata>() {
@Override
public boolean apply(ComputeMetadata input) {
@ -217,28 +214,7 @@ public class ComputeServiceUtils {
public static boolean isKeyAuth(NodeMetadata createdNode) {
return createdNode.getCredentials().credential != null
&& createdNode.getCredentials().credential.startsWith("-----BEGIN RSA PRIVATE KEY-----");
}
/**
* Given the instances of {@link NodeMetadata} (immutable) and {@link Credentials} (immutable),
* returns a new instance of {@link NodeMetadata} that has new credentials
*/
public static NodeMetadata installNewCredentials(NodeMetadata node, Credentials newCredentials) {
return new NodeMetadataImpl(node.getProviderId(), node.getName(), node.getId(), node.getLocation(),
node.getUri(), node.getUserMetadata(), node.getTag(), node.getHardware(), node.getImageId(), node
.getOperatingSystem(), node.getState(), node.getPublicAddresses(), node.getPrivateAddresses(),
newCredentials);
}
/**
* Given the instances of {@link Hardware} (immutable) and {@link Iterable<? extends Volume>}
* (immutable), returns a new instance of {@link Hardware} with the new volumes
*/
public static Hardware replacesVolumes(Hardware hardware, Iterable<? extends Volume> volumes) {
return new HardwareImpl(hardware.getProviderId(), hardware.getName(), hardware.getId(), hardware.getLocation(),
hardware.getUri(), hardware.getUserMetadata(), hardware.getProcessors(), hardware.getRam(), volumes,
hardware.supportsImage());
&& createdNode.getCredentials().credential.startsWith("-----BEGIN RSA PRIVATE KEY-----");
}
public static Iterable<String> getSupportedProviders() {

View File

@ -21,7 +21,6 @@ package org.jclouds.compute.util;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.jclouds.compute.util.ComputeServiceUtils.installNewCredentials;
import static org.jclouds.compute.util.ComputeServiceUtils.isKeyAuth;
import static org.jclouds.concurrent.FutureIterables.awaitCompletion;
@ -43,6 +42,7 @@ import org.jclouds.Constants;
import org.jclouds.compute.callables.InitAndStartScriptOnNode;
import org.jclouds.compute.callables.RunScriptOnNode;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;
@ -77,20 +77,19 @@ public class ComputeUtils {
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Inject(optional = true)
private SshClient.Factory sshFactory;
protected SshClient.Factory sshFactory;
protected final Predicate<CommandUsingClient> runScriptNotRunning;
private final Predicate<IPSocket> socketTester;
private final ExecutorService executor;
protected final Predicate<IPSocket> socketTester;
protected final ExecutorService executor;
protected final Predicate<NodeMetadata> nodeRunning;
private final GetNodeMetadataStrategy getNode;
private final Timeouts timeouts;
protected final GetNodeMetadataStrategy getNode;
protected final Timeouts timeouts;
@Inject
public ComputeUtils(Predicate<IPSocket> socketTester,
@Named("SCRIPT_COMPLETE") Predicate<CommandUsingClient> runScriptNotRunning,
GetNodeMetadataStrategy getNode, Timeouts timeouts,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
@Named("SCRIPT_COMPLETE") Predicate<CommandUsingClient> runScriptNotRunning, GetNodeMetadataStrategy getNode,
Timeouts timeouts, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.nodeRunning = nodeRunning;
this.timeouts = timeouts;
this.getNode = getNode;
@ -100,19 +99,18 @@ public class ComputeUtils {
}
public Map<?, Future<Void>> runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(final TemplateOptions options,
Iterable<NodeMetadata> runningNodes, final Set<NodeMetadata> goodNodes,
final Map<NodeMetadata, Exception> badNodes) {
Iterable<NodeMetadata> runningNodes, final Set<NodeMetadata> goodNodes,
final Map<NodeMetadata, Exception> badNodes) {
Map<NodeMetadata, Future<Void>> responses = Maps.newHashMap();
for (final NodeMetadata node : runningNodes) {
responses.put(node, executor.submit(runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes,
goodNodes, options)));
goodNodes, options)));
}
return responses;
}
public Callable<Void> runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(final NodeMetadata node,
final Map<NodeMetadata, Exception> badNodes, final Set<NodeMetadata> goodNodes,
final TemplateOptions options) {
final Map<NodeMetadata, Exception> badNodes, final Set<NodeMetadata> goodNodes, final TemplateOptions options) {
return new Callable<Void>() {
@Override
public Void call() throws Exception {
@ -122,7 +120,7 @@ public class ComputeUtils {
goodNodes.add(node1);
} catch (Exception e) {
logger.error(e, "<< problem applying options to node(%s): ", node.getId(), Throwables.getRootCause(e)
.getMessage());
.getMessage());
badNodes.put(node, e);
}
return null;
@ -135,11 +133,12 @@ public class ComputeUtils {
return node;
if (nodeRunning.apply(node))
node = installNewCredentials(getNode.execute(node.getId()), node.getCredentials());
node = NodeMetadataBuilder.fromNodeMetadata(getNode.execute(node.getId()))
.credentials(node.getCredentials()).build();
else
throw new IllegalStateException(String.format(
"node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(),
timeouts.nodeRunning / 1000, node.getState()));
"node didn't achieve the state running on node %s within %d seconds, final state: %s", node.getId(),
timeouts.nodeRunning / 1000, node.getState()));
List<Statement> bootstrap = Lists.newArrayList();
if (options.getRunScript() != null)
bootstrap.add(options.getRunScript());
@ -170,8 +169,8 @@ public class ComputeUtils {
}
if (options.getPort() > 0) {
checkNodeHasPublicIps(node);
blockUntilPortIsListeningOnPublicIp(options.getPort(), options.getSeconds(), Iterables.get(node
.getPublicAddresses(), 0));
blockUntilPortIsListeningOnPublicIp(options.getPort(), options.getSeconds(),
Iterables.get(node.getPublicAddresses(), 0));
}
return response;
}
@ -189,12 +188,12 @@ public class ComputeUtils {
public InitAndStartScriptOnNode generateScript(NodeMetadata node, Statement script, RunScriptOptions options) {
return options.shouldBlockOnComplete() ? new RunScriptOnNode(runScriptNotRunning, node, options.getTaskName(),
script, options.shouldRunAsRoot()) : new InitAndStartScriptOnNode(node, options.getTaskName(), script,
options.shouldRunAsRoot());
script, options.shouldRunAsRoot()) : new InitAndStartScriptOnNode(node, options.getTaskName(), script,
options.shouldRunAsRoot());
}
public Map<SshCallable<?>, ?> runCallablesOnNode(NodeMetadata node, Iterable<SshCallable<?>> parallel,
@Nullable SshCallable<?> last) {
@Nullable SshCallable<?> last) {
checkState(this.sshFactory != null, "runScript requested, but no SshModule configured");
checkNodeHasPublicIps(node);
checkNotNull(node.getCredentials(), "credentials for node " + node.getName());
@ -210,7 +209,7 @@ public class ComputeUtils {
}
private Map<SshCallable<?>, ?> runTasksUsingSshClient(Iterable<SshCallable<?>> parallel, SshCallable<?> last,
SshClient ssh) {
SshClient ssh) {
Map<SshCallable<?>, Object> responses = Maps.newHashMap();
if (Iterables.size(parallel) > 0) {
responses.putAll(runCallablesUsingSshClient(parallel, ssh));
@ -230,8 +229,8 @@ public class ComputeUtils {
IPSocket socket = new IPSocket(Iterables.get(node.getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient ssh = isKeyAuth(node) ? sshFactory.create(socket, node.getCredentials().identity,
node.getCredentials().credential.getBytes()) : sshFactory.create(socket, node.getCredentials().identity,
node.getCredentials().credential);
node.getCredentials().credential.getBytes()) : sshFactory.create(socket, node.getCredentials().identity,
node.getCredentials().credential);
return ssh;
}

View File

@ -335,6 +335,13 @@ public abstract class BaseComputeServiceLiveTest {
checkOsMatchesTemplate(node);
}
@Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
public void testCredentialsCache() throws Exception {
initializeContextAndClient();
for (NodeMetadata node : nodes)
assert (context.getCredentialStore().get(node.getId()) != null) : "credentials for " + node.getId();
}
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String tag, OperatingSystem os,
Credentials creds) throws RunScriptOnNodesException {
try {
@ -351,6 +358,7 @@ public abstract class BaseComputeServiceLiveTest {
assertNotNull(node.getTag());
assertEquals(node.getTag(), tag);
assertEquals(node.getState(), NodeState.RUNNING);
assertEquals(context.getCredentialStore().get(node.getId()), node.getCredentials());
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
assertNotNull(node.getCredentials());
if (node.getCredentials().identity != null) {
@ -588,6 +596,7 @@ public abstract class BaseComputeServiceLiveTest {
client.destroyNodesMatching(withTag(tag));
for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), withTag(tag))) {
assert node.getState() == NodeState.TERMINATED : node;
assertEquals(context.getCredentialStore().get(node.getId()), null);
}
}
context.close();

View File

@ -41,7 +41,6 @@ import org.easymock.IArgumentMatcher;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.stub.config.StubComputeServiceContextModule.StubNodeMetadata;
import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate;
@ -122,49 +121,49 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
SshClient client5 = createMock(SshClient.class);
expect(factory.create(new IPSocket("144.175.1.1", 22), "root", "password1")).andReturn(client1)
.atLeastOnce();
.atLeastOnce();
runScriptAndService(client1, 1);
expect(factory.create(new IPSocket("144.175.1.2", 22), "root", "romeo")).andThrow(
new SshException("Auth fail"));
new SshException("Auth fail"));
expect(factory.create(new IPSocket("144.175.1.2", 22), "root", "password2")).andReturn(client2)
.atLeastOnce();
.atLeastOnce();
client2.connect();
try {
runScript(client2, "runScriptWithCreds", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/runscript.sh")), 2);
.getResourceAsStream("/runscript.sh")), 2);
} catch (IOException e) {
Throwables.propagate(e);
}
client2.disconnect();
expect(factory.create(new IPSocket("144.175.1.3", 22), "root", "password3")).andReturn(client3)
.atLeastOnce();
.atLeastOnce();
expect(factory.create(new IPSocket("144.175.1.4", 22), "root", "password4")).andReturn(client4)
.atLeastOnce();
.atLeastOnce();
expect(factory.create(new IPSocket("144.175.1.5", 22), "root", "password5")).andReturn(client5)
.atLeastOnce();
.atLeastOnce();
runScriptAndInstallSsh(client3, "bootstrap", 3);
runScriptAndInstallSsh(client4, "bootstrap", 4);
runScriptAndInstallSsh(client5, "bootstrap", 5);
expect(
factory.create(eq(new IPSocket("144.175.1.1", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client1).atLeastOnce();
factory.create(eq(new IPSocket("144.175.1.1", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client1).atLeastOnce();
expect(
factory.create(eq(new IPSocket("144.175.1.2", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client2).atLeastOnce();
factory.create(eq(new IPSocket("144.175.1.2", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client2).atLeastOnce();
expect(
factory.create(eq(new IPSocket("144.175.1.3", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client3).atLeastOnce();
factory.create(eq(new IPSocket("144.175.1.3", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client3).atLeastOnce();
expect(
factory.create(eq(new IPSocket("144.175.1.4", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client4).atLeastOnce();
factory.create(eq(new IPSocket("144.175.1.4", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client4).atLeastOnce();
expect(
factory.create(eq(new IPSocket("155.175.1.5", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client5).atLeastOnce();
factory.create(eq(new IPSocket("155.175.1.5", 22)), eq("root"), aryEq(keyPair.get("private")
.getBytes()))).andReturn(client5).atLeastOnce();
helloAndJava(client2);
helloAndJava(client3);
@ -186,7 +185,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
try {
runScript(client, "jboss", Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/initscript_with_jboss.sh")), nodeId);
.getResourceAsStream("/initscript_with_jboss.sh")), nodeId);
} catch (IOException e) {
Throwables.propagate(e);
}
@ -200,7 +199,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
try {
runScript(client, scriptName, Utils.toStringAndClose(StubComputeServiceIntegrationTest.class
.getResourceAsStream("/initscript_with_java.sh")), nodeId);
.getResourceAsStream("/initscript_with_java.sh")), nodeId);
} catch (IOException e) {
Throwables.propagate(e);
}
@ -252,8 +251,8 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
public void testAssignability() throws Exception {
@SuppressWarnings("unused")
RestContext<ConcurrentMap<Integer, StubNodeMetadata>, ConcurrentMap<Integer, StubNodeMetadata>> stubContext = new ComputeServiceContextFactory()
.createContext(provider, identity, credential).getProviderSpecificContext();
RestContext<ConcurrentMap<String, NodeMetadata>, ConcurrentMap<String, NodeMetadata>> stubContext = new ComputeServiceContextFactory()
.createContext(provider, identity, credential).getProviderSpecificContext();
}
private static class PayloadEquals implements IArgumentMatcher, Serializable {
@ -300,7 +299,7 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
return false;
PayloadEquals other = (PayloadEquals) o;
return this.expected == null && other.expected == null || this.expected != null
&& this.expected.equals(other.expected);
&& this.expected.equals(other.expected);
}
@Override
@ -343,6 +342,11 @@ public class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTes
super.testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired();
}
@Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
public void testCredentialsCache() throws Exception {
super.testCredentialsCache();
}
@Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired")
public void testGet() throws Exception {
super.testGet();

View File

@ -31,12 +31,11 @@ import java.util.Set;
import javax.inject.Provider;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.domain.Location;
@ -44,8 +43,6 @@ import org.testng.annotations.Test;
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;
/**
@ -64,16 +61,14 @@ public class TemplateBuilderImplTest {
Image image2 = createMock(Image.class);
OperatingSystem os2 = createMock(OperatingSystem.class);
Hardware size = new HardwareImpl("hardwareId", null, "hardwareId", defaultLocation, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList.<Volume> of(),
ImagePredicates.any());
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));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(size));
image, image2));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -102,10 +97,10 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
assertEquals(template.resolveImage(size, images.get()), image2);
assertEquals(template.resolveImage(hardware, images.get()), image2);
verify(image);
verify(image2);
@ -126,16 +121,14 @@ public class TemplateBuilderImplTest {
OperatingSystem os = createMock(OperatingSystem.class);
OperatingSystem os2 = createMock(OperatingSystem.class);
Hardware size = new HardwareImpl("hardwareId", null, "hardwareId", defaultLocation, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList.<Volume> of(),
ImagePredicates.any());
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));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(size));
image, image2));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -159,8 +152,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
assertEquals(template.smallest().osArchMatches("X86_32").build().getImage(), image);
@ -181,16 +174,15 @@ public class TemplateBuilderImplTest {
Image image = createMock(Image.class);
OperatingSystem os = createMock(OperatingSystem.class);
Hardware size = new HardwareImpl("hardwareId", null, "hardwareId", defaultLocation, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList.<Volume> of(),
ImagePredicates.idEquals("imageId"));
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));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(size));
.<Image> of(image));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -217,8 +209,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
template.imageId("imageId").build();
@ -237,16 +229,15 @@ public class TemplateBuilderImplTest {
Image image = createMock(Image.class);
OperatingSystem os = createMock(OperatingSystem.class);
Hardware size = new HardwareImpl("hardwareId", null, "hardwareId", defaultLocation, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList.<Volume> of(),
ImagePredicates.idEquals("imageId"));
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));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(size));
.<Image> of(image));
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(hardware));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -273,8 +264,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(image, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(image, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
try {
template.imageId("notImageId").build();
assert false;
@ -295,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -314,8 +305,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
template.options(options).build();
@ -330,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
@ -348,8 +339,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
template.build();
@ -360,10 +351,10 @@ public class TemplateBuilderImplTest {
}
protected TemplateBuilderImpl createTemplateBuilder(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) {
TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, 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;
}
@ -371,10 +362,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -385,8 +376,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
try {
template.imageId("foo").locationId("location").build();
@ -407,10 +398,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -421,8 +412,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
try {
template.imageId("foo").options(provideTemplateOptions()).locationId("location").build();
@ -440,10 +431,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -456,8 +447,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
try {
template.imageId("region/ami").build();
@ -480,10 +471,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
TemplateOptions from = provideTemplateOptions();
@ -497,8 +488,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
try {
template.imageId("region/ami").options(provideTemplateOptions()).build();
@ -516,10 +507,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>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of());
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -528,8 +519,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, sizes, defaultLocation,
optionsProvider, templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,
optionsProvider, templateBuilderProvider);
template.imageDescriptionMatches("imageDescriptionMatches");
template.imageNameMatches("imageNameMatches");

View File

@ -0,0 +1,43 @@
package org.jclouds.collect;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import com.google.common.base.Objects;
public abstract class AbstractMapEntry<K, V> implements Entry<K, V> {
public abstract K getKey();
public abstract V getValue();
public V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue());
}
return false;
}
@Override
public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}

View File

@ -0,0 +1,190 @@
/**
*
* 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.
* ====================================================================
*/
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.io.InputSupplier;
/**
*
*
* @author Adrian Cole
*
*/
public class InputSupplierMap<K, V> extends AbstractMap<K, V> {
final Map<K, InputSupplier<V>> toMap;
final Function<V, InputSupplier<V>> putFunction;
public InputSupplierMap(Map<K, InputSupplier<V>> toMap, Function<V, InputSupplier<V>> putFunction) {
this.toMap = checkNotNull(toMap);
this.putFunction = checkNotNull(putFunction);
}
@Override
public int size() {
return toMap.size();
}
@Override
public V put(K key, V value) {
V old = get(key);
toMap.put(key, value != null ? putFunction.apply(value) : null);
return old;
}
@Override
public boolean containsKey(Object key) {
return toMap.containsKey(key);
}
@Override
public V get(Object key) {
InputSupplier<V> value = toMap.get(key);
try {
return (value != null || toMap.containsKey(key)) ? value.getInput() : null;
} catch (IOException e) {
Throwables.propagate(e);
return null;
}
}
@Override
public V remove(Object key) {
try {
return toMap.containsKey(key) ? toMap.remove(key).getInput() : null;
} catch (IOException e) {
Throwables.propagate(e);
return null;
}
}
@Override
public void clear() {
toMap.clear();
}
@Override
public Set<Entry<K, V>> entrySet() {
return new EntrySet();
}
class EntrySet extends AbstractSet<Entry<K, V>> {
@Override
public int size() {
return InputSupplierMap.this.size();
}
@Override
public Iterator<Entry<K, V>> iterator() {
final Iterator<java.util.Map.Entry<K, InputSupplier<V>>> mapIterator = toMap.entrySet().iterator();
return new Iterator<Entry<K, V>>() {
public boolean hasNext() {
return mapIterator.hasNext();
}
public Entry<K, V> next() {
final java.util.Map.Entry<K, InputSupplier<V>> entry = mapIterator.next();
return new AbstractMapEntry<K, V>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V getValue() {
try {
return entry.getValue().getInput();
} catch (IOException e) {
Throwables.propagate(e);
return null;
}
}
};
}
public void remove() {
mapIterator.remove();
}
};
}
@Override
public void clear() {
toMap.clear();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
Object entryKey = entry.getKey();
Object entryValue = entry.getValue();
V mapValue = InputSupplierMap.this.get(entryKey);
if (mapValue != null) {
return mapValue.equals(entryValue);
}
return entryValue == null && containsKey(entryKey);
}
@Override
public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
toMap.remove(key);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,156 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Function;
/**
* A map that transforms values on the way in and out. Inspired by the guava method
* {@code Maps.transformValues}.
*
* @author Adrian Cole
*
*/
public class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> {
final Map<K, V1> fromMap;
final Function<? super V1, V2> getFunction;
final Function<? super V2, V1> putFunction;
public TransformingMap(Map<K, V1> fromMap, Function<? super V1, V2> getFunction, Function<? super V2, V1> putFunction) {
this.fromMap = checkNotNull(fromMap);
this.getFunction = checkNotNull(getFunction);
this.putFunction = checkNotNull(putFunction);
}
@Override
public int size() {
return fromMap.size();
}
@Override
public V2 put(K key, V2 value) {
V2 old = get(key);
fromMap.put(key, value != null ? putFunction.apply(value) : null);
return old;
}
@Override
public boolean containsKey(Object key) {
return fromMap.containsKey(key);
}
@Override
public V2 get(Object key) {
V1 value = fromMap.get(key);
return (value != null || fromMap.containsKey(key)) ? getFunction.apply(value) : null;
}
@Override
public V2 remove(Object key) {
return fromMap.containsKey(key) ? getFunction.apply(fromMap.remove(key)) : null;
}
@Override
public void clear() {
fromMap.clear();
}
@Override
public Set<Entry<K, V2>> entrySet() {
return new EntrySet();
}
class EntrySet extends AbstractSet<Entry<K, V2>> {
@Override
public int size() {
return TransformingMap.this.size();
}
@Override
public Iterator<Entry<K, V2>> iterator() {
final Iterator<Entry<K, V1>> mapIterator = fromMap.entrySet().iterator();
return new Iterator<Entry<K, V2>>() {
public boolean hasNext() {
return mapIterator.hasNext();
}
public Entry<K, V2> next() {
final Entry<K, V1> entry = mapIterator.next();
return new AbstractMapEntry<K, V2>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V2 getValue() {
return getFunction.apply(entry.getValue());
}
};
}
public void remove() {
mapIterator.remove();
}
};
}
@Override
public void clear() {
fromMap.clear();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> entry = (Entry<?, ?>) o;
Object entryKey = entry.getKey();
Object entryValue = entry.getValue();
V2 mapValue = TransformingMap.this.get(entryKey);
if (mapValue != null) {
return mapValue.equals(entryValue);
}
return entryValue == null && containsKey(entryKey);
}
@Override
public boolean remove(Object o) {
if (contains(o)) {
Entry<?, ?> entry = (Entry<?, ?>) o;
Object key = entry.getKey();
fromMap.remove(key);
return true;
}
return false;
}
}
}

View File

@ -0,0 +1,64 @@
package org.jclouds.domain;
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.util.Map;
import com.google.common.collect.Maps;
/**
*
* @author Adrian Cole
*/
public abstract class ResourceMetadataBuilder<T extends Enum<T>> {
protected String providerId;
protected String name;
protected Location location;
protected URI uri;
protected Map<String, String> userMetadata = Maps.newLinkedHashMap();
public ResourceMetadataBuilder<T> providerId(String providerId) {
this.providerId = providerId;
return this;
}
public ResourceMetadataBuilder<T> name(String name) {
this.name = name;
return this;
}
public ResourceMetadataBuilder<T> location(Location location) {
this.location = location;
return this;
}
public ResourceMetadataBuilder<T> uri(URI uri) {
this.uri = uri;
return this;
}
public ResourceMetadataBuilder<T> userMetadata(Map<String, String> userMetadata) {
this.userMetadata = checkNotNull(userMetadata, "userMetadata");
return this;
}
}

View File

@ -36,12 +36,11 @@ import com.google.inject.internal.Nullable;
*
* @author Adrian Cole
*/
public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata<T>, Serializable {
public abstract class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata<T>, Serializable {
/** The serialVersionUID */
private static final long serialVersionUID = -280558162576368264L;
private final T type;
@Nullable
private final String providerId;
@Nullable
@ -52,9 +51,8 @@ public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata
private final URI uri;
private final Map<String, String> userMetadata = Maps.newLinkedHashMap();
public ResourceMetadataImpl(T type, @Nullable String providerId, @Nullable String name,
@Nullable Location location, @Nullable URI uri, Map<String, String> userMetadata) {
this.type = checkNotNull(type, "type");
public ResourceMetadataImpl(@Nullable String providerId, @Nullable String name, @Nullable Location location,
@Nullable URI uri, Map<String, String> userMetadata) {
this.providerId = providerId;
this.name = name;
this.location = location;
@ -72,14 +70,6 @@ public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata
return (this == o) ? 0 : getName().compareTo(o.getName());
}
/**
* {@inheritDoc}
*/
@Override
public T getType() {
return type;
}
/**
* {@inheritDoc}
*/
@ -122,8 +112,8 @@ public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata
@Override
public String toString() {
return "[type=" + type + ", providerId=" + providerId + ", name=" + name + ", location=" + location
+ ", uri=" + uri + ", userMetadata=" + userMetadata + "]";
return "[type=" + getType() + ", providerId=" + providerId + ", name=" + name + ", location=" + location
+ ", uri=" + uri + ", userMetadata=" + userMetadata + "]";
}
@Override
@ -133,7 +123,6 @@ public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata
result = prime * result + ((providerId == null) ? 0 : providerId.hashCode());
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((uri == null) ? 0 : uri.hashCode());
return result;
}
@ -162,11 +151,6 @@ public class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (uri == null) {
if (other.uri != null)
return false;

View File

@ -17,19 +17,25 @@
* ====================================================================
*/
package com.google.gson;
package org.jclouds.rest;
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 com.google.common.annotations.Beta;
/**
* The gson project use package to control access to their objects. However,
* this prevents us from doing valid work, like controling the json emitted on a
* per-object basis. This is here to afford us to do this.
* designates the module configures a {@code Map<String, ? extends Credentials>}
*
* @author Adrian Cole
*
*/
public class ExposedEscaper extends Escaper {
public ExposedEscaper(boolean escapeHtmlCharacters) {
super(escapeHtmlCharacters);
}
@Beta
@Retention(RUNTIME)
@Target(TYPE)
public @interface ConfiguresCredentialStore {
}

View File

@ -20,10 +20,13 @@
package org.jclouds.rest;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.Future;
import org.jclouds.domain.Credentials;
import org.jclouds.rest.internal.RestContextImpl;
import java.util.concurrent.Future;
import com.google.common.annotations.Beta;
import com.google.inject.ImplementedBy;
/**
@ -56,6 +59,18 @@ public interface RestContext<S, A> {
URI getEndpoint();
/**
* retrieves a list of credentials for resources created within this context, keyed on {@code id}
* of the resource. We are testing this approach for resources such as compute nodes, where you
* could access this externally.
*
*/
@Beta
Map<String, Credentials> getCredentialStore();
@Beta
Map<String, Credentials> credentialStore();
String getIdentity();
String getProvider();

View File

@ -48,6 +48,7 @@ import org.jclouds.rest.annotations.ApiVersion;
import org.jclouds.rest.annotations.Credential;
import org.jclouds.rest.annotations.Identity;
import org.jclouds.rest.annotations.Provider;
import org.jclouds.rest.config.CredentialStoreModule;
import org.jclouds.rest.config.RestClientModule;
import org.jclouds.rest.config.RestModule;
import org.jclouds.rest.internal.RestContextImpl;
@ -67,17 +68,14 @@ import com.google.inject.name.Names;
import com.google.inject.util.Types;
/**
* Creates {@link RestContext} or {@link Injector} instances based on the most
* commonly requested arguments.
* Creates {@link RestContext} or {@link Injector} instances based on the most commonly requested
* arguments.
* <p/>
* Note that Threadsafe objects will be bound as singletons to the Injector or
* Context provided.
* Note that Threadsafe objects will be bound as singletons to the Injector or Context provided.
* <p/>
* <p/>
* If no <code>Module</code>s are specified, the default
* {@link JDKLoggingModule logging} and
* {@link JavaUrlHttpCommandExecutorServiceModule http transports} will be
* installed.
* If no <code>Module</code>s are specified, the default {@link JDKLoggingModule logging} and
* {@link JavaUrlHttpCommandExecutorServiceModule http transports} will be installed.
*
* @author Adrian Cole, Andrew Newdigate
* @see RestContext
@ -137,6 +135,7 @@ public class RestContextBuilder<S, A> {
addHttpModuleIfNeededAndNotPresent(modules);
ifHttpConfigureRestOtherwiseGuiceClientFactory(modules);
addExecutorServiceIfNotPresent(modules);
addCredentialStoreIfNotPresent(modules);
modules.add(new BindPropertiesAndPrincipalContext(properties));
return Guice.createInjector(modules);
}
@ -245,13 +244,27 @@ public class RestContextBuilder<S, A> {
return input.getClass().isAnnotationPresent(SingleThreaded.class);
}
})) {
modules.add(new ExecutorServiceModule(MoreExecutors.sameThreadExecutor(), MoreExecutors.sameThreadExecutor()));
modules.add(new ExecutorServiceModule(MoreExecutors.sameThreadExecutor(), MoreExecutors
.sameThreadExecutor()));
} else {
modules.add(new ExecutorServiceModule());
}
}
}
@VisibleForTesting
protected void addCredentialStoreIfNotPresent(List<Module> modules) {
if (!Iterables.any(modules, new Predicate<Module>() {
public boolean apply(Module input) {
return input.getClass().isAnnotationPresent(ConfiguresCredentialStore.class);
}
}
)) {
modules.add(new CredentialStoreModule());
}
}
@VisibleForTesting
public Properties getProperties() {
return properties;

View File

@ -0,0 +1,182 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.config;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.Utils.toInputStream;
import static org.jclouds.util.Utils.toStringAndClose;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.collect.InputSupplierMap;
import org.jclouds.collect.TransformingMap;
import org.jclouds.domain.Credentials;
import org.jclouds.json.Json;
import org.jclouds.logging.Logger;
import org.jclouds.rest.ConfiguresCredentialStore;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.common.io.InputSupplier;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
/**
*
* @author Adrian Cole
*/
@Beta
@ConfiguresCredentialStore
public class CredentialStoreModule extends AbstractModule {
private static final Map<String, InputSupplier<InputStream>> BACKING = new ConcurrentHashMap<String, InputSupplier<InputStream>>();
private final Map<String, InputStream> backing;
public CredentialStoreModule(Map<String, InputStream> backing) {
this.backing = backing;
}
public CredentialStoreModule() {
this(null);
}
@Override
protected void configure() {
bind(new TypeLiteral<Function<Credentials, InputStream>>() {
}).to(CredentialsToJsonInputStream.class);
bind(new TypeLiteral<Function<InputStream, Credentials>>() {
}).to(CredentialsFromJsonInputStream.class);
if (backing != null) {
bind(new TypeLiteral<Map<String, InputStream>>() {
}).toInstance(backing);
} else {
bind(new TypeLiteral<Map<String, InputSupplier<InputStream>>>() {
}).toInstance(BACKING);
bind(new TypeLiteral<Map<String, InputStream>>() {
}).to(new TypeLiteral<CopyInputStreamInputSupplierMap>() {
});
}
}
@Singleton
public static class CredentialsToJsonInputStream implements Function<Credentials, InputStream> {
private final Json json;
@Inject
CredentialsToJsonInputStream(Json json) {
this.json = json;
}
@Override
public InputStream apply(Credentials from) {
return toInputStream(json.toJson(checkNotNull(from)));
}
}
@Singleton
public static class CopyInputStreamInputSupplierMap extends InputSupplierMap<String, InputStream> {
@Singleton
public static class CopyInputStreamIntoSupplier implements Function<InputStream, InputSupplier<InputStream>> {
@Resource
protected Logger logger = Logger.NULL;
@SuppressWarnings("unchecked")
@Override
public InputSupplier<InputStream> apply(InputStream from) {
if (from == null)
return new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return null;
}
};
try {
return InputSupplier.class.cast(ByteStreams.newInputStreamSupplier(ByteStreams.toByteArray(from)));
} catch (Exception e) {
logger.warn(e, "ignoring problem retrieving credentials");
return null;
} finally {
Closeables.closeQuietly(from);
}
}
}
@Inject
public CopyInputStreamInputSupplierMap(Map<String, InputSupplier<InputStream>> toMap,
CopyInputStreamIntoSupplier putFunction) {
super(toMap, putFunction);
}
public CopyInputStreamInputSupplierMap(Map<String, InputSupplier<InputStream>> toMap) {
super(toMap, new CopyInputStreamIntoSupplier());
}
}
@Singleton
public static class CredentialsFromJsonInputStream implements Function<InputStream, Credentials> {
@Resource
protected Logger logger = Logger.NULL;
private final Json json;
@Inject
CredentialsFromJsonInputStream(Json json) {
this.json = json;
}
private static class PrivateCredentials {
String identity;
String credential;
}
@Override
public Credentials apply(InputStream from) {
try {
PrivateCredentials credentials = json.fromJson(toStringAndClose(checkNotNull(from)),
PrivateCredentials.class);
return new Credentials(credentials.identity, credentials.credential);
} catch (Exception e) {
logger.warn(e, "ignoring problem retrieving credentials");
return null;
}
}
}
@Provides
@Singleton
protected Map<String, Credentials> provideCredentialStore(Map<String, InputStream> backing,
Function<Credentials, InputStream> credentialsSerializer,
Function<InputStream, Credentials> credentialsDeserializer) {
return new TransformingMap<String, InputStream, Credentials>(backing, credentialsDeserializer,
credentialsSerializer);
}
}

View File

@ -21,10 +21,12 @@ package org.jclouds.rest.internal;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import javax.annotation.Resource;
import javax.inject.Inject;
import org.jclouds.domain.Credentials;
import org.jclouds.lifecycle.Closer;
import org.jclouds.logging.Logger;
import org.jclouds.rest.RestContext;
@ -54,11 +56,13 @@ public class RestContextImpl<S, A> implements RestContext<S, A> {
private final String provider;
private final String apiVersion;
private final Utils utils;
private final Map<String, Credentials> credentialStore;
@Inject
protected RestContextImpl(Closer closer, Utils utils, Injector injector, TypeLiteral<S> syncApi,
TypeLiteral<A> asyncApi, @Provider URI endpoint, @Provider String provider, @Identity String identity,
@ApiVersion String apiVersion) {
protected RestContextImpl(Closer closer, Map<String, Credentials> credentialStore, Utils utils, Injector injector,
TypeLiteral<S> syncApi, TypeLiteral<A> asyncApi, @Provider URI endpoint, @Provider String provider,
@Identity String identity, @ApiVersion String apiVersion) {
this.credentialStore = credentialStore;
this.utils = utils;
this.asyncApi = injector.getInstance(Key.get(asyncApi));
this.syncApi = injector.getInstance(Key.get(syncApi));
@ -169,7 +173,17 @@ public class RestContextImpl<S, A> implements RestContext<S, A> {
@Override
public String toString() {
return "RestContextImpl [provider=" + provider + ", endpoint=" + endpoint + ", apiVersion=" + apiVersion
+ ", identity=" + identity + "]";
return " [provider=" + provider + ", endpoint=" + endpoint + ", apiVersion=" + apiVersion + ", identity="
+ identity + "]";
}
@Override
public Map<String, Credentials> getCredentialStore() {
return credentialStore;
}
@Override
public Map<String, Credentials> credentialStore() {
return credentialStore;
}
}

View File

@ -47,10 +47,10 @@ import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -71,7 +71,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.io.OutputSupplier;
import com.google.gson.ExposedEscaper;
import com.google.inject.Module;
import com.google.inject.ProvisionException;
import com.google.inject.spi.Message;
@ -82,11 +81,6 @@ import com.google.inject.spi.Message;
* @author Adrian Cole
*/
public class Utils {
private static final ExposedEscaper escaper = new ExposedEscaper(false);
public static String escapeJsonString(CharSequence plainText) {
return escaper.escapeJsonString(plainText);
}
public static <K, V> Supplier<Map<K, V>> composeMapSupplier(Iterable<Supplier<Map<K, V>>> suppliers) {
return new ListMapSupplier<K, V>(suppliers);

View File

@ -0,0 +1,169 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest;
import static org.jclouds.util.Utils.toStringAndClose;
import static org.testng.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jclouds.crypto.PemsTest;
import org.jclouds.domain.Credentials;
import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule;
import org.jclouds.rest.config.CredentialStoreModule;
import org.jclouds.rest.config.CredentialStoreModule.CopyInputStreamInputSupplierMap;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.google.common.io.InputSupplier;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", sequential = true, testName = "rest.CredentialStoreModuleTest")
public class CredentialStoreModuleTest {
Json json = createInjector().getInstance(Json.class);
@DataProvider(name = "credentials")
public Object[][] createData() {
return new Object[][] { { "root", PemsTest.PRIVATE_KEY }, { "identity", "Base64==" },
{ "user@domain", "pa$sw@rd" }, { "user", "unic₪de" } };
}
@Test(dataProvider = "credentials")
public void deleteObject(String identity, String credential) throws InterruptedException, IOException {
Injector injector = createInjector();
Map<String, InputStream> map = getMap(injector);
check(map, getStore(injector), "i-20312", identity, credential);
}
public void testProvidedMapWithValue() throws IOException {
Map<String, InputStream> map = new CopyInputStreamInputSupplierMap(
new ConcurrentHashMap<String, InputSupplier<InputStream>>());
map.put("test", new ByteArrayInputStream(json.toJson(new Credentials("user", "pass")).getBytes()));
checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass");
checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass");
remove(map, getStore(createInjectorWithProvidedMap(map)), "test");
}
public void testProvidedConsistentAcrossRepeatedWrites() throws IOException {
Map<String, InputStream> map = new CopyInputStreamInputSupplierMap(
new ConcurrentHashMap<String, InputSupplier<InputStream>>());
Injector injector = createInjectorWithProvidedMap(map);
assertEquals(injector.getInstance(Key.get(new TypeLiteral<Map<String, InputStream>>() {
})), map);
Map<String, Credentials> store = getStore(injector);
for (int i = 0; i < 10; i++)
check(map, store, "test" + i, "user" + i, "pass" + i);
}
public void testProvidedConsistentAcrossMultipleInjectors() throws IOException {
Map<String, InputStream> map = new CopyInputStreamInputSupplierMap(
new ConcurrentHashMap<String, InputSupplier<InputStream>>());
put(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass");
checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass");
checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass");
remove(map, getStore(createInjectorWithProvidedMap(map)), "test");
}
public void testDefaultConsistentAcrossMultipleInjectors() throws IOException {
Map<String, InputStream> map = getMap(createInjector());
put(map, getStore(createInjector()), "test", "user", "pass");
checkConsistent(map, getStore(createInjector()), "test", "user", "pass");
checkConsistent(map, getStore(createInjector()), "test", "user", "pass");
remove(map, getStore(createInjector()), "test");
}
protected Map<String, Credentials> getStore(Injector injector) {
return injector.getInstance(Key.get(new TypeLiteral<Map<String, Credentials>>() {
}));
}
protected Map<String, InputStream> getMap(Injector injector) {
return injector.getInstance(Key.get(new TypeLiteral<Map<String, InputStream>>() {
}));
}
protected Injector createInjectorWithProvidedMap(Map<String, InputStream> map) {
return Guice.createInjector(new CredentialStoreModule(map), new GsonModule());
}
protected Injector createInjector() {
return Guice.createInjector(new CredentialStoreModule(), new GsonModule());
}
protected void check(Map<String, InputStream> map, Map<String, Credentials> store, String key, String identity,
String credential) throws IOException {
put(map, store, key, identity, credential);
checkConsistent(map, store, key, identity, credential);
remove(map, store, key);
}
protected void remove(Map<String, InputStream> map, Map<String, Credentials> store, String key) {
store.remove(key);
assertEquals(store.size(), 0);
assertEquals(map.size(), 0);
assertEquals(store.get(key), null);
assertEquals(map.get(key), null);
}
protected void checkConsistent(Map<String, InputStream> map, Map<String, Credentials> store, String key,
String identity, String credential) throws IOException {
assertEquals(store.size(), 1);
assertEquals(map.size(), 1);
// checkRepeatedRead
assertEquals(store.get(key), new Credentials(identity, credential));
assertEquals(store.get(key), new Credentials(identity, credential));
// checkRepeatedRead
checkToJson(map, key, identity, credential);
checkToJson(map, key, identity, credential);
}
protected void checkToJson(Map<String, InputStream> map, String key, String identity, String credential)
throws IOException {
assertEquals(toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential)));
}
protected void put(Map<String, InputStream> map, Map<String, Credentials> store, String key, String identity,
String credential) {
assertEquals(store.size(), 0);
assertEquals(map.size(), 0);
store.put(key, new Credentials(identity, credential));
}
}

View File

@ -26,12 +26,14 @@ import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.http.RequiresHttp;
import org.jclouds.http.config.ConfiguresHttpCommandExecutorService;
import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;
import org.jclouds.logging.config.LoggingModule;
import org.jclouds.logging.config.NullLoggingModule;
import org.jclouds.logging.jdk.config.JDKLoggingModule;
import org.jclouds.rest.config.CredentialStoreModule;
import org.testng.annotations.Test;
import com.google.inject.AbstractModule;
@ -77,6 +79,28 @@ public class RestContextBuilderTest {
assertEquals(modules.remove(0), module);
}
@Test
public void testAddExecutorServiceModuleIfNotPresent() {
List<Module> modules = new ArrayList<Module>();
ExecutorServiceModule module = new ExecutorServiceModule();
modules.add(module);
new RestContextBuilder<String, String>(String.class, String.class, new Properties())
.addExecutorServiceIfNotPresent(modules);
assertEquals(modules.size(), 1);
assertEquals(modules.remove(0), module);
}
@Test
public void testAddCredentialStoreModuleIfNotPresent() {
List<Module> modules = new ArrayList<Module>();
CredentialStoreModule module = new CredentialStoreModule();
modules.add(module);
new RestContextBuilder<String, String>(String.class, String.class, new Properties())
.addCredentialStoreIfNotPresent(modules);
assertEquals(modules.size(), 1);
assertEquals(modules.remove(0), module);
}
@Test
public void testAddNone() {
List<Module> modules = new ArrayList<Module>();

View File

@ -33,9 +33,8 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.Server;
@ -45,8 +44,6 @@ import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
@ -75,8 +72,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() + ""));
}
}
@ -96,8 +93,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) {
Supplier<Set<? extends Image>> images, 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");
@ -107,28 +104,41 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override
public NodeMetadata apply(Server from) {
String tag = parseTagFromName(from.getName());
Set<String> ipSet = ImmutableSet.of(from.getIp().getIp());
NodeState state = serverStateToNodeState.get(from.getState());
Credentials creds = client.getServerServices().getServerCredentialsList().get(from.getName());
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.location(locations.get().get(from.getDatacenter().getId() + ""));
builder.tag(parseTagFromName(from.getName()));
builder.hardware(parseHardware(from));
builder.imageId(from.getImage().getId() + "");
Image image = parseImage(from);
if (image != null)
builder.operatingSystem(image.getOperatingSystem());
builder.state(serverStateToNodeState.get(from.getState()));
builder.publicAddresses(ImmutableSet.of(from.getIp().getIp()));
builder.credentials(client.getServerServices().getServerCredentialsList().get(from.getName()));
return builder.build();
}
protected Image parseImage(Server from) {
Image image = null;
try {
image = Iterables.find(images.get(), new FindImageForServer(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s", from);
}
return image;
}
protected Hardware parseHardware(Server from) {
Hardware hardware = null;
try {
hardware = Iterables.find(hardwares.get(), new FindHardwareForServer(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching hardware for server %s", from);
}
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", locations.get().get(
from.getDatacenter().getId() + ""), null, ImmutableMap.<String, String> of(), tag, hardware, from
.getImage().getId()
+ "", image != null ? image.getOperatingSystem() : null, state, ipSet, ImmutableList.<String> of(),
creds);
return hardware;
}
}

View File

@ -19,20 +19,18 @@
package org.jclouds.gogrid.compute.suppliers;
import static org.jclouds.compute.predicates.ImagePredicates.any;
import java.util.Set;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
@ -42,23 +40,23 @@ import com.google.common.collect.ImmutableSet;
@Singleton
public class GoGridHardwareSupplier implements Supplier<Set<? extends Hardware>> {
public static final HardwareImpl H8192 = new HardwareImpl("5", "5", "5", null, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(8, 1.0)), 8192, ImmutableList.of(new VolumeImpl(
480.0f, true, true)), any());
public static final HardwareImpl H4096 = new HardwareImpl("4", "4", "4", null, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(4, 1.0)), 4096, ImmutableList.of(new VolumeImpl(
240.0f, true, true)), any());
public static final HardwareImpl H2048 = new HardwareImpl("3", "3", "3", null, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(2, 1.0)), 2048, ImmutableList.of(new VolumeImpl(
120.0f, true, true)), any());
public static final HardwareImpl H1024 = new HardwareImpl("2", "2", "2", null, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1, 1.0)), 1024, ImmutableList.of(new VolumeImpl(
60.0f, true, true)), any());
public static final HardwareImpl H512 = new HardwareImpl("1", "1", "1", null, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(0.5, 1.0)), 512, ImmutableList.of(new VolumeImpl(
30.0f, true, true)), any());
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<HardwareImpl> H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192);
public static final ImmutableSet<Hardware> H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192);
@Override
public Set<? extends Hardware> get() {

View File

@ -28,19 +28,17 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.gogrid.GoGridClient;
import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.gogrid.util.GoGridUtils;
import org.jclouds.logging.Logger;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
@ -70,30 +68,34 @@ public class GoGridImageSupplier implements Supplier<Set<? extends Image>> {
logger.debug(">> providing images");
Set<ServerImage> allImages = sync.getImageServices().getImageList();
for (ServerImage from : allImages) {
OsFamily osFamily = null;
String osName = from.getOs().getName();
String osArch = from.getArchitecture().getDescription();
String osVersion = null;// TODO
String osDescription = from.getOs().getDescription();
boolean is64Bit = (from.getOs().getName().indexOf("64") != -1 || from.getDescription().indexOf("64") != -1);
String description = from.getDescription();
String version = "";
String matchedOs = GoGridUtils.parseStringByPatternAndGetNthMatchGroup(osName, GOGRID_OS_NAME_PATTERN, 1);
try {
osFamily = OsFamily.fromValue(matchedOs.toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matchedOs);
}
Credentials defaultCredentials = authenticator.execute(from);
// TODO determine DC images are in
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
images.add(new ImageImpl(from.getId() + "", from.getFriendlyName(), from.getId() + "", null, null,
ImmutableMap.<String, String> of(), os, description, version, defaultCredentials));
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId()+"");
builder.name(from.getFriendlyName());
builder.description(from.getDescription());
builder.defaultCredentials(authenticator.execute(from));
builder.operatingSystem(parseOs(from));
images.add(builder.build());
}
logger.debug("<< images(%d)", images.size());
return images;
}
protected OperatingSystem parseOs(ServerImage from) {
OsFamily osFamily = null;
String osName = from.getOs().getName();
String osArch = from.getArchitecture().getDescription();
String osVersion = null;// TODO
String osDescription = from.getOs().getDescription();
boolean is64Bit = (from.getOs().getName().indexOf("64") != -1 || from.getDescription().indexOf("64") != -1);
String matchedOs = GoGridUtils.parseStringByPatternAndGetNthMatchGroup(osName, GOGRID_OS_NAME_PATTERN, 1);
try {
osFamily = OsFamily.fromValue(matchedOs.toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matchedOs);
}
// TODO determine DC images are in
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
return os;
}
}

View File

@ -30,10 +30,11 @@ 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.Hardware;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.ComputeServiceContextImpl;
@ -44,14 +45,18 @@ 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.rackspace.cloudservers.compute.strategy.CloudServersAddNodeWithTagStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersDestroyNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersGetNodeMetadataStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersListNodesStrategy;
import org.jclouds.rackspace.cloudservers.compute.strategy.CloudServersRebootNodeStrategy;
import org.jclouds.rackspace.cloudservers.compute.suppliers.CloudServersImageSupplier;
import org.jclouds.rackspace.cloudservers.compute.suppliers.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;
@ -82,6 +87,16 @@ public class CloudServersComputeServiceContextModule extends BaseComputeServiceC
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>>() {
@ -102,31 +117,31 @@ public class CloudServersComputeServiceContextModule extends BaseComputeServiceC
}
@VisibleForTesting
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();
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

View File

@ -0,0 +1,56 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rackspace.cloudservers.compute.functions;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class CloudServersImageToImage implements Function<org.jclouds.rackspace.cloudservers.domain.Image, Image> {
private final Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem> imageToOs;
@Inject
CloudServersImageToImage(Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem> imageToOs) {
this.imageToOs = imageToOs;
}
public Image apply(org.jclouds.rackspace.cloudservers.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.description(from.getName());
builder.version(from.getUpdated().getTime() + "");
builder.operatingSystem(imageToOs.apply(from));
builder.defaultCredentials(new Credentials("root", null));
Image image = builder.build();
return image;
}
}

View File

@ -0,0 +1,71 @@
/**
*
* 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.functions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class CloudServersImageToOperatingSystem implements
Function<org.jclouds.rackspace.cloudservers.domain.Image, OperatingSystem> {
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
public OperatingSystem apply(final org.jclouds.rackspace.cloudservers.domain.Image from) {
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
boolean is64Bit = true;
Matcher matcher = RACKSPACE_PATTERN.matcher(from.getName());
if (from.getName().indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
return os;
}
}

View File

@ -0,0 +1,44 @@
/**
*
* 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.functions;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.rackspace.cloudservers.domain.Flavor;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
/**
* @author Adrian Cole
*/
@Singleton
public class FlavorToHardware implements Function<Flavor, Hardware> {
public Hardware apply(Flavor from) {
return new HardwareBuilder().ids(from.getId() + "").name(from.getName())
.processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))).ram(from.getRam())
.volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDisk(), true, true))).build();
}
}

View File

@ -33,8 +33,10 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
@ -52,27 +54,25 @@ import com.google.common.collect.Iterables;
*/
@Singleton
public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
private final Supplier<Location> location;
private final Map<ServerStatus, NodeState> serverToNodeState;
private final Supplier<Set<? extends Image>> images;
private final Supplier<Set<? extends Hardware>> hardwares;
protected final Supplier<Location> location;
protected final Map<String, Credentials> credentialStore;
protected final Map<ServerStatus, NodeState> serverToNodeState;
protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwares;
@Resource
protected Logger logger = Logger.NULL;
private static class FindImageForServer implements Predicate<Image> {
private final Location location;
private final Server instance;
private FindImageForServer(Location location, Server instance) {
this.location = location;
private FindImageForServer(Server instance) {
this.instance = instance;
}
@Override
public boolean apply(Image input) {
return input.getProviderId().equals(instance.getImageId() + "")
&& (input.getLocation() == null || input.getLocation().equals(location.getParent()));
return input.getProviderId().equals(instance.getImageId() + "");
}
}
@ -90,9 +90,10 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
}
@Inject
ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Supplier<Set<? extends Image>> images,
Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Map<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location");
this.hardwares = checkNotNull(hardwares, "hardwares");
@ -100,24 +101,37 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Override
public NodeMetadata apply(Server from) {
String tag = parseTagFromName(from.getName());
Location host = new LocationImpl(LocationScope.HOST, from.getHostId(), from.getHostId(), location.get());
Image image = null;
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.location(new LocationImpl(LocationScope.HOST, from.getHostId(), from.getHostId(), location.get()));
builder.userMetadata(from.getMetadata());
builder.tag(parseTagFromName(from.getName()));
builder.imageId(from.getImageId() + "");
builder.operatingSystem(parseOperatingSystem(from));
builder.hardware(parseHardware(from));
builder.state(serverToNodeState.get(from.getStatus()));
builder.publicAddresses(from.getAddresses().getPublicAddresses());
builder.privateAddresses(from.getAddresses().getPrivateAddresses());
builder.credentials(credentialStore.get(from.getId() + ""));
return builder.build();
}
protected Hardware parseHardware(Server from) {
try {
image = Iterables.find(images.get(), new FindImageForServer(host, from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}
Hardware hardware = null;
try {
hardware = Iterables.find(hardwares.get(), new FindHardwareForServer(from));
return Iterables.find(hardwares.get(), new FindHardwareForServer(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching hardware for server %s", from);
}
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", host, null, from.getMetadata(),
tag, hardware, from.getImageId() + "", image != null ? image.getOperatingSystem() : null,
serverToNodeState.get(from.getStatus()), from.getAddresses().getPublicAddresses(), from.getAddresses()
.getPrivateAddresses(), null);
return null;
}
protected OperatingSystem parseOperatingSystem(Server from) {
try {
return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem();
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}
return null;
}
}

View File

@ -21,41 +21,43 @@ package org.jclouds.rackspace.cloudservers.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Server;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class CloudServersAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final CloudServersClient client;
protected final CloudServersClient client;
protected final Map<String, Credentials> credentialStore;
protected final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected CloudServersAddNodeWithTagStrategy(CloudServersClient client) {
protected CloudServersAddNodeWithTagStrategy(CloudServersClient client, Map<String, Credentials> credentialStore,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = checkNotNull(client, "client");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.serverToNodeMetadata = checkNotNull(serverToNodeMetadata, "serverToNodeMetadata");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Server server = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getHardware().getProviderId()));
return new NodeMetadataImpl(server.getId() + "", name, server.getId() + "", new LocationImpl(LocationScope.HOST,
server.getHostId(), server.getHostId(), template.getLocation()), null, server.getMetadata(), tag,
template.getHardware(), template.getImage().getId(), template.getImage().getOperatingSystem(),
NodeState.PENDING, server.getAddresses().getPublicAddresses(), server.getAddresses()
.getPrivateAddresses(), new Credentials("root", server.getAdminPass()));
Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()),
Integer.parseInt(template.getHardware().getProviderId()));
credentialStore.put(from.getId() + "", new Credentials("root", from.getAdminPass()));
return serverToNodeMetadata.apply(from);
}
}

View File

@ -19,6 +19,8 @@
package org.jclouds.rackspace.cloudservers.compute.suppliers;
import static org.jclouds.rackspace.cloudservers.options.ListOptions.Builder.withDetails;
import java.util.Set;
import javax.annotation.Resource;
@ -26,23 +28,15 @@ import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.domain.Flavor;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
@ -55,27 +49,20 @@ public class CloudServersHardwareSupplier implements Supplier<Set<? extends Hard
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final CloudServersClient sync;
private final Supplier<Location> location;
private final Function<Flavor, Hardware> flavorToHardware;
@Inject
CloudServersHardwareSupplier(CloudServersClient sync, Supplier<Location> location,
Function<ComputeMetadata, String> indexer) {
CloudServersHardwareSupplier(CloudServersClient sync, Function<Flavor, Hardware> flavorToHardware) {
this.sync = sync;
this.location = location;
this.flavorToHardware = flavorToHardware;
}
@Override
public Set<? extends Hardware> get() {
final Set<Hardware> sizes = Sets.newHashSet();
logger.debug(">> providing sizes");
for (final Flavor from : sync.listFlavors(ListOptions.Builder.withDetails())) {
sizes.add(new HardwareImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0)), from
.getRam(), ImmutableList.of(new VolumeImpl((float) from.getDisk(), true, true)),
ImagePredicates.any()));
}
logger.debug("<< sizes(%d)", sizes.size());
return sizes;
final Set<Hardware> hardware;
logger.debug(">> providing hardware");
hardware = Sets.newLinkedHashSet(Iterables.transform(sync.listFlavors(withDetails()), flavorToHardware));
logger.debug("<< hardware(%d)", hardware.size());
return hardware;
}
}

View File

@ -19,9 +19,9 @@
package org.jclouds.rackspace.cloudservers.compute.suppliers;
import static org.jclouds.rackspace.cloudservers.options.ListOptions.Builder.withDetails;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -29,18 +29,13 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.rackspace.cloudservers.CloudServersClient;
import org.jclouds.rackspace.cloudservers.options.ListOptions;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
@ -49,52 +44,27 @@ import com.google.common.collect.Sets;
*/
@Singleton
public class CloudServersImageSupplier implements Supplier<Set<? extends Image>> {
public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private CloudServersClient sync;
private Supplier<Location> location;
protected final CloudServersClient sync;
protected final Function<org.jclouds.rackspace.cloudservers.domain.Image, Image> cloudServersImageToImage;
@Inject
CloudServersImageSupplier(CloudServersClient sync, Supplier<Location> location) {
CloudServersImageSupplier(CloudServersClient sync,
Function<org.jclouds.rackspace.cloudservers.domain.Image, Image> cloudServersImageToImage) {
this.sync = sync;
this.location = location;
this.cloudServersImageToImage = cloudServersImageToImage;
}
@Override
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
Set<Image> images;
logger.debug(">> providing images");
for (final org.jclouds.rackspace.cloudservers.domain.Image from : sync.listImages(ListOptions.Builder
.withDetails())) {
String version = from.getUpdated().getTime() + "";
Matcher matcher = RACKSPACE_PATTERN.matcher(from.getName());
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
boolean is64Bit = true;
if (from.getName().indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
images.add(new ImageImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), os, from.getName(), version, new Credentials("root", null)));
}
images = Sets.<Image> newLinkedHashSet(Iterables.transform(sync.listImages(withDetails()),
cloudServersImageToImage));
logger.debug("<< images(%d)", images.size());
return images;
}

View File

@ -0,0 +1,59 @@
/**
*
* 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.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.domain.Credentials;
import org.jclouds.rackspace.cloudservers.functions.ParseImageFromJsonResponseTest;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "cloudservers.CloudServersImageToImageTest")
public class CloudServersImageToImageTest {
@Test
public void testApplyWhereImageNotFound() throws UnknownHostException {
assertEquals(
convertImage(),
new ImageBuilder()
.name("CentOS 5.2")
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null))
.ids("2").version("1286712000000").build());
}
public static Image convertImage() {
org.jclouds.rackspace.cloudservers.domain.Image image = ParseImageFromJsonResponseTest.parseImage();
CloudServersImageToImage parser = new CloudServersImageToImage(new CloudServersImageToOperatingSystem());
return parser.apply(image);
}
}

View File

@ -0,0 +1,68 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rackspace.cloudservers.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.rackspace.cloudservers.domain.Flavor;
import org.jclouds.rackspace.cloudservers.functions.ParseFlavorFromJsonResponseTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "cloudservers.FlavorToHardwareTest")
public class FlavorToHardwareTest {
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
@Test
public void test() throws UnknownHostException {
assertEquals(
convertFlavor(),
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());
}
public static Hardware convertFlavor() {
Flavor flavor = ParseFlavorFromJsonResponseTest.parseFlavor();
FlavorToHardware parser = new FlavorToHardware();
return parser.apply(flavor);
}
}

View File

@ -19,10 +19,6 @@
package org.jclouds.rackspace.cloudservers.compute.functions;
import static org.easymock.EasyMock.expect;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
@ -30,19 +26,28 @@ import java.util.Map;
import java.util.Set;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
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.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
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.domain.Addresses;
import org.jclouds.rackspace.cloudservers.compute.config.CloudServersComputeServiceContextModule;
import org.jclouds.rackspace.cloudservers.domain.Server;
import org.jclouds.rackspace.cloudservers.domain.ServerStatus;
import org.jclouds.rackspace.cloudservers.functions.ParseServerFromJsonResponseTest;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
@ -51,76 +56,151 @@ import com.google.common.collect.ImmutableSet;
*/
@Test(groups = "unit", testName = "cloudservers.ServerToNodeMetadataTest")
public class ServerToNodeMetadataTest {
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
@SuppressWarnings("unchecked")
@Test
public void testApplySetsTagFromNameAndSetsMetadata() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = createMock(Map.class);
org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);
public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound()
throws UnknownHostException {
Credentials creds = new Credentials("root", "abdce");
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
org.jclouds.compute.domain.Hardware jcHardware = createMock(org.jclouds.compute.domain.Hardware.class);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(jcHardware);
Server server = createMock(Server.class);
expect(server.getId()).andReturn(10000).atLeastOnce();
expect(server.getName()).andReturn("cloudservers-ea3").atLeastOnce();
expect(server.getHostId()).andReturn("AHOST").atLeastOnce();
expect(server.getMetadata()).andReturn(ImmutableMap.<String, String> of()).atLeastOnce();
expect(server.getStatus()).andReturn(ServerStatus.ACTIVE).atLeastOnce();
expect(serverStateToNodeState.get(ServerStatus.ACTIVE)).andReturn(NodeState.RUNNING);
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
Location location = new LocationImpl(LocationScope.HOST, "AHOST", "AHOST", provider);
Addresses addresses = createMock(Addresses.class);
expect(server.getAddresses()).andReturn(addresses).atLeastOnce();
Set<String> publicAddresses = ImmutableSet.of("12.10.10.1");
Set<String> privateAddresses = ImmutableSet.of("10.10.10.1");
expect(addresses.getPublicAddresses()).andReturn(publicAddresses);
expect(addresses.getPrivateAddresses()).andReturn(privateAddresses);
expect(server.getImageId()).andReturn(2000).atLeastOnce();
expect(jcImage.getProviderId()).andReturn("2000").atLeastOnce();
expect(jcHardware.getProviderId()).andReturn("1000").atLeastOnce();
expect(server.getFlavorId()).andReturn(1000).atLeastOnce();
expect(jcImage.getLocation()).andReturn(provider).atLeastOnce();
expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();
replay(addresses);
replay(jcImage);
replay(jcHardware);
replay(serverStateToNodeState);
replay(server);
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, 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.getLocation(), location);
assertEquals(metadata.getImageId(), "2000");
assert metadata.getUserMetadata() != null;
assertEquals(metadata.getTag(), "cloudservers");
assertEquals(metadata.getCredentials(), null);
assertEquals(metadata.getPrivateAddresses(), privateAddresses);
assertEquals(metadata.getPublicAddresses(), publicAddresses);
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());
}
verify(addresses);
verify(serverStateToNodeState);
verify(server);
verify(jcImage);
verify(jcHardware);
@Test
public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.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));
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());
}
}
@Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.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));
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(
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 testApplyWhereImageAndHardwareFound() throws UnknownHostException {
Map<ServerStatus, NodeState> serverStateToNodeState = CloudServersComputeServiceContextModule.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));
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(
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());
}
}

View File

@ -22,7 +22,6 @@ package org.jclouds.rackspace.cloudservers.functions;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
@ -32,6 +31,7 @@ import org.jclouds.rackspace.cloudservers.domain.Flavor;
import org.jclouds.rackspace.config.RackspaceParserModule;
import org.testng.annotations.Test;
import com.google.gson.Gson;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
@ -44,18 +44,24 @@ import com.google.inject.TypeLiteral;
*/
@Test(groups = "unit", testName = "cloudservers.ParseFlavorFromJsonResponseTest")
public class ParseFlavorFromJsonResponseTest {
Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule());
public void test() {
Flavor response = parseFlavor();
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/cloudservers/test_get_flavor_details.json");
String json = new Gson().toJson(response);
assertEquals(json, "{\"id\":1,\"name\":\"256 MB Server\",\"disk\":10,\"ram\":256}");
}
public static Flavor parseFlavor() {
Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule());
InputStream is = ParseFlavorFromJsonResponseTest.class
.getResourceAsStream("/cloudservers/test_get_flavor_details.json");
UnwrapOnlyJsonValue<Flavor> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Flavor>>() {
}));
Flavor response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
assertEquals(response.getId(), 1);
assertEquals(response.getName(), "256 MB Server");
assertEquals(response.getRam(), new Integer(256));
assertEquals(response.getDisk(), new Integer(10));
return response;
}
}

View File

@ -51,11 +51,7 @@ public class ParseImageFromJsonResponseTest {
DateService dateService = i.getInstance(DateService.class);
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/cloudservers/test_get_image_details.json");
UnwrapOnlyJsonValue<Image> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Image>>() {
}));
Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
Image response = parseImage();
assertEquals(response.getId(), 2);
assertEquals(response.getName(), "CentOS 5.2");
@ -64,5 +60,19 @@ public class ParseImageFromJsonResponseTest {
assertEquals(response.getServerId(), new Integer(12));
assertEquals(response.getStatus(), ImageStatus.SAVING);
assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z")));
}
public static Image parseImage() {
Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule());
InputStream is = ParseImageFromJsonResponseTest.class
.getResourceAsStream("/cloudservers/test_get_image_details.json");
UnwrapOnlyJsonValue<Image> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Image>>() {
}));
Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
return response;
}
}

View File

@ -50,14 +50,8 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit", testName = "cloudservers.ParseServerFromJsonResponseTest")
public class ParseServerFromJsonResponseTest {
Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule());
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/cloudservers/test_get_server_detail.json");
UnwrapOnlyJsonValue<Server> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Server>>() {
}));
Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
Server response = parseServer();
assertEquals(response.getId(), 1234);
assertEquals(response.getName(), "sample-server");
@ -76,4 +70,15 @@ public class ParseServerFromJsonResponseTest {
}
public static Server parseServer() {
Injector i = Guice.createInjector(new RackspaceParserModule(), new GsonModule());
InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/cloudservers/test_get_server_detail.json");
UnwrapOnlyJsonValue<Server> parser = i.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Server>>() {
}));
Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is)));
return response;
}
}

View File

@ -32,8 +32,9 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
@ -45,8 +46,6 @@ import org.jclouds.rimuhosting.miro.domain.internal.RunningState;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
/**
@ -58,9 +57,10 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
@Resource
protected Logger logger = Logger.NULL;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
private final Supplier<Set<? extends Image>> images;
protected final Map<String, Credentials> credentialStore;
protected final Function<Server, Iterable<String>> getPublicAddresses;
protected final Map<RunningState, NodeState> runningStateToNodeState;
protected final Supplier<Set<? extends Image>> images;
private static class FindImageForServer implements Predicate<Image> {
private final Location location;
@ -74,38 +74,46 @@ 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<RunningState, NodeState> runningStateToNodeState, Supplier<Set<? extends Image>> images) {
Map<String, Credentials> credentialStore, Map<RunningState, NodeState> runningStateToNodeState,
Supplier<Set<? extends Image>> images) {
this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState");
this.images = checkNotNull(images, "images");
}
@Override
public NodeMetadata apply(Server from) {
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
// TODO properly look up location
Location location = new LocationImpl(LocationScope.ZONE, from.getLocation().getId(),
from.getLocation().getName(), null);
String tag = parseTagFromName(from.getName());
Credentials creds = null;
LocationImpl location = new LocationImpl(LocationScope.ZONE, from.getLocation().getId(), from.getLocation()
.getName(), null);
builder.location(location);
builder.tag(parseTagFromName(from.getName()));
builder.imageId(from.getImageId() + "");
builder.operatingSystem(parseOperatingSystem(from, location));
builder.hardware(null);// TODO
builder.state(runningStateToNodeState.get(from.getState()));
builder.publicAddresses(getPublicAddresses.apply(from));
builder.credentials(credentialStore.get(from.getId() + ""));
return builder.build();
}
Image image = null;
protected OperatingSystem parseOperatingSystem(Server from, LocationImpl location) {
try {
image = Iterables.find(images.get(), new FindImageForServer(location, from));
return Iterables.find(images.get(), new FindImageForServer(location, from)).getOperatingSystem();
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for server %s in location %s", from, location);
}
NodeState state = runningStateToNodeState.get(from.getState());
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location, null, ImmutableMap
.<String, String> of(), tag, null, from.getImageId(), image != null ? image.getOperatingSystem() : null,
state, getPublicAddresses.apply(from), ImmutableList.<String> of(), creds);
return null;
}
}

View File

@ -27,19 +27,14 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import org.jclouds.rimuhosting.miro.domain.NewServerResponse;
import org.jclouds.rimuhosting.miro.domain.Server;
import org.jclouds.rimuhosting.miro.domain.internal.RunningState;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
*
@ -47,29 +42,27 @@ import com.google.common.collect.ImmutableMap;
*/
@Singleton
public class RimuHostingAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final RimuHostingClient client;
private final Function<Server, Iterable<String>> getPublicAddresses;
private final Map<RunningState, NodeState> runningStateToNodeState;
protected final RimuHostingClient client;
protected final Map<String, Credentials> credentialStore;
protected final Function<Server, NodeMetadata> serverToNodeMetadata;
@Inject
protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client,
Function<Server, Iterable<String>> getPublicAddresses, Map<RunningState, NodeState> runningStateToNodeState) {
protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client, Map<String, Credentials> credentialStore,
Function<Server, NodeMetadata> serverToNodeMetadata) {
this.client = client;
this.getPublicAddresses = getPublicAddresses;
this.runningStateToNodeState = runningStateToNodeState;
this.credentialStore = credentialStore;
this.serverToNodeMetadata = serverToNodeMetadata;
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
NewServerResponse serverResponse = client.createServer(name, checkNotNull(template.getImage().getProviderId(),
"imageId"), checkNotNull(template.getHardware().getProviderId(), "hardwareId"));
Server server = client.getServer(serverResponse.getServer().getId());
NodeMetadata node = new NodeMetadataImpl(server.getId().toString(), name, server.getId().toString(), template
.getLocation(), null, ImmutableMap.<String, String> of(), tag, template.getHardware(), template
.getImage().getId(), template.getImage().getOperatingSystem(), runningStateToNodeState.get(server
.getState()), getPublicAddresses.apply(server), ImmutableList.<String> of(), new Credentials("root",
serverResponse.getNewInstanceRequest().getCreateOptions().getPassword()));
return node;
NewServerResponse serverResponse = client.createServer(name,
checkNotNull(template.getImage().getProviderId(), "imageId"),
checkNotNull(template.getHardware().getProviderId(), "hardwareId"));
Server from = client.getServer(serverResponse.getServer().getId());
credentialStore.put(from.getId() + "", new Credentials("root", serverResponse.getNewInstanceRequest()
.getCreateOptions().getPassword()));
return serverToNodeMetadata.apply(from);
}
}

View File

@ -27,10 +27,10 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
@ -40,7 +40,6 @@ import org.jclouds.rimuhosting.miro.domain.PricingPlan;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
@ -78,9 +77,9 @@ public class RimuHostingHardwareSupplier implements Supplier<Set<? extends Hardw
}
});
sizes.add(new HardwareImpl(from.getId(), from.getId(), from.getId(), location, null, ImmutableMap
.<String, String> of(), ImmutableList.of(new Processor(1, 1.0)), from.getRam(), ImmutableList
.of(new VolumeImpl((float) from.getDiskSize(), true, true)), ImagePredicates.any()));
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

@ -29,16 +29,15 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import org.jclouds.rimuhosting.miro.RimuHostingClient;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
/**
@ -63,32 +62,38 @@ public class RimuHostingImageSupplier implements Supplier<Set<? extends Image>>
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
logger.debug(">> providing images");
for (final org.jclouds.rimuhosting.miro.domain.Image from : sync.getImageList()) {
String version = null;
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getId();
boolean is64Bit = from.getId().indexOf("64") != -1;
osDescription = from.getId();
Matcher matcher = RIMU_PATTERN.matcher(from.getId());
if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(1).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
images.add(new ImageImpl(from.getId(), from.getDescription(), from.getId(), null, null, ImmutableMap
.<String, String> of(), os, from.getDescription(), version, new Credentials("root", null)));
for (org.jclouds.rimuhosting.miro.domain.Image from : sync.getImageList()) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getDescription());
builder.description(from.getDescription());
builder.operatingSystem(parseOs(from));
builder.defaultCredentials(new Credentials("root", null));
images.add(builder.build());
}
logger.debug("<< images(%d)", images.size());
return images;
}
protected OperatingSystem parseOs(final org.jclouds.rimuhosting.miro.domain.Image from) {
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getId();
boolean is64Bit = from.getId().indexOf("64") != -1;
osDescription = from.getId();
Matcher matcher = RIMU_PATTERN.matcher(from.getId());
if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(1).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
return os;
}
}

View File

@ -34,6 +34,7 @@ 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;
@ -50,7 +51,10 @@ 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;
@ -58,6 +62,7 @@ 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;
@ -83,6 +88,15 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont
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>>() {
@ -103,14 +117,14 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont
}
@VisibleForTesting
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();
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

View File

@ -0,0 +1,44 @@
/**
*
* 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.functions;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.slicehost.domain.Flavor;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
/**
* @author Adrian Cole
*/
@Singleton
public class FlavorToHardware implements Function<Flavor, Hardware> {
public Hardware apply(Flavor from) {
return new HardwareBuilder().ids(from.getId() + "").name(from.getName())
.processors(ImmutableList.of(new Processor(from.getRam() / 1024.0, 1.0))).ram(from.getRam())
.volumes(ImmutableList.<Volume> of(new VolumeImpl((from.getRam() * 4) / 1024.0f, true, true))).build();
}
}

View File

@ -32,8 +32,10 @@ import javax.inject.Inject;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.slicehost.domain.Slice;
@ -41,17 +43,17 @@ import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
/**
* @author Adrian Cole
*/
public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
private final Supplier<Location> location;
private final Map<Slice.Status, NodeState> sliceToNodeState;
private final Supplier<Set<? extends Image>> images;
private final Supplier<Set<? extends Hardware>> hardwares;
protected final Supplier<Location> location;
protected final Map<Slice.Status, NodeState> sliceToNodeState;
protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwares;
protected final Map<String, Credentials> credentialStore;
@Resource
protected Logger logger = Logger.NULL;
@ -83,9 +85,10 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
}
@Inject
SliceToNodeMetadata(Map<Slice.Status, NodeState> sliceStateToNodeState, Supplier<Set<? extends Image>> images,
Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
SliceToNodeMetadata(Map<Slice.Status, NodeState> sliceStateToNodeState, Map<String, Credentials> credentialStore,
Supplier<Set<? extends Image>> images, Supplier<Location> location, Supplier<Set<? extends Hardware>> hardwares) {
this.sliceToNodeState = checkNotNull(sliceStateToNodeState, "sliceStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location");
this.hardwares = checkNotNull(hardwares, "hardwares");
@ -93,36 +96,50 @@ public class SliceToNodeMetadata implements Function<Slice, NodeMetadata> {
@Override
public NodeMetadata apply(Slice from) {
String tag = parseTagFromName(from.getName());
Image image = null;
NodeMetadataBuilder builder = new NodeMetadataBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.location(location.get());
builder.tag(parseTagFromName(from.getName()));
builder.imageId(from.getImageId() + "");
builder.operatingSystem(parseOperatingSystem(from));
builder.hardware(parseHardware(from));
builder.state(sliceToNodeState.get(from.getStatus()));
builder.publicAddresses(Iterables.filter(from.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return !input.startsWith("10.");
}
}));
builder.privateAddresses(Iterables.filter(from.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith("10.");
}
}));
builder.credentials(credentialStore.get(from.getId() + ""));
return builder.build();
}
protected Hardware parseHardware(Slice from) {
try {
image = Iterables.find(images.get(), new FindImageForSlice(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for slice %s in location %s", from, location);
}
Hardware hardware = null;
try {
hardware = Iterables.find(hardwares.get(), new FindHardwareForSlice(from));
return Iterables.find(hardwares.get(), new FindHardwareForSlice(from));
} catch (NoSuchElementException e) {
logger.warn("could not find a matching hardware for slice %s", from);
}
return new NodeMetadataImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), tag, hardware, from.getImageId() + "", image != null ? image
.getOperatingSystem() : null, sliceToNodeState.get(from.getStatus()), Iterables.filter(from
.getAddresses(), new Predicate<String>() {
return null;
}
@Override
public boolean apply(String input) {
return !input.startsWith("10.");
}
}), Iterables.filter(from.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith("10.");
}
}), null);
protected OperatingSystem parseOperatingSystem(Slice from) {
try {
return Iterables.find(images.get(), new FindImageForSlice(from)).getOperatingSystem();
} catch (NoSuchElementException e) {
logger.warn("could not find a matching image for slice %s in location %s", from, location);
}
return null;
}
}

View File

@ -0,0 +1,55 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.slicehost.compute.functions;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostImageToImage implements Function<org.jclouds.slicehost.domain.Image, Image> {
private final Function<org.jclouds.slicehost.domain.Image, OperatingSystem> imageToOs;
@Inject
SlicehostImageToImage(Function<org.jclouds.slicehost.domain.Image, OperatingSystem> imageToOs) {
this.imageToOs = imageToOs;
}
public Image apply(org.jclouds.slicehost.domain.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.getId() + "");
builder.name(from.getName());
builder.description(from.getName());
builder.operatingSystem(imageToOs.apply(from));
builder.defaultCredentials(new Credentials("root", null));
Image image = builder.build();
return image;
}
}

View File

@ -0,0 +1,71 @@
/**
*
* 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.functions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class SlicehostImageToOperatingSystem implements
Function<org.jclouds.slicehost.domain.Image, OperatingSystem> {
public static final Pattern SLICEHOST_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
public OperatingSystem apply(final org.jclouds.slicehost.domain.Image from) {
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
boolean is64Bit = true;
Matcher matcher = SLICEHOST_PATTERN.matcher(from.getName());
if (from.getName().indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
return os;
}
}

View File

@ -21,21 +21,19 @@ package org.jclouds.slicehost.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.compute.strategy.AddNodeWithTagStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.domain.Slice;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.base.Function;
/**
*
@ -43,35 +41,23 @@ import com.google.common.collect.Iterables;
*/
@Singleton
public class SlicehostAddNodeWithTagStrategy implements AddNodeWithTagStrategy {
private final SlicehostClient client;
protected final SlicehostClient client;
protected final Map<String, Credentials> credentialStore;
protected final Function<Slice, NodeMetadata> sliceToNodeMetadata;
@Inject
protected SlicehostAddNodeWithTagStrategy(SlicehostClient client) {
protected SlicehostAddNodeWithTagStrategy(SlicehostClient client, Map<String, Credentials> credentialStore,
Function<Slice, NodeMetadata> sliceToNodeMetadata) {
this.client = checkNotNull(client, "client");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.sliceToNodeMetadata = checkNotNull(sliceToNodeMetadata, "sliceToNodeMetadata");
}
@Override
public NodeMetadata execute(String tag, String name, Template template) {
Slice slice = client.createSlice(name, Integer.parseInt(template.getImage().getProviderId()), Integer
.parseInt(template.getHardware().getProviderId()));
return new NodeMetadataImpl(slice.getId() + "", name, slice.getId() + "", template.getLocation(), null,
ImmutableMap.<String, String> of(), tag, template.getHardware(), template.getImage().getId(), template
.getImage().getOperatingSystem(), NodeState.PENDING, Iterables.filter(slice.getAddresses(),
new Predicate<String>() {
@Override
public boolean apply(String input) {
return !input.startsWith("10.");
}
}), Iterables.filter(slice.getAddresses(), new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.startsWith("10.");
}
}), new Credentials("root", slice.getRootPassword()));
Slice from = client.createSlice(name, Integer.parseInt(template.getImage().getProviderId()),
Integer.parseInt(template.getHardware().getProviderId()));
credentialStore.put(from.getId() + "", new Credentials("root", from.getRootPassword()));
return sliceToNodeMetadata.apply(from);
}
}

View File

@ -27,19 +27,14 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.internal.HardwareImpl;
import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.predicates.ImagePredicates;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.slicehost.SlicehostClient;
import org.jclouds.slicehost.domain.Flavor;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
@ -53,25 +48,20 @@ public class SlicehostHardwareSupplier implements Supplier<Set<? extends Hardwar
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final SlicehostClient sync;
private final Supplier<Location> location;
private final Function<Flavor, Hardware> flavorToHardware;
@Inject
SlicehostHardwareSupplier(SlicehostClient sync, Supplier<Location> location) {
SlicehostHardwareSupplier(SlicehostClient sync, Function<Flavor, Hardware> flavorToHardware) {
this.sync = sync;
this.location = location;
this.flavorToHardware = flavorToHardware;
}
@Override
public Set<? extends Hardware> get() {
final Set<Hardware> sizes = Sets.newHashSet();
logger.debug(">> providing sizes");
for (final Flavor from : sync.listFlavors()) {
sizes.add(new HardwareImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), ImmutableList.of(new Processor(from.getRam() / 1024.0, 1.0)),
from.getRam(), ImmutableList.of(new VolumeImpl((from.getRam() * 4) / 1024.0f, true, true)),
ImagePredicates.any()));
}
logger.debug("<< sizes(%d)", sizes.size());
return sizes;
final Set<Hardware> hardware;
logger.debug(">> providing hardware");
hardware = Sets.newLinkedHashSet(Iterables.transform(sync.listFlavors(), flavorToHardware));
logger.debug("<< hardware(%d)", hardware.size());
return hardware;
}
}

View File

@ -20,8 +20,6 @@
package org.jclouds.slicehost.compute.suppliers;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -29,17 +27,13 @@ import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.logging.Logger;
import org.jclouds.slicehost.SlicehostClient;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
/**
@ -48,52 +42,28 @@ import com.google.common.collect.Sets;
*/
@Singleton
public class SlicehostImageSupplier implements Supplier<Set<? extends Image>> {
public static final Pattern SLICEHOST_PATTERN = Pattern.compile("(([^ ]*) .*)");
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final SlicehostClient sync;
private final Supplier<Location> location;
protected final SlicehostClient sync;
protected final Function<org.jclouds.slicehost.domain.Image, Image> slicehostImageToImage;
@Inject
SlicehostImageSupplier(SlicehostClient sync, Supplier<Location> location) {
SlicehostImageSupplier(SlicehostClient sync,
Function<org.jclouds.slicehost.domain.Image, Image> slicehostImageToImage) {
this.sync = sync;
this.location = location;
this.slicehostImageToImage = slicehostImageToImage;
}
@Override
public Set<? extends Image> get() {
final Set<Image> images = Sets.newHashSet();
Set<Image> images;
logger.debug(">> providing images");
for (final org.jclouds.slicehost.domain.Image from : sync.listImages()) {
String version = null;
Matcher matcher = SLICEHOST_PATTERN.matcher(from.getName());
OsFamily osFamily = null;
String osName = null;
String osArch = null;
String osVersion = null;
String osDescription = from.getName();
boolean is64Bit = true;
if (from.getName().indexOf("Red Hat EL") != -1) {
osFamily = OsFamily.RHEL;
} else if (from.getName().indexOf("Oracle EL") != -1) {
osFamily = OsFamily.OEL;
} else if (matcher.find()) {
try {
osFamily = OsFamily.fromValue(matcher.group(2).toLowerCase());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", matcher.group(2));
}
}
OperatingSystem os = new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);
images.add(new ImageImpl(from.getId() + "", from.getName(), from.getId() + "", location.get(), null,
ImmutableMap.<String, String> of(), os, from.getName(), version, new Credentials("root", null)));
}
images = Sets.newLinkedHashSet(Iterables.transform(sync.listImages(), slicehostImageToImage));
logger.debug("<< images(%d)", images.size());
return images;
}
}

View File

@ -0,0 +1,68 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.slicehost.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope;
import org.jclouds.domain.internal.LocationImpl;
import org.jclouds.slicehost.domain.Flavor;
import org.jclouds.slicehost.xml.FlavorHandlerTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "cloudservers.FlavorToHardwareTest")
public class FlavorToHardwareTest {
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
@Test
public void test() throws UnknownHostException {
assertEquals(
convertFlavor(),
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());
}
public static Hardware convertFlavor() {
Flavor flavor = FlavorHandlerTest.parseFlavor();
FlavorToHardware parser = new FlavorToHardware();
return parser.apply(flavor);
}
}

View File

@ -0,0 +1,164 @@
/**
*
* 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.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder;
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.domain.Slice;
import org.jclouds.slicehost.xml.SliceHandlerTest;
import org.testng.annotations.Test;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "slicehost.SliceToNodeMetadataTest")
public class SliceToNodeMetadataTest {
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
@Test
public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException {
Credentials creds = new Credentials("root", "abdce");
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.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));
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());
}
@Test
public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException {
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.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));
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());
}
@Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException {
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.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));
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(
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());
}
@Test
public void testApplyWhereImageAndHardwareFound() throws UnknownHostException {
Map<Slice.Status, NodeState> sliceStateToNodeState = SlicehostComputeServiceContextModule.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));
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(
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());
}
}

View File

@ -0,0 +1,63 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.slicehost.compute.functions;
import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
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.xml.ImageHandlerTest;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "slicehost.SlicehostImageToImageTest")
public class SlicehostImageToImageTest {
Location provider = new LocationImpl(LocationScope.ZONE, "dallas", "description", null);
@Test
public void testApplyWhereImageNotFound() throws UnknownHostException {
assertEquals(
convertImage(),
new ImageBuilder()
.name("CentOS 5.2")
.operatingSystem(
new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").is64Bit(true)
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null))
.ids("2").build());
}
public static Image convertImage() {
org.jclouds.slicehost.domain.Image image = ImageHandlerTest.parseImage();
SlicehostImageToImage parser = new SlicehostImageToImage(new SlicehostImageToOperatingSystem());
return parser.apply(image);
}
}

View File

@ -23,29 +23,38 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.slicehost.domain.Flavor;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code FlavorHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "slicehost.FlavorHandler")
public class FlavorHandlerTest extends BaseHandlerTest {
public class FlavorHandlerTest {
ParseSax<Flavor> createParser() {
ParseSax<Flavor> parser = (ParseSax<Flavor>) factory.create(injector.getInstance(FlavorHandler.class));
static ParseSax<Flavor> createParser() {
Injector injector = Guice.createInjector(new SaxParserModule());
ParseSax<Flavor> parser = (ParseSax<Flavor>) injector.getInstance(ParseSax.Factory.class).create(
injector.getInstance(FlavorHandler.class));
return parser;
}
public static Flavor parseFlavor() {
InputStream is = FlavorHandlerTest.class.getResourceAsStream("/test_get_flavor.xml");
return createParser().parse(is);
}
public void test() {
InputStream is = getClass().getResourceAsStream("/test_get_flavor.xml");
Flavor expects = new Flavor(1, "256 slice", 2000, 256);
assertEquals(createParser().parse(is), expects);
assertEquals(parseFlavor(), expects);
}
}

View File

@ -0,0 +1,59 @@
/**
*
* 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.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.slicehost.domain.Image;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ImageHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "slicehost.ImageHandler")
public class ImageHandlerTest {
static ParseSax<Image> createParser() {
Injector injector = Guice.createInjector(new SaxParserModule());
ParseSax<Image> parser = (ParseSax<Image>) injector.getInstance(ParseSax.Factory.class).create(
injector.getInstance(ImageHandler.class));
return parser;
}
public static Image parseImage() {
InputStream is = ImageHandlerTest.class.getResourceAsStream("/test_get_image.xml");
return createParser().parse(is);
}
public void test() {
Image expects = new Image(2, "CentOS 5.2");
assertEquals(parseImage(), expects);
}
}

View File

@ -0,0 +1,73 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.slicehost.xml;
import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.util.Set;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.slicehost.domain.Image;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code ImagesHandler}
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "slicehost.ImagesHandler")
public class ImagesHandlerTest extends BaseHandlerTest {
ParseSax<Set<? extends Image>> createParser() {
ParseSax<Set<? extends Image>> parser = (ParseSax<Set<? extends Image>>) factory.create(injector
.getInstance(ImagesHandler.class));
return parser;
}
public void test() {
InputStream is = getClass().getResourceAsStream("/test_list_images.xml");
Set<? extends Image> expects = ImmutableSet.of(new Image(2, "CentOS 5.2"), new Image(3, "Gentoo 2008.0"),
new Image(4, "Debian 5.0 (lenny)"),
new Image(5, "Fedora 10 (Cambridge)"),
new Image(7, "CentOS 5.3"),
new Image(8, "Ubuntu 9.04 (jaunty)"),
new Image(9, "Arch 2009.02"),
new Image(10, "Ubuntu 8.04.2 LTS (hardy)"),
new Image(11, "Ubuntu 8.10 (intrepid)"),
new Image(12, "Red Hat EL 5.3"),
new Image(13, "Fedora 11 (Leonidas)")
);
assertEquals(createParser().parse(is), expects);
}
}

View File

@ -25,10 +25,13 @@ import java.io.InputStream;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.config.SaxParserModule;
import org.jclouds.slicehost.domain.Slice;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code SliceHandler}
@ -38,26 +41,35 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit", testName = "slicehost.SliceHandler")
public class SliceHandlerTest extends BaseHandlerTest {
ParseSax<Slice> createParser() {
ParseSax<Slice> parser = (ParseSax<Slice>) factory.create(injector.getInstance(SliceHandler.class));
static ParseSax<Slice> createParser() {
Injector injector = Guice.createInjector(new SaxParserModule());
ParseSax<Slice> parser = (ParseSax<Slice>) injector.getInstance(ParseSax.Factory.class).create(
injector.getInstance(SliceHandler.class));
return parser;
}
public static Slice parseSlice() {
return parseSlice("/test_get_slice.xml");
}
public static Slice parseSlice(String resource) {
InputStream is = SliceHandlerTest.class.getResourceAsStream(resource);
return createParser().parse(is);
}
public void test() {
InputStream is = getClass().getResourceAsStream("/test_get_slice.xml");
Slice expects = new Slice(1, "jclouds-foo", 1, 10, null, Slice.Status.BUILD, 0, 0, 0, ImmutableSet.<String> of(
Slice expects = new Slice(1, "jclouds-foo", 1, 2, null, Slice.Status.BUILD, 0, 0, 0, ImmutableSet.<String> of(
"174.143.212.229", "10.176.164.199"), null);
assertEquals(createParser().parse(is), expects);
assertEquals(parseSlice("/test_get_slice.xml"), expects);
}
public void testNew() {
InputStream is = getClass().getResourceAsStream("/test_new_slice.xml");
Slice expects = new Slice(71907, "slicetest", 1, 11, null, Slice.Status.BUILD, 0, 0, 0, ImmutableSet.<String> of(
"10.176.168.15", "67.23.20.114"), "fooadfa1231");
assertEquals(createParser().parse(is), expects);
assertEquals(parseSlice("/test_new_slice.xml"), expects);
}
}

View File

@ -47,7 +47,7 @@ public class SlicesHandlerTest extends BaseHandlerTest {
public void test() {
InputStream is = getClass().getResourceAsStream("/test_get_slice.xml");
Set<? extends Slice> expects = ImmutableSet.of(new Slice(1, "jclouds-foo", 1, 10, null, Slice.Status.BUILD, 0, 0,
Set<? extends Slice> expects = ImmutableSet.of(new Slice(1, "jclouds-foo", 1, 2, null, Slice.Status.BUILD, 0, 0,
0, ImmutableSet.<String> of("174.143.212.229", "10.176.164.199"), null));
assertEquals(createParser().parse(is), expects);

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