From a9de959146d2e0913f41dc661a5338311d06ff9c Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 16 Oct 2010 22:24:22 -0700 Subject: [PATCH] Issue 377: refactored value classes and tests so that we could test and implement credential storage --- .../aws/ec2/compute/EC2ComputeService.java | 37 +- .../EC2ComputeServiceContextModule.java | 45 +- .../aws/ec2/compute/domain/EC2Hardware.java | 197 -- .../compute/domain/EC2HardwareBuilder.java | 262 +++ .../functions/CredentialsForInstance.java | 79 + .../ec2/compute/functions/ImageParser.java | 45 +- .../RunningInstanceToNodeMetadata.java | 158 +- .../internal/EC2TemplateBuilderImpl.java | 14 +- ...rityGroupsAsNeededAndReturnRunOptions.java | 34 +- .../strategy/EC2GetNodeMetadataStrategy.java | 10 +- .../strategy/EC2ListNodesStrategy.java | 21 +- ...faultLoginCredentialsForImageStrategy.java | 15 +- .../EC2RunNodesAndAddToSetStrategy.java | 53 +- .../suppliers/EC2HardwareSupplier.java | 33 +- .../RegionAndNameToImageSupplier.java | 18 +- .../aws/ec2/xml/BaseReservationHandler.java | 16 +- .../xml/DescribeImagesResponseHandler.java | 9 +- ...teAndBlobStoreTogetherHappilyLiveTest.java | 4 + .../aws/CredentialsStoredInBlobStoreTest.java | 102 + .../ec2/compute/EC2ComputeServiceTest.java | 75 +- .../functions/CredentialsForInstanceTest.java | 879 ++++++++ .../compute/functions/ImageParserTest.java | 712 ++----- .../RunningInstanceToNodeMetadataTest.java | 1845 +++++++++-------- .../internal/EC2TemplateBuilderImplTest.java | 53 +- ...GroupsAsNeededAndReturnRunOptionsTest.java | 13 +- .../EC2RunNodesAndAddToSetStrategyTest.java | 45 +- .../DescribeImagesResponseHandlerTest.java | 86 +- .../DescribeInstancesResponseHandlerTest.java | 141 +- .../resources/ec2/describe_instances_nova.xml | 2 +- .../domain/internal/StorageMetadataImpl.java | 53 +- .../compute/ComputeServiceContext.java | 16 + .../domain/ComputeMetadataBuilder.java | 90 + .../compute/domain/HardwareBuilder.java | 124 ++ .../jclouds/compute/domain/ImageBuilder.java | 107 + .../compute/domain/NodeMetadataBuilder.java | 148 ++ .../domain/OperatingSystemBuilder.java | 80 + .../jclouds/compute/domain/VolumeBuilder.java | 80 + .../domain/internal/ComputeMetadataImpl.java | 23 +- .../compute/domain/internal/HardwareImpl.java | 25 +- .../compute/domain/internal/ImageImpl.java | 9 +- .../domain/internal/NodeMetadataImpl.java | 36 +- .../compute/internal/BaseComputeService.java | 127 +- .../internal/ComputeServiceContextImpl.java | 21 +- .../compute/predicates/ImagePredicates.java | 32 +- .../StubComputeServiceContextModule.java | 226 +- .../compute/util/ComputeServiceUtils.java | 60 +- .../jclouds/compute/util/ComputeUtils.java | 53 +- .../compute/BaseComputeServiceLiveTest.java | 9 + .../StubComputeServiceIntegrationTest.java | 50 +- .../internal/TemplateBuilderImplTest.java | 151 +- .../org/jclouds/collect/AbstractMapEntry.java | 43 + .../org/jclouds/collect/InputSupplierMap.java | 190 ++ .../org/jclouds/collect/TransformingMap.java | 156 ++ .../domain/ResourceMetadataBuilder.java | 64 + .../domain/internal/ResourceMetadataImpl.java | 26 +- .../rest/ConfiguresCredentialStore.java} | 24 +- .../java/org/jclouds/rest/RestContext.java | 17 +- .../org/jclouds/rest/RestContextBuilder.java | 31 +- .../rest/config/CredentialStoreModule.java | 182 ++ .../rest/internal/RestContextImpl.java | 24 +- .../src/main/java/org/jclouds/util/Utils.java | 8 +- .../rest/CredentialStoreModuleTest.java | 169 ++ .../jclouds/rest/RestContextBuilderTest.java | 24 + .../functions/ServerToNodeMetadata.java | 46 +- .../suppliers/GoGridHardwareSupplier.java | 38 +- .../suppliers/GoGridImageSupplier.java | 52 +- ...oudServersComputeServiceContextModule.java | 69 +- .../functions/CloudServersImageToImage.java | 56 + .../CloudServersImageToOperatingSystem.java | 71 + .../compute/functions/FlavorToHardware.java | 44 + .../functions/ServerToNodeMetadata.java | 66 +- .../CloudServersAddNodeWithTagStrategy.java | 28 +- .../CloudServersHardwareSupplier.java | 35 +- .../suppliers/CloudServersImageSupplier.java | 56 +- .../CloudServersImageToImageTest.java | 59 + .../functions/FlavorToHardwareTest.java | 68 + .../functions/ServerToNodeMetadataTest.java | 216 +- .../ParseFlavorFromJsonResponseTest.java | 22 +- .../ParseImageFromJsonResponseTest.java | 20 +- .../ParseServerFromJsonResponseTest.java | 19 +- .../functions/ServerToNodeMetadata.java | 50 +- .../RimuHostingAddNodeWithTagStrategy.java | 35 +- .../RimuHostingHardwareSupplier.java | 11 +- .../suppliers/RimuHostingImageSupplier.java | 57 +- .../SlicehostComputeServiceContextModule.java | 30 +- .../compute/functions/FlavorToHardware.java | 44 + .../functions/SliceToNodeMetadata.java | 85 +- .../functions/SlicehostImageToImage.java | 55 + .../SlicehostImageToOperatingSystem.java | 71 + .../SlicehostAddNodeWithTagStrategy.java | 42 +- .../suppliers/SlicehostHardwareSupplier.java | 30 +- .../suppliers/SlicehostImageSupplier.java | 52 +- .../functions/FlavorToHardwareTest.java | 68 + .../functions/SliceToNodeMetadataTest.java | 164 ++ .../functions/SlicehostImageToImageTest.java | 63 + .../slicehost/xml/FlavorHandlerTest.java | 21 +- .../slicehost/xml/ImageHandlerTest.java | 59 + .../slicehost/xml/ImagesHandlerTest.java | 73 + .../slicehost/xml/SliceHandlerTest.java | 30 +- .../slicehost/xml/SlicesHandlerTest.java | 2 +- .../src/test/resources/test_get_image.xml | 7 + .../src/test/resources/test_get_slice.xml | 2 +- .../compute/VCloudExpressComputeClient.java | 4 +- .../VCloudComputeServiceContextModule.java | 13 +- ...oudExpressComputeServiceContextModule.java | 5 + .../compute/domain/VCloudExpressImage.java | 55 - .../vcloud/compute/domain/VCloudImage.java | 55 - .../compute/functions/HardwareForVApp.java | 28 +- .../functions/HardwareForVAppTemplate.java | 28 +- .../HardwareForVCloudExpressVApp.java | 28 +- .../functions/ImageForVAppTemplate.java | 27 +- .../ImageForVCloudExpressVAppTemplate.java | 40 +- .../ResourceAllocationsToVolumes.java | 29 +- .../compute/functions/VAppToNodeMetadata.java | 81 + .../VCloudExpressVAppToNodeMetadata.java | 87 + .../CommonVCloudComputeClientImpl.java | 20 - .../VCloudExpressComputeClientImpl.java | 15 +- .../VCloudExpressAddNodeWithTagStrategy.java | 41 +- .../VCloudExpressGetNodeMetadataStrategy.java | 50 +- .../VCloudExpressListNodesStrategy.java | 17 +- .../VCloudGetNodeMetadataStrategy.java | 47 +- .../strategy/VCloudListNodesStrategy.java | 13 +- .../suppliers/StaticHardwareSupplier.java | 16 +- .../compute/TerremarkVCloudComputeClient.java | 105 +- .../TerremarkVCloudComputeService.java | 28 +- ...markVCloudComputeServiceContextModule.java | 12 +- ...emarkVCloudExpressVAppToNodeMetadata.java} | 39 +- ...TerremarkVCloudAddNodeWithTagStrategy.java | 23 +- .../TerremarkVCloudComputeClientTest.java | 33 +- 129 files changed, 6918 insertions(+), 3518 deletions(-) delete mode 100644 aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2Hardware.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2HardwareBuilder.java create mode 100644 aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstance.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/CredentialsStoredInBlobStoreTest.java create mode 100644 aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataBuilder.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/HardwareBuilder.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/OperatingSystemBuilder.java create mode 100644 compute/src/main/java/org/jclouds/compute/domain/VolumeBuilder.java create mode 100644 core/src/main/java/org/jclouds/collect/AbstractMapEntry.java create mode 100644 core/src/main/java/org/jclouds/collect/InputSupplierMap.java create mode 100644 core/src/main/java/org/jclouds/collect/TransformingMap.java create mode 100644 core/src/main/java/org/jclouds/domain/ResourceMetadataBuilder.java rename core/src/main/java/{com/google/gson/ExposedEscaper.java => org/jclouds/rest/ConfiguresCredentialStore.java} (65%) create mode 100644 core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java create mode 100755 core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java create mode 100644 rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImage.java create mode 100644 rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToOperatingSystem.java create mode 100644 rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardware.java create mode 100644 rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java create mode 100644 rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java create mode 100644 slicehost/src/main/java/org/jclouds/slicehost/compute/functions/FlavorToHardware.java create mode 100644 slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java create mode 100644 slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToOperatingSystem.java create mode 100644 slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java create mode 100644 slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java create mode 100644 slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java create mode 100644 slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java create mode 100644 slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java create mode 100644 slicehost/src/test/resources/test_get_image.xml delete mode 100644 vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudExpressImage.java delete mode 100644 vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudImage.java create mode 100644 vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java create mode 100644 vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java rename vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/{strategy/TerremarkVCloudGetNodeMetadataStrategy.java => functions/TerremarkVCloudExpressVAppToNodeMetadata.java} (65%) diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java index c968259751..dcb9619252 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/EC2ComputeService.java @@ -24,8 +24,8 @@ import static org.jclouds.aws.ec2.util.EC2Utils.parseHandle; import static org.jclouds.util.Utils.checkNotEmpty; import java.util.Map; -import java.util.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 placementGroupDeleted; @Inject - protected EC2ComputeService(ComputeServiceContext context, Supplier> images, - Supplier> sizes, Supplier> locations, - ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, - RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, - DestroyNodeStrategy destroyNodeStrategy, Provider templateBuilderProvider, - Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, - Map credentialsMap, @Named("SECURITY") Map securityGroupMap, - @Named("PLACEMENT") Map placementGroupMap, - @Named("DELETED") Predicate placementGroupDeleted) { - super(context, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, runNodesAndAddToSetStrategy, - rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning, - nodeTerminated, utils, timeouts, executor); + protected EC2ComputeService(ComputeServiceContext context, Map credentialStore, + Supplier> images, Supplier> sizes, + Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, EC2Client ec2Client, + Map credentialsMap, @Named("SECURITY") Map securityGroupMap, + @Named("PLACEMENT") Map placementGroupMap, + @Named("DELETED") Predicate placementGroupDeleted) { + 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) { diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java index e126db52c1..ad56c28f01 100755 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/config/EC2ComputeServiceContextModule.java @@ -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 instanceToNodeState = ImmutableMap + . builder().put(InstanceState.PENDING, NodeState.PENDING) + .put(InstanceState.RUNNING, NodeState.RUNNING).put(InstanceState.SHUTTING_DOWN, NodeState.PENDING) + .put(InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING) + .put(InstanceState.STOPPED, NodeState.SUSPENDED).put(InstanceState.UNRECOGNIZED, NodeState.UNRECOGNIZED) + .build(); + + @Singleton + @Provides + Map provideServerToNodeState() { + return instanceToNodeState; + } + @Provides @Singleton @Named("PRESENT") @@ -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>() { + }).to(RunningInstanceToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(CredentialsForInstance.class); bind(new TypeLiteral() { }).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); @@ -220,28 +243,28 @@ public class EC2ComputeServiceContextModule extends BaseComputeServiceContextMod @Provides @Singleton - protected ConcurrentMap provideImageMap(RegionAndIdToImage regionAndIdToImage) { + protected Map provideImageMap(RegionAndIdToImage regionAndIdToImage) { return new MapMaker().makeComputingMap(regionAndIdToImage); } @Provides @Singleton protected Supplier> provideRegionAndNameToImageSupplierCache( - @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) { + @Named(PROPERTY_SESSION_INTERVAL) long seconds, final RegionAndNameToImageSupplier supplier) { return new RetryOnTimeOutButNotOnAuthorizationExceptionSupplier>( - authException, seconds, new Supplier>() { - @Override - public Map get() { - return supplier.get(); - } - }); + authException, seconds, new Supplier>() { + @Override + public Map get() { + return supplier.get(); + } + }); } @Override protected Supplier> getSourceImageSupplier(Injector injector) { Supplier> map = injector.getInstance(Key - .get(new TypeLiteral>>() { - })); + .get(new TypeLiteral>>() { + })); return Suppliers.compose(new Function, Set>() { @Override public Set apply(Map from) { diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2Hardware.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2Hardware.java deleted file mode 100644 index f96cc46414..0000000000 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2Hardware.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.aws.ec2.compute.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 - */ -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 hasRootDeviceType(final RootDeviceType type) { - checkNotNull(type, "type must be defined"); - return new Predicate() { - @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 processors, Integer ram, - Iterable volumes, RootDeviceType rootDeviceType) { - this(null, instanceType, processors, ram, volumes, hasRootDeviceType(rootDeviceType)); - } - - EC2Hardware(Location location, String instanceType, Iterable processors, Integer ram, - Iterable volumes, Predicate supportsImage) { - super(instanceType, instanceType, instanceType, location, null, ImmutableMap. of(), processors, - ram, volumes, supportsImage); - this.instanceType = instanceType; - } - - EC2Hardware(String instanceType, Iterable processors, Integer ram, - Iterable volumes, boolean is64Bit) { - this(null, instanceType, processors, ram, volumes, is64Bit ? is64Bit() : not(is64Bit())); - } - - public EC2Hardware(Location location, String instanceType, Iterable processors, Integer ram, - Iterable 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. 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; - } - -} diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2HardwareBuilder.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2HardwareBuilder.java new file mode 100644 index 0000000000..a234c39968 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/domain/EC2HardwareBuilder.java @@ -0,0 +1,262 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.ec2.compute.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 + */ +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 { + 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 processors) { + return EC2HardwareBuilder.class.cast(super.processors(processors)); + } + + public EC2HardwareBuilder volumes(List volumes) { + return EC2HardwareBuilder.class.cast(super.volumes(volumes)); + } + + public EC2HardwareBuilder supportsImage(Predicate 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 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. 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. 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. 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. 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. 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. 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. 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. 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. 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))); + } + +} diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstance.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstance.java new file mode 100644 index 0000000000..4206ba5a89 --- /dev/null +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstance.java @@ -0,0 +1,79 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.ec2.compute.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 { + private final Map credentialsMap; + private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider; + private final Map imageForInstance; + + @Inject + CredentialsForInstance(Map credentialsMap, + PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, Map 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; + } +} \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java index 1c300d533e..d39f6d0d5f 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/functions/ImageParser.java @@ -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> locations; @@ -92,7 +91,7 @@ public class ImageParser implements Function> locations, Supplier defaultLocation, @Provider String provider) { + Supplier> locations, Supplier 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 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() { + builder.location(Iterables.find(locations.get(), new Predicate() { @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 - . 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 instanceToNodeState = ImmutableMap. builder() - .put(InstanceState.PENDING, NodeState.PENDING).put(InstanceState.RUNNING, NodeState.RUNNING).put( - InstanceState.SHUTTING_DOWN, NodeState.PENDING) - .put(InstanceState.TERMINATED, NodeState.TERMINATED).put(InstanceState.STOPPING, NodeState.PENDING).put( - InstanceState.STOPPED, NodeState.SUSPENDED) - .put(InstanceState.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); - - private final EC2Client client; - private final Map credentialsMap; - private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider; - private final Supplier> locations; - private final Supplier> hardware; - private final ConcurrentMap imageMap; + protected final Supplier> locations; + protected final Supplier> hardware; + protected final Map instanceToImage; + protected final Map credentialStore; + protected final Map instanceToNodeState; @Inject - RunningInstanceToNodeMetadata(EC2Client client, Map credentialsMap, - PopulateDefaultLoginCredentialsForImageStrategy credentialProvider, - ConcurrentMap imageMap, Supplier> locations, - Supplier> hardware) { - this.client = checkNotNull(client, "client"); - this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); - this.credentialProvider = checkNotNull(credentialProvider, "credentialProvider"); + RunningInstanceToNodeMetadata(Map instanceToNodeState, + Map credentialStore, Map instanceToImage, + Supplier> locations, Supplier> 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 userMetadata = ImmutableMap. of(); - - NodeState state = instanceToNodeState.get(instance.getInstanceState()); - - Set publicAddresses = nullSafeSet(instance.getIpAddress()); - Set 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 addEBS(final RunningInstance instance, Iterable volumes) { + static List addEBS(final RunningInstance instance, Iterable volumes) { Iterable ebsVolumes = Iterables.transform(instance.getEbsBlockDevices().entrySet(), - new Function, Volume>() { + new Function, Volume>() { - @Override - public Volume apply(Entry from) { - return new VolumeImpl(from.getValue().getVolumeId(), Volume.Type.SAN, null, from.getKey(), - instance.getRootDeviceName() != null - && instance.getRootDeviceName().equals(from.getKey()), true); - } - }); + @Override + public Volume apply(Entry from) { + return new VolumeImpl(from.getValue().getVolumeId(), Volume.Type.SAN, null, from.getKey(), instance + .getRootDeviceName() != null && instance.getRootDeviceName().equals(from.getKey()), true); + } + }); if (instance.getRootDeviceType() == RootDeviceType.EBS) { volumes = Iterables.filter(volumes, new Predicate() { @@ -156,19 +139,10 @@ public class RunningInstanceToNodeMetadata implements Function imageMap; + private final Map imageMap; @Inject protected EC2TemplateBuilderImpl(Supplier> locations, Supplier> images, - Supplier> sizes, Supplier defaultLocation, - Provider optionsProvider, - @Named("DEFAULT") Provider defaultTemplateProvider, - ConcurrentMap imageMap) { + Supplier> sizes, Supplier defaultLocation, + Provider optionsProvider, + @Named("DEFAULT") Provider defaultTemplateProvider, Map 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); diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java index 1bcf789798..64c8eb219a 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java @@ -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 credentialsMap, - @Named("SECURITY") Map securityGroupMap, - @Named("PLACEMENT") Map placementGroupMap, CreateUniqueKeyPair createUniqueKeyPair, - CreateSecurityGroupIfNeeded createSecurityGroupIfNeeded, - CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded) { + @Named("SECURITY") Map securityGroupMap, + @Named("PLACEMENT") Map 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; diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2GetNodeMetadataStrategy.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2GetNodeMetadataStrategy.java index cc656b6d92..001af59126 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2GetNodeMetadataStrategy.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2GetNodeMetadataStrategy.java @@ -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 runningInstanceToNodeMetadata; @Inject - protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) { + protected EC2GetNodeMetadataStrategy(EC2Client client, + Function 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; diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2ListNodesStrategy.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2ListNodesStrategy.java index b6e1adf7ca..3085055ab5 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2ListNodesStrategy.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2ListNodesStrategy.java @@ -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 regionMap; - private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata; + private final Function runningInstanceToNodeMetadata; private final ExecutorService executor; @Inject protected EC2ListNodesStrategy(EC2AsyncClient client, @Region Map regionMap, - RunningInstanceToNodeMetadata runningInstanceToNodeMetadata, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { + Function 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 listDetailsOnNodesMatching(Predicate filter) { - Iterable>> reservations = transformParallel(regionMap - .keySet(), new Function>>>() { + Iterable>> reservations = transformParallel( + regionMap.keySet(), new Function>>>() { - @Override - public Future>> apply(String from) { - return client.getInstanceServices().describeInstancesInRegion(from); - } + @Override + public Future>> apply(String from) { + return client.getInstanceServices().describeInstancesInRegion(from); + } - }, executor, null, logger, "reservations"); + }, executor, null, logger, "reservations"); Iterable instances = concat(concat(reservations)); Iterable nodes = filter(transform(instances, runningInstanceToNodeMetadata), filter); diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2PopulateDefaultLoginCredentialsForImageStrategy.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2PopulateDefaultLoginCredentialsForImageStrategy.java index 6fda83850e..dbbdbe0824 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2PopulateDefaultLoginCredentialsForImageStrategy.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2PopulateDefaultLoginCredentialsForImageStrategy.java @@ -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); } } diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategy.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategy.java index 5774177d32..10136c5d42 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategy.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategy.java @@ -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 runningInstanceToNodeMetadata; @VisibleForTesting final ComputeUtils utils; - final Predicate instancePresent; + final Function instanceToCredentials; + final Map credentialStore; @Inject EC2RunNodesAndAddToSetStrategy( - EC2Client client, - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions, - @Named("PRESENT") Predicate instancePresent, - RunningInstanceToNodeMetadata runningInstanceToNodeMetadata, ComputeUtils utils) { + EC2Client client, + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions, + @Named("PRESENT") Predicate instancePresent, + Function runningInstanceToNodeMetadata, + Function instanceToCredentials, Map 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> execute(String tag, int count, Template template, Set goodNodes, - Map badNodes) { + Map badNodes) { Reservation reservation = createKeyPairAndSecurityGroupsAsNeededThenRunInstances(tag, - count, template); + count, template); Iterable 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 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 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); } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java index 16c081ea4e..8bdf4e6615 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/EC2HardwareSupplier.java @@ -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> { @Inject EC2HardwareSupplier(Supplier> 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> { @Override public Set get() { - Set sizes = newHashSet(); + Set sizes = newLinkedHashSet(); for (String ccAmi : ccAmis) { final String region = ccAmi.split("/")[0]; Location location = find(locations.get(), new Predicate() { @@ -80,14 +86,11 @@ public class EC2HardwareSupplier implements Supplier> { } }); - 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. 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. 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; } } \ No newline at end of file diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/RegionAndNameToImageSupplier.java b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/RegionAndNameToImageSupplier.java index 09d507f0a3..19b2da8eeb 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/RegionAndNameToImageSupplier.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/compute/suppliers/RegionAndNameToImageSupplier.java @@ -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 images; + private final Map images; @Inject RegionAndNameToImageSupplier(@Region Map regionMap, DescribeImagesParallel describer, - @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, - final ImageParser parser, final ConcurrentMap images) { + @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, + final ImageParser parser, final Map images) { this.regionMap = regionMap; this.describer = describer; this.ccAmis = ccAmis; @@ -108,11 +107,12 @@ public class RegionAndNameToImageSupplier implements Supplier> providing images"); - Iterable> queries = concat(getDescribeQueriesForOwnersInRegions( - regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis).entrySet()); + Iterable> queries = concat( + getDescribeQueriesForOwnersInRegions(regionMap, amiOwners).entrySet(), ccAmisToDescribeQueries(ccAmis) + .entrySet()); - Iterable parsedImages = filter(transform(describer.apply(queries), parser), Predicates - .notNull()); + Iterable parsedImages = filter(transform(describer.apply(queries), parser), + Predicates.notNull()); images.putAll(uniqueIndex(parsedImages, new Function() { @@ -137,7 +137,7 @@ public class RegionAndNameToImageSupplier implements Supplier getDescribeQueriesForOwnersInRegions(Map regionMap, - final String[] amiOwners) { + final String[] amiOwners) { final DescribeImagesOptions options = getOptionsForOwners(amiOwners); return transformValues(regionMap, new Function() { diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/BaseReservationHandler.java b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/BaseReservationHandler.java index d25c699c67..04c867735b 100644 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/BaseReservationHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/BaseReservationHandler.java @@ -230,14 +230,14 @@ public abstract class BaseReservationHandler 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 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 extends HandlerForGeneratedReque } protected Reservation newReservation() { - String region = EC2Utils.findRegionInArgsOrNull(getRequest()); + String region = getRequest() != null ? EC2Utils.findRegionInArgsOrNull(getRequest()) : null; if (region == null) region = defaultRegion; Reservation info = new Reservation(region, groupIds, instances, - ownerId, requesterId, reservationId); + ownerId, requesterId, reservationId); this.groupIds = Sets.newLinkedHashSet(); this.instances = Sets.newLinkedHashSet(); this.ownerId = null; diff --git a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java index 244d4d2c72..ddee393a37 100755 --- a/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java +++ b/aws/core/src/main/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandler.java @@ -46,7 +46,8 @@ import com.google.common.collect.Sets; * DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2010-06-15/" * * @author Adrian Cole - * @see */ public class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { @@ -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); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ComputeAndBlobStoreTogetherHappilyLiveTest.java b/aws/core/src/test/java/org/jclouds/aws/ComputeAndBlobStoreTogetherHappilyLiveTest.java index aac06fb99e..c250f99847 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ComputeAndBlobStoreTogetherHappilyLiveTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ComputeAndBlobStoreTogetherHappilyLiveTest.java @@ -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. + *

+ * 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 */ diff --git a/aws/core/src/test/java/org/jclouds/aws/CredentialsStoredInBlobStoreTest.java b/aws/core/src/test/java/org/jclouds/aws/CredentialsStoredInBlobStoreTest.java new file mode 100644 index 0000000000..7b09e8fab3 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/CredentialsStoredInBlobStoreTest.java @@ -0,0 +1,102 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws; + +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. + *

+ * 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 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 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 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 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)); + } + } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java index ce59b6b315..e865f9c6e4 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/EC2ComputeServiceTest.java @@ -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 - . 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> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); + . of(image)); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . 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)); + . of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(), m1_small() + .build(), m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(), m2_4xlarge().build(), + CC1_4XLARGE)); return new TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(location), optionsProvider, - templateBuilderProvider) { + templateBuilderProvider) { }; } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java new file mode 100644 index 0000000000..28664cde04 --- /dev/null +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/CredentialsForInstanceTest.java @@ -0,0 +1,879 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.aws.ec2.compute.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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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. 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 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. of(new Processor(1.0, 1.0))); +// assertEquals(metadata.getHardware().getRam(), 1740); +// assertEquals(metadata.getHardware().getVolumes(), +// ImmutableList. 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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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()).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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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. newHashMap()); +// expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); +// +// replay(imageMap); +// replay(client); +// replay(amiClient); +// replay(credentialsMap); +// replay(credentialProvider); +// replay(instance); +// replay(jcImage); +// +// Function 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. of(new Processor(1.0, 1.0))); +// assertEquals(metadata.getHardware().getRam(), 1740); +// assertEquals(metadata.getHardware().getVolumes(), +// ImmutableList. 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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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()).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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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. 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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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. newHashMap()); +// expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); +// +// replay(imageMap); +// replay(client); +// replay(amiClient); +// replay(credentialsMap); +// replay(credentialProvider); +// replay(instance); +// replay(jcImage); +// +// Function 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. of(new Processor(1.0, 1.0))); +// assertEquals(metadata.getHardware().getRam(), 1740); +// assertEquals(metadata.getHardware().getVolumes(), +// ImmutableList. 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 credentialsMap = createMock(Map.class); +// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); +// +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// +// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); +// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// . of(location)); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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 credentialsMap = createMock(Map.class); +// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); +// +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// +// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); +// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// . of(location)); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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 credentialsMap = createMock(Map.class); +// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); +// +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// +// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); +// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// . of(location)); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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 credentialsMap = createMock(Map.class); +// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); +// +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// +// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); +// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// . of(location)); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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()).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 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 credentialsMap = createMock(Map.class); +// org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// +// Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); +// Supplier> locations = Suppliers.> ofInstance(ImmutableSet +// . of(location)); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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 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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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 credentialsMap = createMock(Map.class); +// ConcurrentMap imageMap = createMock(ConcurrentMap.class); +// Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet +// . 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> locations = Suppliers.> ofInstance(ImmutableSet +// . 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. 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 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); +// +// } +} diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java index 51683ed795..a5f0443a5f 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/ImageParserTest.java @@ -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 result = parseImages(is); - assertEquals(result.size(), 8); + Set result = convertImages("/ec2/alestic_canonical.xml"); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. 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. 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. 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. 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. 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. 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. 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 result = parseImages(is); + Set result = convertImages("/ec2/vostok.xml"); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. 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 result = parseImages(is); + Set result = convertImages("/ec2/describe_images_cc.xml"); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. 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 result = parseImages(is); + Set result = convertImages("/ec2/rightscale_images.xml"); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. 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. 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 result = parseImages(is); - assertEquals(result.size(), 4); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. of("owner", "admin", "rootDeviceType", - "instance-store")); - assertEquals(image.getVersion(), null); + Set 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 result = parseImages(is); - assertEquals(result.size(), 4); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers - .ofInstance(defaultLocation), "ec2"); + Set 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. 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. 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. 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. 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 result = parseImages(is); - assertEquals(result.size(), 19); - ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), Suppliers - .> ofInstance(ImmutableSet. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. of("owner", "admin", "rootDeviceType", - "instance-store")); - assertEquals(image.getVersion(), null); + Set 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 parseImages(InputStream is) { - DescribeImagesResponseHandler handler = injector.getInstance(DescribeImagesResponseHandler.class); - addDefaultRegionToHandler(handler); - Set 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 convertImages(String resource) { + Set result = DescribeImagesResponseHandlerTest.parseImages(resource); + ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), + Suppliers.> ofInstance(ImmutableSet. 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); - } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index 041a707e21..8ddf849bf5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -19,39 +19,24 @@ 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.options.DescribeImagesOptions.Builder.imageIds; +import static org.jclouds.aws.ec2.compute.domain.EC2HardwareBuilder.m1_small; 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.EC2Hardware; +import org.jclouds.aws.ec2.compute.config.EC2ComputeServiceContextModule; 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.aws.ec2.xml.DescribeInstancesResponseHandlerTest; 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.compute.domain.Image; +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.date.DateService; import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.domain.Credentials; @@ -60,11 +45,11 @@ 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.Iterables; import com.google.common.collect.Maps; /** @@ -76,807 +61,1021 @@ public class RunningInstanceToNodeMetadataTest { public void testAllStatesCovered() { for (InstanceState state : InstanceState.values()) { - assert RunningInstanceToNodeMetadata.instanceToNodeState.containsKey(state) : state; + assert EC2ComputeServiceContextModule.instanceToNodeState.containsKey(state) : state; } } + Location provider = new LocationImpl(LocationScope.REGION, "us-east-1", "description", null); + + @Test + public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound() + throws UnknownHostException { + Credentials creds = new Credentials("root", "abdce"); + + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), + ImmutableSet. of(), ImmutableSet. of(), + ImmutableMap. of("us-east-1/i-9slweygo", creds)); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals(parser.apply(server), + new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses(ImmutableSet. of()) + .privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo").credentials(creds) + .imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo").providerId("i-9slweygo").build()); + } + + @Test + public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFound() throws UnknownHostException { + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), + ImmutableSet. of(), ImmutableSet. of(), ImmutableMap. of()); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals( + parser.apply(server), + new NodeMetadataBuilder().state(NodeState.TERMINATED).publicAddresses(ImmutableSet. of()) + .privateAddresses(ImmutableSet.of("10.128.207.5")).tag("NOTAG-i-9slweygo") + .imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo").providerId("i-9slweygo").build()); + } + + @Test + public void testApplyWhereTagDoesntMatchAndLocationFoundAndImageAndHardwareNotFound() throws UnknownHostException { + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet.of(provider), + ImmutableSet. of(), ImmutableMap. of()); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals( + parser.apply(server), + new NodeMetadataBuilder().state(NodeState.TERMINATED).privateAddresses(ImmutableSet.of("10.128.207.5")) + .tag("NOTAG-i-9slweygo").imageId("us-east-1/ami-25CB1213").id("us-east-1/i-9slweygo") + .providerId("i-9slweygo").location(provider).build()); + } + + @Test + public void testApplyWhereTagDoesntMatchAndImageAndLocationFoundAndHardwareNotFound() throws UnknownHostException { + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet.of(provider), + ImageParserTest.convertImages("/ec2/nova_images.xml"), ImmutableMap. of()); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals( + parser.apply(server), + new NodeMetadataBuilder() + .state(NodeState.TERMINATED) + .privateAddresses(ImmutableSet.of("10.128.207.5")) + .tag("NOTAG-i-9slweygo") + .imageId("us-east-1/ami-25CB1213") + .operatingSystem( + new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("9.10").arch("paravirtual") + .description("nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo") + .providerId("i-9slweygo").location(provider).build()); + } + + @Test + public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationFound() throws UnknownHostException { + RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), + ImmutableSet.of(provider), ImageParserTest.convertImages("/ec2/nova_images.xml"), + ImmutableMap. of()); + + RunningInstance server = firstInstanceFromResource("/ec2/describe_instances_nova.xml"); + + assertEquals( + parser.apply(server), + new NodeMetadataBuilder() + .state(NodeState.TERMINATED) + .privateAddresses(ImmutableSet.of("10.128.207.5")) + .tag("NOTAG-i-9slweygo") + .imageId("us-east-1/ami-25CB1213") + .hardware(m1_small().build()) + .operatingSystem( + new OperatingSystemBuilder().family(OsFamily.UBUNTU).version("9.10").arch("paravirtual") + .description("nebula/ubuntu-karmic").is64Bit(true).build()).id("us-east-1/i-9slweygo") + .providerId("i-9slweygo").location(provider).build()); + } + + protected RunningInstance firstInstanceFromResource(String resource) { + RunningInstance server = Iterables.get( + Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0); + return server; + } + + protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet hardware, + final ImmutableSet locations, Set images, + Map credentialStore) { + Map instanceToNodeState = EC2ComputeServiceContextModule.instanceToNodeState; + + Map instanceToImage = Maps.uniqueIndex(images, new Function() { + + @Override + public RegionAndName apply(Image from) { + return new RegionAndName(from.getLocation().getId(), from.getProviderId()); + } + + }); + Supplier> locationSupplier = new Supplier>() { + + @Override + public Set get() { + return locations; + } + + }; + Supplier> hardwareSupplier = new Supplier>() { + + @Override + public Set get() { + return hardware; + } + + }; + RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(instanceToNodeState, credentialStore, + instanceToImage, locationSupplier, hardwareSupplier); + return parser; + } + 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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M1_SMALL)); - 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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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. of(new Processor(1.0, 1.0))); - assertEquals(metadata.getHardware().getRam(), 1740); - assertEquals(metadata.getHardware().getVolumes(), ImmutableList. 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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M1_SMALL)); - 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()).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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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. newHashMap()); - expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); - - replay(imageMap); - replay(client); - replay(amiClient); - replay(credentialsMap); - replay(credentialProvider); - replay(instance); - replay(jcImage); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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. of(new Processor(1.0, 1.0))); - assertEquals(metadata.getHardware().getRam(), 1740); - assertEquals(metadata.getHardware().getVolumes(), ImmutableList. 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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M1_SMALL)); - 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()).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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M1_SMALL)); - PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); - RunningInstance instance = createMock(RunningInstance.class); - - expect(instance.getId()).andReturn("i-3d640055").atLeastOnce(); - expect(instance.getGroupIds()).andReturn(ImmutableSet. 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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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. newHashMap()); - expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); - - replay(imageMap); - replay(client); - replay(amiClient); - replay(credentialsMap); - replay(credentialProvider); - replay(instance); - replay(jcImage); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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. of(new Processor(1.0, 1.0))); - assertEquals(metadata.getHardware().getRam(), 1740); - assertEquals(metadata.getHardware().getVolumes(), ImmutableList. 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 credentialsMap = createMock(Map.class); - org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); - - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - - Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); - RunningInstance instance = createMock(RunningInstance.class); - - expect(instance.getId()).andReturn("id").atLeastOnce(); - expect(instance.getGroupIds()).andReturn(ImmutableSet. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); - - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - - Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); - RunningInstance instance = createMock(RunningInstance.class); - - expect(instance.getId()).andReturn("id").atLeastOnce(); - expect(instance.getGroupIds()).andReturn(ImmutableSet. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); - - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - - Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - PopulateDefaultLoginCredentialsForImageStrategy credentialProvider = createMock(PopulateDefaultLoginCredentialsForImageStrategy.class); - RunningInstance instance = createMock(RunningInstance.class); - - expect(instance.getId()).andReturn("id").atLeastOnce(); - expect(instance.getGroupIds()).andReturn(ImmutableSet. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); - - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - - Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - 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()).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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - - Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); - Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - 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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); - ConcurrentMap imageMap = createMock(ConcurrentMap.class); - Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet - . of(EC2Hardware.M2_4XLARGE)); - 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> locations = Suppliers.> ofInstance(ImmutableSet - . 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. 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); - - RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(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); - - } + // + // @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 credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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. 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 parser = new RunningInstanceToNodeMetadata(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. of(new + // Processor(1.0, 1.0))); + // assertEquals(metadata.getHardware().getRam(), 1740); + // assertEquals(metadata.getHardware().getVolumes(), + // ImmutableList. 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 testApplyForNovaWhereTagDoesntMatchAndNullAvailabilityZoneIpAddressNoGroups() + // throws + // UnknownHostException { + // EC2Client client = createMock(EC2Client.class); + // AMIClient amiClient = createMock(AMIClient.class); + // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); + // Map credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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()).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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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. newHashMap()); + // expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); + // + // replay(imageMap); + // replay(client); + // replay(amiClient); + // replay(credentialsMap); + // replay(credentialProvider); + // replay(instance); + // replay(jcImage); + // + // Function parser = new RunningInstanceToNodeMetadata(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. of(new + // Processor(1.0, 1.0))); + // assertEquals(metadata.getHardware().getRam(), 1740); + // assertEquals(metadata.getHardware().getVolumes(), + // ImmutableList. 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 testApplyWhereTagDoesntMatchAndUnknownInstanceType() throws UnknownHostException { + // EC2Client client = createMock(EC2Client.class); + // AMIClient amiClient = createMock(AMIClient.class); + // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); + // Map credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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()).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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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 testApplyForNovaWhereTagDoesntMatchAndImageNotFound() throws UnknownHostException + // { + // EC2Client client = createMock(EC2Client.class); + // AMIClient amiClient = createMock(AMIClient.class); + // expect(client.getAMIServices()).andReturn(amiClient).atLeastOnce(); + // Map credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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. newHashMap()); + // expect(instance.getRootDeviceType()).andReturn(RootDeviceType.INSTANCE_STORE); + // + // replay(imageMap); + // replay(client); + // replay(amiClient); + // replay(credentialsMap); + // replay(credentialProvider); + // replay(instance); + // replay(jcImage); + // + // Function parser = new RunningInstanceToNodeMetadata(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. of(new + // Processor(1.0, 1.0))); + // assertEquals(metadata.getHardware().getRam(), 1740); + // assertEquals(metadata.getHardware().getVolumes(), + // ImmutableList. 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 credentialsMap = createMock(Map.class); + // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); + // + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // + // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); + // Supplier> locations = Suppliers.> + // ofInstance(ImmutableSet + // . of(location)); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); + // + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // + // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); + // Supplier> locations = Suppliers.> + // ofInstance(ImmutableSet + // . of(location)); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); + // + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // + // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); + // Supplier> locations = Suppliers.> + // ofInstance(ImmutableSet + // . of(location)); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); + // + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // + // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); + // Supplier> locations = Suppliers.> + // ofInstance(ImmutableSet + // . of(location)); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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()).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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // + // Location location = new LocationImpl(LocationScope.ZONE, "us-east-1a", "description", null); + // Supplier> locations = Suppliers.> + // ofInstance(ImmutableSet + // . of(location)); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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 credentialsMap = createMock(Map.class); + // ConcurrentMap imageMap = + // createMock(ConcurrentMap.class); + // Supplier> hardwares = Suppliers.> + // ofInstance(ImmutableSet + // . 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> locations = Suppliers.> + // ofInstance(ImmutableSet + // . 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. 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 parser = new RunningInstanceToNodeMetadata(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); + // + // } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java index 8b56c4456e..72b4598821 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/internal/EC2TemplateBuilderImplTest.java @@ -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> locations, Supplier> images, - Supplier> sizes, Location defaultLocation, - Provider optionsProvider, Provider templateBuilderProvider) { + Supplier> locations, Supplier> images, + Supplier> sizes, Location defaultLocation, Provider optionsProvider, + Provider templateBuilderProvider) { final RegionAndName knownRegionAndName = new RegionAndName("region", "ami"); ConcurrentMap imageMap = new MapMaker() - .makeComputingMap(new Function() { - @Override - public Image apply(RegionAndName from) { - return from.equals(knownRegionAndName) ? knownImage : null; - } + .makeComputingMap(new Function() { + @Override + public Image apply(RegionAndName from) { + return from.equals(knownRegionAndName) ? knownImage : null; + } - }); + }); return new EC2TemplateBuilderImpl(locations, images, sizes, Suppliers.ofInstance(defaultLocation), - optionsProvider, templateBuilderProvider, imageMap); + optionsProvider, templateBuilderProvider, imageMap); } @SuppressWarnings("unchecked") @@ -96,13 +91,11 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest { Location location = new LocationImpl(LocationScope.REGION, "region", "region", null); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(Sets - . newLinkedHashSet()); + . newLinkedHashSet()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(new HardwareImpl("1", "1", "region/1", location, null, - ImmutableMap. of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList - . of(), ImagePredicates.any()))); + . of(c1_medium().build())); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(new HardwareImpl("1", "1", "region/1", location, null, - ImmutableMap. of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList - . of(), ImagePredicates.any()))); + . of(c1_medium().build())); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of(location)); + . of(location)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(new HardwareImpl("1", "1", "region/1", location, null, - ImmutableMap. of(), ImmutableList.of(new Processor(1, 1.0)), 1, ImmutableList - . of(), ImagePredicates.any()))); + . of(c1_medium().build())); Location defaultLocation = createMock(Location.class); Provider 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); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java index bde0cf8938..c65f73be49 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java @@ -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 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 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 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 generatedGroups = ImmutableSet.of(generatedGroup); diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java index df0ecfbd59..8dde1b4cf5 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/compute/strategy/EC2RunNodesAndAddToSetStrategyTest.java @@ -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 reservation = new Reservation(region, ImmutableSet - . of(), ImmutableSet. of(instance), "ownerId", "requesterId", "reservationId"); + Reservation reservation = new Reservation(region, + ImmutableSet. of(), ImmutableSet. 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 nodes = createMock(Set.class); Map 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 instanceStateRunning = createMock(Predicate.class); RunningInstanceToNodeMetadata runningInstanceToNodeMetadata = createMock(RunningInstanceToNodeMetadata.class); + Function instanceToCredentials = createMock(Function.class); + Map 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); } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java index 305f8c6af6..4c51f9329c 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeImagesResponseHandlerTest.java @@ -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 contents = Sets.newLinkedHashSet(); + Set 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. newHashSet("9961934F"), "aki-4438dd2d", null, "ari-4538dd2c", + RootDeviceType.INSTANCE_STORE, null, ImmutableMap. 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. newHashSet("9961934F"), "aki-4438dd2d", null, "ari-4538dd2c", - RootDeviceType.INSTANCE_STORE, null, ImmutableMap. of(),"paravirtual")); - - Set result = parseImages(is); + Set result = parseImages("/ec2/describe_images.xml"); assertEquals(result, contents); } public void testWindows() { - InputStream is = getClass().getResourceAsStream("/ec2/describe_images_windows.xml"); - Set contents = Sets.newLinkedHashSet(); + Set 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. newHashSet("5771E9A6"), null, "windows", null, + RootDeviceType.INSTANCE_STORE, null, ImmutableMap. 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 - . newHashSet("5771E9A6"), null, "windows", null, - RootDeviceType.INSTANCE_STORE, null, ImmutableMap. of(),"paravirtual")); - - Set result = parseImages(is); + Set result = parseImages("/ec2/describe_images_windows.xml"); assertEquals(result, contents); } public void testEBS() { - InputStream is = getClass().getResourceAsStream("/ec2/describe_images_ebs.xml"); - Set contents = Sets.newLinkedHashSet(); + Set 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. newHashSet(), null, "windows", null, RootDeviceType.EBS, + "/dev/sda1", ImmutableMap. 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. newHashSet(), null, - "windows", null, RootDeviceType.EBS, "/dev/sda1", ImmutableMap - . of("/dev/sda1", new EbsBlockDevice( - "snap-d01272b9", 30, true), "xvdf", new EbsBlockDevice( - "snap-d31272ba", 250, false)),"hvm")); - - Set result = parseImages(is); + Set result = parseImages("/ec2/describe_images_ebs.xml"); assertEquals(result, contents); } - private Set parseImages(InputStream is) { - DescribeImagesResponseHandler handler = injector - .getInstance(DescribeImagesResponseHandler.class); - addDefaultRegionToHandler(handler); - Set result = factory.create(handler).parse(is); - return result; + static ParseSax> createParser() { + Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() { + + @Override + protected void configure() { + bind(String.class).annotatedWith(Region.class).toInstance("us-east-1"); + } + + }); + ParseSax> parser = (ParseSax>) 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 parseImages(String resource) { + InputStream is = ImageParserTest.class.getResourceAsStream(resource); + return createParser().parse(is); } } diff --git a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java index 5d173062e9..f2d6d4e210 100644 --- a/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java +++ b/aws/core/src/test/java/org/jclouds/aws/ec2/xml/DescribeInstancesResponseHandlerTest.java @@ -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> contents = Sets.newLinkedHashSet(); contents.add(new Reservation(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. of(), "ari-a51cf9cc", - null, null, null, null, RootDeviceType.INSTANCE_STORE, null, ImmutableMap - . 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. of(), "ari-a51cf9cc", null, null, null, null, + RootDeviceType.INSTANCE_STORE, null, ImmutableMap. of())), "993194456877", + null, "r-a3c508cb")); - Set> result = getReservations(is); + Set> result = parseRunningInstances("/ec2/describe_instances_running.xml"); assertEquals(result, contents); } public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/ec2/describe_instances.xml"); Set> contents = Sets.newLinkedHashSet(); contents.add(new Reservation(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. 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. 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. 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. of())), "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", null, + "r-44a5402d")); - Set> result = getReservations(is); + Set> 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> contents = Sets.newLinkedHashSet(); contents.add(new Reservation(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 - . of(), "eri-A97113E4", null, null, null, null, RootDeviceType.INSTANCE_STORE, - null, ImmutableMap. 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. of(), "eri-A97113E4", + null, null, null, null, RootDeviceType.INSTANCE_STORE, null, ImmutableMap + . of())), "jclouds", null, "r-4D2A08AD")); - Set> result = getReservations(is); + Set> result = parseRunningInstances("/ec2/describe_instances_euc.xml"); assertEquals(result, contents); } public void testApplyInputStreamNovaNoAvailabilityZone() { - InputStream is = getClass().getResourceAsStream("/ec2/describe_instances_nova.xml"); Set> contents = Sets.newLinkedHashSet(); contents.add(new Reservation(defaultRegion, ImmutableSet.of("default"), ImmutableSet - .of(new RunningInstance(defaultRegion, ImmutableSet. 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. of("None"), null, null, null, null, null, - RootDeviceType.INSTANCE_STORE, null, ImmutableMap. of())), "tislam1", - null, "r-opqeylmj")); + .of(new RunningInstance(defaultRegion, ImmutableSet. 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. of("None"), null, null, null, null, null, + RootDeviceType.INSTANCE_STORE, null, ImmutableMap. of())), "tislam1", null, + "r-opqeylmj")); - Set> result = getReservations(is); + Set> 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> contents = Sets.newLinkedHashSet(); contents.add(new Reservation(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. of(), - "ari-a51cf9cc", null, null, null, null, RootDeviceType.EBS, "/dev/sda1", ImmutableMap - . 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. of(), "ari-a51cf9cc", null, null, null, null, + RootDeviceType.EBS, "/dev/sda1", ImmutableMap. of( + "/dev/sda1", + new EbsBlockDevice("vol-dc6ca8b5", Attachment.Status.ATTACHED, dateService + .iso8601DateParse("2009-12-30T04:06:29.000Z"), true)))), "993194456877", null, + "r-596dd731")); - Set> result = getReservations(is); + Set> result = parseRunningInstances("/ec2/describe_instances_ebs.xml"); assertEquals(result, contents); } - private Set> getReservations(InputStream is) { - DescribeInstancesResponseHandler handler = injector.getInstance(DescribeInstancesResponseHandler.class); - addDefaultRegionToHandler(handler); - Set> result = factory.create(handler).parse(is); - return result; + static ParseSax>> createParser() { + Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() { + + @Override + protected void configure() { + bind(String.class).annotatedWith(Region.class).toInstance("us-east-1"); + } + + }); + ParseSax>> parser = (ParseSax>>) 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> parseRunningInstances(String resource) { + InputStream is = DescribeInstancesResponseHandlerTest.class.getResourceAsStream(resource); + return createParser().parse(is); } } diff --git a/aws/core/src/test/resources/ec2/describe_instances_nova.xml b/aws/core/src/test/resources/ec2/describe_instances_nova.xml index ac9b55209a..4717ec132d 100644 --- a/aws/core/src/test/resources/ec2/describe_instances_nova.xml +++ b/aws/core/src/test/resources/ec2/describe_instances_nova.xml @@ -11,7 +11,7 @@ 2010-09-09T18:09:42Z i-9slweygo - ami-h30p5im0 + ami-25CB1213 1 shutdown diff --git a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java index 74350f0a58..4e416806d9 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java @@ -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 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 userMetadata) { - super(type, id, name, location, uri, userMetadata); + @Nullable Location location, @Nullable URI uri, @Nullable String eTag, @Nullable Date lastModified, + Map 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; } /** diff --git a/compute/src/main/java/org/jclouds/compute/ComputeServiceContext.java b/compute/src/main/java/org/jclouds/compute/ComputeServiceContext.java index 452f2cd0a3..393ee006e6 100644 --- a/compute/src/main/java/org/jclouds/compute/ComputeServiceContext.java +++ b/compute/src/main/java/org/jclouds/compute/ComputeServiceContext.java @@ -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 { RestContext 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 getCredentialStore(); + + @Beta + Map credentialStore(); + Utils getUtils(); /** diff --git a/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataBuilder.java new file mode 100644 index 0000000000..56198a6c32 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataBuilder.java @@ -0,0 +1,90 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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 { + 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 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()); + } +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/HardwareBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/HardwareBuilder.java new file mode 100644 index 0000000000..353b855c2a --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/HardwareBuilder.java @@ -0,0 +1,124 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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 processors = Lists.newArrayList(); + private int ram; + private List volumes = Lists.newArrayList(); + private Predicate supportsImage = any(); + + public HardwareBuilder() { + super(ComputeType.HARDWARE); + } + + public HardwareBuilder processors(List processors) { + this.processors = checkNotNull(processors, "processors"); + return this; + } + + public HardwareBuilder ram(int ram) { + this.ram = ram; + return this; + } + + public HardwareBuilder volumes(List volumes) { + this.volumes = checkNotNull(volumes, "volumes"); + return this; + } + + public HardwareBuilder supportsImage(Predicate 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 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()); + } +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java new file mode 100644 index 0000000000..1650e2bdd2 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java @@ -0,0 +1,107 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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 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); + } + +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java new file mode 100644 index 0000000000..b4a6170c45 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java @@ -0,0 +1,148 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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 publicAddresses = Sets.newLinkedHashSet(); + private Set 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 publicAddresses) { + this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); + return this; + } + + public NodeMetadataBuilder privateAddresses(Iterable 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 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()); + } + +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/OperatingSystemBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/OperatingSystemBuilder.java new file mode 100644 index 0000000000..b6ce0cacb2 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/OperatingSystemBuilder.java @@ -0,0 +1,80 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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()); + } +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/VolumeBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/VolumeBuilder.java new file mode 100644 index 0000000000..eea36bc7ea --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/domain/VolumeBuilder.java @@ -0,0 +1,80 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.compute.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()); + } +} \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/ComputeMetadataImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/ComputeMetadataImpl.java index 5ab9469353..2ae4b8559b 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/ComputeMetadataImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/ComputeMetadataImpl.java @@ -33,17 +33,25 @@ import org.jclouds.domain.internal.ResourceMetadataImpl; * @author Adrian Cole * @author Ivan Meredith */ -public class ComputeMetadataImpl extends ResourceMetadataImpl implements - ComputeMetadata { - +public class ComputeMetadataImpl extends ResourceMetadataImpl 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 userMetadata) { - super(type, providerId, name, location, uri, userMetadata); + public ComputeMetadataImpl(ComputeType type, String providerId, String name, String id, Location location, URI uri, + Map 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 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 imple return false; } else if (!id.equals(other.id)) return false; + if (type != other.type) + return false; return true; } diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/HardwareImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/HardwareImpl.java index 0c9fb52bbf..51d058fcfa 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/HardwareImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/HardwareImpl.java @@ -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 processors = Lists.newArrayList(); + private final List processors; private final int ram; - private final List volumes = Lists.newArrayList(); - - private Predicate supportsImage; + private final List volumes; + private final Predicate supportsImage; public HardwareImpl(String providerId, String name, String id, @Nullable Location location, URI uri, - Map userMetadata, Iterable processors, int ram, - Iterable volumes, Predicate supportsImage) { + Map userMetadata, Iterable processors, int ram, + Iterable volumes, Predicate 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 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 + "]"; } /** diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java index 3f29f85e16..6a2de25eb5 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java @@ -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 userMetadata, OperatingSystem operatingSystem, String description, - @Nullable String version, @Nullable Credentials defaultCredentials) { + Map 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 diff --git a/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java b/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java index fcff05a6da..17ebfa8ab9 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java +++ b/compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java @@ -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 publicAddresses = Sets.newLinkedHashSet(); - private final Set privateAddresses = Sets.newLinkedHashSet(); + private final Set publicAddresses; + private final Set 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 userMetadata, @Nullable String tag, @Nullable Hardware hardware, - @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, Iterable publicAddresses, - Iterable privateAddresses, @Nullable Credentials credentials) { + Map userMetadata, @Nullable String tag, @Nullable Hardware hardware, @Nullable String imageId, + @Nullable OperatingSystem os, NodeState state, Iterable publicAddresses, + Iterable 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; } diff --git a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java index e250685ab0..63092898da 100755 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java @@ -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 credentialStore; protected final Supplier> images; protected final Supplier> hardwareProfiles; protected final Supplier> locations; @@ -110,16 +119,17 @@ public class BaseComputeService implements ComputeService { protected final ExecutorService executor; @Inject - protected BaseComputeService(ComputeServiceContext context, Supplier> images, - Supplier> hardwareProfiles, Supplier> locations, - ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, - RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, - DestroyNodeStrategy destroyNodeStrategy, Provider templateBuilderProvider, - Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { + protected BaseComputeService(ComputeServiceContext context, Map credentialStore, + Supplier> images, Supplier> hardwareProfiles, + Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { 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 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 nodes = Sets.newHashSet(); - Map badNodes = Maps.newLinkedHashMap(); + count > 1 ? "s" : "", tag, template.getLocation().getId(), template.getImage().getId(), template + .getHardware().getId(), template.getOptions()); + Set nodes = newHashSet(); + Map badNodes = newLinkedHashMap(); Map> responses = runNodesAndAddToSetStrategy.execute(tag, count, template, nodes, badNodes); Map 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 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 destroyNodesMatching(Predicate filter) { logger.debug(">> destroying nodes matching(%s)", filter); - Set set = Sets.newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter), - new Function>() { + Set set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter), + new Function>() { - // TODO make an async interface instead of re-wrapping - @Override - public Future apply(final NodeMetadata from) { - return executor.submit(new Callable() { + // TODO make an async interface instead of re-wrapping + @Override + public Future apply(final NodeMetadata from) { + return executor.submit(new Callable() { - @Override - public NodeMetadata call() throws Exception { - destroyNode(from.getId()); - return from; - } + @Override + public NodeMetadata call() throws Exception { + destroyNode(from.getId()); + return from; + } - }); - } + }); + } - }, executor, null, logger, "destroying nodes")); + }, executor, null, logger, "destroying nodes")); logger.debug("<< destroyed(%d)", set.size()); return set; } private Iterable nodesMatchingFilterAndNotTerminated(Predicate 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 listNodes() { logger.debug(">> listing nodes"); - Set set = Sets.newLinkedHashSet(listNodesStrategy.list()); + Set set = newLinkedHashSet(listNodesStrategy.list()); logger.debug("<< list(%d)", set.size()); return set; } @@ -264,7 +279,7 @@ public class BaseComputeService implements ComputeService { public Set listNodesDetailsMatching(Predicate filter) { checkNotNull(filter, "filter"); logger.debug(">> listing node details matching(%s)", filter); - Set set = Sets.newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(filter)); + Set 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 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 runScriptOnNodesMatching(Predicate 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 runScriptOnNodesMatching(Predicate filter, - final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException { + final Payload runScript, @Nullable final RunScriptOptions options) throws RunScriptOnNodesException { checkNotNull(filter, "Filter must be provided"); checkNotNull(runScript, "runScript"); @@ -362,11 +377,11 @@ public class BaseComputeService implements ComputeService { if (options.getTaskName() == null) options.nameTask("jclouds-script-" + System.currentTimeMillis()); - Iterable nodes = Iterables.filter(detailsOnAllNodes(), filter); + Iterable nodes = filter(detailsOnAllNodes(), filter); - final Map execs = Maps.newHashMap(); - final Map> responses = Maps.newHashMap(); - final Map badNodes = Maps.newLinkedHashMap(); + final Map execs = newHashMap(); + final Map> responses = newHashMap(); + final Map 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 filterNodesWhoCanRunScripts(Iterable nodes, - final Map badNodes, final @Nullable Credentials overridingCredentials) { - nodes = Iterables.filter(Iterables.transform(nodes, new Function() { + final Map badNodes, final @Nullable Credentials overridingCredentials) { + nodes = filter(transform(nodes, new Function() { @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 detailsOnAllNodes() { - return Sets.newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(NodePredicates.all())); + return newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(all())); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java b/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java index 6c5701da87..aa53efc78f 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java +++ b/compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java @@ -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 implements ComputeServiceContext { private final LoadBalancerService loadBalancerService; private final RestContext providerSpecificContext; private final Utils utils; + private final Map credentialStore; @SuppressWarnings({ "unchecked" }) @Inject - public ComputeServiceContextImpl(ComputeService computeService, Utils utils, - @Nullable LoadBalancerService loadBalancerService, RestContext providerSpecificContext) { + public ComputeServiceContextImpl(ComputeService computeService, Map 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 implements ComputeServiceContext { return computeService; } - @SuppressWarnings( { "unchecked", "hiding" }) + @SuppressWarnings({ "unchecked", "hiding" }) @Override public RestContext getProviderSpecificContext() { return (RestContext) providerSpecificContext; @@ -94,4 +99,14 @@ public class ComputeServiceContextImpl implements ComputeServiceContext { public boolean equals(Object obj) { return providerSpecificContext.equals(obj); } + + @Override + public Map getCredentialStore() { + return credentialStore; + } + + @Override + public Map credentialStore() { + return credentialStore; + } } diff --git a/compute/src/main/java/org/jclouds/compute/predicates/ImagePredicates.java b/compute/src/main/java/org/jclouds/compute/predicates/ImagePredicates.java index 141ba842b7..87000d2200 100644 --- a/compute/src/main/java/org/jclouds/compute/predicates/ImagePredicates.java +++ b/compute/src/main/java/org/jclouds/compute/predicates/ImagePredicates.java @@ -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 { + @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 is64Bit() { - return new Predicate() { - @Override - public boolean apply(Image image) { - return image.getOperatingSystem().is64Bit(); - } - - @Override - public String toString() { - return "is64Bit()"; - } - }; + return new Is64BitPredicate(); } /** diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java index e14ad735f7..1e52db74a3 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java @@ -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 nodes = new ConcurrentHashMap(); + private static final ConcurrentMap nodes = new ConcurrentHashMap(); + private static final ExecutorService service = Executors.newCachedThreadPool(); @Provides @Singleton - ConcurrentMap provideNodes() { + ConcurrentMap provideNodes() { return nodes; } @@ -136,12 +134,11 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo @Singleton public static class StubSocketOpen implements SocketOpen { - private final ConcurrentMap nodes; + private final ConcurrentMap nodes; private final String publicIpPrefix; @Inject - public StubSocketOpen(ConcurrentMap nodes, - @Named("PUBLIC_IP_PREFIX") String publicIpPrefix) { + public StubSocketOpen(ConcurrentMap 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. 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 userMetadata, String tag, @Nullable Hardware hardware, String imageId, Image image, - OperatingSystem os, NodeState state, Iterable publicAddresses, - Iterable 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; - private final ExecutorService service; - private final ConcurrentMap nodes; + private final ConcurrentMap nodes; private final Provider idProvider; private final String publicIpPrefix; private final String privateIpPrefix; private final String passwordPrefix; + private final Map credentialStore; @Inject - public StubAddNodeWithTagStrategy(ConcurrentMap nodes, Supplier location, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, - @Named("NODE_ID") Provider idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, - @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix) { + public StubAddNodeWithTagStrategy(ConcurrentMap nodes, Supplier location, + @Named("NODE_ID") Provider idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, + @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix, + Map credentialStore) { this.nodes = nodes; this.location = location; - this.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 - . of(), tag, null, template.getImage().getId(), template.getImage(), template - .getImage().getOperatingSystem(), NodeState.PENDING, ImmutableSet. of(publicIpPrefix + id), - ImmutableSet. 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. of(publicIpPrefix + id)); + builder.privateAddresses(ImmutableSet. of(privateIpPrefix + id)); + builder.credentials(new Credentials("root", passwordPrefix + id)); + NodeMetadata node = builder.build(); + nodes.put(node.getId(), node); + credentialStore.put(node.getId(), node.getCredentials()); + setState(node, NodeState.RUNNING, 100); return node; } + } + protected static void nodeWithState(NodeMetadata node, NodeState state) { + nodes.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).state(state).build()); + } + + public static void setState(final NodeMetadata node, final NodeState state, final long millis) { + if (millis == 0l) + nodeWithState(node, state); + else + service.execute(new Runnable() { + + @Override + public void run() { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Throwables.propagate(e); + } + nodeWithState(node, state); + } + + }); } @Singleton public static class StubGetNodeMetadataStrategy implements GetNodeMetadataStrategy { - private final ConcurrentMap nodes; + private final ConcurrentMap nodes; @Inject - protected StubGetNodeMetadataStrategy(ConcurrentMap nodes) { + protected StubGetNodeMetadataStrategy(ConcurrentMap 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 nodes; + private final ConcurrentMap nodes; @Inject - protected StubListNodesStrategy(ConcurrentMap nodes) { + protected StubListNodesStrategy(ConcurrentMap nodes) { this.nodes = nodes; } @@ -293,44 +277,43 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo @Singleton public static class StubRebootNodeStrategy implements RebootNodeStrategy { - private final ConcurrentMap nodes; + private final ConcurrentMap nodes; @Inject - protected StubRebootNodeStrategy(ConcurrentMap nodes) { + protected StubRebootNodeStrategy(ConcurrentMap 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 nodes; + private final ConcurrentMap nodes; private final ExecutorService service; @Inject - protected StubDestroyNodeStrategy(ConcurrentMap nodes, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service) { + protected StubDestroyNodeStrategy(ConcurrentMap 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.> ofInstance(ImmutableSet. of(// - new ImageImpl("1", OsFamily.UBUNTU.name(), parentId + "/1", zone, null, - ImmutableMap. 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. 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. 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 + .> ofInstance(ImmutableSet. of( + // + new ImageBuilder() + .providerId("1") + .name(OsFamily.UBUNTU.name()) + .id(parentId + "/1") + .location(zone) + .operatingSystem( + new OperatingSystem(OsFamily.UBUNTU, "ubuntu 32", null, "X86_32", "ubuntu 32", false)) + .description("stub ubuntu 32").defaultCredentials(defaultCredentials).build(), // + new ImageBuilder() + .providerId("2") + .name(OsFamily.UBUNTU.name()) + .id(parentId + "/2") + .location(zone) + .operatingSystem( + new OperatingSystem(OsFamily.UBUNTU, "ubuntu 64", null, "X86_64", "ubuntu 64", true)) + .description("stub ubuntu 64").defaultCredentials(defaultCredentials).build(), // + new ImageBuilder() + .providerId("3") + .name(OsFamily.CENTOS.name()) + .id(parentId + "/3") + .location(zone) + .operatingSystem( + new OperatingSystem(OsFamily.CENTOS, "centos 64", null, "X86_64", "centos 64", true)) + .description("stub centos 64").defaultCredentials(defaultCredentials).build() // + + )); } @Provides @@ -375,24 +375,24 @@ public class StubComputeServiceContextModule extends BaseComputeServiceContextMo protected Set provideLocations(@org.jclouds.rest.annotations.Provider String providerName) { Location provider = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null); Location region = new LocationImpl(LocationScope.REGION, providerName + "region", providerName + "region", - provider); + 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> getSourceSizeSupplier(Injector injector) { - return Suppliers.> ofInstance(ImmutableSet. of(new StubHardware("small", 1, - 1740, 160), new StubHardware("medium", 4, 7680, 850), new StubHardware("large", 8, 15360, 1690))); + return Suppliers.> ofInstance(ImmutableSet. 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. 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. of(new VolumeImpl(disk, true, false))).build(); } } diff --git a/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java b/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java index 4ef27221cb..5175dcbb32 100644 --- a/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java +++ b/compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java @@ -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> NAME_VERSION_MAP = ImmutableMap - .> of(org.jclouds.compute.domain.OsFamily.CENTOS, - ImmutableMap. builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5") - .build(), org.jclouds.compute.domain.OsFamily.RHEL, - ImmutableMap. builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5") - .build(), org.jclouds.compute.domain.OsFamily.UBUNTU, ImmutableMap - . 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()); + .> of( + org.jclouds.compute.domain.OsFamily.CENTOS, + ImmutableMap. builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5").build(), + org.jclouds.compute.domain.OsFamily.RHEL, + ImmutableMap. builder().put("5.3", "5.3").put("5.4", "5.4").put("5.5", "5.5").build(), + org.jclouds.compute.domain.OsFamily.UBUNTU, + ImmutableMap. 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 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 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 filterByName(Iterable nodes, - final String name) { + final String name) { return filter(nodes, new Predicate() { @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} - * (immutable), returns a new instance of {@link Hardware} with the new volumes - */ - public static Hardware replacesVolumes(Hardware hardware, Iterable 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 getSupportedProviders() { diff --git a/compute/src/main/java/org/jclouds/compute/util/ComputeUtils.java b/compute/src/main/java/org/jclouds/compute/util/ComputeUtils.java index e09cbf509e..52d947d512 100644 --- a/compute/src/main/java/org/jclouds/compute/util/ComputeUtils.java +++ b/compute/src/main/java/org/jclouds/compute/util/ComputeUtils.java @@ -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 runScriptNotRunning; - private final Predicate socketTester; - private final ExecutorService executor; + protected final Predicate socketTester; + protected final ExecutorService executor; protected final Predicate nodeRunning; - private final GetNodeMetadataStrategy getNode; - private final Timeouts timeouts; + protected final GetNodeMetadataStrategy getNode; + protected final Timeouts timeouts; @Inject public ComputeUtils(Predicate socketTester, - @Named("SCRIPT_COMPLETE") Predicate runScriptNotRunning, - GetNodeMetadataStrategy getNode, Timeouts timeouts, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { + @Named("SCRIPT_COMPLETE") Predicate runScriptNotRunning, GetNodeMetadataStrategy getNode, + Timeouts timeouts, @Named("NODE_RUNNING") Predicate 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> runOptionsOnNodesAndAddToGoodSetOrPutExceptionIntoBadMap(final TemplateOptions options, - Iterable runningNodes, final Set goodNodes, - final Map badNodes) { + Iterable runningNodes, final Set goodNodes, + final Map badNodes) { Map> responses = Maps.newHashMap(); for (final NodeMetadata node : runningNodes) { responses.put(node, executor.submit(runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(node, badNodes, - goodNodes, options))); + goodNodes, options))); } return responses; } public Callable runOptionsOnNodeAndAddToGoodSetOrPutExceptionIntoBadMap(final NodeMetadata node, - final Map badNodes, final Set goodNodes, - final TemplateOptions options) { + final Map badNodes, final Set goodNodes, final TemplateOptions options) { return new Callable() { @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 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, ?> runCallablesOnNode(NodeMetadata node, Iterable> 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, ?> runTasksUsingSshClient(Iterable> parallel, SshCallable last, - SshClient ssh) { + SshClient ssh) { Map, 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; } diff --git a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java index 2beda76590..692106d0ce 100755 --- a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java @@ -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 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(); diff --git a/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java b/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java index 16f7c1446f..d36118244c 100644 --- a/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java +++ b/compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java @@ -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> stubContext = new ComputeServiceContextFactory() - .createContext(provider, identity, credential).getProviderSpecificContext(); + RestContext, ConcurrentMap> 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(); diff --git a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java index 35beaee5c6..a3f7c58059 100644 --- a/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java +++ b/compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java @@ -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 - . of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList. of(), - ImagePredicates.any()); + Hardware hardware = new HardwareBuilder().id("hardwareId").build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of( - image, image2)); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(size)); + image, image2)); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider 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 - . of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList. of(), - ImagePredicates.any()); + Hardware hardware = new HardwareBuilder().id("hardwareId").build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of( - image, image2)); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(size)); + image, image2)); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider 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 - . of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList. of(), - ImagePredicates.idEquals("imageId")); + Hardware hardware = new HardwareBuilder().id("hardwareId") + .supportsImage(ImagePredicates.idEquals("imageId")).build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(size)); + . of(image)); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider 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 - . of(), ImmutableList.of(new Processor(1.0, 1.0)), 0, ImmutableList. of(), - ImagePredicates.idEquals("imageId")); + Hardware hardware = new HardwareBuilder().id("hardwareId") + .supportsImage(ImagePredicates.idEquals("imageId")).build(); Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of(defaultLocation)); + . of(defaultLocation)); Supplier> images = Suppliers.> ofInstance(ImmutableSet - . of(image)); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of(size)); + . of(image)); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of(hardware)); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider 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> locations, - Supplier> images, Supplier> sizes, Location defaultLocation, - Provider optionsProvider, Provider templateBuilderProvider) { - TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, Suppliers - .ofInstance(defaultLocation), optionsProvider, templateBuilderProvider); + Supplier> images, Supplier> hardwares, Location defaultLocation, + Provider optionsProvider, Provider templateBuilderProvider) { + TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, hardwares, + Suppliers.ofInstance(defaultLocation), optionsProvider, templateBuilderProvider); return template; } @@ -371,10 +362,10 @@ public class TemplateBuilderImplTest { @Test public void testSuppliedLocationWithNoOptions() { Supplier> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider 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> locations = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); Supplier> images = Suppliers.> ofInstance(ImmutableSet. of()); - Supplier> sizes = Suppliers.> ofInstance(ImmutableSet - . of()); + Supplier> hardwares = Suppliers.> ofInstance(ImmutableSet + . of()); Location defaultLocation = createMock(Location.class); Provider optionsProvider = createMock(Provider.class); Provider 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"); diff --git a/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java b/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java new file mode 100644 index 0000000000..f03f96a82a --- /dev/null +++ b/core/src/main/java/org/jclouds/collect/AbstractMapEntry.java @@ -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 implements Entry { + + 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 {key}={value}. + */ + @Override + public String toString() { + return getKey() + "=" + getValue(); + } +} diff --git a/core/src/main/java/org/jclouds/collect/InputSupplierMap.java b/core/src/main/java/org/jclouds/collect/InputSupplierMap.java new file mode 100644 index 0000000000..6e647f4dae --- /dev/null +++ b/core/src/main/java/org/jclouds/collect/InputSupplierMap.java @@ -0,0 +1,190 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + + +package org.jclouds.collect; + +import static 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 extends AbstractMap { + final Map> toMap; + final Function> putFunction; + + public InputSupplierMap(Map> toMap, Function> 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 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> entrySet() { + return new EntrySet(); + + } + + class EntrySet extends AbstractSet> { + @Override + public int size() { + return InputSupplierMap.this.size(); + } + + @Override + public Iterator> iterator() { + final Iterator>> mapIterator = toMap.entrySet().iterator(); + + return new Iterator>() { + public boolean hasNext() { + return mapIterator.hasNext(); + } + + public Entry next() { + final java.util.Map.Entry> entry = mapIterator.next(); + return new AbstractMapEntry() { + @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; + } + } +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/collect/TransformingMap.java b/core/src/main/java/org/jclouds/collect/TransformingMap.java new file mode 100644 index 0000000000..644c6da61c --- /dev/null +++ b/core/src/main/java/org/jclouds/collect/TransformingMap.java @@ -0,0 +1,156 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.collect; + +import static 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 extends AbstractMap { + final Map fromMap; + final Function getFunction; + final Function putFunction; + + public TransformingMap(Map fromMap, Function getFunction, Function 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> entrySet() { + return new EntrySet(); + + } + + class EntrySet extends AbstractSet> { + @Override + public int size() { + return TransformingMap.this.size(); + } + + @Override + public Iterator> iterator() { + final Iterator> mapIterator = fromMap.entrySet().iterator(); + + return new Iterator>() { + public boolean hasNext() { + return mapIterator.hasNext(); + } + + public Entry next() { + final Entry entry = mapIterator.next(); + return new AbstractMapEntry() { + @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; + } + } +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/domain/ResourceMetadataBuilder.java b/core/src/main/java/org/jclouds/domain/ResourceMetadataBuilder.java new file mode 100644 index 0000000000..01db58a97d --- /dev/null +++ b/core/src/main/java/org/jclouds/domain/ResourceMetadataBuilder.java @@ -0,0 +1,64 @@ +package org.jclouds.domain; + +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +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> { + protected String providerId; + protected String name; + protected Location location; + protected URI uri; + protected Map userMetadata = Maps.newLinkedHashMap(); + + public ResourceMetadataBuilder providerId(String providerId) { + this.providerId = providerId; + return this; + } + + public ResourceMetadataBuilder name(String name) { + this.name = name; + return this; + } + + public ResourceMetadataBuilder location(Location location) { + this.location = location; + return this; + } + + public ResourceMetadataBuilder uri(URI uri) { + this.uri = uri; + return this; + } + + public ResourceMetadataBuilder userMetadata(Map userMetadata) { + this.userMetadata = checkNotNull(userMetadata, "userMetadata"); + return this; + } +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java b/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java index 022e357c73..fbc55edde7 100644 --- a/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java +++ b/core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java @@ -36,12 +36,11 @@ import com.google.inject.internal.Nullable; * * @author Adrian Cole */ -public class ResourceMetadataImpl> implements ResourceMetadata, Serializable { +public abstract class ResourceMetadataImpl> implements ResourceMetadata, 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> implements ResourceMetadata private final URI uri; private final Map userMetadata = Maps.newLinkedHashMap(); - public ResourceMetadataImpl(T type, @Nullable String providerId, @Nullable String name, - @Nullable Location location, @Nullable URI uri, Map userMetadata) { - this.type = checkNotNull(type, "type"); + public ResourceMetadataImpl(@Nullable String providerId, @Nullable String name, @Nullable Location location, + @Nullable URI uri, Map userMetadata) { this.providerId = providerId; this.name = name; this.location = location; @@ -72,14 +70,6 @@ public class ResourceMetadataImpl> 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> 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> 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> 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; diff --git a/core/src/main/java/com/google/gson/ExposedEscaper.java b/core/src/main/java/org/jclouds/rest/ConfiguresCredentialStore.java similarity index 65% rename from core/src/main/java/com/google/gson/ExposedEscaper.java rename to core/src/main/java/org/jclouds/rest/ConfiguresCredentialStore.java index 364f14b462..84b5431758 100644 --- a/core/src/main/java/com/google/gson/ExposedEscaper.java +++ b/core/src/main/java/org/jclouds/rest/ConfiguresCredentialStore.java @@ -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} * * @author Adrian Cole + * */ -public class ExposedEscaper extends Escaper { - - public ExposedEscaper(boolean escapeHtmlCharacters) { - super(escapeHtmlCharacters); - } +@Beta +@Retention(RUNTIME) +@Target(TYPE) +public @interface ConfiguresCredentialStore { } diff --git a/core/src/main/java/org/jclouds/rest/RestContext.java b/core/src/main/java/org/jclouds/rest/RestContext.java index 5baefaa9e8..116e2313bd 100755 --- a/core/src/main/java/org/jclouds/rest/RestContext.java +++ b/core/src/main/java/org/jclouds/rest/RestContext.java @@ -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 { 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 getCredentialStore(); + + @Beta + Map credentialStore(); + String getIdentity(); String getProvider(); diff --git a/core/src/main/java/org/jclouds/rest/RestContextBuilder.java b/core/src/main/java/org/jclouds/rest/RestContextBuilder.java index 2798e2c485..5a5aa2621f 100755 --- a/core/src/main/java/org/jclouds/rest/RestContextBuilder.java +++ b/core/src/main/java/org/jclouds/rest/RestContextBuilder.java @@ -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. *

- * 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. *

*

- * If no Modules are specified, the default - * {@link JDKLoggingModule logging} and - * {@link JavaUrlHttpCommandExecutorServiceModule http transports} will be - * installed. + * If no Modules 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 { addHttpModuleIfNeededAndNotPresent(modules); ifHttpConfigureRestOtherwiseGuiceClientFactory(modules); addExecutorServiceIfNotPresent(modules); + addCredentialStoreIfNotPresent(modules); modules.add(new BindPropertiesAndPrincipalContext(properties)); return Guice.createInjector(modules); } @@ -245,13 +244,27 @@ public class RestContextBuilder { 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 modules) { + if (!Iterables.any(modules, new Predicate() { + public boolean apply(Module input) { + return input.getClass().isAnnotationPresent(ConfiguresCredentialStore.class); + } + } + + )) { + modules.add(new CredentialStoreModule()); + } + } + @VisibleForTesting public Properties getProperties() { return properties; diff --git a/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java new file mode 100644 index 0000000000..2d8438002b --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java @@ -0,0 +1,182 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.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> BACKING = new ConcurrentHashMap>(); + private final Map backing; + + public CredentialStoreModule(Map backing) { + this.backing = backing; + } + + public CredentialStoreModule() { + this(null); + } + + @Override + protected void configure() { + bind(new TypeLiteral>() { + }).to(CredentialsToJsonInputStream.class); + bind(new TypeLiteral>() { + }).to(CredentialsFromJsonInputStream.class); + if (backing != null) { + bind(new TypeLiteral>() { + }).toInstance(backing); + } else { + bind(new TypeLiteral>>() { + }).toInstance(BACKING); + bind(new TypeLiteral>() { + }).to(new TypeLiteral() { + }); + } + } + + @Singleton + public static class CredentialsToJsonInputStream implements Function { + 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 { + @Singleton + public static class CopyInputStreamIntoSupplier implements Function> { + @Resource + protected Logger logger = Logger.NULL; + + @SuppressWarnings("unchecked") + @Override + public InputSupplier apply(InputStream from) { + if (from == null) + return new InputSupplier() { + + @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> toMap, + CopyInputStreamIntoSupplier putFunction) { + super(toMap, putFunction); + } + + public CopyInputStreamInputSupplierMap(Map> toMap) { + super(toMap, new CopyInputStreamIntoSupplier()); + } + + } + + @Singleton + public static class CredentialsFromJsonInputStream implements Function { + @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 provideCredentialStore(Map backing, + Function credentialsSerializer, + Function credentialsDeserializer) { + return new TransformingMap(backing, credentialsDeserializer, + credentialsSerializer); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java index a44b188ca6..04dfd6e313 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java @@ -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 implements RestContext { private final String provider; private final String apiVersion; private final Utils utils; + private final Map credentialStore; @Inject - protected RestContextImpl(Closer closer, Utils utils, Injector injector, TypeLiteral syncApi, - TypeLiteral asyncApi, @Provider URI endpoint, @Provider String provider, @Identity String identity, - @ApiVersion String apiVersion) { + protected RestContextImpl(Closer closer, Map credentialStore, Utils utils, Injector injector, + TypeLiteral syncApi, TypeLiteral 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 implements RestContext { @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 getCredentialStore() { + return credentialStore; + } + + @Override + public Map credentialStore() { + return credentialStore; } } diff --git a/core/src/main/java/org/jclouds/util/Utils.java b/core/src/main/java/org/jclouds/util/Utils.java index 8c4d3527cf..b8720e2f7b 100644 --- a/core/src/main/java/org/jclouds/util/Utils.java +++ b/core/src/main/java/org/jclouds/util/Utils.java @@ -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 Supplier> composeMapSupplier(Iterable>> suppliers) { return new ListMapSupplier(suppliers); diff --git a/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java new file mode 100755 index 0000000000..cdf0fa1f4c --- /dev/null +++ b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java @@ -0,0 +1,169 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.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 map = getMap(injector); + check(map, getStore(injector), "i-20312", identity, credential); + } + + public void testProvidedMapWithValue() throws IOException { + Map map = new CopyInputStreamInputSupplierMap( + new ConcurrentHashMap>()); + + 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 map = new CopyInputStreamInputSupplierMap( + new ConcurrentHashMap>()); + + Injector injector = createInjectorWithProvidedMap(map); + assertEquals(injector.getInstance(Key.get(new TypeLiteral>() { + })), map); + Map 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 map = new CopyInputStreamInputSupplierMap( + new ConcurrentHashMap>()); + + 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 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 getStore(Injector injector) { + return injector.getInstance(Key.get(new TypeLiteral>() { + })); + } + + protected Map getMap(Injector injector) { + return injector.getInstance(Key.get(new TypeLiteral>() { + })); + } + + protected Injector createInjectorWithProvidedMap(Map map) { + return Guice.createInjector(new CredentialStoreModule(map), new GsonModule()); + } + + protected Injector createInjector() { + return Guice.createInjector(new CredentialStoreModule(), new GsonModule()); + } + + protected void check(Map map, Map 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 map, Map 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 map, Map 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 map, String key, String identity, String credential) + throws IOException { + assertEquals(toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential))); + } + + protected void put(Map map, Map store, String key, String identity, + String credential) { + assertEquals(store.size(), 0); + assertEquals(map.size(), 0); + store.put(key, new Credentials(identity, credential)); + } +} \ No newline at end of file diff --git a/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java b/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java index 05c572903f..0cb8ae6c41 100755 --- a/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java +++ b/core/src/test/java/org/jclouds/rest/RestContextBuilderTest.java @@ -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 modules = new ArrayList(); + ExecutorServiceModule module = new ExecutorServiceModule(); + modules.add(module); + new RestContextBuilder(String.class, String.class, new Properties()) + .addExecutorServiceIfNotPresent(modules); + assertEquals(modules.size(), 1); + assertEquals(modules.remove(0), module); + } + + @Test + public void testAddCredentialStoreModuleIfNotPresent() { + List modules = new ArrayList(); + CredentialStoreModule module = new CredentialStoreModule(); + modules.add(module); + new RestContextBuilder(String.class, String.class, new Properties()) + .addCredentialStoreIfNotPresent(modules); + assertEquals(modules.size(), 1); + assertEquals(modules.remove(0), module); + } + @Test public void testAddNone() { List modules = new ArrayList(); diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java index 91d8c7abf6..1967083cd6 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java @@ -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 { @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 { @Inject ServerToNodeMetadata(Map serverStateToNodeState, GoGridClient client, - Supplier> images, Supplier> hardwares, - Supplier> locations) { + Supplier> images, Supplier> hardwares, + Supplier> 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 { @Override public NodeMetadata apply(Server from) { - String tag = parseTagFromName(from.getName()); - Set 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. of(), tag, hardware, from - .getImage().getId() - + "", image != null ? image.getOperatingSystem() : null, state, ipSet, ImmutableList. of(), - creds); + return hardware; } } \ No newline at end of file diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java index 6fac7c7e12..ae8ee11f1b 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java @@ -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> { - public static final HardwareImpl H8192 = new HardwareImpl("5", "5", "5", null, null, ImmutableMap - . 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 - . 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 - . 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 - . 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 - . 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. of(new VolumeImpl(480.0f, true, true))).build(); + public static final Hardware H4096 = new HardwareBuilder().ids("4").ram(4096) + .processors(ImmutableList.of(new Processor(4, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(240.0f, true, true))).build(); + public static final Hardware H2048 = new HardwareBuilder().ids("3").ram(2048) + .processors(ImmutableList.of(new Processor(2, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(120.0f, true, true))).build(); + public static final Hardware H1024 = new HardwareBuilder().ids("2").ram(1024) + .processors(ImmutableList.of(new Processor(1, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(60.0f, true, true))).build(); + public static final Hardware H512 = new HardwareBuilder().ids("1").ram(512) + .processors(ImmutableList.of(new Processor(0.5, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(30.0f, true, true))).build(); - public static final ImmutableSet H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192); + public static final ImmutableSet H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192); @Override public Set get() { diff --git a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java index 98d3b47498..142600faca 100644 --- a/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java +++ b/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java @@ -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> { logger.debug(">> providing images"); Set 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. 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; + } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java index 377e9f1110..e1aeeb9ed1 100755 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/config/CloudServersComputeServiceContextModule.java @@ -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>() { }).to(ServerToNodeMetadata.class); + + bind(new TypeLiteral>() { + }).to(CloudServersImageToImage.class); + + bind(new TypeLiteral>() { + }).to(CloudServersImageToOperatingSystem.class); + + bind(new TypeLiteral>() { + }).to(FlavorToHardware.class); + bind(LoadBalancerService.class).toProvider(Providers. of(null)); bind(new TypeLiteral() { }).to(new TypeLiteral>() { @@ -102,31 +117,31 @@ public class CloudServersComputeServiceContextModule extends BaseComputeServiceC } @VisibleForTesting - static final Map serverToNodeState = ImmutableMap. builder().put( - ServerStatus.ACTIVE, NodeState.RUNNING)// - .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// - .put(ServerStatus.DELETED, NodeState.TERMINATED)// - .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// - .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// - .put(ServerStatus.RESIZE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// - .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// - .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// - .put(ServerStatus.MOVE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// - .put(ServerStatus.RESCUE, NodeState.PENDING)// - .put(ServerStatus.ERROR, NodeState.ERROR)// - .put(ServerStatus.BUILD, NodeState.PENDING)// - .put(ServerStatus.RESTORING, NodeState.PENDING)// - .put(ServerStatus.PASSWORD, NodeState.PENDING)// - .put(ServerStatus.REBUILD, NodeState.PENDING)// - .put(ServerStatus.DELETE_IP, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP, NodeState.PENDING)// - .put(ServerStatus.REBOOT, NodeState.PENDING)// - .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// - .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// - .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + public static final Map serverToNodeState = ImmutableMap + . builder().put(ServerStatus.ACTIVE, NodeState.RUNNING)// + .put(ServerStatus.SUSPENDED, NodeState.SUSPENDED)// + .put(ServerStatus.DELETED, NodeState.TERMINATED)// + .put(ServerStatus.QUEUE_RESIZE, NodeState.PENDING)// + .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// + .put(ServerStatus.RESIZE, NodeState.PENDING)// + .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// + .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// + .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// + .put(ServerStatus.MOVE, NodeState.PENDING)// + .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// + .put(ServerStatus.RESCUE, NodeState.PENDING)// + .put(ServerStatus.ERROR, NodeState.ERROR)// + .put(ServerStatus.BUILD, NodeState.PENDING)// + .put(ServerStatus.RESTORING, NodeState.PENDING)// + .put(ServerStatus.PASSWORD, NodeState.PENDING)// + .put(ServerStatus.REBUILD, NodeState.PENDING)// + .put(ServerStatus.DELETE_IP, NodeState.PENDING)// + .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// + .put(ServerStatus.SHARE_IP, NodeState.PENDING)// + .put(ServerStatus.REBOOT, NodeState.PENDING)// + .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// + .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// + .put(ServerStatus.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); @Singleton @Provides diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImage.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImage.java new file mode 100644 index 0000000000..9d5575a573 --- /dev/null +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImage.java @@ -0,0 +1,56 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.rackspace.cloudservers.compute.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 { + private final Function imageToOs; + + @Inject + CloudServersImageToImage(Function 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; + } +} \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToOperatingSystem.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToOperatingSystem.java new file mode 100644 index 0000000000..f03c2d6c70 --- /dev/null +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToOperatingSystem.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.rackspace.cloudservers.compute.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 { + 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; + } +} \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardware.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardware.java new file mode 100644 index 0000000000..dcefae5d63 --- /dev/null +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardware.java @@ -0,0 +1,44 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.rackspace.cloudservers.compute.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 { + 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. of(new VolumeImpl((float) from.getDisk(), true, true))).build(); + } +} \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java index 8ef0aebfa9..fecc700a45 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadata.java @@ -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 { - private final Supplier location; - private final Map serverToNodeState; - private final Supplier> images; - private final Supplier> hardwares; + protected final Supplier location; + protected final Map credentialStore; + protected final Map serverToNodeState; + protected final Supplier> images; + protected final Supplier> hardwares; @Resource protected Logger logger = Logger.NULL; private static class FindImageForServer implements Predicate { - 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 { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, Supplier> images, - Supplier location, Supplier> hardwares) { + ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, + Supplier> images, Supplier location, Supplier> 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 { @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; + } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/strategy/CloudServersAddNodeWithTagStrategy.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/strategy/CloudServersAddNodeWithTagStrategy.java index 798b44d632..2a645e163f 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/strategy/CloudServersAddNodeWithTagStrategy.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/strategy/CloudServersAddNodeWithTagStrategy.java @@ -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 credentialStore; + protected final Function serverToNodeMetadata; @Inject - protected CloudServersAddNodeWithTagStrategy(CloudServersClient client) { + protected CloudServersAddNodeWithTagStrategy(CloudServersClient client, Map credentialStore, + Function 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); } } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersHardwareSupplier.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersHardwareSupplier.java index 1f70ccabca..9440e9c214 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersHardwareSupplier.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersHardwareSupplier.java @@ -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 location; + private final Function flavorToHardware; @Inject - CloudServersHardwareSupplier(CloudServersClient sync, Supplier location, - Function indexer) { + CloudServersHardwareSupplier(CloudServersClient sync, Function flavorToHardware) { this.sync = sync; - this.location = location; + this.flavorToHardware = flavorToHardware; } @Override public Set get() { - final Set 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. 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; + logger.debug(">> providing hardware"); + hardware = Sets.newLinkedHashSet(Iterables.transform(sync.listFlavors(withDetails()), flavorToHardware)); + logger.debug("<< hardware(%d)", hardware.size()); + return hardware; } - } \ No newline at end of file diff --git a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java index 71d3653972..8ac4b63a1d 100644 --- a/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java +++ b/rackspace/src/main/java/org/jclouds/rackspace/cloudservers/compute/suppliers/CloudServersImageSupplier.java @@ -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> { - public static final Pattern RACKSPACE_PATTERN = Pattern.compile("(([^ ]*) .*)"); @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private CloudServersClient sync; - private Supplier location; + + protected final CloudServersClient sync; + protected final Function cloudServersImageToImage; @Inject - CloudServersImageSupplier(CloudServersClient sync, Supplier location) { + CloudServersImageSupplier(CloudServersClient sync, + Function cloudServersImageToImage) { this.sync = sync; - this.location = location; + this.cloudServersImageToImage = cloudServersImageToImage; } @Override public Set get() { - final Set images = Sets.newHashSet(); + Set 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. of(), os, from.getName(), version, new Credentials("root", null))); - } + images = Sets. newLinkedHashSet(Iterables.transform(sync.listImages(withDetails()), + cloudServersImageToImage)); logger.debug("<< images(%d)", images.size()); return images; } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java new file mode 100644 index 0000000000..fbfc1ec638 --- /dev/null +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/CloudServersImageToImageTest.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.rackspace.cloudservers.compute.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); + } +} diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java new file mode 100644 index 0000000000..15dcf01811 --- /dev/null +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/FlavorToHardwareTest.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.rackspace.cloudservers.compute.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); + } +} diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java index c889ffa6c6..5a863b1bba 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/compute/functions/ServerToNodeMetadataTest.java @@ -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 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 images = ImmutableSet.of(jcImage); + Map serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - org.jclouds.compute.domain.Hardware jcHardware = createMock(org.jclouds.compute.domain.Hardware.class); - - Set 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. 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 publicAddresses = ImmutableSet.of("12.10.10.1"); - Set 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 - .> ofInstance(images), Suppliers.ofInstance(provider), Suppliers - .> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ImmutableMap. of("1234", creds), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - assertEquals(metadata.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 serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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 serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + org.jclouds.compute.domain.Image jcImage = CloudServersImageToImageTest.convertImage(); + Set images = ImmutableSet.of(jcImage); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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 serverStateToNodeState = CloudServersComputeServiceContextModule.serverToNodeState; + Set images = ImmutableSet.of(CloudServersImageToImageTest.convertImage()); + Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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()); + } +} \ No newline at end of file diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java index abee165dd1..0b7e4922ba 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseFlavorFromJsonResponseTest.java @@ -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 parser = i.getInstance(Key.get(new TypeLiteral>() { })); 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; } } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java index 35400f7aa5..39f692cacb 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseImageFromJsonResponseTest.java @@ -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 parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - 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 parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; + } + } diff --git a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java index 7688274c13..2345c5a406 100644 --- a/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java +++ b/rackspace/src/test/java/org/jclouds/rackspace/cloudservers/functions/ParseServerFromJsonResponseTest.java @@ -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 parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - 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 parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; + } + } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java index 6e138cd979..54d4d77cf6 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java @@ -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 { @Resource protected Logger logger = Logger.NULL; - private final Function> getPublicAddresses; - private final Map runningStateToNodeState; - private final Supplier> images; + protected final Map credentialStore; + protected final Function> getPublicAddresses; + protected final Map runningStateToNodeState; + protected final Supplier> images; private static class FindImageForServer implements Predicate { private final Location location; @@ -74,38 +74,46 @@ public class ServerToNodeMetadata implements Function { @Override public boolean apply(Image input) { return input.getProviderId().equals(instance.getImageId()) - && (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation() - .equals(location.getParent())); + && (input.getLocation() == null || input.getLocation().equals(location) || input.getLocation().equals( + location.getParent())); } } @Inject ServerToNodeMetadata(Function> getPublicAddresses, - Map runningStateToNodeState, Supplier> images) { + Map credentialStore, Map runningStateToNodeState, + Supplier> 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 - . of(), tag, null, from.getImageId(), image != null ? image.getOperatingSystem() : null, - state, getPublicAddresses.apply(from), ImmutableList. of(), creds); - + return null; } } \ No newline at end of file diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/strategy/RimuHostingAddNodeWithTagStrategy.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/strategy/RimuHostingAddNodeWithTagStrategy.java index 1a02e0b73d..e3adecf336 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/strategy/RimuHostingAddNodeWithTagStrategy.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/strategy/RimuHostingAddNodeWithTagStrategy.java @@ -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> getPublicAddresses; - private final Map runningStateToNodeState; + protected final RimuHostingClient client; + protected final Map credentialStore; + protected final Function serverToNodeMetadata; @Inject - protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client, - Function> getPublicAddresses, Map runningStateToNodeState) { + protected RimuHostingAddNodeWithTagStrategy(RimuHostingClient client, Map credentialStore, + Function 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. of(), tag, template.getHardware(), template - .getImage().getId(), template.getImage().getOperatingSystem(), runningStateToNodeState.get(server - .getState()), getPublicAddresses.apply(server), ImmutableList. 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); } } \ No newline at end of file diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java index e658a87fb2..288331c82c 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingHardwareSupplier.java @@ -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 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. of(new VolumeImpl((float) from.getDiskSize(), true, true))).build()); } catch (NullPointerException e) { logger.warn("datacenter not present in " + from.getId()); } diff --git a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java index bdeb149e9c..7d584ca2e2 100644 --- a/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java +++ b/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java @@ -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> public Set get() { final Set 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 - . 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; + } } \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java index c41ca022d7..3f7ec9c8bd 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/config/SlicehostComputeServiceContextModule.java @@ -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>() { }).to(SliceToNodeMetadata.class); + + bind(new TypeLiteral>() { + }).to(SlicehostImageToImage.class); + + bind(new TypeLiteral>() { + }).to(SlicehostImageToOperatingSystem.class); + bind(new TypeLiteral>() { + }).to(FlavorToHardware.class); + bind(LoadBalancerService.class).toProvider(Providers. of(null)); bind(new TypeLiteral() { }).to(new TypeLiteral>() { @@ -103,14 +117,14 @@ public class SlicehostComputeServiceContextModule extends BaseComputeServiceCont } @VisibleForTesting - static final Map sliceStatusToNodeState = ImmutableMap. builder() - .put(Slice.Status.ACTIVE, NodeState.RUNNING)// - .put(Slice.Status.BUILD, NodeState.PENDING)// - .put(Slice.Status.REBOOT, NodeState.PENDING)// - .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// - .put(Slice.Status.TERMINATED, NodeState.TERMINATED)// - .put(Slice.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// - .build(); + public static final Map sliceStatusToNodeState = ImmutableMap + . builder().put(Slice.Status.ACTIVE, NodeState.RUNNING)// + .put(Slice.Status.BUILD, NodeState.PENDING)// + .put(Slice.Status.REBOOT, NodeState.PENDING)// + .put(Slice.Status.HARD_REBOOT, NodeState.PENDING)// + .put(Slice.Status.TERMINATED, NodeState.TERMINATED)// + .put(Slice.Status.UNRECOGNIZED, NodeState.UNRECOGNIZED)// + .build(); @Singleton @Provides diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/FlavorToHardware.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/FlavorToHardware.java new file mode 100644 index 0000000000..78481477db --- /dev/null +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/FlavorToHardware.java @@ -0,0 +1,44 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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 { + 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. of(new VolumeImpl((from.getRam() * 4) / 1024.0f, true, true))).build(); + } +} \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java index cb9104567d..5b6a86fbbd 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java @@ -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 { - private final Supplier location; - private final Map sliceToNodeState; - private final Supplier> images; - private final Supplier> hardwares; + protected final Supplier location; + protected final Map sliceToNodeState; + protected final Supplier> images; + protected final Supplier> hardwares; + protected final Map credentialStore; @Resource protected Logger logger = Logger.NULL; @@ -83,9 +85,10 @@ public class SliceToNodeMetadata implements Function { } @Inject - SliceToNodeMetadata(Map sliceStateToNodeState, Supplier> images, - Supplier location, Supplier> hardwares) { + SliceToNodeMetadata(Map sliceStateToNodeState, Map credentialStore, + Supplier> images, Supplier location, Supplier> 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 { @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() { + + @Override + public boolean apply(String input) { + return !input.startsWith("10."); + } + + })); + builder.privateAddresses(Iterables.filter(from.getAddresses(), new Predicate() { + + @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. of(), tag, hardware, from.getImageId() + "", image != null ? image - .getOperatingSystem() : null, sliceToNodeState.get(from.getStatus()), Iterables.filter(from - .getAddresses(), new Predicate() { + return null; + } - @Override - public boolean apply(String input) { - return !input.startsWith("10."); - } - - }), Iterables.filter(from.getAddresses(), new Predicate() { - - @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; } } diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java new file mode 100644 index 0000000000..7ce8eeaa68 --- /dev/null +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java @@ -0,0 +1,55 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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 { + private final Function imageToOs; + + @Inject + SlicehostImageToImage(Function 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; + } +} \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToOperatingSystem.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToOperatingSystem.java new file mode 100644 index 0000000000..54c76bbe34 --- /dev/null +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToOperatingSystem.java @@ -0,0 +1,71 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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 { + 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; + } +} \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/strategy/SlicehostAddNodeWithTagStrategy.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/strategy/SlicehostAddNodeWithTagStrategy.java index fded60d0e7..ac14176dab 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/strategy/SlicehostAddNodeWithTagStrategy.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/strategy/SlicehostAddNodeWithTagStrategy.java @@ -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 credentialStore; + protected final Function sliceToNodeMetadata; @Inject - protected SlicehostAddNodeWithTagStrategy(SlicehostClient client) { + protected SlicehostAddNodeWithTagStrategy(SlicehostClient client, Map credentialStore, + Function 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. of(), tag, template.getHardware(), template.getImage().getId(), template - .getImage().getOperatingSystem(), NodeState.PENDING, Iterables.filter(slice.getAddresses(), - new Predicate() { - - @Override - public boolean apply(String input) { - return !input.startsWith("10."); - } - - }), Iterables.filter(slice.getAddresses(), new Predicate() { - - @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); } - } \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostHardwareSupplier.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostHardwareSupplier.java index 95ee7034b7..a41e5f175c 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostHardwareSupplier.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostHardwareSupplier.java @@ -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 location; + private final Function flavorToHardware; @Inject - SlicehostHardwareSupplier(SlicehostClient sync, Supplier location) { + SlicehostHardwareSupplier(SlicehostClient sync, Function flavorToHardware) { this.sync = sync; - this.location = location; + this.flavorToHardware = flavorToHardware; } @Override public Set get() { - final Set 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. 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; + logger.debug(">> providing hardware"); + hardware = Sets.newLinkedHashSet(Iterables.transform(sync.listFlavors(), flavorToHardware)); + logger.debug("<< hardware(%d)", hardware.size()); + return hardware; } } \ No newline at end of file diff --git a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java index 21c168439d..02ed757134 100644 --- a/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java +++ b/slicehost/src/main/java/org/jclouds/slicehost/compute/suppliers/SlicehostImageSupplier.java @@ -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> { - 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; + + protected final SlicehostClient sync; + protected final Function slicehostImageToImage; @Inject - SlicehostImageSupplier(SlicehostClient sync, Supplier location) { + SlicehostImageSupplier(SlicehostClient sync, + Function slicehostImageToImage) { this.sync = sync; - this.location = location; + this.slicehostImageToImage = slicehostImageToImage; } @Override public Set get() { - final Set images = Sets.newHashSet(); + Set 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. 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; } + } \ No newline at end of file diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java new file mode 100644 index 0000000000..0b4e9a9079 --- /dev/null +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/FlavorToHardwareTest.java @@ -0,0 +1,68 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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); + } +} diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java new file mode 100644 index 0000000000..fe0bafd649 --- /dev/null +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadataTest.java @@ -0,0 +1,164 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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 sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Slice slice = SliceHandlerTest.parseSlice(); + + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, + ImmutableMap. of("1", creds), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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 sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Slice slice = SliceHandlerTest.parseSlice(); + + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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 sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + org.jclouds.compute.domain.Image jcImage = SlicehostImageToImageTest.convertImage(); + Set images = ImmutableSet.of(jcImage); + Set hardwares = ImmutableSet.of(); + Slice slice = SliceHandlerTest.parseSlice(); + + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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 sliceStateToNodeState = SlicehostComputeServiceContextModule.sliceStatusToNodeState; + Set images = ImmutableSet.of(SlicehostImageToImageTest.convertImage()); + Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); + Slice slice = SliceHandlerTest.parseSlice(); + + SliceToNodeMetadata parser = new SliceToNodeMetadata(sliceStateToNodeState, + ImmutableMap. of(), Suppliers.> ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + + 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()); + } +} \ No newline at end of file diff --git a/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java new file mode 100644 index 0000000000..f8c937949b --- /dev/null +++ b/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java @@ -0,0 +1,63 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.compute.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); + } +} diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java index 235aef01b8..4ad6d83065 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/FlavorHandlerTest.java @@ -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 createParser() { - ParseSax parser = (ParseSax) factory.create(injector.getInstance(FlavorHandler.class)); + static ParseSax createParser() { + Injector injector = Guice.createInjector(new SaxParserModule()); + ParseSax parser = (ParseSax) 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); } } diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java new file mode 100644 index 0000000000..b7f2cd906b --- /dev/null +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImageHandlerTest.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.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 createParser() { + Injector injector = Guice.createInjector(new SaxParserModule()); + ParseSax parser = (ParseSax) 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); + } + +} diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java new file mode 100644 index 0000000000..cbf83686c7 --- /dev/null +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/ImagesHandlerTest.java @@ -0,0 +1,73 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.slicehost.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> createParser() { + ParseSax> parser = (ParseSax>) factory.create(injector + .getInstance(ImagesHandler.class)); + return parser; + } + + public void test() { + InputStream is = getClass().getResourceAsStream("/test_list_images.xml"); + Set 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); + } +} diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java index 7a99cbba93..4a3c670832 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/SliceHandlerTest.java @@ -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 createParser() { - ParseSax parser = (ParseSax) factory.create(injector.getInstance(SliceHandler.class)); + static ParseSax createParser() { + Injector injector = Guice.createInjector(new SaxParserModule()); + ParseSax parser = (ParseSax) 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. of( + Slice expects = new Slice(1, "jclouds-foo", 1, 2, null, Slice.Status.BUILD, 0, 0, 0, ImmutableSet. 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. of( "10.176.168.15", "67.23.20.114"), "fooadfa1231"); - assertEquals(createParser().parse(is), expects); - + assertEquals(parseSlice("/test_new_slice.xml"), expects); + } - + } diff --git a/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java b/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java index 7530a1d0d1..ae50e86f1f 100644 --- a/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java +++ b/slicehost/src/test/java/org/jclouds/slicehost/xml/SlicesHandlerTest.java @@ -47,7 +47,7 @@ public class SlicesHandlerTest extends BaseHandlerTest { public void test() { InputStream is = getClass().getResourceAsStream("/test_get_slice.xml"); - Set expects = ImmutableSet.of(new Slice(1, "jclouds-foo", 1, 10, null, Slice.Status.BUILD, 0, 0, + Set expects = ImmutableSet.of(new Slice(1, "jclouds-foo", 1, 2, null, Slice.Status.BUILD, 0, 0, 0, ImmutableSet. of("174.143.212.229", "10.176.164.199"), null)); assertEquals(createParser().parse(is), expects); diff --git a/slicehost/src/test/resources/test_get_image.xml b/slicehost/src/test/resources/test_get_image.xml new file mode 100644 index 0000000000..144e73e43b --- /dev/null +++ b/slicehost/src/test/resources/test_get_image.xml @@ -0,0 +1,7 @@ + + + + CentOS 5.2 + 2 + + diff --git a/slicehost/src/test/resources/test_get_slice.xml b/slicehost/src/test/resources/test_get_slice.xml index dbe8d32fd1..a4b373fe2c 100644 --- a/slicehost/src/test/resources/test_get_slice.xml +++ b/slicehost/src/test/resources/test_get_slice.xml @@ -1,7 +1,7 @@ jclouds-foo - 10 + 2

174.143.212.229
10.176.164.199
diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/VCloudExpressComputeClient.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/VCloudExpressComputeClient.java index e58d4da07a..db2f5b23ff 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/VCloudExpressComputeClient.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/VCloudExpressComputeClient.java @@ -20,11 +20,11 @@ package org.jclouds.vcloud.compute; import java.net.URI; -import java.util.Map; import javax.annotation.Nullable; import org.jclouds.vcloud.compute.internal.VCloudExpressComputeClientImpl; +import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import com.google.inject.ImplementedBy; @@ -63,7 +63,7 @@ public interface VCloudExpressComputeClient extends CommonVCloudComputeClient { * login password * */ - Map start(@Nullable URI VDC, URI templateId, String name, InstantiateVAppTemplateOptions options, + VCloudExpressVApp start(@Nullable URI VDC, URI templateId, String name, InstantiateVAppTemplateOptions options, int... portsToOpen); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java index c2d660073e..a8c4805a93 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudComputeServiceContextModule.java @@ -22,8 +22,9 @@ package org.jclouds.vcloud.compute.config; import java.util.Set; import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.options.TemplateOptions; @@ -36,8 +37,10 @@ import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.rest.RestContext; import org.jclouds.rest.internal.RestContextImpl; import org.jclouds.vcloud.VCloudClient; -import org.jclouds.vcloud.compute.functions.ImagesInOrg; +import org.jclouds.vcloud.compute.functions.HardwareForVApp; import org.jclouds.vcloud.compute.functions.HardwareInOrg; +import org.jclouds.vcloud.compute.functions.ImagesInOrg; +import org.jclouds.vcloud.compute.functions.VAppToNodeMetadata; import org.jclouds.vcloud.compute.internal.VCloudTemplateBuilderImpl; import org.jclouds.vcloud.compute.options.VCloudTemplateOptions; import org.jclouds.vcloud.compute.strategy.GetLoginCredentialsFromGuestConfiguration; @@ -48,6 +51,7 @@ import org.jclouds.vcloud.compute.strategy.VCloudListNodesStrategy; import org.jclouds.vcloud.compute.strategy.VCloudRebootNodeStrategy; import org.jclouds.vcloud.compute.suppliers.VCloudHardwareSupplier; import org.jclouds.vcloud.domain.Org; +import org.jclouds.vcloud.domain.VApp; import com.google.common.base.Function; import com.google.common.base.Supplier; @@ -66,9 +70,14 @@ public class VCloudComputeServiceContextModule extends CommonVCloudComputeServic @Override protected void configure() { super.configure(); + bind(new TypeLiteral>() { + }).to(VAppToNodeMetadata.class); bind(TemplateOptions.class).to(VCloudTemplateOptions.class); bind(TemplateBuilder.class).to(VCloudTemplateBuilderImpl.class); bind(RebootNodeStrategy.class).to(VCloudRebootNodeStrategy.class); + bind(new TypeLiteral>() { + }).to(new TypeLiteral() { + }); bind(GetNodeMetadataStrategy.class).to(VCloudGetNodeMetadataStrategy.class); bind(new TypeLiteral() { }).to(new TypeLiteral>() { diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java index 832b02e6c4..e02b1a1a14 100755 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/config/VCloudExpressComputeServiceContextModule.java @@ -23,6 +23,7 @@ import javax.inject.Singleton; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; import org.jclouds.compute.strategy.DestroyNodeStrategy; @@ -35,6 +36,7 @@ import org.jclouds.vcloud.VCloudExpressClient; import org.jclouds.vcloud.compute.CommonVCloudComputeClient; import org.jclouds.vcloud.compute.VCloudExpressComputeClient; import org.jclouds.vcloud.compute.functions.ImagesInVCloudExpressOrg; +import org.jclouds.vcloud.compute.functions.VCloudExpressVAppToNodeMetadata; import org.jclouds.vcloud.compute.internal.VCloudExpressComputeClientImpl; import org.jclouds.vcloud.compute.strategy.VCloudExpressAddNodeWithTagStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressDestroyNodeStrategy; @@ -42,6 +44,7 @@ import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressListNodesStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressRebootNodeStrategy; import org.jclouds.vcloud.domain.Org; +import org.jclouds.vcloud.domain.VCloudExpressVApp; import com.google.common.base.Function; import com.google.inject.Provides; @@ -61,6 +64,8 @@ public class VCloudExpressComputeServiceContextModule extends CommonVCloudComput super.configure(); bind(RebootNodeStrategy.class).to(VCloudExpressRebootNodeStrategy.class); bind(GetNodeMetadataStrategy.class).to(VCloudExpressGetNodeMetadataStrategy.class); + bind(new TypeLiteral>() { + }).to(VCloudExpressVAppToNodeMetadata.class); bind(new TypeLiteral() { }).to(new TypeLiteral>() { }).in(Scopes.SINGLETON); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudExpressImage.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudExpressImage.java deleted file mode 100644 index 8a835ef620..0000000000 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudExpressImage.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.vcloud.compute.domain; - -import java.net.URI; -import java.util.Map; - -import javax.annotation.Nullable; - -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.internal.ImageImpl; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.vcloud.domain.VCloudExpressVAppTemplate; - -/** - * @author Adrian Cole - */ -public class VCloudExpressImage extends ImageImpl { - - /** The serialVersionUID */ - private static final long serialVersionUID = -8520373150950058296L; - - private final VCloudExpressVAppTemplate template; - - public VCloudExpressImage(VCloudExpressVAppTemplate template, String providerId, String name, String id, Location location, URI uri, - Map userMetadata, OperatingSystem operatingSystem, String description, - @Nullable String version, @Nullable Credentials defaultCredentials) { - super(providerId, name, id, location, uri, userMetadata, operatingSystem, description, version, - defaultCredentials); - this.template = template; - } - - public VCloudExpressVAppTemplate getVAppTemplate() { - return template; - } - -} \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudImage.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudImage.java deleted file mode 100644 index 660c57735f..0000000000 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/domain/VCloudImage.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * - * Copyright (C) 2010 Cloud Conscious, LLC. - * - * ==================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.jclouds.vcloud.compute.domain; - -import java.net.URI; -import java.util.Map; - -import javax.annotation.Nullable; - -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.internal.ImageImpl; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.vcloud.domain.VAppTemplate; - -/** - * @author Adrian Cole - */ -public class VCloudImage extends ImageImpl { - - /** The serialVersionUID */ - private static final long serialVersionUID = -8520373150950058296L; - - private final VAppTemplate template; - - public VCloudImage(VAppTemplate template, String providerId, String name, String id, Location location, URI uri, - Map userMetadata, OperatingSystem operatingSystem, String description, - @Nullable String version, @Nullable Credentials defaultCredentials) { - super(providerId, name, id, location, uri, userMetadata, operatingSystem, description, version, - defaultCredentials); - this.template = template; - } - - public VAppTemplate getVAppTemplate() { - return template; - } - -} \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVApp.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVApp.java index b283372273..cb1a134e34 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVApp.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVApp.java @@ -31,9 +31,9 @@ import javax.annotation.Resource; import javax.inject.Inject; 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.HardwareImpl; import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -44,7 +44,6 @@ import org.jclouds.vcloud.domain.ovf.ResourceType; import org.jclouds.vcloud.domain.ovf.VirtualHardwareSection; import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -61,7 +60,7 @@ public class HardwareForVApp implements Function { @Inject protected HardwareForVApp(FindLocationForResource findLocationForResource, - ResourceAllocationsToVolumes resourceAllocationsToVolumes) { + ResourceAllocationsToVolumes resourceAllocationsToVolumes) { this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); this.resourceAllocationsToVolumes = checkNotNull(resourceAllocationsToVolumes, "resourceAllocationsToVolumes"); } @@ -79,18 +78,19 @@ public class HardwareForVApp implements Function { int ram = (int) find(hardware.getResourceAllocations(), resourceType(ResourceType.MEMORY)).getVirtualQuantity(); - List processors = Lists.newArrayList(transform(filter(hardware.getResourceAllocations(), - resourceType(ResourceType.PROCESSOR)), new Function() { + List processors = Lists.newArrayList(transform( + filter(hardware.getResourceAllocations(), resourceType(ResourceType.PROCESSOR)), + new Function() { - @Override - public Processor apply(ResourceAllocation arg0) { - return new Processor(arg0.getVirtualQuantity(), 1); - } + @Override + public Processor apply(ResourceAllocation arg0) { + return new Processor(arg0.getVirtualQuantity(), 1); + } - })); - Iterable volumes = resourceAllocationsToVolumes.apply(hardware.getResourceAllocations()); - return new HardwareImpl(from.getHref().toASCIIString(), from.getName(), from.getHref().toASCIIString(), location, - null, ImmutableMap. of(), processors, ram, volumes, ImagePredicates.idEquals(from - .getHref().toASCIIString())); + })); + List volumes = Lists.newArrayList(resourceAllocationsToVolumes.apply(hardware.getResourceAllocations())); + return new HardwareBuilder().ids(from.getHref().toASCIIString()).uri(from.getHref()).name(from.getName()) + .location(location).processors(processors).ram(ram).volumes(volumes) + .supportsImage(ImagePredicates.idEquals(from.getHref().toASCIIString())).build(); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVAppTemplate.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVAppTemplate.java index 86142b570e..973a7d3269 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVAppTemplate.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVAppTemplate.java @@ -31,9 +31,9 @@ import javax.annotation.Resource; import javax.inject.Inject; 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.HardwareImpl; import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -46,7 +46,6 @@ import org.jclouds.vcloud.domain.ovf.ResourceType; import org.jclouds.vcloud.domain.ovf.VirtualHardwareSection; import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; @@ -66,7 +65,7 @@ public class HardwareForVAppTemplate implements Function @Inject protected HardwareForVAppTemplate(VCloudClient client, FindLocationForResource findLocationForResource, - ResourceAllocationsToVolumes resourceAllocationsToVolumes) { + ResourceAllocationsToVolumes resourceAllocationsToVolumes) { this.client = checkNotNull(client, "client"); this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); this.resourceAllocationsToVolumes = checkNotNull(resourceAllocationsToVolumes, "resourceAllocationsToVolumes"); @@ -104,19 +103,20 @@ public class HardwareForVAppTemplate implements Function int ram = (int) find(hardware.getResourceAllocations(), resourceType(ResourceType.MEMORY)).getVirtualQuantity(); - List processors = Lists.newArrayList(transform(filter(hardware.getResourceAllocations(), - resourceType(ResourceType.PROCESSOR)), new Function() { + List processors = Lists.newArrayList(transform( + filter(hardware.getResourceAllocations(), resourceType(ResourceType.PROCESSOR)), + new Function() { - @Override - public Processor apply(ResourceAllocation arg0) { - return new Processor(arg0.getVirtualQuantity(), 1); - } + @Override + public Processor apply(ResourceAllocation arg0) { + return new Processor(arg0.getVirtualQuantity(), 1); + } - })); - Iterable volumes = resourceAllocationsToVolumes.apply(hardware.getResourceAllocations()); - return new HardwareImpl(from.getHref().toASCIIString(), from.getName(), from.getHref().toASCIIString(), location, - null, ImmutableMap. of(), processors, ram, volumes, ImagePredicates.idEquals(from - .getHref().toASCIIString())); + })); + List volumes = Lists.newArrayList(resourceAllocationsToVolumes.apply(hardware.getResourceAllocations())); + return new HardwareBuilder().ids(from.getHref().toASCIIString()).uri(from.getHref()).name(from.getName()) + .location(location).processors(processors).ram(ram).volumes(volumes) + .supportsImage(ImagePredicates.idEquals(from.getHref().toASCIIString())).build(); } diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVCloudExpressVApp.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVCloudExpressVApp.java index 6872ff1520..3e973ccc8e 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVCloudExpressVApp.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/HardwareForVCloudExpressVApp.java @@ -32,9 +32,9 @@ import javax.annotation.Resource; import javax.inject.Inject; 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.HardwareImpl; import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -43,7 +43,6 @@ import org.jclouds.vcloud.domain.ovf.ResourceAllocation; import org.jclouds.vcloud.domain.ovf.ResourceType; import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; /** @@ -59,7 +58,7 @@ public class HardwareForVCloudExpressVApp implements Function processors = Lists.newArrayList(transform(filter(from.getResourceAllocations(), - resourceType(ResourceType.PROCESSOR)), new Function() { + List processors = Lists.newArrayList(transform( + filter(from.getResourceAllocations(), resourceType(ResourceType.PROCESSOR)), + new Function() { - @Override - public Processor apply(ResourceAllocation arg0) { - return new Processor(arg0.getVirtualQuantity(), 1); - } + @Override + public Processor apply(ResourceAllocation arg0) { + return new Processor(arg0.getVirtualQuantity(), 1); + } - })); - Iterable volumes = resourceAllocationsToVolumes.apply(from.getResourceAllocations()); - return new HardwareImpl(from.getHref().toASCIIString(), from.getName(), from.getHref().toASCIIString(), - location, null, ImmutableMap. of(), processors, ram, volumes, ImagePredicates - .idEquals(from.getHref().toASCIIString())); + })); + List volumes = Lists.newArrayList(resourceAllocationsToVolumes.apply(from.getResourceAllocations())); + return new HardwareBuilder().ids(from.getHref().toASCIIString()).name(from.getName()).location(location) + .processors(processors).ram(ram).volumes(volumes) + .supportsImage(ImagePredicates.idEquals(from.getHref().toASCIIString())).build(); } catch (NoSuchElementException e) { logger.debug("incomplete data to form vApp %s", from.getHref()); return null; diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java index ac8791a926..277b0a12f2 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java @@ -25,17 +25,14 @@ import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.toComputeOs; import javax.inject.Inject; import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; -import org.jclouds.domain.Location; import org.jclouds.vcloud.VCloudClient; -import org.jclouds.vcloud.compute.domain.VCloudImage; import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.VAppTemplate; import org.jclouds.vcloud.domain.ovf.OvfEnvelope; import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole @@ -48,7 +45,7 @@ public class ImageForVAppTemplate implements Function { @Inject protected ImageForVAppTemplate(VCloudClient client, FindLocationForResource findLocationForResource, - PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider) { + PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider) { this.client = checkNotNull(client, "client"); this.findLocationForResource = checkNotNull(findLocationForResource, "findLocationForResource"); this.credentialsProvider = checkNotNull(credentialsProvider, "credentialsProvider"); @@ -61,18 +58,16 @@ public class ImageForVAppTemplate implements Function { @Override public Image apply(VAppTemplate from) { - + ImageBuilder builder = new ImageBuilder(); + builder.ids(from.getHref().toASCIIString()); + builder.uri(from.getHref()); + builder.name(from.getName()); + builder.location(findLocationForResource.apply(checkNotNull(parent, "parent"))); + builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); OvfEnvelope ovf = client.getOvfEnvelopeForVAppTemplate(from.getHref()); - OperatingSystem os = toComputeOs(ovf); - - Location location = findLocationForResource.apply(checkNotNull(parent, "parent")); - String name = getName(from.getName()); - String desc = from.getDescription() != null ? from.getDescription() : from.getName(); - return new VCloudImage(from, from.getHref().toASCIIString(), name, from.getHref().toASCIIString(), location, from - .getHref(), ImmutableMap. of(), os, desc, "", credentialsProvider.execute(from)); + builder.operatingSystem(toComputeOs(ovf)); + builder.defaultCredentials(credentialsProvider.execute(from)); + return builder.build(); } - protected String getName(String name) { - return name; - } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVCloudExpressVAppTemplate.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVCloudExpressVAppTemplate.java index 5b46b5a49d..3cb068aeb6 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVCloudExpressVAppTemplate.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVCloudExpressVAppTemplate.java @@ -25,16 +25,14 @@ import static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrNull; import javax.inject.Inject; 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.OperatingSystemBuilder; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; -import org.jclouds.domain.Location; -import org.jclouds.vcloud.compute.domain.VCloudExpressImage; import org.jclouds.vcloud.domain.ReferenceType; import org.jclouds.vcloud.domain.VCloudExpressVAppTemplate; import com.google.common.base.Function; -import com.google.common.collect.ImmutableMap; /** * @author Adrian Cole @@ -46,7 +44,7 @@ public class ImageForVCloudExpressVAppTemplate implements Function of(), os, desc, "", credentialsProvider - .execute(from)); + ImageBuilder builder = new ImageBuilder(); + builder.ids(from.getHref().toASCIIString()); + builder.uri(from.getHref()); + builder.name(from.getName()); + builder.location(findLocationForResource.apply(checkNotNull(parent, "parent"))); + builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); + builder.operatingSystem(parseOs(from)); + builder.defaultCredentials(credentialsProvider.execute(from)); + return builder.build(); } - protected String getName(String name) { - return name; + protected OperatingSystem parseOs(VCloudExpressVAppTemplate from) { + OperatingSystemBuilder builder = new OperatingSystemBuilder(); + builder.family(parseOsFamilyOrNull("vcloudexpress", checkNotNull(from, "vapp template").getName())); + builder.description(from.getName()); + builder.is64Bit(from.getName().indexOf("64") != -1); + return builder.build(); } + } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ResourceAllocationsToVolumes.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ResourceAllocationsToVolumes.java index c05de3689c..3add051baa 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ResourceAllocationsToVolumes.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/ResourceAllocationsToVolumes.java @@ -37,26 +37,25 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class ResourceAllocationsToVolumes implements - Function, Iterable> { +public class ResourceAllocationsToVolumes implements Function, Iterable> { @Override - public Iterable apply(Iterable resourceAllocations) { + public Iterable apply(Iterable resourceAllocations) { Iterable volumes = transform(filter(resourceAllocations, resourceType(ResourceType.DISK_DRIVE)), - new Function() { + new Function() { - @Override - public Volume apply(ResourceAllocation from) { - if (from instanceof VCloudHardDisk) { - VCloudHardDisk vDisk = VCloudHardDisk.class.cast(from); - return new VolumeImpl(from.getAddressOnParent() + "", Volume.Type.LOCAL, - vDisk.getCapacity() / 1024f, null, from.getAddressOnParent() == 0, true); - } else { - return new VolumeImpl(from.getAddressOnParent() + "", Volume.Type.LOCAL, from - .getVirtualQuantity() / 1024 / 1024f, null, from.getAddressOnParent() == 0, true); - } + @Override + public Volume apply(ResourceAllocation from) { + if (from instanceof VCloudHardDisk) { + VCloudHardDisk vDisk = VCloudHardDisk.class.cast(from); + return new VolumeImpl(from.getAddressOnParent() + "", Volume.Type.LOCAL, + vDisk.getCapacity() / 1024f, null, from.getAddressOnParent() == 0, true); + } else { + return new VolumeImpl(from.getAddressOnParent() + "", Volume.Type.LOCAL, + from.getVirtualQuantity() / 1024 / 1024f, null, from.getAddressOnParent() == 0, true); } + } - }); + }); return volumes; } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java new file mode 100644 index 0000000000..8f2c846a06 --- /dev/null +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java @@ -0,0 +1,81 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vcloud.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; +import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getCredentialsFrom; +import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getPrivateIpsFromVApp; +import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getPublicIpsFromVApp; +import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.toComputeOs; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.domain.Credentials; +import org.jclouds.vcloud.domain.Status; +import org.jclouds.vcloud.domain.VApp; + +import com.google.common.base.Function; + +/** + * @author Adrian Cole + */ +@Singleton +public class VAppToNodeMetadata implements Function { + protected final FindLocationForResource findLocationForResourceInVDC; + protected final Function hardwareForVApp; + protected final Map vAppStatusToNodeState; + protected final Map credentialStore; + + @Inject + protected VAppToNodeMetadata(Map vAppStatusToNodeState, Map credentialStore, + FindLocationForResource findLocationForResourceInVDC, Function hardwareForVApp) { + this.hardwareForVApp = checkNotNull(hardwareForVApp, "hardwareForVApp"); + this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); + this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + } + + public NodeMetadata apply(VApp from) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + builder.ids(from.getHref().toASCIIString()); + builder.uri(from.getHref()); + builder.name(from.getName()); + builder.location(findLocationForResourceInVDC.apply(from.getVDC())); + builder.tag(parseTagFromName(from.getName())); + builder.operatingSystem(toComputeOs(from, null)); + builder.hardware(hardwareForVApp.apply(from)); + builder.state(vAppStatusToNodeState.get(from.getStatus())); + builder.publicAddresses(getPublicIpsFromVApp(from)); + builder.privateAddresses(getPrivateIpsFromVApp(from)); + builder.credentials(getCredentialsFrom(from)); + if (!credentialStore.containsKey(from.getHref().toASCIIString())) + credentialStore.put(from.getHref().toASCIIString(), getCredentialsFrom(from)); + builder.credentials(credentialStore.get(from.getHref().toASCIIString())); + return builder.build(); + } +} \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java new file mode 100644 index 0000000000..9a0dd8f77b --- /dev/null +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/functions/VCloudExpressVAppToNodeMetadata.java @@ -0,0 +1,87 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + */ + +package org.jclouds.vcloud.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; + +import java.util.Map; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.os.CIMOperatingSystem; +import org.jclouds.domain.Credentials; +import org.jclouds.vcloud.compute.VCloudExpressComputeClient; +import org.jclouds.vcloud.domain.Status; +import org.jclouds.vcloud.domain.VCloudExpressVApp; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; + +/** + * @author Adrian Cole + */ +@Singleton +public class VCloudExpressVAppToNodeMetadata implements Function { + + protected final VCloudExpressComputeClient computeClient; + protected final Map credentialStore; + protected final Supplier> images; + protected final FindLocationForResource findLocationForResourceInVDC; + protected final HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp; + protected final Map vAppStatusToNodeState; + + @Inject + protected VCloudExpressVAppToNodeMetadata(VCloudExpressComputeClient computeClient, + Map credentialStore, Map vAppStatusToNodeState, + HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, + FindLocationForResource findLocationForResourceInVDC, Supplier> images) { + this.images = checkNotNull(images, "images"); + this.hardwareForVCloudExpressVApp = checkNotNull(hardwareForVCloudExpressVApp, "hardwareForVCloudExpressVApp"); + this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); + this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + this.computeClient = checkNotNull(computeClient, "computeClient"); + this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + } + + @Override + public NodeMetadata apply(VCloudExpressVApp from) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + builder.ids(from.getHref().toASCIIString()); + builder.uri(from.getHref()); + builder.name(from.getName()); + builder.location(findLocationForResourceInVDC.apply(from.getVDC())); + builder.tag(parseTagFromName(from.getName())); + builder.operatingSystem(from.getOsType() != null ? new CIMOperatingSystem(CIMOperatingSystem.OSType + .fromValue(from.getOsType()), null, null, from.getOperatingSystemDescription()) : null); + builder.hardware(hardwareForVCloudExpressVApp.apply(from)); + builder.state(vAppStatusToNodeState.get(from.getStatus())); + builder.publicAddresses(computeClient.getPublicAddresses(from.getHref())); + builder.privateAddresses(computeClient.getPrivateAddresses(from.getHref())); + builder.credentials(credentialStore.get(from.getHref().toASCIIString())); + return builder.build(); + } +} \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/CommonVCloudComputeClientImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/CommonVCloudComputeClientImpl.java index a6639f505d..d90681a774 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/CommonVCloudComputeClientImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/CommonVCloudComputeClientImpl.java @@ -19,10 +19,7 @@ package org.jclouds.vcloud.compute.internal; -import static com.google.common.base.Preconditions.checkState; - import java.net.URI; -import java.util.Map; import java.util.Set; import javax.annotation.Resource; @@ -38,7 +35,6 @@ import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.Task; import com.google.common.base.Predicate; -import com.google.common.collect.Maps; import com.google.inject.Inject; /** @@ -59,22 +55,6 @@ public abstract class CommonVCloudComputeClientImpl this.taskTester = successTester; } - protected Map parseAndValidateResponse(T template, A vAppResponse) { - Map response = parseResponse(template, vAppResponse); - checkState(response.containsKey("id"), "bad configuration: [id] should be in response"); - checkState(response.containsKey("username"), "bad configuration: [username] should be in response"); - checkState(response.containsKey("password"), "bad configuration: [password] should be in response"); - return response; - } - - protected Map parseResponse(T template, A vAppResponse) { - Map config = Maps.newLinkedHashMap();// Allows nulls - config.put("id", vAppResponse.getHref().toASCIIString()); - config.put("username", null); - config.put("password", null); - return config; - } - @Override public void reset(URI id) { A vApp = refreshVApp(id); diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/VCloudExpressComputeClientImpl.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/VCloudExpressComputeClientImpl.java index 6c18dc3186..a34b92e5a0 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/VCloudExpressComputeClientImpl.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/internal/VCloudExpressComputeClientImpl.java @@ -47,14 +47,13 @@ import com.google.inject.Inject; */ @Singleton public class VCloudExpressComputeClientImpl extends - CommonVCloudComputeClientImpl implements - VCloudExpressComputeClient { + CommonVCloudComputeClientImpl implements VCloudExpressComputeClient { protected final Map vAppStatusToNodeState; @Inject public VCloudExpressComputeClientImpl(VCloudExpressClient client, Predicate successTester, - Map vAppStatusToNodeState) { + Map vAppStatusToNodeState) { super(client, successTester); this.vAppStatusToNodeState = vAppStatusToNodeState; } @@ -66,13 +65,13 @@ public class VCloudExpressComputeClientImpl extends } @Override - public Map start(@Nullable URI VDC, URI templateId, String name, - InstantiateVAppTemplateOptions options, int... portsToOpen) { + public VCloudExpressVApp start(@Nullable URI VDC, URI templateId, String name, + InstantiateVAppTemplateOptions options, int... portsToOpen) { checkNotNull(options, "options"); logger.debug(">> instantiating vApp vDC(%s) template(%s) name(%s) options(%s) ", VDC, templateId, name, options); VCloudExpressVApp vAppResponse = VCloudExpressClient.class.cast(client).instantiateVAppTemplateInVDC(VDC, - templateId, name, options); + templateId, name, options); logger.debug("<< instantiated VApp(%s)", vAppResponse.getName()); if (options.shouldDeploy()) { logger.debug(">> deploying vApp(%s)", vAppResponse.getName()); @@ -88,13 +87,13 @@ public class VCloudExpressComputeClientImpl extends task = VCloudExpressClient.class.cast(client).powerOnVApp(vAppResponse.getHref()); if (!taskTester.apply(task.getHref())) { throw new RuntimeException(String.format("failed to %s %s: %s", "powerOn", vAppResponse.getName(), - task)); + task)); } logger.debug("<< on vApp(%s)", vAppResponse.getName()); } } } - return parseAndValidateResponse(VCloudExpressClient.class.cast(client).getVAppTemplate(templateId), vAppResponse); + return vAppResponse; } @Override diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressAddNodeWithTagStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressAddNodeWithTagStrategy.java index f2d0ba2721..fea8c28b5e 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressAddNodeWithTagStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressAddNodeWithTagStrategy.java @@ -23,26 +23,19 @@ import static org.jclouds.compute.util.ComputeServiceUtils.getCores; import static org.jclouds.vcloud.options.InstantiateVAppTemplateOptions.Builder.processorCount; import java.net.URI; -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.OperatingSystem; import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.internal.NodeMetadataImpl; -import org.jclouds.compute.domain.os.CIMOperatingSystem; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; -import org.jclouds.domain.Credentials; import org.jclouds.vcloud.VCloudExpressClient; import org.jclouds.vcloud.compute.VCloudExpressComputeClient; -import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Function; /** * @author Adrian Cole @@ -51,42 +44,26 @@ import com.google.common.collect.ImmutableMap; public class VCloudExpressAddNodeWithTagStrategy implements AddNodeWithTagStrategy { protected final VCloudExpressClient client; protected final VCloudExpressComputeClient computeClient; - protected final Map vAppStatusToNodeState; + protected final Function vAppToNodeMetadata; @Inject protected VCloudExpressAddNodeWithTagStrategy(VCloudExpressClient client, VCloudExpressComputeClient computeClient, - Map vAppStatusToNodeState) { + Function vAppToNodeMetadata) { this.client = client; this.computeClient = computeClient; - this.vAppStatusToNodeState = vAppStatusToNodeState; + this.vAppToNodeMetadata = vAppToNodeMetadata; } @Override public NodeMetadata execute(String tag, String name, Template template) { InstantiateVAppTemplateOptions options = processorCount((int) getCores(template.getHardware())).memory( - template.getHardware().getRam()).disk( - (long) ((template.getHardware().getVolumes().get(0).getSize()) * 1024 * 1024l)); + template.getHardware().getRam()).disk( + (long) ((template.getHardware().getVolumes().get(0).getSize()) * 1024 * 1024l)); if (!template.getOptions().shouldBlockUntilRunning()) options.block(false); - Map metaMap = computeClient.start(URI.create(template.getLocation().getId()), URI.create(template - .getImage().getId()), name, options, template.getOptions().getInboundPorts()); - VCloudExpressVApp vApp = client.getVApp(URI.create(metaMap.get("id"))); - return newCreateNodeResponse(tag, template, metaMap, vApp); - } - - protected NodeMetadata newCreateNodeResponse(String tag, Template template, Map metaMap, - VCloudExpressVApp vApp) { - return new NodeMetadataImpl(vApp.getHref().toASCIIString(), vApp.getName(), vApp.getHref().toASCIIString(), - template.getLocation(), vApp.getHref(), ImmutableMap. of(), tag, template.getHardware(), - template.getImage().getId(), getOperatingSystemForVAppOrDefaultTo(vApp, template.getImage() - .getOperatingSystem()), vAppStatusToNodeState.get(vApp.getStatus()), computeClient - .getPublicAddresses(vApp.getHref()), computeClient.getPrivateAddresses(vApp.getHref()), - new Credentials(metaMap.get("username"), metaMap.get("password"))); - } - - private OperatingSystem getOperatingSystemForVAppOrDefaultTo(VCloudExpressVApp vApp, OperatingSystem operatingSystem) { - return vApp.getOsType() != null ? new CIMOperatingSystem(CIMOperatingSystem.OSType.fromValue(vApp.getOsType()), - null, null, vApp.getOperatingSystemDescription()) : operatingSystem; + VCloudExpressVApp vApp = computeClient.start(URI.create(template.getLocation().getId()), + URI.create(template.getImage().getId()), name, options, template.getOptions().getInboundPorts()); + return vAppToNodeMetadata.apply(vApp); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressGetNodeMetadataStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressGetNodeMetadataStrategy.java index 20a4315d57..19e4eb2ee7 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressGetNodeMetadataStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressGetNodeMetadataStrategy.java @@ -20,62 +20,33 @@ package org.jclouds.vcloud.compute.strategy; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; import java.net.URI; -import java.util.Map; -import java.util.Set; -import javax.annotation.Resource; import javax.inject.Inject; -import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.internal.NodeMetadataImpl; -import org.jclouds.compute.domain.os.CIMOperatingSystem; -import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.domain.Location; -import org.jclouds.logging.Logger; import org.jclouds.vcloud.VCloudExpressClient; -import org.jclouds.vcloud.compute.VCloudExpressComputeClient; -import org.jclouds.vcloud.compute.functions.FindLocationForResource; -import org.jclouds.vcloud.compute.functions.HardwareForVCloudExpressVApp; -import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.VCloudExpressVApp; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Function; /** * @author Adrian Cole */ @Singleton public class VCloudExpressGetNodeMetadataStrategy implements GetNodeMetadataStrategy { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - public Logger logger = Logger.NULL; + protected final VCloudExpressClient client; - protected final VCloudExpressComputeClient computeClient; - protected final Supplier> images; - protected final FindLocationForResource findLocationForResourceInVDC; - protected final HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp; - protected final Map vAppStatusToNodeState; + protected final Function vAppToNodeMetadata; @Inject - protected VCloudExpressGetNodeMetadataStrategy(VCloudExpressClient client, VCloudExpressComputeClient computeClient, - Map vAppStatusToNodeState, HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, - FindLocationForResource findLocationForResourceInVDC, Supplier> images) { + protected VCloudExpressGetNodeMetadataStrategy(VCloudExpressClient client, + Function vAppToNodeMetadata) { this.client = checkNotNull(client, "client"); - this.images = checkNotNull(images, "images"); - this.hardwareForVCloudExpressVApp = checkNotNull(hardwareForVCloudExpressVApp, "hardwareForVCloudExpressVApp"); - this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); - this.computeClient = checkNotNull(computeClient, "computeClient"); - this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + this.vAppToNodeMetadata = vAppToNodeMetadata; } public NodeMetadata execute(String in) { @@ -83,14 +54,7 @@ public class VCloudExpressGetNodeMetadataStrategy implements GetNodeMetadataStra VCloudExpressVApp from = client.getVApp(id); if (from == null) return null; - String tag = parseTagFromName(from.getName()); - Location location = findLocationForResourceInVDC.apply(from.getVDC()); - Hardware hardware = hardwareForVCloudExpressVApp.apply(from); - return new NodeMetadataImpl(in, from.getName(), in, location, from.getHref(), ImmutableMap. of(), - tag, hardware, null, from.getOsType() != null ? new CIMOperatingSystem(CIMOperatingSystem.OSType - .fromValue(from.getOsType()), null, null, from.getOperatingSystemDescription()) : null, - vAppStatusToNodeState.get(from.getStatus()), computeClient.getPublicAddresses(id), computeClient - .getPrivateAddresses(id), null); + return vAppToNodeMetadata.apply(from); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java index 1f0123c667..0688edce5d 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudExpressListNodesStrategy.java @@ -30,11 +30,10 @@ import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.ComputeMetadataBuilder; import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.internal.ComputeMetadataImpl; import org.jclouds.compute.strategy.ListNodesStrategy; -import org.jclouds.domain.Location; import org.jclouds.logging.Logger; import org.jclouds.vcloud.CommonVCloudClient; import org.jclouds.vcloud.VCloudMediaType; @@ -46,7 +45,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.internal.util.ImmutableSet; @@ -75,8 +73,8 @@ public class VCloudExpressListNodesStrategy implements ListNodesStrategy { @Inject protected VCloudExpressListNodesStrategy(CommonVCloudClient client, - @Org Supplier> orgNameToEndpoint, VCloudExpressGetNodeMetadataStrategy getNodeMetadata, - FindLocationForResource findLocationForResourceInVDC) { + @Org Supplier> orgNameToEndpoint, + VCloudExpressGetNodeMetadataStrategy getNodeMetadata, FindLocationForResource findLocationForResourceInVDC) { this.client = client; this.orgNameToEndpoint = orgNameToEndpoint; this.getNodeMetadata = getNodeMetadata; @@ -103,9 +101,12 @@ public class VCloudExpressListNodesStrategy implements ListNodesStrategy { } private ComputeMetadata convertVAppToComputeMetadata(ReferenceType vdc, ReferenceType resource) { - Location location = findLocationForResourceInVDC.apply(vdc); - return new ComputeMetadataImpl(ComputeType.NODE, resource.getHref().toASCIIString(), resource.getName(), resource - .getHref().toASCIIString(), location, null, ImmutableMap. of()); + ComputeMetadataBuilder builder = new ComputeMetadataBuilder(ComputeType.NODE); + builder.providerId(resource.getHref().toASCIIString()); + builder.name(resource.getName()); + builder.id(resource.getHref().toASCIIString()); + builder.location(findLocationForResourceInVDC.apply(vdc)); + return builder.build(); } @Override diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudGetNodeMetadataStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudGetNodeMetadataStrategy.java index 7f5cee785f..db18b535e1 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudGetNodeMetadataStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudGetNodeMetadataStrategy.java @@ -20,62 +20,32 @@ package org.jclouds.vcloud.compute.strategy; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseTagFromName; -import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getCredentialsFrom; -import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getPrivateIpsFromVApp; -import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.getPublicIpsFromVApp; -import static org.jclouds.vcloud.compute.util.VCloudComputeUtils.toComputeOs; import java.net.URI; -import java.util.Map; -import java.util.Set; -import javax.annotation.Resource; import javax.inject.Inject; -import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.internal.NodeMetadataImpl; -import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.domain.Location; -import org.jclouds.logging.Logger; import org.jclouds.vcloud.VCloudClient; -import org.jclouds.vcloud.compute.functions.FindLocationForResource; -import org.jclouds.vcloud.compute.functions.HardwareForVApp; -import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.VApp; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; +import com.google.common.base.Function; /** * @author Adrian Cole */ @Singleton public class VCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - public Logger logger = Logger.NULL; + protected final VCloudClient client; - protected final Supplier> images; - protected final FindLocationForResource findLocationForResourceInVDC; - protected final HardwareForVApp hardwareForVApp; - protected final Map vAppStatusToNodeState; + protected final Function vAppToNodeMetadata; @Inject - protected VCloudGetNodeMetadataStrategy(VCloudClient client, Map vAppStatusToNodeState, - HardwareForVApp hardwareForVApp, FindLocationForResource findLocationForResourceInVDC, - Supplier> images) { + protected VCloudGetNodeMetadataStrategy(VCloudClient client, Function vAppToNodeMetadata) { this.client = checkNotNull(client, "client"); - this.images = checkNotNull(images, "images"); - this.hardwareForVApp = checkNotNull(hardwareForVApp, "hardwareForVApp"); - this.findLocationForResourceInVDC = checkNotNull(findLocationForResourceInVDC, "findLocationForResourceInVDC"); - this.vAppStatusToNodeState = checkNotNull(vAppStatusToNodeState, "vAppStatusToNodeState"); + this.vAppToNodeMetadata = checkNotNull(vAppToNodeMetadata, "vAppToNodeMetadata"); } public NodeMetadata execute(String in) { @@ -83,11 +53,6 @@ public class VCloudGetNodeMetadataStrategy implements GetNodeMetadataStrategy { VApp from = client.getVApp(id); if (from == null) return null; - String tag = parseTagFromName(from.getName()); - Location location = findLocationForResourceInVDC.apply(from.getVDC()); - Hardware hardware = hardwareForVApp.apply(from); - return new NodeMetadataImpl(in, from.getName(), in, location, from.getHref(), ImmutableMap. of(), - tag, hardware, null, toComputeOs(from, null), vAppStatusToNodeState.get(from.getStatus()), - getPublicIpsFromVApp(from), getPrivateIpsFromVApp(from), getCredentialsFrom(from)); + return vAppToNodeMetadata.apply(from); } } \ No newline at end of file diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java index 78d4902f39..d1faba4277 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/strategy/VCloudListNodesStrategy.java @@ -30,11 +30,10 @@ import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.ComputeMetadataBuilder; import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.internal.ComputeMetadataImpl; import org.jclouds.compute.strategy.ListNodesStrategy; -import org.jclouds.domain.Location; import org.jclouds.logging.Logger; import org.jclouds.vcloud.CommonVCloudClient; import org.jclouds.vcloud.VCloudMediaType; @@ -46,7 +45,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.internal.util.ImmutableSet; @@ -103,9 +101,12 @@ public class VCloudListNodesStrategy implements ListNodesStrategy { } private ComputeMetadata convertVAppToComputeMetadata(ReferenceType vdc, ReferenceType resource) { - Location location = findLocationForResourceInVDC.apply(vdc); - return new ComputeMetadataImpl(ComputeType.NODE, resource.getHref().toASCIIString(), resource.getName(), resource - .getHref().toASCIIString(), location, null, ImmutableMap. of()); + ComputeMetadataBuilder builder = new ComputeMetadataBuilder(ComputeType.NODE); + builder.providerId(resource.getHref().toASCIIString()); + builder.name(resource.getName()); + builder.id(resource.getHref().toASCIIString()); + builder.location(findLocationForResourceInVDC.apply(vdc)); + return builder.build(); } @Override diff --git a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java index 263adc7841..a0a9e5a4b2 100644 --- a/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java +++ b/vcloud/core/src/main/java/org/jclouds/vcloud/compute/suppliers/StaticHardwareSupplier.java @@ -24,14 +24,13 @@ 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 org.jclouds.compute.predicates.ImagePredicates; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; /** @@ -42,15 +41,14 @@ public class StaticHardwareSupplier implements Supplier> @Override public Set get() { - Set sizes = Sets.newHashSet(); + Set hardware = Sets.newHashSet(); for (int cpus : new int[] { 1, 2, 4, 8 }) for (int ram : new int[] { 512, 1024, 2048, 4096, 8192, 16384 }) { String id = String.format("cpu=%d,ram=%s,disk=%d", cpus, ram, 10); - sizes.add(new HardwareImpl(id, null, id, null, null, ImmutableMap. of(), ImmutableList - .of(new Processor(cpus, 1.0)), ram, ImmutableList.of(new VolumeImpl(10f, true, true)), - ImagePredicates.any())); + hardware.add(new HardwareBuilder().ids(id).ram(ram) + .processors(ImmutableList.of(new Processor(cpus, 1.0))) + .volumes(ImmutableList. of(new VolumeImpl(10f, true, true))).build()); } - return sizes; + return hardware; } - } \ No newline at end of file diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java index a1e2aa291d..2ad55295e4 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClient.java @@ -24,7 +24,6 @@ import static com.google.common.collect.Iterables.getLast; import static org.jclouds.vcloud.terremark.options.AddInternetServiceOptions.Builder.withDescription; import java.net.URI; -import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; @@ -64,34 +63,26 @@ import com.google.common.collect.Sets; @Singleton public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl { - private final TerremarkVCloudExpressClient client; - private final PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider; - private Provider passwordGenerator; + protected final TerremarkVCloudExpressClient client; + protected final PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider; + protected final Provider passwordGenerator; + protected final Map credentialStore; @Inject protected TerremarkVCloudComputeClient(TerremarkVCloudExpressClient client, - PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider, - @Named("PASSWORD") Provider passwordGenerator, Predicate successTester, - Map vAppStatusToNodeState) { + PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider, + @Named("PASSWORD") Provider passwordGenerator, Predicate successTester, + Map vAppStatusToNodeState, Map credentialStore) { super(client, successTester, vAppStatusToNodeState); this.client = client; this.credentialsProvider = credentialsProvider; this.passwordGenerator = passwordGenerator; + this.credentialStore = credentialStore; } @Override - protected Map parseAndValidateResponse(VCloudExpressVAppTemplate template, - VCloudExpressVApp vAppResponse) { - Credentials credentials = credentialsProvider.execute(template); - Map toReturn = super.parseResponse(template, vAppResponse); - toReturn.put("username", credentials.identity); - toReturn.put("password", credentials.credential); - return toReturn; - } - - @Override - public Map start(@Nullable URI VDC, URI templateId, String name, - InstantiateVAppTemplateOptions options, int... portsToOpen) { + public VCloudExpressVApp start(@Nullable URI VDC, URI templateId, String name, + InstantiateVAppTemplateOptions options, int... portsToOpen) { if (options.getDiskSizeKilobytes() != null) { logger.warn("trmk does not support resizing the primary disk; unsetting disk size"); } @@ -101,18 +92,20 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl String password = null; VCloudExpressVAppTemplate template = client.getVAppTemplate(templateId); if (template.getDescription().indexOf("Windows") != -1 - && options instanceof TerremarkInstantiateVAppTemplateOptions) { + && options instanceof TerremarkInstantiateVAppTemplateOptions) { password = passwordGenerator.get(); TerremarkInstantiateVAppTemplateOptions.class.cast(options).getProperties().put("password", password); } - Map response = super.start(VDC, templateId, name, options, portsToOpen); + Credentials defaultCredentials = credentialsProvider.execute(template); + + VCloudExpressVApp vAppResponse = super.start(VDC, templateId, name, options, portsToOpen); if (password != null) { - response = new LinkedHashMap(response); - response.put("password", password); + credentialStore.put(vAppResponse.getHref().toASCIIString(), new Credentials(defaultCredentials.identity, + password)); } if (portsToOpen.length > 0) - createPublicAddressMappedToPorts(URI.create(response.get("id")), portsToOpen); - return response; + createPublicAddressMappedToPorts(vAppResponse.getHref(), portsToOpen); + return vAppResponse; } public String createPublicAddressMappedToPorts(URI vAppId, int... ports) { @@ -123,47 +116,51 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl InternetService is = null; Protocol protocol; switch (port) { - case 22: - protocol = Protocol.TCP; - break; - case 80: - case 8080: - protocol = Protocol.HTTP; - break; - case 443: - protocol = Protocol.HTTPS; - break; - default: - protocol = Protocol.HTTP; - break; + case 22: + protocol = Protocol.TCP; + break; + case 80: + case 8080: + protocol = Protocol.HTTP; + break; + case 443: + protocol = Protocol.HTTPS; + break; + default: + protocol = Protocol.HTTP; + break; } if (ip == null) { if (client instanceof TerremarkVCloudExpressClient) { is = TerremarkVCloudExpressClient.class.cast(client).addInternetServiceToVDC( - vApp.getVDC().getHref(), - vApp.getName() + "-" + port, - protocol, - port, - withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), - vApp.getName()))); + vApp.getVDC().getHref(), + vApp.getName() + "-" + port, + protocol, + port, + withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), + vApp.getName()))); ip = is.getPublicIpAddress(); } else { logger.debug(">> creating InternetService in vDC %s:%s:%d", vApp.getVDC().getName(), protocol, port); ip = TerremarkECloudClient.class.cast(client).activatePublicIpInVDC(vApp.getVDC().getHref()); is = client.addInternetServiceToExistingIp(ip.getId(), vApp.getName() + "-" + port, protocol, port, - withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), - vApp.getName()))); + withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), + vApp.getName()))); } } else { logger.debug(">> adding InternetService %s:%s:%d", ip.getAddress(), protocol, port); - is = client.addInternetServiceToExistingIp(ip.getId(), vApp.getName() + "-" + port, protocol, port, - withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), - vApp.getName()))); + is = client.addInternetServiceToExistingIp( + ip.getId(), + vApp.getName() + "-" + port, + protocol, + port, + withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), + vApp.getName()))); } - logger.debug("<< created InternetService(%s) %s:%s:%d", is.getName(), is.getPublicIpAddress().getAddress(), is - .getProtocol(), is.getPort()); + logger.debug("<< created InternetService(%s) %s:%s:%d", is.getName(), is.getPublicIpAddress().getAddress(), + is.getProtocol(), is.getPort()); logger.debug(">> adding Node %s:%d -> %s:%d", is.getPublicIpAddress().getAddress(), is.getPort(), - privateAddress, port); + privateAddress, port); Node node = client.addNode(is.getId(), privateAddress, vApp.getName() + "-" + port, port); logger.debug("<< added Node(%s)", node.getName()); } @@ -177,13 +174,13 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl if (vApp.getNetworkToAddresses().containsValue(node.getIpAddress())) { ipAddresses.add(service.getPublicIpAddress()); logger.debug(">> deleting Node(%s) %s:%d -> %s:%d", node.getName(), service.getPublicIpAddress() - .getAddress(), service.getPort(), node.getIpAddress(), node.getPort()); + .getAddress(), service.getPort(), node.getIpAddress(), node.getPort()); client.deleteNode(node.getId()); logger.debug("<< deleted Node(%s)", node.getName()); Set nodes = client.getNodes(service.getId()); if (nodes.size() == 0) { logger.debug(">> deleting InternetService(%s) %s:%d", service.getName(), service.getPublicIpAddress() - .getAddress(), service.getPort()); + .getAddress(), service.getPort()); client.deleteInternetService(service.getId()); logger.debug("<< deleted InternetService(%s)", service.getName()); continue SERVICE; diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java index 270ff0914a..e14a0db1fb 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeService.java @@ -19,6 +19,7 @@ package org.jclouds.vcloud.terremark.compute; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; @@ -43,6 +44,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 org.jclouds.vcloud.terremark.compute.domain.KeyPairCredentials; import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; @@ -61,19 +63,19 @@ public class TerremarkVCloudComputeService extends BaseComputeService { private final CleanupOrphanKeys cleanupOrphanKeys; @Inject - protected TerremarkVCloudComputeService(ComputeServiceContext context, Supplier> images, - Supplier> sizes, Supplier> locations, - ListNodesStrategy listNodesStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, - RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, - DestroyNodeStrategy destroyNodeStrategy, Provider templateBuilderProvider, - Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, - @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys, - ConcurrentMap credentialsMap, NodeMetadataToOrgAndName nodeToOrgAndName) { - super(context, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, runNodesAndAddToSetStrategy, - rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning, - nodeTerminated, utils, timeouts, executor); + protected TerremarkVCloudComputeService(ComputeServiceContext context, Map credentialStore, + Supplier> images, Supplier> sizes, + Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, RunNodesAndAddToSetStrategy runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, ComputeUtils utils, Timeouts timeouts, + @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, CleanupOrphanKeys cleanupOrphanKeys, + ConcurrentMap credentialsMap, NodeMetadataToOrgAndName nodeToOrgAndName) { + super(context, credentialStore, images, sizes, locations, listNodesStrategy, getNodeMetadataStrategy, + runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, templateBuilderProvider, + templateOptionsProvider, nodeRunning, nodeTerminated, utils, timeouts, executor); this.cleanupOrphanKeys = cleanupOrphanKeys; } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java index 89e360f60f..6ceb5d2aed 100755 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/config/TerremarkVCloudComputeServiceContextModule.java @@ -46,18 +46,20 @@ import org.jclouds.vcloud.VCloudExpressClient; import org.jclouds.vcloud.compute.VCloudExpressComputeClient; import org.jclouds.vcloud.compute.config.VCloudExpressComputeServiceContextModule; import org.jclouds.vcloud.compute.strategy.VCloudExpressDestroyNodeStrategy; +import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressListNodesStrategy; import org.jclouds.vcloud.compute.strategy.VCloudExpressRebootNodeStrategy; +import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeClient; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeService; import org.jclouds.vcloud.terremark.compute.domain.KeyPairCredentials; import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; import org.jclouds.vcloud.terremark.compute.functions.NodeMetadataToOrgAndName; +import org.jclouds.vcloud.terremark.compute.functions.TerremarkVCloudExpressVAppToNodeMetadata; import org.jclouds.vcloud.terremark.compute.options.TerremarkVCloudTemplateOptions; import org.jclouds.vcloud.terremark.compute.strategy.ParseVAppTemplateDescriptionToGetDefaultLoginCredentials; import org.jclouds.vcloud.terremark.compute.strategy.TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy; import org.jclouds.vcloud.terremark.compute.strategy.TerremarkVCloudAddNodeWithTagStrategy; -import org.jclouds.vcloud.terremark.compute.strategy.TerremarkVCloudGetNodeMetadataStrategy; import org.jclouds.vcloud.terremark.compute.suppliers.VAppTemplatesInOrgs; import com.google.common.base.Function; @@ -99,7 +101,9 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom bind(RunNodesAndAddToSetStrategy.class).to(TerremarkEncodeTagIntoNameRunNodesAndAddToSetStrategy.class); bind(ListNodesStrategy.class).to(VCloudExpressListNodesStrategy.class); // NOTE - bind(GetNodeMetadataStrategy.class).to(TerremarkVCloudGetNodeMetadataStrategy.class); + bind(new TypeLiteral>() { + }).to(TerremarkVCloudExpressVAppToNodeMetadata.class); + bind(GetNodeMetadataStrategy.class).to(VCloudExpressGetNodeMetadataStrategy.class); bind(RebootNodeStrategy.class).to(VCloudExpressRebootNodeStrategy.class); bind(DestroyNodeStrategy.class).to(VCloudExpressDestroyNodeStrategy.class); bindLoadBalancer(); @@ -111,7 +115,7 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom bind(ComputeService.class).to(TerremarkVCloudComputeService.class); bind(VCloudExpressComputeClient.class).to(TerremarkVCloudComputeClient.class); bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to( - ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); + ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.class); bind(SecureRandom.class).toInstance(new SecureRandom()); } @@ -127,7 +131,7 @@ public class TerremarkVCloudComputeServiceContextModule extends VCloudExpressCom // bind(LoadBalanceNodesStrategy.class).to(TerremarkLoadBalanceNodesStrategy.class); // bind(DestroyLoadBalancerStrategy.class).to(TerremarkDestroyLoadBalancerStrategy.class); // } - // + // @Named("PASSWORD") @Provides diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java similarity index 65% rename from vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java rename to vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java index b224c43702..2ce137d453 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudGetNodeMetadataStrategy.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/functions/TerremarkVCloudExpressVAppToNodeMetadata.java @@ -17,34 +17,30 @@ * ==================================================================== */ -package org.jclouds.vcloud.terremark.compute.strategy; +package org.jclouds.vcloud.terremark.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.installNewCredentials; import java.net.URI; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; -import javax.annotation.Resource; import javax.inject.Inject; -import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; -import org.jclouds.logging.Logger; -import org.jclouds.vcloud.VCloudExpressClient; import org.jclouds.vcloud.compute.VCloudExpressComputeClient; import org.jclouds.vcloud.compute.domain.VCloudLocation; import org.jclouds.vcloud.compute.functions.FindLocationForResource; import org.jclouds.vcloud.compute.functions.HardwareForVCloudExpressVApp; -import org.jclouds.vcloud.compute.strategy.VCloudExpressGetNodeMetadataStrategy; +import org.jclouds.vcloud.compute.functions.VCloudExpressVAppToNodeMetadata; import org.jclouds.vcloud.domain.Status; +import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.terremark.compute.domain.KeyPairCredentials; import org.jclouds.vcloud.terremark.compute.domain.OrgAndName; @@ -54,25 +50,24 @@ import com.google.common.base.Supplier; * @author Adrian Cole */ @Singleton -public class TerremarkVCloudGetNodeMetadataStrategy extends VCloudExpressGetNodeMetadataStrategy { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; - +public class TerremarkVCloudExpressVAppToNodeMetadata extends VCloudExpressVAppToNodeMetadata { private final ConcurrentMap credentialsMap; @Inject - protected TerremarkVCloudGetNodeMetadataStrategy(VCloudExpressClient client, - VCloudExpressComputeClient computeClient, Map vAppStatusToNodeState, - HardwareForVCloudExpressVApp getExtra, FindLocationForResource findLocationForResourceInVDC, - Supplier> images, ConcurrentMap credentialsMap) { - super(client, computeClient, vAppStatusToNodeState, getExtra, findLocationForResourceInVDC, images); - this.credentialsMap = credentialsMap; + public TerremarkVCloudExpressVAppToNodeMetadata(VCloudExpressComputeClient computeClient, + Map credentialStore, Map vAppStatusToNodeState, + HardwareForVCloudExpressVApp hardwareForVCloudExpressVApp, + FindLocationForResource findLocationForResourceInVDC, Supplier> images, + ConcurrentMap credentialsMap) { + super(computeClient, credentialStore, vAppStatusToNodeState, hardwareForVCloudExpressVApp, + findLocationForResourceInVDC, images); + this.credentialsMap = checkNotNull(credentialsMap, "credentialsMap"); + ; } @Override - public NodeMetadata execute(String id) { - NodeMetadata node = super.execute(checkNotNull(id, "node.id")); + public NodeMetadata apply(VCloudExpressVApp from) { + NodeMetadata node = super.apply(from); if (node == null) return null; if (node.getTag() != null) { @@ -85,7 +80,7 @@ public class TerremarkVCloudGetNodeMetadataStrategy extends VCloudExpressGetNode OrgAndName orgAndName = getOrgAndNameFromNode(node); if (credentialsMap.containsKey(orgAndName)) { Credentials creds = credentialsMap.get(orgAndName); - node = installNewCredentials(node, creds); + node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(creds).build(); } return node; } diff --git a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudAddNodeWithTagStrategy.java b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudAddNodeWithTagStrategy.java index 3568d06029..4b70b38474 100644 --- a/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudAddNodeWithTagStrategy.java +++ b/vcloud/terremark/src/main/java/org/jclouds/vcloud/terremark/compute/strategy/TerremarkVCloudAddNodeWithTagStrategy.java @@ -22,7 +22,6 @@ package org.jclouds.vcloud.terremark.compute.strategy; import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; -import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; @@ -30,38 +29,36 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; import org.jclouds.compute.strategy.AddNodeWithTagStrategy; -import org.jclouds.compute.strategy.GetNodeMetadataStrategy; -import org.jclouds.vcloud.terremark.TerremarkVCloudClient; +import org.jclouds.vcloud.domain.VCloudExpressVApp; import org.jclouds.vcloud.terremark.compute.TerremarkVCloudComputeClient; import org.jclouds.vcloud.terremark.compute.functions.TemplateToInstantiateOptions; import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions; +import com.google.common.base.Function; + /** * @author Adrian Cole */ @Singleton public class TerremarkVCloudAddNodeWithTagStrategy implements AddNodeWithTagStrategy { - protected final TerremarkVCloudClient client; protected final TerremarkVCloudComputeClient computeClient; - protected final GetNodeMetadataStrategy getNode; protected final TemplateToInstantiateOptions getOptions; + protected final Function vAppToNodeMetadata; @Inject - protected TerremarkVCloudAddNodeWithTagStrategy(TerremarkVCloudClient client, - TerremarkVCloudComputeClient computeClient, GetNodeMetadataStrategy getNode, - TemplateToInstantiateOptions getOptions) { - this.client = client; + protected TerremarkVCloudAddNodeWithTagStrategy(TerremarkVCloudComputeClient computeClient, + Function vAppToNodeMetadata, TemplateToInstantiateOptions getOptions) { this.computeClient = computeClient; - this.getNode = getNode; + this.vAppToNodeMetadata = vAppToNodeMetadata; this.getOptions = checkNotNull(getOptions, "getOptions"); } @Override public NodeMetadata execute(String tag, String name, Template template) { TerremarkInstantiateVAppTemplateOptions options = getOptions.apply(template); - Map metaMap = computeClient.start(URI.create(template.getLocation().getId()), URI.create(template - .getImage().getId()), name, options, template.getOptions().getInboundPorts()); - return getNode.execute(metaMap.get("id")); + VCloudExpressVApp vApp = computeClient.start(URI.create(template.getLocation().getId()), + URI.create(template.getImage().getId()), name, options, template.getOptions().getInboundPorts()); + return vAppToNodeMetadata.apply(vApp); } } \ No newline at end of file diff --git a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java index 36f8c01ce4..c447161874 100644 --- a/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java +++ b/vcloud/terremark/src/test/java/org/jclouds/vcloud/terremark/compute/TerremarkVCloudComputeClientTest.java @@ -33,6 +33,7 @@ import java.util.Map; import javax.inject.Provider; import org.jclouds.compute.domain.NodeState; +import org.jclouds.domain.Credentials; import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.Task; import org.jclouds.vcloud.domain.VCloudExpressVApp; @@ -44,6 +45,7 @@ import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOpti import org.testng.annotations.Test; import com.google.common.base.Predicate; +import com.google.common.collect.Maps; import com.google.common.io.ByteStreams; /** @@ -54,6 +56,7 @@ public class TerremarkVCloudComputeClientTest { @SuppressWarnings("unchecked") @Test public void testStartWindows() throws IOException { + Map credentialStore = Maps.newHashMap(); InputStream is = getClass().getResourceAsStream("/terremark/windows_description.txt"); String description = new String(ByteStreams.toByteArray(is)); VCloudExpressVAppTemplate template = createMock(VCloudExpressVAppTemplate.class); @@ -65,14 +68,11 @@ public class TerremarkVCloudComputeClientTest { TerremarkVCloudExpressClient client = createMock(TerremarkVCloudExpressClient.class); VCloudExpressVApp vApp = createMock(VCloudExpressVApp.class); - // TODO make this call only once expect(client.getVAppTemplate(templateURI)).andReturn(template); - expect(client.getVAppTemplate(templateURI)).andReturn(template); - expect( - client.instantiateVAppTemplateInVDC(vdcURI, templateURI, "name", - new TerremarkInstantiateVAppTemplateOptions().productProperty("password", "password"))) - .andReturn(vApp); + client.instantiateVAppTemplateInVDC(vdcURI, templateURI, "name", + new TerremarkInstantiateVAppTemplateOptions().productProperty("password", "password"))).andReturn( + vApp); Task task = createMock(Task.class); URI vappLocation = URI.create("vapp"); URI taskLocation = URI.create("task"); @@ -89,14 +89,14 @@ public class TerremarkVCloudComputeClientTest { Map vAppStatusToNodeState = createMock(Map.class); TerremarkVCloudComputeClient computeClient = new TerremarkVCloudComputeClient(client, - new ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(), new Provider() { + new ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(), new Provider() { - @Override - public String get() { - return "password"; - } + @Override + public String get() { + return "password"; + } - }, successTester, vAppStatusToNodeState); + }, successTester, vAppStatusToNodeState, credentialStore); replay(vdc); replay(template); @@ -107,12 +107,11 @@ public class TerremarkVCloudComputeClientTest { replay(notFoundTester); replay(vAppStatusToNodeState); - Map response = computeClient.start(vdcURI, templateURI, "name", - new TerremarkInstantiateVAppTemplateOptions()); + VCloudExpressVApp response = computeClient.start(vdcURI, templateURI, "name", + new TerremarkInstantiateVAppTemplateOptions()); - assertEquals(response.get("id"), "vapp"); - assertEquals(response.get("username"), "Administrator"); - assertEquals(response.get("password"), "password"); + assertEquals(response.getHref().toASCIIString(), "vapp"); + assertEquals(credentialStore.get("vapp"), new Credentials("Administrator", "password")); verify(vdc); verify(template);