diff --git a/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java b/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java index db17c79f71..878da381b3 100644 --- a/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java +++ b/apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java @@ -42,6 +42,8 @@ import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.logging.Logger; import org.jclouds.util.Strings2; @@ -92,24 +94,25 @@ public class NodeToNodeMetadata implements Function { builder.publicAddresses(ImmutableSet. of(from.getHostname())); if (from.getUsername() != null) { - Credentials creds = null; + Builder credBuilder = LoginCredentials.builder().user(from.getUsername()); if (from.getCredentialUrl() != null) { try { - creds = new Credentials(from.getUsername(), Strings2.toStringAndClose(slurp.apply(from - .getCredentialUrl()))); + credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl()))); } catch (IOException e) { logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); } } else if (from.getCredential() != null) { - creds = new Credentials(from.getUsername(), from.getCredential()); + credBuilder.credential(from.getCredential()); } - if (creds != null) - builder.credentials(creds); + if (from.getSudoPassword() != null){ + credBuilder.password(from.getSudoPassword()); + credBuilder.authenticateSudo(true); + } + LoginCredentials creds = credBuilder.build(); + builder.credentials(creds); credentialStore.put("node#" + from.getId(), creds); } - if (from.getSudoPassword() != null) - builder.adminPassword(from.getSudoPassword()); return builder.build(); } diff --git a/apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceTest.java b/apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceTest.java index de1a4958bc..e284a62484 100644 --- a/apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceTest.java +++ b/apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceTest.java @@ -30,13 +30,16 @@ import org.jclouds.byon.config.CacheNodeStoreModule; import org.jclouds.byon.functions.NodesFromYamlTest; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; import com.google.common.base.Supplier; import com.google.common.cache.Cache; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; import com.google.inject.Module; /** @@ -83,8 +86,8 @@ public class BYONComputeServiceTest { assertEquals(supplier.get().asMap(), ImmutableMap. of(NodesFromYamlTest.TEST1.getId(), NodesFromYamlTest.TEST1)); - assertEquals(context.getComputeService().listNodes(), - ImmutableSet.of(expectedNodeMetadataFromResource(endpoint))); + assertEquals(context.getComputeService().listNodes().toString(), + ImmutableSet.of(expectedNodeMetadataFromResource(endpoint)).toString()); assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(providerLocation)); } finally { if (context != null) @@ -98,8 +101,8 @@ public class BYONComputeServiceTest { String endpoint = "file://" + getClass().getResource("/test_location.yaml").getPath(); Properties props = new Properties(); props.setProperty("byon.endpoint", endpoint); - context = new ComputeServiceContextFactory().createContext("byon", "foo", "bar", - ImmutableSet. of(), props); + context = new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet. of(), + props); assertEquals(context.getProviderSpecificContext().getEndpoint(), URI.create(endpoint)); @@ -115,9 +118,26 @@ public class BYONComputeServiceTest { Location virginia = zoneCalled("virginia", providerLocation); Location maryland = zoneCalled("maryland", providerLocation); - assertEquals(context.getComputeService().listNodes(), ImmutableSet.of( - expectedNodeMetadataFromResource(1, endpoint, virginia), - expectedNodeMetadataFromResource(2, endpoint, maryland, 2022))); + assertEquals( + context.getComputeService().listNodes().toString(), + ImmutableSet.of(expectedNodeMetadataFromResource(1, endpoint, virginia), + expectedNodeMetadataFromResource(2, endpoint, maryland, 2022)).toString()); + + assertEquals(NodeMetadata.class.cast(Iterables.get(context.getComputeService().listNodes(), 0)) + .getCredentials(), + LoginCredentials + .builder() + .user("myUser") + .password("happy bear") + .authenticateSudo(true) + .privateKey( + "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\n" + + "u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\n" + + "lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n" + + "-----END RSA PRIVATE KEY-----\n").build() + + ); assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(virginia, maryland)); } finally { diff --git a/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java b/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java index d74960c03d..f3bb421920 100644 --- a/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java +++ b/apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java @@ -34,6 +34,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; import com.google.common.base.Suppliers; @@ -86,11 +87,15 @@ public class NodeToNodeMetadataTest { .hostname("cluster-" + id + ".mydomain.com") .location(location) .userMetadata(ImmutableMap.of("Name", "foo")) + .tags(ImmutableSet.of("vanilla")) .state(NodeState.RUNNING) .operatingSystem( OperatingSystem.builder().description("redhat").family(OsFamily.RHEL).arch("x86").version("5.3") - .build()).publicAddresses(ImmutableSet.of("cluster-" + id + ".mydomain.com")) - .credentials(new Credentials("myUser", NodesFromYamlTest.key)).adminPassword("happy bear").build(); + .build()) + .publicAddresses(ImmutableSet.of("cluster-" + id + ".mydomain.com")) + .credentials( + LoginCredentials.builder().user("myUser").privateKey(NodesFromYamlTest.key).password("happy bear") + .authenticateSudo(true).build()).build(); } @Test diff --git a/apis/cloudservers/pom.xml b/apis/cloudservers/pom.xml index 8aa24e4f21..4e769921b5 100644 --- a/apis/cloudservers/pom.xml +++ b/apis/cloudservers/pom.xml @@ -40,7 +40,8 @@ ${test.rackspace.identity} ${test.rackspace.credential} - + + @@ -111,7 +112,8 @@ ${test.cloudstack.identity} ${test.cloudstack.credential} ${test.cloudstack.image-id} - ${test.cloudstack.login-user} + ${test.cloudstack.image.login-user} + ${test.cloudstack.image.authenticate-sudo} diff --git a/apis/cloudsigma/pom.xml b/apis/cloudsigma/pom.xml index 1d3d238a7b..66a68ee424 100644 --- a/apis/cloudsigma/pom.xml +++ b/apis/cloudsigma/pom.xml @@ -39,7 +39,8 @@ FIXME FIXME - + + @@ -97,7 +98,8 @@ ${test.cloudsigma.identity} ${test.cloudsigma.credential} ${test.cloudsigma.image-id} - ${test.cloudsigma.login-user} + ${test.cloudsigma.image.login-user} + ${test.cloudsigma.image.authenticate-sudo} diff --git a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceAdapter.java b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceAdapter.java index 01a63767eb..1784adeaa3 100644 --- a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceAdapter.java +++ b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceAdapter.java @@ -50,8 +50,8 @@ import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.location.suppliers.JustProvider; import org.jclouds.logging.Logger; @@ -126,8 +126,8 @@ public class CloudSigmaComputeServiceAdapter implements logger.debug("<< created server(%s)", from.getUuid()); logger.debug(">> starting server(%s)", from.getUuid()); client.startServer(from.getUuid()); - return new NodeAndInitialCredentials(from, from.getUuid(), - new Credentials("root", defaultVncPassword)); + return new NodeAndInitialCredentials(from, from.getUuid(), LoginCredentials.builder() + .password(defaultVncPassword).authenticateSudo(true).build()); } @Override diff --git a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java index ec6e66706b..c64561896e 100644 --- a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java +++ b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/PreinstalledDiskToImage.java @@ -27,8 +27,8 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem.Builder; import org.jclouds.compute.domain.OsFamilyVersion64Bit; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import com.google.common.base.Function; import com.google.common.base.Supplier; @@ -59,9 +59,10 @@ public class PreinstalledDiskToImage implements Function { builder.name(drive.getName()).description(description) .is64Bit(drive.getBits() != null ? drive.getBits() == 64 : parsed.is64Bit).version(parsed.version) .family(parsed.family); - return new ImageBuilder().ids(drive.getUuid()).adminPassword("cloudsigma") + return new ImageBuilder().ids(drive.getUuid()) .userMetadata(ImmutableMap. of("size", drive.getSize() / 1024 / 1024 / 1024 + "")) - .defaultCredentials(new Credentials("cloudsigma", null)).location(locationSupplier.get()) - .name(drive.getName()).description(description).operatingSystem(builder.build()).version("").build(); + .defaultCredentials(new LoginCredentials("cloudsigma", "cloudsigma", null, true)) + .location(locationSupplier.get()).name(drive.getName()).description(description) + .operatingSystem(builder.build()).version("").build(); } } \ No newline at end of file diff --git a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java index 3b50862a0e..4e7ca2bbcb 100644 --- a/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java +++ b/apis/cloudsigma/src/main/java/org/jclouds/cloudsigma/compute/functions/ServerInfoToNodeMetadata.java @@ -44,7 +44,6 @@ import org.jclouds.compute.domain.NodeState; 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.logging.Logger; @@ -73,15 +72,12 @@ public class ServerInfoToNodeMetadata implements Function getImageIdFromServer; private final Function findImageForId; - private final Map credentialStore; private final Supplier locationSupplier; private final Function deviceToVolume; @Inject - ServerInfoToNodeMetadata(Map credentialStore, Function getImageIdFromServer, - Function findImageForId, Function deviceToVolume, - Supplier locationSupplier) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + ServerInfoToNodeMetadata(Function getImageIdFromServer, Function findImageForId, + Function deviceToVolume, Supplier locationSupplier) { this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier"); this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume"); this.findImageForId = checkNotNull(findImageForId, "findImageForId"); @@ -102,7 +98,6 @@ public class ServerInfoToNodeMetadata implements Function of(from.getVnc().getIp())); builder.privateAddresses(ImmutableSet. of()); - builder.credentials(credentialStore.get("node#"+ from.getUuid())); return builder.build(); } @@ -144,8 +138,8 @@ public class ServerInfoToNodeMetadata implements Function - + + @@ -119,7 +120,8 @@ ${test.cloudstack.identity} ${test.cloudstack.credential} ${test.cloudstack.image-id} - ${test.cloudstack.login-user} + ${test.cloudstack.image.login-user} + ${test.cloudstack.image.authenticate-sudo} ${test.cloudstack.domainAdminIdentity} ${test.cloudstack.domainAdminCredential} diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java index 967e245e9f..e1732f15a4 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java @@ -36,7 +36,6 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.util.InetAddresses2; @@ -68,19 +67,16 @@ public class VirtualMachineToNodeMetadata implements Function credentialStore; private final FindLocationForVirtualMachine findLocationForVirtualMachine; private final FindHardwareForVirtualMachine findHardwareForVirtualMachine; private final FindImageForVirtualMachine findImageForVirtualMachine; private final Cache getIPForwardingRuleByVirtualMachine; @Inject - VirtualMachineToNodeMetadata(Map credentialStore, - FindLocationForVirtualMachine findLocationForVirtualMachine, + VirtualMachineToNodeMetadata(FindLocationForVirtualMachine findLocationForVirtualMachine, FindHardwareForVirtualMachine findHardwareForVirtualMachine, FindImageForVirtualMachine findImageForVirtualMachine, Cache getIPForwardingRuleByVirtualMachine) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.findLocationForVirtualMachine = checkNotNull(findLocationForVirtualMachine, "findLocationForVirtualMachine"); this.findHardwareForVirtualMachine = checkNotNull(findHardwareForVirtualMachine, "findHardwareForVirtualMachine"); this.findImageForVirtualMachine = checkNotNull(findImageForVirtualMachine, "findImageForVirtualMachine"); @@ -127,7 +123,6 @@ public class VirtualMachineToNodeMetadata implements Function credentialStore = ImmutableMap. of(); - Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet . of(ZoneToLocationTest.one, ZoneToLocationTest.two)); @@ -70,17 +62,17 @@ public class VirtualMachineToNodeMetadataTest { Supplier> imageSupplier = Suppliers.> ofInstance(ImmutableSet . of(TemplateToImageTest.one, TemplateToImageTest.two)); - VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore, - new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), - new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder(). build( - new CacheLoader() { + VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(new FindLocationForVirtualMachine( + locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), new FindImageForVirtualMachine( + imageSupplier), CacheBuilder.newBuilder(). build( + new CacheLoader() { - @Override - public IPForwardingRule load(Long arg0) throws Exception { - return IPForwardingRule.builder().id(1234l).IPAddress("1.1.1.1").build(); - } + @Override + public IPForwardingRule load(Long arg0) throws Exception { + return IPForwardingRule.builder().id(1234l).IPAddress("1.1.1.1").build(); + } - })); + })); // notice if we've already parsed this properly here, we can rely on it. VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0); @@ -89,24 +81,17 @@ public class VirtualMachineToNodeMetadataTest { assertEquals( node.toString(), - new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3").location(ZoneToLocationTest.one) - .state(NodeState.PENDING).privateAddresses(ImmutableSet.of("10.1.1.18")) - .publicAddresses(ImmutableSet.of("1.1.1.1")).hardware(ServiceOfferingToHardwareTest.one) - .imageId(TemplateToImageTest.one.getId()) + new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3") + .location(ZoneToLocationTest.one).state(NodeState.PENDING) + .privateAddresses(ImmutableSet.of("10.1.1.18")).publicAddresses(ImmutableSet.of("1.1.1.1")) + .hardware(ServiceOfferingToHardwareTest.one).imageId(TemplateToImageTest.one.getId()) .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), null); } @Test public void testApplyWhereVirtualMachineWithNoPassword() throws UnknownHostException { - // note we are testing when no credentials are here. otherwise would be - // ("node#416696", new - // Credentials("root", "password")) - Map credentialStore = ImmutableMap. of(); - Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet . of(ZoneToLocationTest.one, ZoneToLocationTest.two)); @@ -115,17 +100,17 @@ public class VirtualMachineToNodeMetadataTest { Supplier> imageSupplier = Suppliers.> ofInstance(ImmutableSet . of(TemplateToImageTest.one, TemplateToImageTest.two)); - VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore, - new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), - new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder(). build( - new CacheLoader() { + VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(new FindLocationForVirtualMachine( + locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), new FindImageForVirtualMachine( + imageSupplier), CacheBuilder.newBuilder(). build( + new CacheLoader() { - @Override - public IPForwardingRule load(Long arg0) throws Exception { - throw new ResourceNotFoundException("no ip forwarding rule for: " + arg0); - } + @Override + public IPForwardingRule load(Long arg0) throws Exception { + throw new ResourceNotFoundException("no ip forwarding rule for: " + arg0); + } - })); + })); // notice if we've already parsed this properly here, we can rely on it. VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0); @@ -134,55 +119,11 @@ public class VirtualMachineToNodeMetadataTest { assertEquals( node.toString(), - new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3").location(ZoneToLocationTest.one) - .state(NodeState.PENDING).privateAddresses(ImmutableSet.of("10.1.1.18")) - .hardware(ServiceOfferingToHardwareTest.one).imageId(TemplateToImageTest.one.getId()) + new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3") + .location(ZoneToLocationTest.one).state(NodeState.PENDING) + .privateAddresses(ImmutableSet.of("10.1.1.18")).hardware(ServiceOfferingToHardwareTest.one) + .imageId(TemplateToImageTest.one.getId()) .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); - - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), null); } - @Test - public void testApplyWhereVirtualMachineWithPassword() throws UnknownHostException { - - Map credentialStore = ImmutableMap. of("node#54", new Credentials( - "root", "password")); - - Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of(ZoneToLocationTest.one, ZoneToLocationTest.two)); - - Supplier> hardwareSupplier = Suppliers.> ofInstance(ImmutableSet - . of(ServiceOfferingToHardwareTest.one, ServiceOfferingToHardwareTest.two)); - - Supplier> imageSupplier = Suppliers.> ofInstance(ImmutableSet - . of(TemplateToImageTest.one, TemplateToImageTest.two)); - - VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore, - new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), - new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder(). build( - new CacheLoader() { - - @Override - public IPForwardingRule load(Long arg0) throws Exception { - throw new ResourceNotFoundException("no ip forwarding rule for: " + arg0); - } - - })); - - // notice if we've already parsed this properly here, we can rely on it. - VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0); - - NodeMetadata node = parser.apply(guest); - - assertEquals( - node.toString(), - new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3").location(ZoneToLocationTest.one) - .state(NodeState.PENDING).privateAddresses(ImmutableSet.of("10.1.1.18")) - .hardware(ServiceOfferingToHardwareTest.one).imageId(TemplateToImageTest.one.getId()) - .credentials(new Credentials("root", "password")) - .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); - - assertEquals(node.getCredentials(), new Credentials("root", "password")); - } } diff --git a/apis/deltacloud/pom.xml b/apis/deltacloud/pom.xml index 970db810d9..22f18bb3c1 100644 --- a/apis/deltacloud/pom.xml +++ b/apis/deltacloud/pom.xml @@ -53,7 +53,8 @@ mockuser mockpassword - + + @@ -110,7 +111,8 @@ ${test.deltacloud.identity} ${test.deltacloud.credential} ${test.deltacloud.image-id} - ${test.deltacloud.login-user} + ${test.deltacloud.image.login-user} + ${test.deltacloud.image.authenticate-sudo} diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java index 1e15f9a200..b50c3c9079 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/functions/InstanceToNodeMetadata.java @@ -39,7 +39,6 @@ import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.deltacloud.domain.Instance; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; @@ -56,16 +55,15 @@ import com.google.common.collect.Iterables; public class InstanceToNodeMetadata implements Function { public static final Map instanceToNodeState = ImmutableMap - . builder().put(Instance.State.STOPPED, NodeState.SUSPENDED).put( - Instance.State.RUNNING, NodeState.RUNNING).put(Instance.State.PENDING, NodeState.PENDING).put( - Instance.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, - NodeState.PENDING).put(Instance.State.START, NodeState.PENDING).build(); + . builder().put(Instance.State.STOPPED, NodeState.SUSPENDED) + .put(Instance.State.RUNNING, NodeState.RUNNING).put(Instance.State.PENDING, NodeState.PENDING) + .put(Instance.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, NodeState.PENDING) + .put(Instance.State.START, NodeState.PENDING).build(); @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - protected final Map credentialStore; protected final Supplier> locations; protected final Supplier> images; protected final Supplier> hardwares; @@ -137,10 +135,8 @@ public class InstanceToNodeMetadata implements Function } @Inject - InstanceToNodeMetadata(Map credentialStore, - @Memoized Supplier> locations, @Memoized Supplier> images, - @Memoized Supplier> hardwares) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + InstanceToNodeMetadata(@Memoized Supplier> locations, + @Memoized Supplier> images, @Memoized Supplier> hardwares) { this.images = checkNotNull(images, "images"); this.locations = checkNotNull(locations, "locations"); this.hardwares = checkNotNull(hardwares, "hardwares"); @@ -159,7 +155,6 @@ public class InstanceToNodeMetadata implements Function builder.state(instanceToNodeState.get(from.getState())); builder.publicAddresses(from.getPublicAddresses()); builder.privateAddresses(from.getPrivateAddresses()); - builder.credentials(credentialStore.get(from.getHref().toASCIIString())); return builder.build(); } } diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/strategy/DeltacloudComputeServiceAdapter.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/strategy/DeltacloudComputeServiceAdapter.java index 809c59520e..0e304deaf6 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/strategy/DeltacloudComputeServiceAdapter.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/compute/strategy/DeltacloudComputeServiceAdapter.java @@ -43,7 +43,7 @@ import org.jclouds.deltacloud.domain.TransitionOnAction; import org.jclouds.deltacloud.options.CreateInstanceOptions; import org.jclouds.deltacloud.predicates.InstanceFinished; import org.jclouds.deltacloud.predicates.InstanceRunning; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.http.HttpRequest; import org.jclouds.logging.Logger; import org.jclouds.predicates.RetryablePredicate; @@ -86,7 +86,7 @@ public class DeltacloudComputeServiceAdapter implements Template template) { Instance instance = client.createInstance(template.getImage().getProviderId(), CreateInstanceOptions.Builder .named(name).hardwareProfile(template.getHardware().getId()).realm(template.getLocation().getId())); - Credentials creds = null; + LoginCredentials creds = null; if (instance.getAuthentication() != null && instance.getAuthentication() instanceof PasswordAuthentication) { creds = PasswordAuthentication.class.cast(instance.getAuthentication()).getLoginCredentials(); } diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/domain/PasswordAuthentication.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/domain/PasswordAuthentication.java index b682c7067c..bd466c59b6 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/domain/PasswordAuthentication.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/domain/PasswordAuthentication.java @@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; /** * @@ -32,13 +32,13 @@ public class PasswordAuthentication implements Instance.Authentication, Serializ /** The serialVersionUID */ private static final long serialVersionUID = 7669076186483470376L; - private final Credentials login; + private final LoginCredentials login; - public PasswordAuthentication(Credentials login) { + public PasswordAuthentication(LoginCredentials login) { this.login = checkNotNull(login, "login"); } - public Credentials getLoginCredentials() { + public LoginCredentials getLoginCredentials() { return login; } diff --git a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/xml/InstanceHandler.java b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/xml/InstanceHandler.java index 50b7e62dce..98ecc44514 100644 --- a/apis/deltacloud/src/main/java/org/jclouds/deltacloud/xml/InstanceHandler.java +++ b/apis/deltacloud/src/main/java/org/jclouds/deltacloud/xml/InstanceHandler.java @@ -27,10 +27,11 @@ import java.util.Set; import javax.annotation.Resource; import org.jclouds.deltacloud.domain.Instance; +import org.jclouds.deltacloud.domain.Instance.Authentication; import org.jclouds.deltacloud.domain.KeyAuthentication; import org.jclouds.deltacloud.domain.PasswordAuthentication; -import org.jclouds.deltacloud.domain.Instance.Authentication; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; import org.jclouds.logging.Logger; @@ -67,7 +68,7 @@ public class InstanceHandler extends ParseSax.HandlerWithResult { private Instance instance; - private Credentials.Builder credentialsBuilder = new Credentials.Builder(); + private Builder credentialsBuilder = LoginCredentials.builder(); private String keyName; private Authentication authentication; @@ -125,19 +126,19 @@ public class InstanceHandler extends ParseSax.HandlerWithResult { } else if (qName.equalsIgnoreCase("keyname")) { this.keyName = currentOrNull(currentText); } else if (qName.equalsIgnoreCase("username")) { - this.credentialsBuilder.identity(currentOrNull(currentText)); + this.credentialsBuilder.user(currentOrNull(currentText)); } else if (qName.equalsIgnoreCase("password")) { - this.credentialsBuilder.credential(currentOrNull(currentText)); + this.credentialsBuilder.password(currentOrNull(currentText)); } else if (qName.equalsIgnoreCase("authentication")) { if (keyName != null) { this.authentication = new KeyAuthentication(keyName); } else { - Credentials creds = credentialsBuilder.build(); - if (creds.identity != null) + LoginCredentials creds = credentialsBuilder.build(); + if (creds != null && creds.identity != null) this.authentication = new PasswordAuthentication(creds); } this.keyName = null; - this.credentialsBuilder = new Credentials.Builder(); + this.credentialsBuilder = LoginCredentials.builder(); } else if (qName.equalsIgnoreCase("state")) { this.state = Instance.State.fromValue(currentOrNull(currentText)); } else if (qName.equalsIgnoreCase("address")) { diff --git a/apis/deltacloud/src/test/java/org/jclouds/deltacloud/xml/InstanceHandlerTest.java b/apis/deltacloud/src/test/java/org/jclouds/deltacloud/xml/InstanceHandlerTest.java index c0ee78c181..3c335e0b9c 100644 --- a/apis/deltacloud/src/test/java/org/jclouds/deltacloud/xml/InstanceHandlerTest.java +++ b/apis/deltacloud/src/test/java/org/jclouds/deltacloud/xml/InstanceHandlerTest.java @@ -24,10 +24,10 @@ import java.io.InputStream; import java.net.URI; import org.jclouds.deltacloud.domain.Instance; +import org.jclouds.deltacloud.domain.Instance.Authentication; import org.jclouds.deltacloud.domain.KeyAuthentication; import org.jclouds.deltacloud.domain.PasswordAuthentication; -import org.jclouds.deltacloud.domain.Instance.Authentication; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.config.SaxParserModule; @@ -49,7 +49,7 @@ public class InstanceHandlerTest { static ParseSax createParser() { Injector injector = Guice.createInjector(new SaxParserModule()); ParseSax parser = injector.getInstance(ParseSax.Factory.class).create( - injector.getInstance(InstanceHandler.class)); + injector.getInstance(InstanceHandler.class)); return parser; } @@ -68,7 +68,8 @@ public class InstanceHandlerTest { } public void testWithPasswordAuthentication() { - Instance expects = instanceWithAuthentication(new PasswordAuthentication(new Credentials("root", "FOO"))); + Instance expects = instanceWithAuthentication(new PasswordAuthentication(LoginCredentials.builder().user("root") + .password("FOO").build())); assertEquals(parseInstance("/test_get_instance_pw.xml").toString(), expects.toString()); } @@ -84,15 +85,15 @@ public class InstanceHandlerTest { private Instance instanceWithAuthentication(Authentication authentication) { return new Instance(URI.create("http://fancycloudprovider.com/api/instances/inst1"), "inst1", "larry", - "Production JBoss Instance", URI.create("http://fancycloudprovider.com/api/images/img3"), URI - .create("http://fancycloudprovider.com/api/hardware_profiles/m1-small"), URI - .create("http://fancycloudprovider.com/api/realms/us"), Instance.State.RUNNING, ImmutableMap - .of(Instance.Action.REBOOT, new HttpRequest("POST", URI - .create("http://fancycloudprovider.com/api/instances/inst1/reboot")), - Instance.Action.STOP, new HttpRequest("POST", URI - .create("http://fancycloudprovider.com/api/instances/inst1/stop"))), - authentication, ImmutableSet.of("inst1.larry.fancycloudprovider.com"), ImmutableSet - .of("inst1.larry.internal")); + "Production JBoss Instance", URI.create("http://fancycloudprovider.com/api/images/img3"), + URI.create("http://fancycloudprovider.com/api/hardware_profiles/m1-small"), + URI.create("http://fancycloudprovider.com/api/realms/us"), Instance.State.RUNNING, ImmutableMap.of( + Instance.Action.REBOOT, + new HttpRequest("POST", URI.create("http://fancycloudprovider.com/api/instances/inst1/reboot")), + Instance.Action.STOP, + new HttpRequest("POST", URI.create("http://fancycloudprovider.com/api/instances/inst1/stop"))), + authentication, ImmutableSet.of("inst1.larry.fancycloudprovider.com"), + ImmutableSet.of("inst1.larry.internal")); } } diff --git a/apis/ec2/pom.xml b/apis/ec2/pom.xml index f5c8400ebb..308adc5edc 100644 --- a/apis/ec2/pom.xml +++ b/apis/ec2/pom.xml @@ -39,7 +39,8 @@ ${test.aws.identity} ${test.aws.credential} - + + @@ -105,7 +106,8 @@ ${test.ec2.identity} ${test.ec2.credential} ${test.ec2.image-id} - ${test.ec2.login-user} + ${test.ec2.image.login-user} + ${test.ec2.image.authenticate-sudo} diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java index 52653dd97c..1cdaf72b5e 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java @@ -102,7 +102,7 @@ public class EC2ImageParser implements Function() { diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java index bc4ccdf855..abdc0e45d7 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java @@ -41,6 +41,7 @@ import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.domain.BlockDevice; import org.jclouds.ec2.domain.InstanceState; @@ -125,7 +126,7 @@ public class RunningInstanceToNodeMetadata implements Function> images = Suppliers.> ofInstance(ImmutableSet. of( new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "hvm", "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new Credentials("root", null)) + .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", null, null, false)) .build(), new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/cc-image") .location(location).operatingSystem( new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "paravirtual", "ubuntu", true)) - .description("description").version("1.0").defaultCredentials(new Credentials("root", null)) + .description("description").version("1.0").defaultCredentials(new LoginCredentials("root", null, null, false)) .build())); Supplier> sizes = Suppliers.> ofInstance(ImmutableSet . of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(), diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java index c52429a8db..0972b9dff3 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java @@ -28,10 +28,10 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.compute.strategy.ReviseParsedImage; import org.jclouds.ec2.domain.Image; @@ -61,14 +61,14 @@ public class EC2ImageParserTest { assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").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( + .defaultCredentials(new LoginCredentials("ec2-user", null, null, false)).id("us-east-1/ami-82e4b5c7").providerId( "ami-82e4b5c7").location(defaultLocation).userMetadata( ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); assertEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").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( + .description("Amazon Linux AMI x86_64 S3").defaultCredentials(new LoginCredentials("ec2-user", null, null, false)).id( "us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").location(defaultLocation).userMetadata( ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index 50a1eec4da..f2cff94228 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -36,6 +36,7 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.domain.InstanceState; @@ -75,7 +76,7 @@ public class RunningInstanceToNodeMetadataTest { @Test public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound() throws UnknownHostException { - Credentials creds = new Credentials("root", "abdce"); + LoginCredentials creds = LoginCredentials.builder().user("root").password("abdce").build(); RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet. of(), ImmutableSet . of(), ImmutableSet. of(), ImmutableMap. of( diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java index 6ee15cc0b4..8a56084c02 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java @@ -35,7 +35,7 @@ import org.jclouds.aws.domain.Region; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.domain.EC2HardwareBuilder; import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.compute.domain.RegionNameAndIngressRules; @@ -58,33 +58,36 @@ import com.google.common.collect.ImmutableSet; @Test(groups = "unit", singleThreaded = true, testName = "CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest") public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { - public static final Credentials CREDENTIALS = new Credentials(null, "-----BEGIN RSA PRIVATE KEY-----\n" - + "MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\n" - + "W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\n" - + "EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\n" - + "gqTsuInhuBRMx+wxff8Z43ECdJV6UPoXK3der1dlZunxGCFkCeYq0kCX7FZ7PV35X744jqhD8P+7\n" - + "y5prO4W+M3DWgChUx0OlbDbSHtDVlcfdbj/+4AKYKU6rQOqh+4DPDQIDAQABAoIBAHjQuEiXKJSV\n" - + "1U2RZcVtENInws9AL/2I/Jfa5Qh6vTqXG9EjklywfzkK72x7tDVvD3ngmAoAs5WwLFDL+fXvYhOk\n" - + "sbql8ZCahVdYRWME7XsSu2IZYHDZipXe1XzLS7b9X8uos5Ns4E8bZuNKtI1RJDdD1vPMqRNR2z0T\n" - + "0Dn3eC7t+t+t7PWaK5AXu2ot7DoOeG1QhqJbwd5pMkIn2ydBILytgmDk/2P3EtJGePIJIeQBicmw\n" - + "Z0KrJFa/K2cC8AtmMJUoZMo+mh1yemDbDLCZW30PjFHbZtcszS2cydAgq/HDFkZynvZG0zhbx/To\n" - + "jzcNza1AyypYwOwb2/9/ulXZp0UCgYEA+QFgWDfYLH2zwjU5b6e0UbIyd/X/yRZ+L8lOEBd0Bbu8\n" - + "qO3txaDbwi7o2mG7pJENHJ3u62CHjgTGDNW9V9Q8eNoGtj3uHvMvi7FdDEK8B6izdZyR7hmZmQ/5\n" - + "MIldelyiGZlz1KBSoy4FsCpA7hV7cI6H6x+Im24NxG90/wd/EgMCgYEA1f+cUyUisIO3yKOCf0hQ\n" - + "aL289q2//F2cbvBxtki6I8JzTg1H3oTO2WVrXQeCA3a/yiuRUatgGH4mxrpCF6byVJyqrEWAj4kU\n" - + "uTbhMgIYhLGoaF1e+vMirCRXUXox0i5X976ASzHn64V9JSd1B+UbKfpcFTYYnChmrRDzmhKN1a8C\n" - + "gYBTvIHAyO7ab18/BRUOllAOVSWhr8lXv0eqHEEzKh/rOaoFCRY3qpOcZpgJsGogumK1Z+sLnoeX\n" - + "W8WaVVp6KbY4UeGF8aedItyvVnLbB6ohzTqkZ4Wvk05S6cs75kXYO0SL5U3NiCiiFXz2NA9nwTOk\n" - + "s1nD2PPgiQ76Kx0mEkhKLwKBgFhHEJqv+AZu37Kx2NRe5WS/2KK9/DPD/hM5tv7mM3sq7Nvm2J3v\n" - + "lVDS6J5AyZ5aLzXcER9qncKcz6wtC7SsFs1Wr4VPSoBroRPikrVJbgnXK8yZr+O/xq7Scv7WdJTq\n" - + "rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\n" - + "3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\n" - + "DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\n" - + "-----END RSA PRIVATE KEY-----"); + public static final LoginCredentials CREDENTIALS = LoginCredentials + .builder() + .privateKey( + "-----BEGIN RSA PRIVATE KEY-----\n" + + "MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\n" + + "W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\n" + + "EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\n" + + "gqTsuInhuBRMx+wxff8Z43ECdJV6UPoXK3der1dlZunxGCFkCeYq0kCX7FZ7PV35X744jqhD8P+7\n" + + "y5prO4W+M3DWgChUx0OlbDbSHtDVlcfdbj/+4AKYKU6rQOqh+4DPDQIDAQABAoIBAHjQuEiXKJSV\n" + + "1U2RZcVtENInws9AL/2I/Jfa5Qh6vTqXG9EjklywfzkK72x7tDVvD3ngmAoAs5WwLFDL+fXvYhOk\n" + + "sbql8ZCahVdYRWME7XsSu2IZYHDZipXe1XzLS7b9X8uos5Ns4E8bZuNKtI1RJDdD1vPMqRNR2z0T\n" + + "0Dn3eC7t+t+t7PWaK5AXu2ot7DoOeG1QhqJbwd5pMkIn2ydBILytgmDk/2P3EtJGePIJIeQBicmw\n" + + "Z0KrJFa/K2cC8AtmMJUoZMo+mh1yemDbDLCZW30PjFHbZtcszS2cydAgq/HDFkZynvZG0zhbx/To\n" + + "jzcNza1AyypYwOwb2/9/ulXZp0UCgYEA+QFgWDfYLH2zwjU5b6e0UbIyd/X/yRZ+L8lOEBd0Bbu8\n" + + "qO3txaDbwi7o2mG7pJENHJ3u62CHjgTGDNW9V9Q8eNoGtj3uHvMvi7FdDEK8B6izdZyR7hmZmQ/5\n" + + "MIldelyiGZlz1KBSoy4FsCpA7hV7cI6H6x+Im24NxG90/wd/EgMCgYEA1f+cUyUisIO3yKOCf0hQ\n" + + "aL289q2//F2cbvBxtki6I8JzTg1H3oTO2WVrXQeCA3a/yiuRUatgGH4mxrpCF6byVJyqrEWAj4kU\n" + + "uTbhMgIYhLGoaF1e+vMirCRXUXox0i5X976ASzHn64V9JSd1B+UbKfpcFTYYnChmrRDzmhKN1a8C\n" + + "gYBTvIHAyO7ab18/BRUOllAOVSWhr8lXv0eqHEEzKh/rOaoFCRY3qpOcZpgJsGogumK1Z+sLnoeX\n" + + "W8WaVVp6KbY4UeGF8aedItyvVnLbB6ohzTqkZ4Wvk05S6cs75kXYO0SL5U3NiCiiFXz2NA9nwTOk\n" + + "s1nD2PPgiQ76Kx0mEkhKLwKBgFhHEJqv+AZu37Kx2NRe5WS/2KK9/DPD/hM5tv7mM3sq7Nvm2J3v\n" + + "lVDS6J5AyZ5aLzXcER9qncKcz6wtC7SsFs1Wr4VPSoBroRPikrVJbgnXK8yZr+O/xq7Scv7WdJTq\n" + + "rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\n" + + "3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\n" + + "DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\n" + + "-----END RSA PRIVATE KEY-----").build(); public static final KeyPair KEYPAIR = KeyPair.builder().region(Region.AP_SOUTHEAST_1).keyName("myKeyPair") - .sha1OfPrivateKey("13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32").fingerprint( - "60:15:d1:f1:d9:e2:3c:e2:ee:a9:64:6a:42:a7:34:0c").keyMaterial(CREDENTIALS.credential).build(); + .sha1OfPrivateKey("13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32") + .fingerprint("60:15:d1:f1:d9:e2:3c:e2:ee:a9:64:6a:42:a7:34:0c").keyMaterial(CREDENTIALS.credential).build(); private static final Provider OPTIONS_PROVIDER = new javax.inject.Provider() { @@ -106,15 +109,15 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // create mocks CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); Template template = createMock(Template.class); @@ -125,7 +128,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getUserData()).andReturn(null); @@ -137,9 +140,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", generatedGroup, "KeyName", systemGeneratedKeyPairName) - .entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", + generatedGroup, "KeyName", systemGeneratedKeyPairName).entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -161,15 +165,15 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // create mocks CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); Template template = createMock(Template.class); @@ -180,7 +184,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getUserData()).andReturn("hello".getBytes()); @@ -192,9 +196,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", "group", "KeyName", systemGeneratedKeyPairName, "UserData", - Base64.encodeBytes("hello".getBytes())).entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", "group", + "KeyName", systemGeneratedKeyPairName, "UserData", Base64.encodeBytes("hello".getBytes())).entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -218,7 +223,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(null); // replay mocks @@ -249,7 +254,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginUser()).andReturn(null); + expect(options.getLoginPassword()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); + expect(options.shouldAuthenticateSudo()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); @@ -281,7 +289,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true); @@ -313,7 +321,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); - expect(options.getOverridingCredentials()).andReturn(CREDENTIALS).atLeastOnce(); + expect(options.getLoginPrivateKey()).andReturn(CREDENTIALS.getPrivateKey()).atLeastOnce(); // Notice that the fingerprint and sha1 generated expect(strategy.credentialsMap.put(new RegionAndName(region, userSuppliedKeyPair), KEYPAIR)).andReturn(null); @@ -335,7 +343,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { } public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_createsNewKeyPairAndReturnsItsNameByDefault() - throws ExecutionException { + throws ExecutionException { // setup constants String region = Region.AP_SOUTHEAST_1; String group = "group"; @@ -363,7 +371,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // run assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); // verify mocks verify(options); @@ -404,7 +412,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { } public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesntExist() - throws ExecutionException { + throws ExecutionException { // setup constants String region = Region.AP_SOUTHEAST_1; String group = "group"; @@ -422,7 +430,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { expect(options.getGroups()).andReturn(groupIds).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(group); // replay mocks @@ -438,7 +446,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { } public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenPortsAreSpecifiedWhenDoesntExist() - throws ExecutionException { + throws ExecutionException { // setup constants String region = Region.AP_SOUTHEAST_1; String group = "group"; @@ -456,7 +464,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { expect(options.getGroups()).andReturn(groupIds).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup); // replay mocks @@ -472,7 +480,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { } public void testGetSecurityGroupsForTagAndOptions_reusesGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExist() - throws ExecutionException { + throws ExecutionException { // setup constants String region = Region.AP_SOUTHEAST_1; String group = "group"; @@ -490,7 +498,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { expect(options.getGroups()).andReturn(groupIds).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup); // replay mocks @@ -523,10 +531,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { // setup expectations expect(options.getGroups()).andReturn(groupIds).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)) - .andReturn(groupExisted ? "group" : null); + .andReturn(groupExisted ? "group" : null); // replay mocks replay(options); @@ -552,7 +560,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { ConcurrentMap credentialsMap = createMock(ConcurrentMap.class); Cache securityGroupMap = createMock(Cache.class); return new CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions(makeKeyPair, credentialsMap, - securityGroupMap, OPTIONS_PROVIDER); + securityGroupMap, OPTIONS_PROVIDER); } private void replayStrategy(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy) { diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/services/KeyPairClientLiveTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/services/KeyPairClientLiveTest.java index c18a0cfc99..3107404eb6 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/services/KeyPairClientLiveTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/services/KeyPairClientLiveTest.java @@ -121,7 +121,7 @@ public class KeyPairClientLiveTest { KeyPair result = client.createKeyPairInRegion(null, keyName); assertNotNull(result); assertNotNull(result.getKeyMaterial()); - assertNotNull(result.getKeyFingerprint()); + assertNotNull(result.getSha1OfPrivateKey()); assertEquals(result.getKeyName(), keyName); Set twoResults = Sets.newLinkedHashSet(client.describeKeyPairsInRegion(null, keyName)); @@ -129,7 +129,7 @@ public class KeyPairClientLiveTest { assertEquals(twoResults.size(), 1); KeyPair listPair = twoResults.iterator().next(); assertEquals(listPair.getKeyName(), result.getKeyName()); - assertEquals(listPair.getKeyFingerprint(), result.getKeyFingerprint()); + assertEquals(listPair.getSha1OfPrivateKey(), result.getSha1OfPrivateKey()); } @AfterTest diff --git a/apis/elasticstack/pom.xml b/apis/elasticstack/pom.xml index 09fc0e56b5..03ac365535 100644 --- a/apis/elasticstack/pom.xml +++ b/apis/elasticstack/pom.xml @@ -53,7 +53,8 @@ FIXME FIXME - + + @@ -110,7 +111,8 @@ ${test.elasticstack.identity} ${test.elasticstack.credential} ${test.elasticstack.image-id} - ${test.elasticstack.login-user} + ${test.elasticstack.image.login-user} + ${test.elasticstack.image.authenticate-sudo} diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java index 0f0402d060..0bcccf6065 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java @@ -44,8 +44,8 @@ import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.elasticstack.ElasticStackClient; import org.jclouds.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.Drive; @@ -126,7 +126,8 @@ public class ElasticStackComputeServiceAdapter implements ServerInfo from = client.createServer(toCreate); client.startServer(from.getUuid()); from = client.getServerInfo(from.getUuid()); - return new NodeAndInitialCredentials(from, from.getUuid(), new Credentials(null, defaultVncPassword)); + return new NodeAndInitialCredentials(from, from.getUuid(), LoginCredentials.builder() + .password(defaultVncPassword).build()); } @Override diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java index 7576e9f6f5..d868ff90ed 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java @@ -39,7 +39,6 @@ import org.jclouds.compute.domain.NodeState; 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.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.DriveInfo; @@ -73,15 +72,12 @@ public class ServerInfoToNodeMetadata implements Function getImageIdFromServer; private final Function findImageForId; - private final Map credentialStore; private final Supplier locationSupplier; private final Function deviceToVolume; @Inject - ServerInfoToNodeMetadata(Map credentialStore, Function getImageIdFromServer, - Function findImageForId, Function deviceToVolume, - Supplier locationSupplier) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + ServerInfoToNodeMetadata(Function getImageIdFromServer, Function findImageForId, + Function deviceToVolume, Supplier locationSupplier) { this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier"); this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume"); this.findImageForId = checkNotNull(findImageForId, "findImageForId"); @@ -110,7 +106,6 @@ public class ServerInfoToNodeMetadata implements Function of(from.getNics().get(0).getDhcp())); builder.privateAddresses(ImmutableSet. of()); - builder.credentials(credentialStore.get("node#" + from.getUuid())); return builder.build(); } diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java index a1b82384dc..acbcc3a1c5 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java @@ -26,8 +26,8 @@ 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 org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.elasticstack.domain.WellKnownImage; @@ -52,13 +52,18 @@ public class WellKnownImageToImage implements Function { @Override public Image apply(DriveInfo drive) { WellKnownImage input = preinstalledImages.get(drive.getUuid()); - return new ImageBuilder().ids(drive.getUuid()).userMetadata( - ImmutableMap. builder().putAll(drive.getUserMetadata()) - .put("size", input.getSize() + "").build()).defaultCredentials( - new Credentials(input.getLoginUser(), null)).location(locationSupplier.get()).name( - input.getDescription()).description(drive.getName()).operatingSystem( - new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion()).name( - input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build()).version( - "").build(); + return new ImageBuilder() + .ids(drive.getUuid()) + .userMetadata( + ImmutableMap. builder().putAll(drive.getUserMetadata()) + .put("size", input.getSize() + "").build()) + .defaultCredentials(LoginCredentials.builder().user(input.getLoginUser()).build()) + .location(locationSupplier.get()) + .name(input.getDescription()) + .description(drive.getName()) + .operatingSystem( + new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion()) + .name(input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build()) + .version("").build(); } } \ No newline at end of file diff --git a/apis/eucalyptus/pom.xml b/apis/eucalyptus/pom.xml index 09130d8d0e..78e6ff1317 100644 --- a/apis/eucalyptus/pom.xml +++ b/apis/eucalyptus/pom.xml @@ -39,7 +39,8 @@ FIXME_IDENTITY FIXME_CREDENTIAL - + + @@ -105,7 +106,8 @@ ${test.eucalyptus.identity} ${test.eucalyptus.credential} ${test.eucalyptus.image-id} - ${test.eucalyptus.login-user} + ${test.eucalyptus.image.login-user} + ${test.eucalyptus.image.authenticate-sudo} diff --git a/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java b/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java index 8056edf97b..6f7d9493ea 100644 --- a/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java +++ b/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java @@ -38,6 +38,7 @@ import java.util.Properties; import java.util.Set; import junit.framework.Assert; + import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.jclouds.blobstore.BlobRequestSigner; @@ -46,7 +47,6 @@ import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.blobstore.BlobStoreContextFactory; import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.blobstore.domain.Blob; -import org.jclouds.blobstore.domain.BlobBuilder; import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.MutableBlobMetadata; import org.jclouds.blobstore.domain.PageSet; @@ -66,6 +66,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.google.inject.CreationException; +import com.google.inject.Module; /** * Test class for {@link FilesystemAsyncBlobStore} class @@ -95,7 +96,7 @@ public class FilesystemAsyncBlobStoreTest { // create context for filesystem container Properties prop = new Properties(); prop.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR); - context = (BlobStoreContext) new BlobStoreContextFactory().createContext(PROVIDER, "identity", "credential", Collections.EMPTY_LIST, prop); + context = (BlobStoreContext) new BlobStoreContextFactory().createContext(PROVIDER, "identity", "credential", Collections.emptyList(), prop); // create a container in the default location blobStore = context.getBlobStore(); diff --git a/apis/nova/pom.xml b/apis/nova/pom.xml index 2cb21d56a2..ec08c44e20 100644 --- a/apis/nova/pom.xml +++ b/apis/nova/pom.xml @@ -39,7 +39,8 @@ FIXME_IDENTITY FIXME_CREDENTIALS - + + @@ -130,7 +131,8 @@ ${test.nova.identity} ${test.nova.credential} ${test.nova.image-id} - ${test.nova.login-user} + ${test.nova.image.login-user} + ${test.nova.image.authenticate-sudo} ${test.ssh.keyfile.public} ${test.ssh.keyfile.private} diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java index 21b1d9f7ff..de4f1feeff 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java @@ -20,10 +20,9 @@ package org.jclouds.openstack.nova; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import javax.ws.rs.PathParam; - import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Flavor; @@ -35,8 +34,6 @@ import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.rest.ResourceNotFoundException; -import java.util.concurrent.Future; - /** * Provides access to OpenStack Nova via their REST API. *

diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index 125584360a..ef811ad851 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -24,7 +24,6 @@ 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; @@ -48,7 +47,6 @@ public class NovaImageToImage implements Function { protected Logger logger = Logger.NULL; protected final Supplier location; - protected final Map credentialStore; protected final Map serverToNodeState; protected final Supplier> images; protected final Supplier> hardwares; @@ -87,11 +91,10 @@ public class ServerToNodeMetadata implements Function { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, + ServerToNodeMetadata(Map serverStateToNodeState, @Memoized Supplier> images, Supplier location, @Memoized 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"); @@ -115,7 +118,6 @@ public class ServerToNodeMetadata implements Function { builder.state(serverToNodeState.get(from.getStatus())); builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction())); builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction())); - builder.credentials(credentialStore.get("node#" + from.getId())); builder.uri(from.getURI()); return builder.build(); } diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java index 3697f2443f..cd9ea432a7 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java @@ -30,6 +30,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.openstack.nova.NovaClient; import org.jclouds.openstack.nova.domain.Server; @@ -56,7 +57,7 @@ public class NovaCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGro public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) { Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId(), withMetadata(template.getOptions().getUserMetadata())); - credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass())); + credentialStore.put("node#" + from.getId(), LoginCredentials.builder().password(from.getAdminPass()).build()); return serverToNodeMetadata.apply(from); } diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index 7ba8599fe6..5ce5dde3f2 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -18,24 +18,22 @@ */ package org.jclouds.openstack.nova.compute.functions; -import com.google.inject.Guice; +import static org.testng.Assert.assertEquals; + +import java.net.URI; + import org.jclouds.compute.config.BaseComputeServiceContextModule; 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.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.testng.annotations.Test; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; - -import static org.testng.Assert.assertEquals; +import com.google.inject.Guice; /** * @author Adrian Cole @@ -44,13 +42,13 @@ import static org.testng.Assert.assertEquals; public class NovaImageToImageTest { @Test - public void testApplyWhereImageNotFound() throws UnknownHostException, URISyntaxException { + public void testApplyWhereImageNotFound() { Image image = new ImageBuilder() .name("CentOS 5.2") .operatingSystem( - new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) - .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("2").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); + new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2") + .is64Bit(true).build()).description("CentOS 5.2").ids("2").version("1286712000000") + .uri(URI.create("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); Image parsedImage = convertImage(); assertEquals(parsedImage, image); @@ -59,9 +57,10 @@ public class NovaImageToImageTest { public static Image convertImage() { org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); - NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)))); + NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem( + new BaseComputeServiceContextModule() { + }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) + .getInstance(Json.class)))); return parser.apply(image); } diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index 758089458d..867e1cf75f 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -16,155 +16,138 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.openstack.nova.compute.functions; - -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 org.jclouds.compute.domain.*; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; -import org.testng.annotations.Test; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.util.Map; -import java.util.Set; - -import static org.testng.Assert.assertEquals; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServerToNodeMetadataTest { - Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); - - @Test - public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Credentials creds = new Credentials("root", "abdce"); - - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); - - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - .of("node#1234", creds), Suppliers.>ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.>ofInstance(hardwares)); - - NodeMetadata metadata = parser.apply(server); - - NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .credentials(creds).build(); - assertEquals(metadata, constructedMetadata); - } - - @Test - public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.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); - - NodeMetadata constructedMetadata = newNodeMetadataBuilder().build(); - - assertEquals(metadata, constructedMetadata); - - } - - private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException { - return new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) - .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) - .id("1234") - .providerId("1234") - .name("sample-server") - .location(new LocationBuilder() - .scope(LocationScope.HOST) - .id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0") - .parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) - .uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); - } - - @Test - public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.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); - - NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .imageId("2") - .operatingSystem(new OperatingSystem.Builder() - .family(OsFamily.CENTOS) - .description("CentOS 5.2") - .version("5.2") - .is64Bit(true).build()) - .build(); - - assertEquals(metadata, constructedMetadata); - - } - - @Test - public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(NovaImageToImageTest.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); - - NodeMetadata constructedMetadata = newNodeMetadataBuilder() +package org.jclouds.openstack.nova.compute.functions; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.net.URISyntaxException; +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.OperatingSystem; +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.Location; +import org.jclouds.domain.LocationBuilder; +import org.jclouds.domain.LocationScope; +import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.jclouds.openstack.nova.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; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ServerToNodeMetadataTest { + Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); + + @Test + public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, + ClassNotFoundException, URISyntaxException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), + Suppliers.> ofInstance(hardwares)); + + NodeMetadata metadata = parser.apply(server); + + NodeMetadata constructedMetadata = newNodeMetadataBuilder().build(); + + assertEquals(metadata, constructedMetadata); + + } + + private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException { + return new NodeMetadataBuilder() + .state(NodeState.PENDING) + .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) + .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) + .id("1234") + .providerId("1234") + .name("sample-server") + .location( + new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) + .uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); + } + + @Test + public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, + ClassNotFoundException, URISyntaxException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); + Set images = ImmutableSet.of(jcImage); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), + Suppliers.> ofInstance(hardwares)); + + NodeMetadata metadata = parser.apply(server); + + NodeMetadata constructedMetadata = newNodeMetadataBuilder() .imageId("2") - .operatingSystem(new OperatingSystem.Builder() - .family(OsFamily.CENTOS) - .description("CentOS 5.2") - .version("5.2") - .is64Bit(true).build()) - .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())) - .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) - .build()) - .build(); - - assertEquals(metadata, constructedMetadata); - } -} + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") + .is64Bit(true).build()).build(); + + assertEquals(metadata, constructedMetadata); + + } + + @Test + public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, + ClassNotFoundException, URISyntaxException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); + Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); + Server server = ParseServerFromJsonResponseTest.parseServer(); + + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, + Suppliers.> ofInstance(images), Suppliers.ofInstance(provider), + Suppliers.> ofInstance(hardwares)); + + NodeMetadata metadata = parser.apply(server); + + NodeMetadata constructedMetadata = newNodeMetadataBuilder() + .imageId("2") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") + .is64Bit(true).build()) + .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())) + .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")).build()).build(); + + assertEquals(metadata, constructedMetadata); + } +} diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonNoAddressesResponseTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonNoAddressesResponseTest.java index 38eb531ff9..2bd76298b6 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonNoAddressesResponseTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonNoAddressesResponseTest.java @@ -18,10 +18,13 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.text.ParseException; + import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -30,12 +33,10 @@ import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; import org.testng.annotations.Test; -import java.io.InputStream; -import java.net.UnknownHostException; -import java.text.ParseException; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; @Test(groups = "unit") public class ParseServerFromJsonNoAddressesResponseTest { diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseDiabloTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseDiabloTest.java index 63d349b271..9d7a4559ee 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseDiabloTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseDiabloTest.java @@ -18,13 +18,16 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.net.URI; +import java.text.SimpleDateFormat; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.SimpleTimeZone; + import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -35,17 +38,13 @@ import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; import org.testng.annotations.Test; -import java.io.InputStream; -import java.net.URI; -import java.net.UnknownHostException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.SimpleTimeZone; - -import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseServerFromJsonResponse} for the transitional nova api 1.1 in the Diablo release diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 3eee267b3a..2e0e7742be 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -18,22 +18,7 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.jclouds.openstack.nova.domain.Address; -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; import java.io.InputStream; import java.net.UnknownHostException; @@ -44,7 +29,23 @@ import java.util.List; import java.util.Locale; import java.util.SimpleTimeZone; -import static org.testng.Assert.assertEquals; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseServerFromJsonResponse} diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java index 8a070f7082..5854e4a28e 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java @@ -70,6 +70,7 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.rest.AuthorizationException; import org.jclouds.scriptbuilder.domain.Statements; @@ -85,7 +86,7 @@ import com.google.inject.Module; /** * Generally disabled, as it incurs higher fees. - * + * * @author Adrian Cole */ @Test(groups = "novalive", enabled = true, sequential = true) @@ -93,27 +94,25 @@ public class NovaComputeServiceLiveTest extends ComputeBase { private static String group = "compute service test group"; - protected void checkNodes(Iterable nodes, String tag) throws IOException { for (NodeMetadata node : nodes) { assertNotNull(node.getProviderId()); assertNotNull(node.getGroup()); assertEquals(node.getGroup(), group); - //assertEquals(node.getState(), NodeState.RUNNING); + // assertEquals(node.getState(), NodeState.RUNNING); Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); assertEquals(fromStore, node.getCredentials()); assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; -// assertNotNull(node.getCredentials()); -// if (node.getCredentials().identity != null) { -// assertNotNull(node.getCredentials().identity); -// assertNotNull(node.getCredentials().credential); -// doCheckJavaIsInstalledViaSsh(node); -// } + // assertNotNull(node.getCredentials()); + // if (node.getCredentials().identity != null) { + // assertNotNull(node.getCredentials().identity); + // assertNotNull(node.getCredentials().credential); + // doCheckJavaIsInstalledViaSsh(node); + // } assertEquals(node.getLocation().getScope(), LocationScope.HOST); } } - @BeforeTest @Override public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException { @@ -128,8 +127,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase { properties.remove(provider + ".identity"); ComputeServiceContext context = null; try { - context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ImmutableSet - .of(new SLF4JLoggingModule()), properties); + context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", + ImmutableSet. of(new SLF4JLoggingModule()), properties); context.getComputeService().listNodes(); } finally { if (context != null) @@ -148,8 +147,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase { @Test(enabled = true, expectedExceptions = NoSuchElementException.class, timeOut = 60000) public void testCorrectExceptionRunningNodesNotFound() throws Exception { - computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() - .family(OsFamily.UBUNTU).description("ffoo").build())); + computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), + buildScript(new OperatingSystem.Builder().family(OsFamily.UBUNTU).description("ffoo").build())); } @Test(expectedExceptions = UserAuthException.class, timeOut = 240000) @@ -160,35 +159,38 @@ public class NovaComputeServiceLiveTest extends ComputeBase { OperatingSystem os = node.getOperatingSystem(); try { @SuppressWarnings("unused") - Map responses = runJavaInstallationScriptWithCreds(group, os, new Credentials( - "root", "romeo")); + Map responses = runJavaInstallationScriptWithCreds(group, os, + LoginCredentials.builder().user("root").password("romeo").build()); } catch (RunScriptOnNodesException e) { throw e.getNodeErrors().values().iterator().next().getCause(); } } @Test(timeOut = 240000) - public void testScriptExecutionAfterBootWithBasicTemplate() throws InterruptedException, RunNodesException, RunScriptOnNodesException, URISyntaxException, IOException { + public void testScriptExecutionAfterBootWithBasicTemplate() throws InterruptedException, RunNodesException, + RunScriptOnNodesException, URISyntaxException, IOException { NodeMetadata node = getDefaultNodeImmediately(group); String address = awaitForStartup(node.getId()); awaitForSshPort(address, new Credentials("root", keyPair.get("private"))); for (Map.Entry response : computeService.runScriptOnNodesMatching( - runningInGroup(group), Statements.exec("echo hello"), - overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet()) - assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " - + response.getValue(); + runningInGroup(group), + Statements.exec("echo hello"), + overrideCredentialsWith(LoginCredentials.builder().user("root").privateKey(keyPair.get("private")).build()) + .wrapInInitScript(false).runAsRoot(false)).entrySet()) + assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + response.getValue(); - //TODO runJavaInstallationScriptWithCreds(group, os, new Credentials("root", keyPair.get("private"))); - //TODO no response? if os is null (ZYPPER) + // TODO runJavaInstallationScriptWithCreds(group, os, new + // Credentials("root", keyPair.get("private"))); + // TODO no response? if os is null (ZYPPER) node = computeService.getNodeMetadata(node.getId()); checkNodes(Sets.newHashSet(node), group); @SuppressWarnings("unused") Credentials good = node.getCredentials(); - //TODO check good is being private key .overrideCredentialsWith - //TODO test for .blockOnPort + // TODO check good is being private key .overrideCredentialsWith + // TODO test for .blockOnPort } @Test(timeOut = 60000) @@ -198,9 +200,9 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assertEquals(toMatch.getImage(), template.getImage()); } -// protected void checkHttpGet(NodeMetadata node) { -// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); -// } + // protected void checkHttpGet(NodeMetadata node) { + // ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); + // } @Test(timeOut = 60000) public void testCreateTwoNodesWithRunScript() throws Exception { @@ -219,18 +221,21 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assertLocationSameOrChild(node2.getLocation(), template.getLocation()); assertEquals(node1.getImageId(), template.getImage().getId()); assertEquals(node2.getImageId(), template.getImage().getId()); -// checkOsMatchesTemplate(node1); -// checkOsMatchesTemplate(node2); - //TODO add with script; + // checkOsMatchesTemplate(node1); + // checkOsMatchesTemplate(node2); + // TODO add with script; } -// protected void checkOsMatchesTemplate(NodeMetadata node) { -// if (node.getOperatingSystem() != null) -// assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String -// .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node -// .getOperatingSystem()); -// } - + // protected void checkOsMatchesTemplate(NodeMetadata node) { + // if (node.getOperatingSystem() != null) + // assert + // node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) + // : String + // .format("expecting family %s but got %s", + // getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), + // node + // .getOperatingSystem()); + // } @Test(timeOut = 60000) public void testCreateAnotherNodeWithNewContextToEnsureSharedMemIsntRequired() throws Exception { @@ -238,9 +243,9 @@ public class NovaComputeServiceLiveTest extends ComputeBase { initializeContextAndComputeService(overrides); NodeMetadata node = createDefaultNode(TemplateOptions.Builder.blockUntilRunning(true), group); - checkNodes(Sets.newHashSet(node), group); + checkNodes(Sets. newHashSet(node), group); assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation()); -// checkOsMatchesTemplate(node); + // checkOsMatchesTemplate(node); } @Test(timeOut = 60000) @@ -254,14 +259,13 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); } - protected Map runJavaInstallationScriptWithCreds(final String group, OperatingSystem os, - Credentials creds) throws RunScriptOnNodesException { - return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) - .nameTask("runJavaInstallationScriptWithCreds")); + protected Map runJavaInstallationScriptWithCreds(final String group, + OperatingSystem os, LoginCredentials creds) throws RunScriptOnNodesException { + return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), + overrideCredentialsWith(creds).nameTask("runJavaInstallationScriptWithCreds")); } - protected Template buildTemplate(TemplateBuilder templateBuilder) { return templateBuilder.build(); } @@ -269,8 +273,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase { @Test(timeOut = 120000) public void testGetNodeMetadata() throws Exception { Set nodes = Sets.newHashSet(getDefaultNodeImmediately(group)); - Map metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService - .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), + Map metadataMap = newLinkedHashMap(uniqueIndex( + filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), new Function() { @Override @@ -288,7 +292,7 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assertEquals(nodeMetadata.getGroup(), node.getGroup()); assertLocationSameOrChild(nodeMetadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); assertEquals(nodeMetadata.getImageId(), getDefaultTemplateBuilder().build().getImage().getId()); -// checkOsMatchesTemplate(metadata); + // checkOsMatchesTemplate(metadata); assertEquals(nodeMetadata.getState(), NodeState.RUNNING); // due to DHCP the addresses can actually change in-between runs. assertTrue(nodeMetadata.getPrivateAddresses().size() > 0); @@ -297,13 +301,11 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assertNodeZero(metadataMap.values(), nodes); } - protected void assertNodeZero(Collection metadataSet, Set nodes) { assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", metadataSet, nodes); } - @Test(timeOut = 60000) public void testListNodes() throws Exception { for (ComputeMetadata node : computeService.listNodes()) { @@ -323,7 +325,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase { // nullable // assert nodeMetadata.getImage() != null : node; // user specified name is not always supported - // assert nodeMetadata.getName().parseGroupFromName() != null : nodeMetadata; + // assert nodeMetadata.getName().parseGroupFromName() != null : + // nodeMetadata; if (node.getState() == NodeState.RUNNING) { assert node.getPublicAddresses() != null : node; @@ -344,15 +347,14 @@ public class NovaComputeServiceLiveTest extends ComputeBase { } } - @Test(timeOut = 60000) public void testCreateAndRunService() throws Exception { @SuppressWarnings("unused") NodeMetadata node = getDefaultNodeImmediately(group); - //TODO .inboundPorts - //checkHttpGet(node); + // TODO .inboundPorts + // checkHttpGet(node); } - + public void testListImages() throws Exception { for (Image image : computeService.listImages()) { assert image.getProviderId() != null : image; @@ -369,35 +371,37 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assert location != location.getParent() : location; assert location.getScope() != null : location; switch (location.getScope()) { - case PROVIDER: - assertProvider(location); - break; - case REGION: - assertProvider(location.getParent()); - break; - case ZONE: - Location provider = location.getParent().getParent(); - // zone can be a direct descendant of provider - if (provider == null) - provider = location.getParent(); - assertProvider(provider); - break; - case HOST: - Location provider2 = location.getParent().getParent().getParent(); - // zone can be a direct descendant of provider - if (provider2 == null) - provider2 = location.getParent().getParent(); - assertProvider(provider2); - break; + case PROVIDER: + assertProvider(location); + break; + case REGION: + assertProvider(location.getParent()); + break; + case ZONE: + Location provider = location.getParent().getParent(); + // zone can be a direct descendant of provider + if (provider == null) + provider = location.getParent(); + assertProvider(provider); + break; + case HOST: + Location provider2 = location.getParent().getParent().getParent(); + // zone can be a direct descendant of provider + if (provider2 == null) + provider2 = location.getParent().getParent(); + assertProvider(provider2); + break; } } } public void testOptionToNotBlock() throws Exception { - //TODO no inbound ports - //TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); + // TODO no inbound ports + // TemplateOptions options = + // computeService.templateOptions().blockUntilRunning(false).inboundPorts(); long time = System.currentTimeMillis(); - NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build())); + NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder() + .build())); assert node.getState() != NodeState.RUNNING; long duration = System.currentTimeMillis() - time; assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; @@ -410,7 +414,7 @@ public class NovaComputeServiceLiveTest extends ComputeBase { @Test(timeOut = 60000, enabled = false) public void testListHardwareProfiles() throws Exception { - //TODO: failing, OpenStack returns a hardware with 0 CPU cores + // TODO: failing, OpenStack returns a hardware with 0 CPU cores for (Hardware hardware : computeService.listHardwareProfiles()) { assert hardware.getProviderId() != null; assert getCores(hardware) > 0; @@ -420,7 +424,6 @@ public class NovaComputeServiceLiveTest extends ComputeBase { } } - @Test(timeOut = 60000) public void testCompareSizes() throws Exception { TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); @@ -447,7 +450,6 @@ public class NovaComputeServiceLiveTest extends ComputeBase { assert getCores(fastest) >= getCores(smallest); } - protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { SshClient ssh = context.utils().sshForNode().apply(node); diff --git a/apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java b/apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java index 536fb1e397..ec0cfd4750 100644 --- a/apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java +++ b/apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java @@ -18,23 +18,31 @@ */ package org.jclouds.openstack.nova.live.novaclient; -import com.google.common.collect.Iterables; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.io.IOException; +import java.util.Set; + import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; import org.jclouds.net.IPSocket; -import org.jclouds.openstack.nova.domain.*; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.ImageStatus; +import org.jclouds.openstack.nova.domain.RebootType; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.ssh.SshClient; import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; -import java.io.IOException; -import java.util.Set; - -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.testng.Assert.*; +import com.google.common.collect.Iterables; /** * Tests behavior of {@code NovaClient} diff --git a/apis/vcloud/pom.xml b/apis/vcloud/pom.xml index 6184e623da..f7cfef97cc 100644 --- a/apis/vcloud/pom.xml +++ b/apis/vcloud/pom.xml @@ -39,7 +39,8 @@ FIXME FIXME - + + @@ -108,7 +109,8 @@ ${test.vcloud.identity} ${test.vcloud.credential} ${test.vcloud.image-id} - ${test.vcloud.login-user} + ${test.vcloud.image.login-user} + ${test.vcloud.image.authenticate-sudo} diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java index 6fea7ebc4e..82c1d875e0 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/ImageForVAppTemplate.java @@ -65,7 +65,7 @@ public class ImageForVAppTemplate implements Function { builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); Envelope ovf = client.getVAppTemplateClient().getOvfEnvelopeForVAppTemplate(from.getHref()); builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf)); - builder.defaultCredentials(credentialsProvider.execute(from)); + builder.defaultCredentials(credentialsProvider.apply(from)); return builder.build(); } diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java index fd44871ba8..b898d4c54b 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/functions/VAppToNodeMetadata.java @@ -38,6 +38,7 @@ 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.domain.LoginCredentials; import org.jclouds.logging.Logger; import org.jclouds.util.InetAddresses2.IsPrivateIPAddress; import org.jclouds.vcloud.domain.Status; @@ -80,11 +81,11 @@ public class VAppToNodeMetadata implements Function { Set addresses = getIpsFromVApp(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); - builder.credentials(getCredentialsFrom(from)); Credentials fromApi = getCredentialsFrom(from); if (fromApi != null && !credentialStore.containsKey("node#" + from.getHref().toASCIIString())) credentialStore.put("node#" + from.getHref().toASCIIString(), fromApi); - builder.credentials(credentialStore.get("node#" + from.getHref().toASCIIString())); + builder.credentials(LoginCredentials.builder(credentialStore.get("node#" + from.getHref().toASCIIString())) + .build()); return builder.build(); } } \ No newline at end of file diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/strategy/GetLoginCredentialsFromGuestConfiguration.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/strategy/GetLoginCredentialsFromGuestConfiguration.java index 23fa1eedd5..f9a80c3707 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/strategy/GetLoginCredentialsFromGuestConfiguration.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/strategy/GetLoginCredentialsFromGuestConfiguration.java @@ -27,7 +27,7 @@ import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; import org.jclouds.vcloud.domain.VAppTemplate; @@ -37,12 +37,12 @@ import org.jclouds.vcloud.domain.VAppTemplate; @Singleton public class GetLoginCredentialsFromGuestConfiguration extends ReturnCredentialsBoundToImage { @Inject - public GetLoginCredentialsFromGuestConfiguration(@Nullable @Named("image") Credentials creds) { + public GetLoginCredentialsFromGuestConfiguration(@Nullable @Named("image") LoginCredentials creds) { super(creds); } @Override - public Credentials execute(Object resourceToAuthenticate) { + public LoginCredentials apply(Object resourceToAuthenticate) { if (creds != null) return creds; checkNotNull(resourceToAuthenticate); diff --git a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java index 658ae31bf3..26d73bca86 100644 --- a/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java +++ b/apis/vcloud/src/main/java/org/jclouds/vcloud/compute/util/VCloudComputeUtils.java @@ -27,7 +27,7 @@ import org.jclouds.cim.ResourceAllocationSettingData; import org.jclouds.cim.ResourceAllocationSettingData.ResourceType; import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.vcloud.domain.NetworkConnection; import org.jclouds.vcloud.domain.VApp; import org.jclouds.vcloud.domain.VAppTemplate; @@ -35,8 +35,8 @@ import org.jclouds.vcloud.domain.Vm; import org.jclouds.vcloud.domain.ovf.VCloudNetworkAdapter; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.collect.ImmutableSet.Builder; +import com.google.common.collect.Iterables; /** * @@ -67,23 +67,23 @@ public class VCloudComputeUtils { return null; } - public static Credentials getCredentialsFrom(VApp vApp) { + public static LoginCredentials getCredentialsFrom(VApp vApp) { return vApp.getChildren().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null; } - public static Credentials getCredentialsFrom(VAppTemplate vApp) { + public static LoginCredentials getCredentialsFrom(VAppTemplate vApp) { return vApp.getChildren().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null; } - public static Credentials getCredentialsFrom(Vm vm) { - String user = "root"; + public static LoginCredentials getCredentialsFrom(Vm vm) { + LoginCredentials.Builder builder = LoginCredentials.builder(); + builder.user("root"); if (vm.getOperatingSystemSection() != null && vm.getOperatingSystemSection().getDescription() != null && vm.getOperatingSystemSection().getDescription().indexOf("Windows") >= 0) - user = "Administrator"; - String password = null; + builder.user("Administrator"); if (vm.getGuestCustomizationSection() != null) - password = vm.getGuestCustomizationSection().getAdminPassword(); - return new Credentials(user, password); + builder.password(vm.getGuestCustomizationSection().getAdminPassword()); + return builder.build(); } public static Set getIpsFromVApp(VApp vApp) { diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/internal/BaseVCloudClientLiveTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/internal/BaseVCloudClientLiveTest.java index 91fd1fbd2f..4ba2dbe5cd 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/internal/BaseVCloudClientLiveTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/internal/BaseVCloudClientLiveTest.java @@ -18,13 +18,10 @@ */ package org.jclouds.vcloud.internal; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; -import org.jclouds.Constants; import org.jclouds.compute.BaseVersionedServiceLiveTest; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContextFactory; @@ -33,7 +30,6 @@ import org.jclouds.rest.RestContextFactory; import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.vcloud.VCloudClient; import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java index 0fd18a71fa..7a229b37f1 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/TerremarkVCloudComputeClient.java @@ -29,7 +29,6 @@ import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; -import org.jclouds.javax.annotation.Nullable; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; @@ -40,6 +39,8 @@ import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient; import org.jclouds.trmk.vcloud_0_8.domain.InternetService; @@ -134,7 +135,7 @@ public class TerremarkVCloudComputeClient { password = passwordGenerator.get(); options.getProperties().put("password", password); } - Credentials defaultCredentials = credentialsProvider.execute(template); + LoginCredentials defaultCredentials = credentialsProvider.apply(template); checkNotNull(options, "options"); logger.debug(">> instantiating vApp vDC(%s) template(%s) name(%s) options(%s) ", VDC, templateId, name, options); diff --git a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.java b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.java index b172547c44..51bb55b8cc 100644 --- a/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.java +++ b/common/trmk/src/main/java/org/jclouds/trmk/vcloud_0_8/compute/strategy/ParseVAppTemplateDescriptionToGetDefaultLoginCredentials.java @@ -31,7 +31,7 @@ import javax.inject.Singleton; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate; @@ -42,7 +42,7 @@ import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate; @Singleton public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends ReturnCredentialsBoundToImage { @Inject - public ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(@Nullable @Named("image") Credentials creds) { + public ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(@Nullable @Named("image") LoginCredentials creds) { super(creds); } @@ -54,7 +54,7 @@ public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends Re .compile(".*[Uu]sername: ([a-z]+) ?.*\n[Pp]assword: ([^ \n\r]+) ?\r?\n.*"); @Override - public Credentials execute(Object resourceToAuthenticate) { + public LoginCredentials apply(Object resourceToAuthenticate) { if (creds != null) return creds; checkNotNull(resourceToAuthenticate); @@ -62,11 +62,11 @@ public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends Re VAppTemplate template = (VAppTemplate) resourceToAuthenticate; String search = template.getDescription() != null ? template.getDescription() : template.getName(); if (search.indexOf("Windows") >= 0) { - return new Credentials("Administrator", null); + return LoginCredentials.builder().user("Administrator").build(); } else { Matcher matcher = USER_PASSWORD_PATTERN.matcher(search); if (matcher.find()) { - return new Credentials(matcher.group(1), matcher.group(2)); + return LoginCredentials.builder().user(matcher.group(1)).password(matcher.group(2)).build(); } else { logger.warn("could not parse username/password for image: " + template.getHref() + "\n" + search); return null; diff --git a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/internal/BaseTerremarkClientLiveTest.java b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/internal/BaseTerremarkClientLiveTest.java index 7d8d2c15af..b4d2a28909 100644 --- a/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/internal/BaseTerremarkClientLiveTest.java +++ b/common/trmk/src/test/java/org/jclouds/trmk/vcloud_0_8/internal/BaseTerremarkClientLiveTest.java @@ -18,8 +18,6 @@ */ package org.jclouds.trmk.vcloud_0_8.internal; -import static com.google.common.base.Preconditions.checkNotNull; - import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; diff --git a/compute/src/main/java/org/jclouds/compute/ComputeServiceAdapter.java b/compute/src/main/java/org/jclouds/compute/ComputeServiceAdapter.java index 38fa9f15b1..bbd896269b 100644 --- a/compute/src/main/java/org/jclouds/compute/ComputeServiceAdapter.java +++ b/compute/src/main/java/org/jclouds/compute/ComputeServiceAdapter.java @@ -21,7 +21,7 @@ package org.jclouds.compute; import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; /** @@ -66,9 +66,9 @@ public interface ComputeServiceAdapter { public static class NodeAndInitialCredentials { private final N node; private final String nodeId; - private final Credentials credentials; + private final LoginCredentials credentials; - public NodeAndInitialCredentials(N node, String nodeId, @Nullable Credentials credentials) { + public NodeAndInitialCredentials(N node, String nodeId, @Nullable LoginCredentials credentials) { this.node = checkNotNull(node, "node"); this.nodeId = checkNotNull(nodeId, "nodeId"); this.credentials = credentials; @@ -96,7 +96,7 @@ public interface ComputeServiceAdapter { * information is not available */ @Nullable - public Credentials getCredentials() { + public LoginCredentials getCredentials() { return credentials; } } diff --git a/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSsh.java b/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSsh.java index 74e9469f6a..2f778f1f9f 100644 --- a/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSsh.java +++ b/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSsh.java @@ -31,6 +31,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import org.jclouds.scriptbuilder.InitBuilder; import org.jclouds.scriptbuilder.domain.AdminAccessVisitor; @@ -106,8 +107,8 @@ public class RunScriptOnNodeAsInitScriptUsingSsh extends SudoAwareInitManager im if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) { ssh.disconnect(); logger.debug(">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress()); - ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node).adminPassword(null).credentials( - input.getAdminCredentials()).build()); + ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(LoginCredentials.builder( + input.getAdminCredentials()).build()).build()); ssh.connect(); setupLinkToInitFile(); } diff --git a/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSsh.java b/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSsh.java index b23310a816..f45b108353 100644 --- a/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSsh.java +++ b/compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSsh.java @@ -59,7 +59,7 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode { @AssistedInject public RunScriptOnNodeUsingSsh(Function sshFactory, @Assisted NodeMetadata node, - @Assisted Statement statement, @Assisted RunScriptOptions options) { + @Assisted Statement statement, @Assisted RunScriptOptions options) { this.sshFactory = checkNotNull(sshFactory, "sshFactory"); this.node = checkNotNull(node, "node"); this.statement = checkNotNull(statement, "statement"); @@ -73,7 +73,7 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode { ssh.connect(); ExecResponse returnVal; String command = (runAsRoot) ? execAsRoot(statement.render(OsFamily.UNIX)) : execScriptAsDefaultUser(statement - .render(OsFamily.UNIX)); + .render(OsFamily.UNIX)); returnVal = runCommand(command); if (logger.isTraceEnabled()) logger.trace("<< %s[%s]", statement, returnVal); @@ -94,8 +94,8 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode { protected ExecResponse runCommand(String command) { ExecResponse returnVal; - logger.debug(">> running [%s] as %s@%s", command.replace(node.getAdminPassword() != null ? node - .getAdminPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); + logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().getPassword() != null ? node + .getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); returnVal = ssh.exec(command); return returnVal; } @@ -103,10 +103,10 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode { @VisibleForTesting public String execAsRoot(String command) { if (node.getCredentials().identity.equals("root")) { - } else if (node.getAdminPassword() != null) { - command = String.format("sudo -S sh <<'%s'\n%s\n%s%s\n", MARKER, node.getAdminPassword(), command, MARKER); + } else if (node.getCredentials().shouldAuthenticateSudo()) { + command = String.format("sudo -S sh <<'%s'\n%s\n%s%s\n", MARKER, node.getCredentials().getPassword(), command, MARKER); } else { - command = String.format("sudo sh <<'%s'\n%s%s\n", MARKER, command, MARKER); + command = String.format("sudo sh <<'%s'\n%s%s\n", MARKER, command, MARKER); } return command; } @@ -122,7 +122,7 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode { @Override public String toString() { return Objects.toStringHelper(this).add("node", node).add("name", statement).add("runAsRoot", runAsRoot) - .toString(); + .toString(); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/callables/SudoAwareInitManager.java b/compute/src/main/java/org/jclouds/compute/callables/SudoAwareInitManager.java index 17326073c7..f05300b56c 100644 --- a/compute/src/main/java/org/jclouds/compute/callables/SudoAwareInitManager.java +++ b/compute/src/main/java/org/jclouds/compute/callables/SudoAwareInitManager.java @@ -54,7 +54,7 @@ public class SudoAwareInitManager { protected SshClient ssh; public SudoAwareInitManager(Function sshFactory, boolean runAsRoot, NodeMetadata node, - InitBuilder init) { + InitBuilder init) { this.sshFactory = checkNotNull(sshFactory, "sshFactory"); this.runAsRoot = runAsRoot; this.node = checkNotNull(node, "node"); @@ -81,7 +81,7 @@ public class SudoAwareInitManager { public ExecResponse runAction(String action) { ExecResponse returnVal; String command = (runAsRoot && Predicates.in(ImmutableSet.of("start", "stop", "run")).apply(action)) ? execScriptAsRoot(action) - : execScriptAsDefaultUser(action); + : execScriptAsDefaultUser(action); returnVal = runCommand(command); if ("status".equals(action)) logger.trace("<< %s(%d)", action, returnVal.getExitCode()); @@ -94,8 +94,8 @@ public class SudoAwareInitManager { ExecResponse runCommand(String command) { String statement = String.format(">> running [%s] as %s@%s", command.replace( - node.getAdminPassword() != null ? node.getAdminPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh - .getHostAddress()); + node.getCredentials().getPassword() != null ? node.getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh + .getUsername(), ssh.getHostAddress()); if (command.endsWith("status")) logger.trace(statement); else @@ -108,8 +108,9 @@ public class SudoAwareInitManager { String command; if (node.getCredentials().identity.equals("root")) { command = "./" + init.getInstanceName() + " " + action; - } else if (node.getAdminPassword() != null) { - command = String.format("echo '%s'|sudo -S ./%s %s", node.getAdminPassword(), init.getInstanceName(), action); + } else if (node.getCredentials().shouldAuthenticateSudo()) { + command = String.format("echo '%s'|sudo -S ./%s %s", node.getCredentials().getPassword(), + init.getInstanceName(), action); } else { command = "sudo ./" + init.getInstanceName() + " " + action; } @@ -126,8 +127,8 @@ public class SudoAwareInitManager { @Override public String toString() { - return Objects.toStringHelper(this).add("node", node).add("name", init.getInstanceName()).add("runAsRoot", - runAsRoot).toString(); + return Objects.toStringHelper(this).add("node", node).add("name", init.getInstanceName()) + .add("runAsRoot", runAsRoot).toString(); } public InitBuilder getStatement() { diff --git a/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java b/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java index 56c759d738..6ab0101c57 100644 --- a/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java @@ -52,7 +52,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap; import org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap; import org.jclouds.config.ValueOfConfigurationKeyOrNull; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.json.Json; import org.jclouds.location.Provider; import org.jclouds.location.config.LocationModule; @@ -87,9 +87,9 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule { }).to(CreateSshClientOncePortIsListeningOnNode.class); bind(new TypeLiteral>() { }).to(TemplateOptionsToStatement.class); - bind(Credentials.class).annotatedWith(Names.named("image")).toProvider( + bind(LoginCredentials.class).annotatedWith(Names.named("image")).toProvider( GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.class); - bind(new TypeLiteral>() { + bind(new TypeLiteral>() { }).to(DefaultCredentialsFromImageOrOverridingCredentials.class); install(new FactoryModuleBuilder() diff --git a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceAdapterContextModule.java b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceAdapterContextModule.java index a1ce092806..5c915b342b 100644 --- a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceAdapterContextModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceAdapterContextModule.java @@ -39,8 +39,8 @@ import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.ResumeNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import com.google.common.base.Function; import com.google.common.base.Functions; @@ -126,7 +126,7 @@ public class ComputeServiceAdapterContextModule extends BaseCo @Override public Image apply(Image arg0) { - Credentials credentials = credsForImage.execute(arg0); + LoginCredentials credentials = credsForImage.apply(arg0); return credentials != null ? ImageBuilder.fromImage(arg0).defaultCredentials(credentials).build() : arg0; } diff --git a/compute/src/main/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.java b/compute/src/main/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.java index 41600c6f91..4da602e72a 100644 --- a/compute/src/main/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.java +++ b/compute/src/main/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.java @@ -26,6 +26,8 @@ import javax.inject.Singleton; import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.Provider; @@ -36,7 +38,7 @@ import com.google.inject.Inject; */ @Singleton public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull implements - javax.inject.Provider { + javax.inject.Provider { private final ValueOfConfigurationKeyOrNull config; private final String provider; private final Map credentialStore; @@ -51,22 +53,33 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull im @Override @Nullable - public Credentials get() { - if (credentialStore.containsKey("image")) - return credentialStore.get("image"); - Credentials creds = null; - String loginUser = config.apply(provider + ".login-user"); + public LoginCredentials get() { + if (credentialStore.containsKey("image")) { + return LoginCredentials.builder(credentialStore.get("image")).build(); + } + Builder builder = LoginCredentials.builder(); + + String loginUser = config.apply(provider + ".image.login-user"); if (loginUser == null) - loginUser = config.apply("jclouds.login-user"); + loginUser = config.apply("jclouds.image.login-user"); if (loginUser != null) { int pos = loginUser.indexOf(':'); if (pos != -1) { - creds = new Credentials(loginUser.substring(0, pos), loginUser.substring(pos + 1)); + builder.user(loginUser.substring(0, pos)).password(loginUser.substring(pos + 1)); } else - creds = new Credentials(loginUser, null); - credentialStore.put("image", creds); + builder.user(loginUser); } + + String authenticateSudo = config.apply(provider + ".image.authenticate-sudo"); + if (authenticateSudo == null) + authenticateSudo = config.apply("jclouds.image.authenticate-sudo"); + if (authenticateSudo != null) { + builder.authenticateSudo(Boolean.valueOf(authenticateSudo)); + } + + LoginCredentials creds = builder.build(); + if (creds != null) + credentialStore.put("image", creds); return creds; } - } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/config/PersistNodeCredentialsModule.java b/compute/src/main/java/org/jclouds/compute/config/PersistNodeCredentialsModule.java index db1cfd84da..8f76cc83ea 100644 --- a/compute/src/main/java/org/jclouds/compute/config/PersistNodeCredentialsModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/PersistNodeCredentialsModule.java @@ -20,12 +20,12 @@ package org.jclouds.compute.config; import java.util.Map; -import org.jclouds.javax.annotation.Nullable; - import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.internal.PersistNodeCredentials; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.functions.CredentialsFromAdminAccess; @@ -60,7 +60,8 @@ public class PersistNodeCredentialsModule extends AbstractModule { return input; Credentials credentials = CredentialsFromAdminAccess.INSTANCE.apply(statement); if (credentials != null) { - input = NodeMetadataBuilder.fromNodeMetadata(input).credentials(credentials).build(); + LoginCredentials creds = LoginCredentials.builder(credentials).build(); + input = NodeMetadataBuilder.fromNodeMetadata(input).credentials(creds).build(); credentialStore.put("node#" + input.getId(), input.getCredentials()); } return input; diff --git a/compute/src/main/java/org/jclouds/compute/domain/Image.java b/compute/src/main/java/org/jclouds/compute/domain/Image.java index 820caee90d..fe4537f67b 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/Image.java +++ b/compute/src/main/java/org/jclouds/compute/domain/Image.java @@ -18,10 +18,9 @@ */ package org.jclouds.compute.domain; -import org.jclouds.javax.annotation.Nullable; - import org.jclouds.compute.domain.internal.ImageImpl; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; import com.google.common.annotations.Beta; import com.google.inject.ImplementedBy; @@ -50,19 +49,24 @@ public interface Image extends ComputeMetadata { String getDescription(); /** + *

will be removed in jclouds 1.4.0

+ * * secures access to root with a password. This password is required to access either the console * or run sudo as root. *

* ex. {@code echo 'password' |sudo -S command} * + * * @return root or console password, if configured, or null. + * @see LoginCredentials#shouldAuthenticateSudo */ @Nullable + @Deprecated String getAdminPassword(); /** * Default credentials for the current image */ - Credentials getDefaultCredentials(); + LoginCredentials getDefaultCredentials(); } \ 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 index 98135d08fe..2350e1816e 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java @@ -23,11 +23,12 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; import java.util.Map; -import org.jclouds.javax.annotation.Nullable; - import org.jclouds.compute.domain.internal.ImageImpl; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; +import org.jclouds.javax.annotation.Nullable; /** * @author Adrian Cole @@ -36,9 +37,7 @@ public class ImageBuilder extends ComputeMetadataBuilder { private OperatingSystem operatingSystem; private String version; private String description; - @Nullable - private String adminPassword; - private Credentials defaultCredentials; + private LoginCredentials defaultLoginCredentials; public ImageBuilder() { super(ComputeType.IMAGE); @@ -59,13 +58,30 @@ public class ImageBuilder extends ComputeMetadataBuilder { return this; } + /** + *

will be removed in jclouds 1.4.0

+ * + * @see LoginCredentials#shouldAuthenticateSudo + */ + @Deprecated public ImageBuilder adminPassword(@Nullable String adminPassword) { - this.adminPassword = adminPassword; + if (adminPassword != null) { + Builder builder = defaultLoginCredentials != null ? defaultLoginCredentials.toBuilder() : LoginCredentials + .builder(); + builder.authenticateSudo(true); + builder.password(adminPassword); + this.defaultLoginCredentials = builder.build(); + } return this; } - public ImageBuilder defaultCredentials(@Nullable Credentials defaultCredentials) { - this.defaultCredentials = defaultCredentials; + @Deprecated + public ImageBuilder defaultCredentials(@Nullable Credentials defaultLoginCredentials) { + return defaultCredentials(LoginCredentials.builder(defaultLoginCredentials).build()); + } + + public ImageBuilder defaultCredentials(@Nullable LoginCredentials defaultLoginCredentials) { + this.defaultLoginCredentials = defaultLoginCredentials; return this; } @@ -73,7 +89,7 @@ public class ImageBuilder extends ComputeMetadataBuilder { public ImageBuilder id(String id) { return ImageBuilder.class.cast(super.id(id)); } - + public ImageBuilder tags(Iterable tags) { return ImageBuilder.class.cast(super.tags(tags)); } @@ -110,15 +126,15 @@ public class ImageBuilder extends ComputeMetadataBuilder { @Override public Image build() { - return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, description, version, - adminPassword, defaultCredentials); + return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, description, + version, defaultLoginCredentials); } public static ImageBuilder fromImage(Image image) { - return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()).location( - image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()).tags(image.getTags()).version( - image.getVersion()).description(image.getDescription()).operatingSystem(image.getOperatingSystem()) - .adminPassword(image.getAdminPassword()).defaultCredentials(image.getDefaultCredentials()); + return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()) + .location(image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()) + .tags(image.getTags()).version(image.getVersion()).description(image.getDescription()) + .operatingSystem(image.getOperatingSystem()).defaultCredentials(image.getDefaultCredentials()); } } \ No newline at end of file diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java index d95dcc1669..6fb1c7b656 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java @@ -20,10 +20,9 @@ package org.jclouds.compute.domain; import java.util.Set; -import org.jclouds.javax.annotation.Nullable; - import org.jclouds.compute.domain.internal.NodeMetadataImpl; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; import com.google.inject.ImplementedBy; @@ -92,21 +91,25 @@ public interface NodeMetadata extends ComputeMetadata { int getLoginPort(); /** + *

will be removed in jclouds 1.4.0

+ * * secures access to root with a password. This password is required to access either the console * or run sudo as root. *

* ex. {@code echo 'password' |sudo -S command} * * @return root or console password, if configured, or null. + * @see LoginCredentials#shouldAuthenticateSudo */ @Nullable + @Deprecated String getAdminPassword(); /** * If possible, these are returned upon all detail requests. However, it is often the case that * credentials are only available at "run" time. */ - Credentials getCredentials(); + LoginCredentials getCredentials(); /** * All public IP addresses, potentially including shared ips. diff --git a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java index 8a5f2bc7a7..6fae4ffcc6 100644 --- a/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java +++ b/compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java @@ -29,6 +29,8 @@ import org.jclouds.javax.annotation.Nullable; import org.jclouds.compute.domain.internal.NodeMetadataImpl; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; @@ -41,9 +43,7 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { private Set publicAddresses = Sets.newLinkedHashSet(); private Set privateAddresses = Sets.newLinkedHashSet(); @Nullable - private String adminPassword; - @Nullable - private Credentials credentials; + private LoginCredentials credentials; @Nullable private String group; private int loginPort = 22; @@ -80,15 +80,33 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { return this; } + /** + *

will be removed in jclouds 1.4.0

+ * + * @see LoginCredentials#shouldAuthenticateSudo + */ + @Deprecated + public NodeMetadataBuilder adminPassword(@Nullable String adminPassword) { + if (adminPassword != null) { + Builder builder = credentials != null ? credentials.toBuilder() : LoginCredentials + .builder(); + builder.authenticateSudo(true); + builder.password(adminPassword); + this.credentials = builder.build(); + } + return this; + } + + @Deprecated public NodeMetadataBuilder credentials(@Nullable Credentials credentials) { + return credentials(LoginCredentials.builder(credentials).build()); + } + + public NodeMetadataBuilder credentials(@Nullable LoginCredentials credentials) { this.credentials = credentials; return this; } - public NodeMetadataBuilder adminPassword(@Nullable String adminPassword) { - this.adminPassword = adminPassword; - return this; - } public NodeMetadataBuilder group(@Nullable String group) { this.group = group; @@ -158,7 +176,7 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { @Override public NodeMetadata build() { return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tags, group, hardware, imageId, - os, state, loginPort, publicAddresses, privateAddresses, adminPassword, credentials, hostname); + os, state, loginPort, publicAddresses, privateAddresses, credentials, hostname); } public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) { @@ -166,8 +184,7 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder { node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tags(node.getTags()).group( node.getGroup()).hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem( node.getOperatingSystem()).state(node.getState()).loginPort(node.getLoginPort()).publicAddresses( - node.getPublicAddresses()).privateAddresses(node.getPrivateAddresses()).adminPassword( - node.getAdminPassword()).credentials(node.getCredentials()).hostname(node.getHostname()); + node.getPublicAddresses()).privateAddresses(node.getPrivateAddresses()).credentials(node.getCredentials()).hostname(node.getHostname()); } } \ No newline at end of file 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 cfe5163800..ca1a8d9276 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 @@ -24,13 +24,14 @@ import java.net.URI; import java.util.Map; import java.util.Set; -import org.jclouds.javax.annotation.Nullable; - import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; +import org.jclouds.javax.annotation.Nullable; /** * @author Adrian Cole @@ -43,18 +44,34 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { private final OperatingSystem operatingSystem; private final String version; private final String description; - @Nullable - private final String adminPassword; - private final Credentials defaultCredentials; + private final LoginCredentials defaultCredentials; + /** + *

will be removed in jclouds 1.4.0

+ */ + @Deprecated public ImageImpl(String providerId, String name, String id, Location location, URI uri, - Map userMetadata, Set tags, OperatingSystem operatingSystem, String description, - @Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) { + Map userMetadata, Set tags, OperatingSystem operatingSystem, String description, + @Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) { + super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata, tags); + this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); + this.version = version; + this.description = checkNotNull(description, "description"); + Builder builder = LoginCredentials.builder(defaultCredentials); + if (adminPassword != null) { + builder.authenticateSudo(true); + builder.password(adminPassword); + } + this.defaultCredentials = builder.build(); + } + + public ImageImpl(String providerId, String name, String id, Location location, URI uri, + Map userMetadata, Set tags, OperatingSystem operatingSystem, String description, + @Nullable String version, @Nullable LoginCredentials defaultCredentials) { super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata, tags); this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); this.version = version; this.description = checkNotNull(description, "description"); - this.adminPassword = adminPassword; this.defaultCredentials = defaultCredentials; } @@ -86,7 +103,7 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { * {@inheritDoc} */ @Override - public Credentials getDefaultCredentials() { + public LoginCredentials getDefaultCredentials() { return defaultCredentials; } @@ -94,23 +111,24 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { * {@inheritDoc} */ @Override + @Deprecated public String getAdminPassword() { - return adminPassword; + return (defaultCredentials != null && defaultCredentials.shouldAuthenticateSudo()) ? defaultCredentials + .getPassword() : null; } @Override public String toString() { return "[id=" + getId() + ", name=" + getName() + ", operatingSystem=" + operatingSystem + ", description=" - + description + ", version=" + version + ", location=" + getLocation() + ", loginUser=" - + ((defaultCredentials != null) ? defaultCredentials.identity : null) + ", userMetadata=" - + getUserMetadata() + ", tags=" + tags + "]"; + + description + ", version=" + version + ", location=" + getLocation() + ", loginUser=" + + ((defaultCredentials != null) ? defaultCredentials.identity : null) + ", userMetadata=" + + getUserMetadata() + ", tags=" + tags + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + ((adminPassword == null) ? 0 : adminPassword.hashCode()); result = prime * result + ((defaultCredentials == null) ? 0 : defaultCredentials.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode()); @@ -127,11 +145,6 @@ public class ImageImpl extends ComputeMetadataImpl implements Image { if (getClass() != obj.getClass()) return false; ImageImpl other = (ImageImpl) obj; - if (adminPassword == null) { - if (other.adminPassword != null) - return false; - } else if (!adminPassword.equals(other.adminPassword)) - return false; if (defaultCredentials == null) { if (other.defaultCredentials != null) return false; 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 f4ad4620a9..56373130c1 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 @@ -33,6 +33,8 @@ import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import com.google.common.collect.ImmutableSet; @@ -50,9 +52,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat private final Set publicAddresses; private final Set privateAddresses; @Nullable - private final String adminPassword; - @Nullable - private final Credentials credentials; + private final LoginCredentials credentials; @Nullable private final String group; @Nullable @@ -63,12 +63,39 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat private final OperatingSystem os; @Nullable private final String hostname; - + + /** + *

will be removed in jclouds 1.4.0

+ */ + @Deprecated public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, - Map userMetadata, Set tags, @Nullable String group, @Nullable Hardware hardware, - @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, - Iterable publicAddresses, Iterable privateAddresses, @Nullable String adminPassword, - @Nullable Credentials credentials, String hostname) { + Map userMetadata, Set tags, @Nullable String group, @Nullable Hardware hardware, + @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, + Iterable publicAddresses, Iterable privateAddresses, @Nullable String adminPassword, + @Nullable Credentials credentials, String hostname) { + super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata, tags); + this.group = group; + this.hardware = hardware; + this.imageId = imageId; + this.os = os; + this.state = checkNotNull(state, "state"); + this.loginPort = loginPort; + this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); + this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); + this.hostname = hostname; + Builder builder = LoginCredentials.builder(credentials); + if (adminPassword != null) { + builder.authenticateSudo(true); + builder.password(adminPassword); + } + this.credentials = builder.build(); + } + + public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, + Map userMetadata, Set tags, @Nullable String group, @Nullable Hardware hardware, + @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, + Iterable publicAddresses, Iterable privateAddresses, @Nullable LoginCredentials credentials, + String hostname) { super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata, tags); this.group = group; this.hardware = hardware; @@ -78,7 +105,6 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat this.loginPort = loginPort; this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); - this.adminPassword = adminPassword; this.credentials = credentials; this.hostname = hostname; } @@ -111,15 +137,16 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat * {@inheritDoc} */ @Override + @Deprecated public String getAdminPassword() { - return adminPassword; + return (credentials != null && credentials.shouldAuthenticateSudo()) ? credentials.getPassword() : null; } /** * {@inheritDoc} */ @Override - public Credentials getCredentials() { + public LoginCredentials getCredentials() { return credentials; } @@ -178,7 +205,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat public String getHostname() { return hostname; } - + @Override public String toString() { return "[id=" + getId() + ", providerId=" + getProviderId() + ", group=" + getTag() + ", name=" + getName() @@ -201,7 +228,6 @@ 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 + ((adminPassword == null) ? 0 : adminPassword.hashCode()); result = prime * result + ((credentials == null) ? 0 : credentials.hashCode()); return result; } @@ -252,11 +278,6 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat return false; } else if (!os.equals(other.os)) return false; - if (adminPassword == null) { - if (other.adminPassword != null) - return false; - } else if (!adminPassword.equals(other.adminPassword)) - return false; if (credentials == null) { if (other.credentials != null) return false; diff --git a/compute/src/main/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentials.java b/compute/src/main/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentials.java index 2221ecb33d..6bc8f8fd61 100644 --- a/compute/src/main/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentials.java +++ b/compute/src/main/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentials.java @@ -18,13 +18,12 @@ */ package org.jclouds.compute.functions; -import static org.jclouds.domain.Credentials.NO_CREDENTIALS; - import javax.inject.Singleton; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import com.google.common.base.Function; @@ -33,21 +32,21 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class DefaultCredentialsFromImageOrOverridingCredentials implements Function { +public class DefaultCredentialsFromImageOrOverridingCredentials implements Function { @Override - public Credentials apply(Template template) { + public LoginCredentials apply(Template template) { TemplateOptions options = template.getOptions(); - Credentials creds = template.getImage().getDefaultCredentials(); - Credentials overridingCredentials = options.getOverridingCredentials(); - Credentials overrideCreds = (overridingCredentials != null) ? overridingCredentials : NO_CREDENTIALS; - if (creds == null) - creds = overrideCreds; - if (overrideCreds.identity != null) - creds = creds.toBuilder().identity(overrideCreds.identity).build(); - if (overrideCreds.credential != null) - creds = creds.toBuilder().credential(overrideCreds.credential).build(); - return creds.equals(NO_CREDENTIALS) ? null : creds; + Builder builder = LoginCredentials.builder(template.getImage().getDefaultCredentials()); + if (options.getLoginUser() != null) + builder.user(options.getLoginUser()); + if (options.getLoginPassword() != null) + builder.password(options.getLoginPassword()); + if (options.getLoginPrivateKey() != null) + builder.privateKey(options.getLoginPrivateKey()); + if (options.shouldAuthenticateSudo() != null) + builder.authenticateSudo(true); + return builder.build(); } } \ No newline at end of file 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 36f68b3020..cda8067a69 100644 --- a/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java +++ b/compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java @@ -80,7 +80,8 @@ import org.jclouds.compute.strategy.RunScriptOnNodeAndAddToGoodMapOrPutException import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; -import org.jclouds.domain.Credentials.Builder; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import org.jclouds.io.Payload; import org.jclouds.logging.Logger; import org.jclouds.predicates.RetryablePredicate; @@ -139,20 +140,18 @@ public class BaseComputeService implements ComputeService { @Inject protected BaseComputeService(ComputeServiceContext context, Map credentialStore, - @Memoized Supplier> images, - @Memoized Supplier> hardwareProfiles, - @Memoized Supplier> locations, ListNodesStrategy listNodesStrategy, - GetNodeMetadataStrategy getNodeMetadataStrategy, - CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, - DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy, - SuspendNodeStrategy suspendNodeStrategy, Provider templateBuilderProvider, - Provider templateOptionsProvider, - @Named("NODE_RUNNING") Predicate nodeRunning, - @Named("NODE_TERMINATED") Predicate nodeTerminated, - @Named("NODE_SUSPENDED") Predicate nodeSuspended, - InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess, - RunScriptOnNode.Factory runScriptOnNodeFactory, PersistNodeCredentials persistNodeCredentials, - Timeouts timeouts, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { + @Memoized Supplier> images, @Memoized Supplier> hardwareProfiles, + @Memoized Supplier> locations, ListNodesStrategy listNodesStrategy, + GetNodeMetadataStrategy getNodeMetadataStrategy, CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, + RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy, + ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy, + Provider templateBuilderProvider, Provider templateOptionsProvider, + @Named("NODE_RUNNING") Predicate nodeRunning, + @Named("NODE_TERMINATED") Predicate nodeTerminated, + @Named("NODE_SUSPENDED") Predicate nodeSuspended, + InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess, + RunScriptOnNode.Factory runScriptOnNodeFactory, PersistNodeCredentials persistNodeCredentials, + Timeouts timeouts, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { this.context = checkNotNull(context, "context"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); @@ -191,7 +190,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Set runNodesWithTag(String group, int count, Template template) - throws RunNodesException { + throws RunNodesException { return createNodesInGroup(group, count, template); } @@ -200,7 +199,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Set runNodesWithTag(String group, int count, TemplateOptions templateOptions) - throws RunNodesException { + throws RunNodesException { return createNodesInGroup(group, count, templateBuilder().any().options(templateOptions).build()); } @@ -214,12 +213,12 @@ public class BaseComputeService implements ComputeService { @Override public Set createNodesInGroup(String group, int count, Template template) - throws RunNodesException { + throws RunNodesException { checkNotNull(group, "group cannot be null"); checkNotNull(template.getLocation(), "location"); logger.debug(">> running %d node%s group(%s) location(%s) image(%s) hardwareProfile(%s) options(%s)", count, - count > 1 ? "s" : "", group, template.getLocation().getId(), template.getImage().getId(), template - .getHardware().getId(), template.getOptions()); + count > 1 ? "s" : "", group, template.getLocation().getId(), template.getImage().getId(), template + .getHardware().getId(), template.getOptions()); Set goodNodes = newLinkedHashSet(); Map badNodes = newLinkedHashMap(); Multimap customizationResponses = LinkedHashMultimap.create(); @@ -228,9 +227,9 @@ public class BaseComputeService implements ComputeService { initAdminAccess.visit(template.getOptions().getRunScript()); Map> responses = runNodesAndAddToSetStrategy.execute(group, count, template, goodNodes, badNodes, - customizationResponses); + customizationResponses); Map executionExceptions = awaitCompletion(responses, executor, null, logger, "runNodesWithTag(" - + group + ")"); + + group + ")"); Function fn = persistNodeCredentials.always(template.getOptions().getRunScript()); badNodes = Maps2.transformKeys(badNodes, fn); goodNodes = ImmutableSet.copyOf(Iterables.transform(goodNodes, fn)); @@ -242,7 +241,7 @@ public class BaseComputeService implements ComputeService { @Override public Set createNodesInGroup(String group, int count, TemplateOptions templateOptions) - throws RunNodesException { + throws RunNodesException { return createNodesInGroup(group, count, templateBuilder().any().options(templateOptions).build()); } @@ -288,27 +287,27 @@ public class BaseComputeService implements ComputeService { public Set destroyNodesMatching(Predicate filter) { logger.debug(">> destroying nodes matching(%s)", filter); Set set = newLinkedHashSet(transformParallel(nodesMatchingFilterAndNotTerminated(filter), - new Function>() { + new Function>() { - // TODO make an async interface instead of re-wrapping - @Override - public Future apply(final NodeMetadata from) { - return executor.submit(new Callable() { + // TODO make an async interface instead of re-wrapping + @Override + public Future apply(final NodeMetadata from) { + return executor.submit(new Callable() { - @Override - public NodeMetadata call() throws Exception { - destroyNode(from.getId()); - return from; - } + @Override + public NodeMetadata call() throws Exception { + destroyNode(from.getId()); + return from; + } - @Override - public String toString() { - return "destroyNode(" + from.getId() + ")"; - } - }); - } + @Override + public String toString() { + return "destroyNode(" + from.getId() + ")"; + } + }); + } - }, executor, null, logger, "destroyNodesMatching(" + filter + ")")); + }, executor, null, logger, "destroyNodesMatching(" + filter + ")")); logger.debug("<< destroyed(%d)", set.size()); return set; } @@ -322,7 +321,7 @@ public class BaseComputeService implements ComputeService { * if none found */ Iterable nodesMatchingFilterAndNotTerminatedExceptionIfNotFound( - Predicate filter) { + Predicate filter) { Iterable nodes = nodesMatchingFilterAndNotTerminated(filter); if (Iterables.size(nodes) == 0) throw new NoSuchElementException("no nodes matched filter: " + filter); @@ -412,15 +411,15 @@ public class BaseComputeService implements ComputeService { public void rebootNodesMatching(Predicate filter) { logger.debug(">> rebooting nodes matching(%s)", filter); transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), - new Function>() { - // TODO use native async - @Override - public Future apply(NodeMetadata from) { - rebootNode(from.getId()); - return immediateFuture(null); - } + new Function>() { + // TODO use native async + @Override + public Future apply(NodeMetadata from) { + rebootNode(from.getId()); + return immediateFuture(null); + } - }, executor, null, logger, "rebootNodesMatching(" + filter + ")"); + }, executor, null, logger, "rebootNodesMatching(" + filter + ")"); logger.debug("<< rebooted"); } @@ -443,15 +442,15 @@ public class BaseComputeService implements ComputeService { public void resumeNodesMatching(Predicate filter) { logger.debug(">> resuming nodes matching(%s)", filter); transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), - new Function>() { - // TODO use native async - @Override - public Future apply(NodeMetadata from) { - resumeNode(from.getId()); - return immediateFuture(null); - } + new Function>() { + // TODO use native async + @Override + public Future apply(NodeMetadata from) { + resumeNode(from.getId()); + return immediateFuture(null); + } - }, executor, null, logger, "resumeNodesMatching(" + filter + ")"); + }, executor, null, logger, "resumeNodesMatching(" + filter + ")"); logger.debug("<< resumed"); } @@ -474,15 +473,15 @@ public class BaseComputeService implements ComputeService { public void suspendNodesMatching(Predicate filter) { logger.debug(">> suspending nodes matching(%s)", filter); transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), - new Function>() { - // TODO use native async - @Override - public Future apply(NodeMetadata from) { - suspendNode(from.getId()); - return immediateFuture(null); - } + new Function>() { + // TODO use native async + @Override + public Future apply(NodeMetadata from) { + suspendNode(from.getId()); + return immediateFuture(null); + } - }, executor, null, logger, "suspendNodesMatching(" + filter + ")"); + }, executor, null, logger, "suspendNodesMatching(" + filter + ")"); logger.debug("<< suspended"); } @@ -491,7 +490,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, Payload runScript) - throws RunScriptOnNodesException { + throws RunScriptOnNodesException { return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE); } @@ -500,10 +499,10 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, Payload runScript, - RunScriptOptions options) throws RunScriptOnNodesException { + RunScriptOptions options) throws RunScriptOnNodesException { try { - return runScriptOnNodesMatching(filter, Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript, - "runScript").getInput())), options); + return runScriptOnNodesMatching(filter, + Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript, "runScript").getInput())), options); } catch (IOException e) { Throwables.propagate(e); return null; @@ -515,7 +514,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, String runScript) - throws RunScriptOnNodesException { + throws RunScriptOnNodesException { return runScriptOnNodesMatching(filter, Statements.exec(checkNotNull(runScript, "runScript"))); } @@ -524,13 +523,13 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, Statement runScript) - throws RunScriptOnNodesException { + throws RunScriptOnNodesException { return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE); } @Override public Map runScriptOnNodesMatching(Predicate filter, - String runScript, RunScriptOptions options) throws RunScriptOnNodesException { + String runScript, RunScriptOptions options) throws RunScriptOnNodesException { return runScriptOnNodesMatching(filter, Statements.exec(checkNotNull(runScript, "runScript")), options); } @@ -539,7 +538,7 @@ public class BaseComputeService implements ComputeService { */ @Override public Map runScriptOnNodesMatching(Predicate filter, Statement runScript, - RunScriptOptions options) throws RunScriptOnNodesException { + RunScriptOptions options) throws RunScriptOnNodesException { checkNotNull(filter, "filter"); checkNotNull(runScript, "runScript"); @@ -553,11 +552,11 @@ public class BaseComputeService implements ComputeService { initAdminAccess.visit(runScript); Iterable scriptRunners = transformNodesIntoInitializedScriptRunners( - nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), runScript, options, badNodes); + nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), runScript, options, badNodes); if (Iterables.size(scriptRunners) > 0) { for (RunScriptOnNode runner : scriptRunners) { responses.put(runner.getNode(), executor.submit(new RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap( - runner, goodNodes, badNodes))); + runner, goodNodes, badNodes))); } exceptions = awaitCompletion(responses, executor, null, logger, "runScriptOnNodesMatching(" + filter + ")"); } @@ -606,7 +605,7 @@ public class BaseComputeService implements ComputeService { throw new NoSuchElementException(id); if (node.getState() != NodeState.RUNNING) throw new IllegalStateException("node " + id - + " needs to be running before executing a script on it. current state: " + node.getState()); + + " needs to be running before executing a script on it. current state: " + node.getState()); initAdminAccess.visit(runScript); node = updateNodeWithCredentialsIfPresent(node, options); ExecResponse response = runScriptOnNodeFactory.create(node, runScript, options).init().call(); @@ -619,13 +618,13 @@ public class BaseComputeService implements ComputeService { */ @Override public ListenableFuture submitScriptOnNode(String id, final Statement runScript, - RunScriptOptions options) { + RunScriptOptions options) { NodeMetadata node = this.getNodeMetadata(id); if (node == null) throw new NoSuchElementException(id); if (node.getState() != NodeState.RUNNING) throw new IllegalStateException("node " + id - + " needs to be running before executing a script on it. current state: " + node.getState()); + + " needs to be running before executing a script on it. current state: " + node.getState()); initAdminAccess.visit(runScript); final NodeMetadata node1 = updateNodeWithCredentialsIfPresent(node, options); ListenableFuture response = runScriptOnNodeFactory.submit(node1, runScript, options); @@ -641,10 +640,11 @@ public class BaseComputeService implements ComputeService { } private Iterable transformNodesIntoInitializedScriptRunners( - Iterable nodes, Statement script, RunScriptOptions options, - Map badNodes) { - return filter(transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes), - executor, null, logger, "initialize script runners"), notNull()); + Iterable nodes, Statement script, RunScriptOptions options, + Map badNodes) { + return filter( + transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes), + executor, null, logger, "initialize script runners"), notNull()); } private Set detailsOnAllNodes() { @@ -658,31 +658,26 @@ public class BaseComputeService implements ComputeService { protected NodeMetadata updateNodeWithCredentialsIfPresent(NodeMetadata node, RunScriptOptions options) { checkNotNull(node, "node"); - if (options.getOverridingCredentials() != null) { - Builder builder = node.getCredentials() != null ? node.getCredentials().toBuilder() - : new Credentials.Builder(); - if (options.getOverridingCredentials().identity != null) - builder.identity(options.getOverridingCredentials().identity); - if (options.getOverridingCredentials().credential != null) { - // custom credentials are related to the input - builder = options.getOverridingCredentials().toBuilder(); - Credentials cred = builder.build(); - builder.identity(cred.identity); - builder.credential(options.getOverridingCredentials().credential); - } - node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(builder.build()).build(); - } - return node; + Builder builder = LoginCredentials.builder(node.getCredentials()); + if (options.getLoginUser() != null) + builder.user(options.getLoginUser()); + if (options.getLoginPassword() != null) + builder.password(options.getLoginPassword()); + if (options.getLoginPrivateKey() != null) + builder.privateKey(options.getLoginPrivateKey()); + if (options.shouldAuthenticateSudo() != null) + builder.authenticateSudo(true); + return NodeMetadataBuilder.fromNodeMetadata(node).credentials(builder.build()).build(); } private final class TransformNodesIntoInitializedScriptRunners implements - Function> { + Function> { private final Map badNodes; private final Statement script; private final RunScriptOptions options; private TransformNodesIntoInitializedScriptRunners(Statement script, RunScriptOptions options, - Map badNodes) { + Map badNodes) { this.badNodes = checkNotNull(badNodes, "badNodes"); this.script = checkNotNull(script, "script"); this.options = checkNotNull(options, "options"); diff --git a/compute/src/main/java/org/jclouds/compute/options/RunScriptOptions.java b/compute/src/main/java/org/jclouds/compute/options/RunScriptOptions.java index 51b4ba3ad4..4c6ce0e0e4 100644 --- a/compute/src/main/java/org/jclouds/compute/options/RunScriptOptions.java +++ b/compute/src/main/java/org/jclouds/compute/options/RunScriptOptions.java @@ -22,6 +22,9 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.util.CredentialUtils; /** * Enables additional options for running a script. @@ -52,12 +55,6 @@ public class RunScriptOptions { return delegate.toString(); } - @Override - public Credentials getOverridingCredentials() { - return delegate.getOverridingCredentials(); - - } - @Override public boolean shouldRunAsRoot() { return delegate.shouldRunAsRoot(); @@ -80,11 +77,62 @@ public class RunScriptOptions { throw new IllegalArgumentException("blockOnComplete is immutable"); } + @Override + public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { + throw new IllegalArgumentException("overridingCredentials is immutable"); + } + + @Override + public RunScriptOptions overrideLoginPassword(String password) { + throw new IllegalArgumentException("password is immutable"); + } + + @Override + public RunScriptOptions overrideLoginPrivateKey(String privateKey) { + throw new IllegalArgumentException("privateKey is immutable"); + } + + @Override + public RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) { + throw new IllegalArgumentException("authenticateSudo is immutable"); + } + + @Override + public String getLoginUser() { + return delegate.getLoginUser(); + } + + @Override + public Boolean shouldAuthenticateSudo() { + return delegate.shouldAuthenticateSudo(); + } + + @Override + public String getLoginPassword() { + return delegate.getLoginPassword(); + } + + @Override + public String getLoginPrivateKey() { + return delegate.getLoginPrivateKey(); + } + + @Override + public boolean shouldWrapInInitScript() { + return delegate.shouldWrapInInitScript(); + } + + @Deprecated @Override public RunScriptOptions overrideLoginUserWith(String loginUser) { throw new IllegalArgumentException("loginUser is immutable"); } + @Override + public RunScriptOptions overrideLoginUser(String loginUser) { + throw new IllegalArgumentException("loginUser is immutable"); + } + @Override public RunScriptOptions overrideLoginCredentialWith(String loginCredential) { throw new IllegalArgumentException("loginCredential is immutable"); @@ -95,6 +143,7 @@ public class RunScriptOptions { throw new IllegalArgumentException("wrapInInitScript is immutable"); } + @Deprecated @Override public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) { throw new IllegalArgumentException("overridingCredentials is immutable"); @@ -129,36 +178,72 @@ public class RunScriptOptions { protected int port = -1; protected int seconds = -1; protected String taskName; - protected Credentials overridingCredentials; protected boolean runAsRoot = true; protected boolean blockOnComplete = true; protected boolean wrapInInitScript = true; + protected String loginUser; + protected Boolean authenticateSudo; + protected String loginPassword; + protected String loginPrivateKey; + + @Deprecated public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) { + return overrideLoginCredentials(LoginCredentials.builder(overridingCredentials).build()); + } + + public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { checkNotNull(overridingCredentials, "overridingCredentials"); - this.overridingCredentials = overridingCredentials; + this.loginUser = overridingCredentials.getUser(); + this.loginPassword = overridingCredentials.getPassword(); + this.loginPrivateKey = overridingCredentials.getPrivateKey(); + this.authenticateSudo = overridingCredentials.shouldAuthenticateSudo() ? true : null; return this; } + @Deprecated public RunScriptOptions overrideLoginUserWith(String loginUser) { + return overrideLoginUser(loginUser); + } + + public RunScriptOptions overrideLoginUser(String loginUser) { checkNotNull(loginUser, "loginUser"); - org.jclouds.domain.Credentials.Builder builder = overridingCredentials != null ? overridingCredentials - .toBuilder() : new Credentials.Builder(); - this.overridingCredentials = builder.identity(loginUser).build(); + this.loginUser = loginUser; return this; } + @Deprecated public RunScriptOptions overrideLoginCredentialWith(String loginCredential) { checkNotNull(loginCredential, "loginCredential"); - org.jclouds.domain.Credentials.Builder builder = overridingCredentials != null ? overridingCredentials - .toBuilder() : new Credentials.Builder(); - this.overridingCredentials = builder.credential(loginCredential).build(); + if (CredentialUtils.isPrivateKeyCredential(loginCredential)) { + this.loginPrivateKey = loginCredential; + } else { + this.loginPassword = loginCredential; + } + return this; + } + + public RunScriptOptions overrideLoginPassword(String password) { + checkNotNull(password, "password"); + this.loginPassword = password; + return this; + } + + public RunScriptOptions overrideLoginPrivateKey(String privateKey) { + checkNotNull(privateKey, "privateKey"); + this.loginPrivateKey = privateKey; + return this; + } + + public RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) { + this.authenticateSudo = authenticateSudo; return this; } /** * @return What to call the task relating to this script; default - * {@code jclouds-script-timestamp} where timestamp is millis since epoch + * {@code jclouds-script-timestamp} where timestamp is millis since + * epoch * */ public RunScriptOptions nameTask(String name) { @@ -176,8 +261,9 @@ public class RunScriptOptions { *

* * @param wrapInInitScript - * if the command is long-running, use this option to ensure it is wrapInInitScripted - * properly. (ex. have jclouds wrap it an init script, nohup, etc) + * if the command is long-running, use this option to ensure it is + * wrapInInitScripted properly. (ex. have jclouds wrap it an init + * script, nohup, etc) * @return */ public RunScriptOptions wrapInInitScript(boolean wrapInInitScript) { @@ -189,10 +275,10 @@ public class RunScriptOptions { * As of version 1.1.0, we cannot kick off a script unless a node is in * RUNNING state. * - * @param blockOnComplete (default true) - * false means kick off the script in the background, but don't - * wait for it to finish. (as of version 1.1.0, implemented as - * nohup) + * @param blockOnComplete + * (default true) false means kick off the script in the + * background, but don't wait for it to finish. (as of version + * 1.1.0, implemented as nohup) */ public RunScriptOptions blockOnComplete(boolean blockOnComplete) { this.blockOnComplete = blockOnComplete; @@ -223,17 +309,52 @@ public class RunScriptOptions { } /** - * Whether to override the credentials with ones supplied in call to - * {@link org.jclouds.compute.ComputeService#runScriptOnNodesWithTag}. By default, true. * - * @return value + * @return the login user for + * {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By + * default, null. */ - public Credentials getOverridingCredentials() { - return overridingCredentials; + @Nullable + public String getLoginUser() { + return loginUser; } /** - * Whether to run the script as root (or run with current privileges). By default, true. + * + * @return Whether the login user should authenticate sudo during + * {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By + * default, null. + */ + @Nullable + public Boolean shouldAuthenticateSudo() { + return authenticateSudo; + } + + /** + * + * @return the login password for + * {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By + * default, null. + */ + @Nullable + public String getLoginPassword() { + return loginPassword; + } + + /** + * + * @return the login ssh key for + * {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By + * default, null. + */ + @Nullable + public String getLoginPrivateKey() { + return loginPrivateKey; + } + + /** + * Whether to run the script as root (or run with current privileges). By + * default, true. * * @return value */ @@ -264,26 +385,54 @@ public class RunScriptOptions { return options.nameTask(name); } + @Deprecated public static RunScriptOptions overrideLoginUserWith(String user) { RunScriptOptions options = new RunScriptOptions(); return options.overrideLoginUserWith(user); } + public static RunScriptOptions overrideLoginUser(String user) { + RunScriptOptions options = new RunScriptOptions(); + return options.overrideLoginUser(user); + } + + public static RunScriptOptions overrideLoginPassword(String password) { + RunScriptOptions options = new RunScriptOptions(); + return options.overrideLoginPassword(password); + } + + public static RunScriptOptions overrideLoginPrivateKey(String privateKey) { + RunScriptOptions options = new RunScriptOptions(); + return options.overrideLoginPrivateKey(privateKey); + } + + public static RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) { + RunScriptOptions options = new RunScriptOptions(); + return options.overrideAuthenticateSudo(authenticateSudo); + } + + @Deprecated public static RunScriptOptions overrideLoginCredentialWith(String credential) { RunScriptOptions options = new RunScriptOptions(); return options.overrideLoginCredentialWith(credential); } + @Deprecated public static RunScriptOptions overrideCredentialsWith(Credentials credentials) { RunScriptOptions options = new RunScriptOptions(); return options.overrideCredentialsWith(credentials); } + public static RunScriptOptions overrideLoginCredentials(LoginCredentials credentials) { + RunScriptOptions options = new RunScriptOptions(); + return options.overrideLoginCredentials(credentials); + } + public static RunScriptOptions runAsRoot(boolean value) { RunScriptOptions options = new RunScriptOptions(); return options.runAsRoot(value); } - + /** * @see RunScriptOptions#blockOnComplete(boolean) */ @@ -306,9 +455,74 @@ public class RunScriptOptions { @Override public String toString() { - return "[overridingCredentials=" + (overridingCredentials != null) + ", port:seconds=" + port + ":" + seconds - + ", runAsRoot=" + runAsRoot + ", blockOnComplete=" + blockOnComplete + ", wrapInInitScript=" - + wrapInInitScript + "]"; + return "[loginUser=" + loginUser + ", loginPasswordPresent=" + (loginPassword != null) + + ", loginPrivateKeyPresent=" + (loginPrivateKey != null) + ", shouldAuthenticateSudo=" + authenticateSudo + + ", port:seconds=" + port + ":" + seconds + ", runAsRoot=" + runAsRoot + ", blockOnComplete=" + + blockOnComplete + ", wrapInInitScript=" + wrapInInitScript + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((authenticateSudo == null) ? 0 : authenticateSudo.hashCode()); + result = prime * result + (blockOnComplete ? 1231 : 1237); + result = prime * result + ((loginPassword == null) ? 0 : loginPassword.hashCode()); + result = prime * result + ((loginPrivateKey == null) ? 0 : loginPrivateKey.hashCode()); + result = prime * result + ((loginUser == null) ? 0 : loginUser.hashCode()); + result = prime * result + port; + result = prime * result + (runAsRoot ? 1231 : 1237); + result = prime * result + seconds; + result = prime * result + ((taskName == null) ? 0 : taskName.hashCode()); + result = prime * result + (wrapInInitScript ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RunScriptOptions other = (RunScriptOptions) obj; + if (authenticateSudo == null) { + if (other.authenticateSudo != null) + return false; + } else if (!authenticateSudo.equals(other.authenticateSudo)) + return false; + if (blockOnComplete != other.blockOnComplete) + return false; + if (loginPassword == null) { + if (other.loginPassword != null) + return false; + } else if (!loginPassword.equals(other.loginPassword)) + return false; + if (loginPrivateKey == null) { + if (other.loginPrivateKey != null) + return false; + } else if (!loginPrivateKey.equals(other.loginPrivateKey)) + return false; + if (loginUser == null) { + if (other.loginUser != null) + return false; + } else if (!loginUser.equals(other.loginUser)) + return false; + if (port != other.port) + return false; + if (runAsRoot != other.runAsRoot) + return false; + if (seconds != other.seconds) + return false; + if (taskName == null) { + if (other.taskName != null) + return false; + } else if (!taskName.equals(other.taskName)) + return false; + if (wrapInInitScript != other.wrapInInitScript) + return false; + return true; } } diff --git a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java index 8e4fcdb507..2e2d3df0a7 100644 --- a/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java +++ b/compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java @@ -28,6 +28,7 @@ import java.util.Set; import org.jclouds.compute.domain.NodeState; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.io.Payload; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statements; @@ -82,8 +83,14 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { to.blockUntilRunning(false); if (!this.shouldBlockOnComplete()) to.blockOnComplete(false); - if (this.getOverridingCredentials() != null) - to.overrideCredentialsWith(this.getOverridingCredentials()); + if (this.getLoginUser() != null) + to.overrideLoginUser(this.getLoginUser()); + if (this.getLoginPassword() != null) + to.overrideLoginPassword(this.getLoginPassword()); + if (this.getLoginPrivateKey() != null) + to.overrideLoginPrivateKey(this.getLoginPrivateKey()); + if (this.shouldAuthenticateSudo() != null) + to.overrideAuthenticateSudo(this.shouldAuthenticateSudo()); if (this.getTaskName() != null) to.nameTask(this.getTaskName()); } @@ -113,11 +120,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { return delegate.getSeconds(); } - @Override - public Credentials getOverridingCredentials() { - return delegate.getOverridingCredentials(); - } - @Override public boolean shouldRunAsRoot() { return delegate.shouldRunAsRoot(); @@ -191,21 +193,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { throw new IllegalArgumentException("runAsRoot is immutable"); } - @Override - public TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { - throw new IllegalArgumentException("credentials are immutable"); - } - - @Override - public TemplateOptions overrideLoginUserWith(String loginUser) { - throw new IllegalArgumentException("credentials are immutable"); - } - - @Override - public TemplateOptions overrideLoginCredentialWith(String loginCredential) { - throw new IllegalArgumentException("credentials are immutable"); - } - @Override public TemplateOptions wrapInInitScript(boolean wrapInInitScript) { throw new IllegalArgumentException("wrapInInitScript is immutable"); @@ -216,6 +203,68 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { throw new IllegalArgumentException("blockOnComplete is immutable"); } + @Override + public TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { + throw new IllegalArgumentException("overridingCredentials is immutable"); + } + + @Override + public TemplateOptions overrideLoginPassword(String password) { + throw new IllegalArgumentException("password is immutable"); + } + + @Override + public TemplateOptions overrideLoginPrivateKey(String privateKey) { + throw new IllegalArgumentException("privateKey is immutable"); + } + + @Override + public TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) { + throw new IllegalArgumentException("authenticateSudo is immutable"); + } + + @Override + public String getLoginUser() { + return delegate.getLoginUser(); + } + + @Override + public Boolean shouldAuthenticateSudo() { + return delegate.shouldAuthenticateSudo(); + } + + @Override + public String getLoginPassword() { + return delegate.getLoginPassword(); + } + + @Override + public String getLoginPrivateKey() { + return delegate.getLoginPrivateKey(); + } + + @Deprecated + @Override + public TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { + throw new IllegalArgumentException("overridingCredentials is immutable"); + } + + @Deprecated + @Override + public TemplateOptions overrideLoginUserWith(String loginUser) { + throw new IllegalArgumentException("loginUser is immutable"); + } + + @Override + public TemplateOptions overrideLoginUser(String loginUser) { + throw new IllegalArgumentException("loginUser is immutable"); + } + + @Override + public TemplateOptions overrideLoginCredentialWith(String loginCredential) { + throw new IllegalArgumentException("loginCredential is immutable"); + } + @Override public T as(Class clazz) { return delegate.as(clazz); @@ -465,21 +514,49 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { return options.nameTask(name); } + @Deprecated public static TemplateOptions overrideLoginUserWith(String user) { TemplateOptions options = new TemplateOptions(); return options.overrideLoginUserWith(user); } + public static TemplateOptions overrideLoginUser(String user) { + TemplateOptions options = new TemplateOptions(); + return options.overrideLoginUser(user); + } + + public static TemplateOptions overrideLoginPassword(String password) { + TemplateOptions options = new TemplateOptions(); + return options.overrideLoginPassword(password); + } + + public static TemplateOptions overrideLoginPrivateKey(String privateKey) { + TemplateOptions options = new TemplateOptions(); + return options.overrideLoginPrivateKey(privateKey); + } + + public static TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) { + TemplateOptions options = new TemplateOptions(); + return options.overrideAuthenticateSudo(authenticateSudo); + } + + @Deprecated public static TemplateOptions overrideLoginCredentialWith(String credential) { TemplateOptions options = new TemplateOptions(); return options.overrideLoginCredentialWith(credential); } + @Deprecated public static TemplateOptions overrideCredentialsWith(Credentials credentials) { TemplateOptions options = new TemplateOptions(); return options.overrideCredentialsWith(credentials); } + public static TemplateOptions overrideLoginCredentials(LoginCredentials credentials) { + TemplateOptions options = new TemplateOptions(); + return options.overrideLoginCredentials(credentials); + } + public static TemplateOptions runAsRoot(boolean value) { TemplateOptions options = new TemplateOptions(); return options.runAsRoot(value); @@ -736,21 +813,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { return TemplateOptions.class.cast(super.runAsRoot(runAsRoot)); } - @Override - public TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { - return TemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials)); - } - - @Override - public TemplateOptions overrideLoginUserWith(String loginUser) { - return TemplateOptions.class.cast(super.overrideLoginUserWith(loginUser)); - } - - @Override - public TemplateOptions overrideLoginCredentialWith(String loginCredential) { - return TemplateOptions.class.cast(super.overrideLoginCredentialWith(loginCredential)); - } - @Override public TemplateOptions wrapInInitScript(boolean wrapInInitScript) { return TemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript)); @@ -760,4 +822,48 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions blockOnComplete(boolean blockOnComplete) { return TemplateOptions.class.cast(super.blockOnComplete(blockOnComplete)); } + + @Deprecated + @Override + public TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { + return TemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials)); + } + + @Deprecated + @Override + public TemplateOptions overrideLoginUserWith(String loginUser) { + return TemplateOptions.class.cast(super.overrideLoginUserWith(loginUser)); + } + + @Deprecated + @Override + public TemplateOptions overrideLoginCredentialWith(String loginCredential) { + return TemplateOptions.class.cast(super.overrideLoginCredentialWith(loginCredential)); + } + + @Override + public TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { + return TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials)); + } + + @Override + public TemplateOptions overrideLoginPassword(String password) { + return TemplateOptions.class.cast(super.overrideLoginPassword(password)); + } + + @Override + public TemplateOptions overrideLoginPrivateKey(String privateKey) { + return TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey)); + } + + @Override + public TemplateOptions overrideLoginUser(String loginUser) { + return TemplateOptions.class.cast(super.overrideLoginUser(loginUser)); + } + + @Override + public TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) { + return TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo)); + } + } diff --git a/compute/src/main/java/org/jclouds/compute/strategy/PopulateDefaultLoginCredentialsForImageStrategy.java b/compute/src/main/java/org/jclouds/compute/strategy/PopulateDefaultLoginCredentialsForImageStrategy.java index b273dd8815..8b29416a14 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/PopulateDefaultLoginCredentialsForImageStrategy.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/PopulateDefaultLoginCredentialsForImageStrategy.java @@ -20,26 +20,39 @@ package org.jclouds.compute.strategy; import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import com.google.common.base.Function; import com.google.inject.ImplementedBy; /** * @author Oleksiy Yarmula */ @ImplementedBy(ReturnCredentialsBoundToImage.class) -public interface PopulateDefaultLoginCredentialsForImageStrategy { - - /** - * Processes the resource to determine credentials. - * - * @param resourceToAuthenticate - * this can be any resource, such as an image, - * running server instance or other. It's the - * responsibility of an implementation to apply - * the cloud-specific logic. - * @return credentials object. Note: the key - * may not be set, but the identity must be set - */ - Credentials execute(Object resourceToAuthenticate); +public interface PopulateDefaultLoginCredentialsForImageStrategy extends Function { + /** + *

will be removed in jclouds 1.4.0


+ * + * Processes the resource to determine credentials. + * + * @param resourceToAuthenticate + * this can be any resource, such as an image, running server + * instance or other. It's the responsibility of an implementation + * to apply the cloud-specific logic. + * @return credentials object. Note: the key may not be set, but the identity + * must be set + */ + @Deprecated + Credentials execute(Object resourceToAuthenticate); + + /** + * + * Processes the cloud-specific resources to determine the login credentials. + * + * @param resourceToAuthenticate + * this is the cloud-specific representation of the image object. + * @return credentials parsed from the image if not null + */ + LoginCredentials apply(Object image); } diff --git a/compute/src/main/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplate.java b/compute/src/main/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplate.java index 3d5319414b..1f4f357988 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplate.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplate.java @@ -19,13 +19,13 @@ package org.jclouds.compute.strategy; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.domain.Credentials.NO_CREDENTIALS; import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.domain.LoginCredentials.Builder; import com.google.common.base.Function; @@ -35,25 +35,29 @@ import com.google.common.base.Function; */ @Singleton public class PrioritizeCredentialsFromTemplate { - private final Function credentialsFromImageOrTemplateOptions; + private final Function credentialsFromImageOrTemplateOptions; @Inject - public PrioritizeCredentialsFromTemplate(Function credentialsFromImageOrTemplateOptions) { + public PrioritizeCredentialsFromTemplate(Function credentialsFromImageOrTemplateOptions) { this.credentialsFromImageOrTemplateOptions = checkNotNull(credentialsFromImageOrTemplateOptions, "credentialsFromImageOrTemplateOptions"); } - public Credentials apply(Template template, Credentials fromNode) { - Credentials creds = (fromNode != null) ? fromNode : NO_CREDENTIALS; - Credentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template); + public LoginCredentials apply(Template template, LoginCredentials fromNode) { + LoginCredentials creds = fromNode; + LoginCredentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template); if (credsFromParameters != null) { - if (credsFromParameters.identity != null) - creds = creds.toBuilder().identity(credsFromParameters.identity).build(); - if (credsFromParameters.credential != null) - creds = creds.toBuilder().credential(credsFromParameters.credential).build(); + Builder builder = LoginCredentials.builder(creds); + if (credsFromParameters.getUser() != null) + builder.user(credsFromParameters.getUser()); + if (credsFromParameters.getPassword() != null) + builder.password(credsFromParameters.getPassword()); + if (credsFromParameters.getPrivateKey() != null) + builder.privateKey(credsFromParameters.getPrivateKey()); + if (credsFromParameters.shouldAuthenticateSudo()) + builder.authenticateSudo(true); + creds = builder.build(); } - if (creds.equals(NO_CREDENTIALS)) - creds = null; return creds; } diff --git a/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java b/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java index a583ba96eb..4e5febc51d 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java @@ -32,6 +32,7 @@ import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.Template; import org.jclouds.compute.predicates.NodePredicates; @@ -45,9 +46,11 @@ import org.jclouds.compute.strategy.RebootNodeStrategy; import org.jclouds.compute.strategy.ResumeNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import com.google.common.base.Function; +import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; @@ -76,9 +79,25 @@ public class AdaptingComputeServiceStrategies implements CreateNodeW this.prioritizeCredentialsFromTemplate = checkNotNull(prioritizeCredentialsFromTemplate, "prioritizeCredentialsFromTemplate"); this.client = checkNotNull(client, "client"); - this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter"); + this.nodeMetadataAdapter = Functions.compose(addLoginCredentials, + checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter")); } + private final Function addLoginCredentials = new Function() { + + @Override + public NodeMetadata apply(NodeMetadata arg0) { + return credentialStore.containsKey("node#" + arg0.getId()) ? NodeMetadataBuilder.fromNodeMetadata(arg0) + .credentials(LoginCredentials.builder(credentialStore.get("node#" + arg0.getId())).build()).build() + : arg0; + } + + @Override + public String toString() { + return "addLoginCredentialsFromCredentialStore()"; + } + }; + @Override public Iterable listNodes() { return listDetailsOnNodesMatching(NodePredicates.all()); @@ -92,7 +111,9 @@ public class AdaptingComputeServiceStrategies implements CreateNodeW @Override public NodeMetadata getNode(String id) { N node = client.getNode(checkNotNull(id, "id")); - return node == null ? null : nodeMetadataAdapter.apply(node); + if (node == null) + return null; + return nodeMetadataAdapter.apply(node); } @Override @@ -141,8 +162,8 @@ public class AdaptingComputeServiceStrategies implements CreateNodeW checkState(template != null, "template must be specified"); NodeAndInitialCredentials from = client.createNodeWithGroupEncodedIntoName(group, name, template); - Credentials fromNode = from.getCredentials(); - Credentials creds = prioritizeCredentialsFromTemplate.apply(template, fromNode); + LoginCredentials fromNode = from.getCredentials(); + LoginCredentials creds = prioritizeCredentialsFromTemplate.apply(template, fromNode); if (creds != null) credentialStore.put("node#" + from.getNodeId(), creds); NodeMetadata node = nodeMetadataAdapter.apply(from.getNode()); diff --git a/compute/src/main/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImage.java b/compute/src/main/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImage.java index eeacda820d..3c528359d9 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImage.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImage.java @@ -28,6 +28,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; /** @@ -36,23 +37,28 @@ import org.jclouds.javax.annotation.Nullable; @Singleton public class ReturnCredentialsBoundToImage implements PopulateDefaultLoginCredentialsForImageStrategy { - protected final Credentials creds; + protected final LoginCredentials creds; @Inject - public ReturnCredentialsBoundToImage(@Nullable @Named("image") Credentials creds) { + public ReturnCredentialsBoundToImage(@Nullable @Named("image") LoginCredentials creds) { this.creds = creds; } @Override - public Credentials execute(Object resourceToAuthenticate) { + public LoginCredentials apply(Object resourceToAuthenticate) { checkState(resourceToAuthenticate instanceof Image, "this is only valid for images"); if (creds != null) return creds; Image image = Image.class.cast(resourceToAuthenticate); if (image.getOperatingSystem() != null && OsFamily.WINDOWS.equals(image.getOperatingSystem().getFamily())) { - return new Credentials("Administrator", null); + return LoginCredentials.builder().user("Administrator").build(); } else { - return new Credentials("root", null); + return LoginCredentials.builder().user("root").build(); } } + + @Override + public Credentials execute(Object resourceToAuthenticate) { + return apply(resourceToAuthenticate); + } } diff --git a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java index 4817d5072d..fa93c4a5c0 100644 --- a/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java +++ b/compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java @@ -38,8 +38,8 @@ import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.location.suppliers.JustProvider; import org.jclouds.rest.ResourceNotFoundException; @@ -63,14 +63,12 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda private final String passwordPrefix; private final Supplier> locationSupplier; private final Map> osToVersionMap; - private final Map credentialStore; @Inject public StubComputeServiceAdapter(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, - JustProvider locationSupplier, Map> osToVersionMap, - Map credentialStore) { + JustProvider locationSupplier, Map> osToVersionMap) { this.nodes = nodes; this.location = location; this.idProvider = idProvider; @@ -79,7 +77,6 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda this.passwordPrefix = passwordPrefix; this.locationSupplier = locationSupplier; this.osToVersionMap = osToVersionMap; - this.credentialStore = credentialStore; } @Override @@ -99,9 +96,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda builder.state(NodeState.PENDING); builder.publicAddresses(ImmutableSet. of(publicIpPrefix + id)); builder.privateAddresses(ImmutableSet. of(privateIpPrefix + id)); - builder.credentials(new Credentials(null, passwordPrefix + id)); + builder.credentials(LoginCredentials.builder().user("root").password(passwordPrefix + id).build()); NodeMetadata node = builder.build(); - credentialStore.put("node#" + node.getId(), node.getCredentials()); nodes.put(node.getId(), node); StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100); return new NodeWithInitialCredentials(node); @@ -116,7 +112,6 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda @Override public Iterable listImages() { - Credentials defaultCredentials = new Credentials("root", null); // initializing as a List, as ImmutableSet does not allow you to put // duplicates Builder images = ImmutableList. builder(); @@ -127,7 +122,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda String desc = String.format("stub %s %s", osVersions.getKey(), is64Bit); images.add(new ImageBuilder().ids(id++ + "").name(osVersions.getKey().name()).location(location.get()) .operatingSystem(new OperatingSystem(osVersions.getKey(), desc, version, null, desc, is64Bit)) - .description(desc).defaultCredentials(defaultCredentials).build()); + .description(desc).build()); } } return images.build(); @@ -146,9 +141,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda @Override public NodeMetadata getNode(String id) { - NodeMetadata node = nodes.get(id); - return node == null ? null : NodeMetadataBuilder.fromNodeMetadata(node) - .credentials(credentialStore.get("node#" + node.getId())).build(); + return nodes.get(id); } @Override diff --git a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java index b449360a7c..73db4e40c6 100644 --- a/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseComputeServiceLiveTest.java @@ -40,7 +40,7 @@ import static org.jclouds.compute.RunScriptData.startJBoss; import static org.jclouds.compute.options.RunScriptOptions.Builder.nameTask; import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; import static org.jclouds.compute.options.TemplateOptions.Builder.inboundPorts; -import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; +import static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials; import static org.jclouds.compute.options.TemplateOptions.Builder.runAsRoot; import static org.jclouds.compute.predicates.NodePredicates.TERMINATED; import static org.jclouds.compute.predicates.NodePredicates.all; @@ -85,6 +85,7 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.net.IPSocket; import org.jclouds.predicates.RetryablePredicate; @@ -228,13 +229,13 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv try { Set nodes = client.createNodesInGroup(group, 1, options); NodeMetadata node = get(nodes, 0); - Credentials good = node.getCredentials(); + LoginCredentials good = node.getCredentials(); assert good.identity != null : nodes; assert good.credential != null : nodes; for (Entry response : client.runScriptOnNodesMatching( runningInGroup(group), Statements.exec("hostname"), - wrapInInitScript(false).runAsRoot(false).overrideCredentialsWith(good)).entrySet()) { + wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(good)).entrySet()) { checkResponseEqualsHostname(response.getValue(), response.getKey()); } @@ -281,10 +282,12 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv @Test(enabled = false) protected void tryBadPassword(String group, Credentials good) throws AssertionError { try { - Map responses = client.runScriptOnNodesMatching(runningInGroup(group), + Map responses = client.runScriptOnNodesMatching( + runningInGroup(group), "echo I put a bad password", - wrapInInitScript(false).runAsRoot(false) - .overrideCredentialsWith(new Credentials(good.identity, "romeo"))); + wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials( + LoginCredentials.builder().user(good.identity).credential(null).privateKey(null).password("romeo") + .build())); assert responses.size() == 0 : "shouldn't pass with a bad password\n" + responses; } catch (AssertionError e) { throw e; @@ -433,8 +436,8 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv } protected Map runScriptWithCreds(final String group, OperatingSystem os, - Credentials creds) throws RunScriptOnNodesException { - return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + LoginCredentials creds) throws RunScriptOnNodesException { + return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideLoginCredentials(creds) .nameTask("runScriptWithCreds")); } diff --git a/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java index 64333ac214..a862f57bb8 100644 --- a/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java @@ -37,9 +37,9 @@ import org.jclouds.compute.domain.OsFamilyVersion64Bit; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule; @@ -257,8 +257,8 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi @Test public void testTemplateBuilderWithLoginUserSpecified() throws IOException { - tryOverrideUsingPropertyKey("jclouds.login-user"); - tryOverrideUsingPropertyKey(provider + ".login-user"); + tryOverrideUsingPropertyKey("jclouds"); + tryOverrideUsingPropertyKey(provider); } protected void tryOverrideUsingPropertyKey(String propertyKey) { @@ -266,7 +266,9 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi try { Properties overrides = setupProperties(); String login = loginUser != null ? loginUser : "foo:bar"; - overrides.setProperty(propertyKey, login); + overrides.setProperty(propertyKey + ".image.login-user", login); + boolean auth = authenticateSudo != null ? Boolean.valueOf(authenticateSudo) : true; + overrides.setProperty(propertyKey + ".image.authenticate-sudo", auth + ""); context = new ComputeServiceContextFactory().createContext(provider, ImmutableSet. of(new Log4JLoggingModule()), overrides); @@ -275,7 +277,7 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi String user = Iterables.get(userPass, 0); String pass = Iterables.size(userPass) > 1 ? Iterables.get(userPass, 1) : null; assertEquals(context.getComputeService().templateBuilder().build().getImage().getDefaultCredentials(), - new Credentials(user, pass)); + LoginCredentials.builder().user(user).password(pass).authenticateSudo(auth).build()); } finally { if (context != null) context.close(); diff --git a/compute/src/test/java/org/jclouds/compute/BaseVersionedServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/BaseVersionedServiceLiveTest.java index 2249a4cf36..309cc2bd4d 100644 --- a/compute/src/test/java/org/jclouds/compute/BaseVersionedServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/BaseVersionedServiceLiveTest.java @@ -33,7 +33,7 @@ import org.testng.annotations.BeforeClass; */ public abstract class BaseVersionedServiceLiveTest { protected String prefix = System.getProperty("user.name"); - + protected String provider; protected String identity; protected String credential; @@ -41,6 +41,7 @@ public abstract class BaseVersionedServiceLiveTest { protected String apiversion; protected String imageId; protected String loginUser; + protected String authenticateSudo; protected Properties setupRestProperties() { return RestContextFactory.getPropertiesFromResource("/rest.properties"); @@ -68,7 +69,9 @@ public abstract class BaseVersionedServiceLiveTest { if (imageId != null) overrides.setProperty(provider + ".image-id", imageId); if (loginUser != null) - overrides.setProperty(provider + ".login-user", loginUser); + overrides.setProperty(provider + ".image.login-user", loginUser); + if (authenticateSudo != null) + overrides.setProperty(provider + ".image.authenticate-sudo", authenticateSudo); return overrides; } @@ -80,7 +83,8 @@ public abstract class BaseVersionedServiceLiveTest { endpoint = System.getProperty("test." + provider + ".endpoint"); apiversion = System.getProperty("test." + provider + ".apiversion"); imageId = System.getProperty("test." + provider + ".image-id"); - loginUser = System.getProperty("test." + provider + ".login-user"); + loginUser = System.getProperty("test." + provider + ".image.login-user"); + authenticateSudo = System.getProperty("test." + provider + ".image.authenticate-sudo"); } } diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java index 6f2e092c85..3655c782c6 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java @@ -35,7 +35,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.scriptbuilder.InitBuilder; import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.Statement; @@ -84,7 +84,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).build(); + new LoginCredentials("tester", "testpassword!", null, false)).build(); SshClient sshClient = createMock(SshClient.class); @@ -101,7 +101,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testDefault() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).build(); + new LoginCredentials("tester", "testpassword!", null, false)).build(); SshClient sshClient = createMock(SshClient.class); @@ -150,7 +150,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testWithSudoPassword() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).adminPassword("rootme").build(); + new LoginCredentials("tester", "testpassword!", null, true)).build(); SshClient sshClient = createMock(SshClient.class); @@ -169,7 +169,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0)); // since there's an adminPassword we must pass this in - expect(sshClient.exec("echo 'rootme'|sudo -S ./jclouds-script-0 start")).andReturn(new ExecResponse("", "", 0)); + expect(sshClient.exec("echo 'testpassword!'|sudo -S ./jclouds-script-0 start")).andReturn(new ExecResponse("", "", 0)); // signal the command completed expect(sshClient.exec("./jclouds-script-0 status")).andReturn(new ExecResponse("", "", 1)); @@ -198,7 +198,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest { public void testNotRoot() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).adminPassword("rootme").build(); + new LoginCredentials("tester", "testpassword!", null, true)).build(); SshClient sshClient = createMock(SshClient.class); diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java index 16878c855f..bb74d982d9 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java @@ -30,7 +30,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.options.RunScriptOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.scriptbuilder.InitBuilder; import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.Statement; @@ -51,7 +51,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).build(); + LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -67,7 +67,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testDefault() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).build(); + LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -108,7 +108,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testWithSudoPassword() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).adminPassword("rootme").build(); + LoginCredentials.builder().user("tester").password("notalot").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); @@ -126,7 +126,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0)); // since there's an adminPassword we must pass this in - expect(sshClient.exec("echo 'rootme'|sudo -S ./jclouds-script-0 start")).andReturn(new ExecResponse("", "", 0)); + expect(sshClient.exec("echo 'notalot'|sudo -S ./jclouds-script-0 start")).andReturn(new ExecResponse("", "", 0)); sshClient.disconnect(); @@ -150,7 +150,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest { public void testNotRoot() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( - new Credentials("tester", "notalot")).adminPassword("rootme").build(); + LoginCredentials.builder().user("tester").password("notalot").authenticateSudo(true).build()).build(); SshClient sshClient = createMock(SshClient.class); diff --git a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java index 7674ce26fa..2c117ff8c1 100644 --- a/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java +++ b/compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java @@ -26,7 +26,7 @@ import static org.jclouds.scriptbuilder.domain.Statements.exec; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; import org.jclouds.scriptbuilder.statements.login.UserAdd; import org.jclouds.ssh.SshClient; @@ -38,104 +38,98 @@ import com.google.common.base.Function; /** * @author Adam Lowe */ -@Test(groups={"unit"}, singleThreaded = true) -public class RunScriptOnNodeUsingSshTest { - private SshClient sshClient; - private NodeMetadata node; - private Function sshFactory; +@Test(groups = { "unit" }, singleThreaded = true) +public class RunScriptOnNodeUsingSshTest { + private SshClient sshClient; + private NodeMetadata node; + private Function sshFactory; - @BeforeMethod(groups={"unit"}) - public void init() { - sshClient = createMock(SshClient.class); - sshFactory = new Function() { - @Override - public SshClient apply(@Nullable NodeMetadata nodeMetadata) { - return sshClient; - } - }; - node = createMock(NodeMetadata.class); - expect(node.getCredentials()).andReturn(new Credentials("tester", "notalot")); - expect(node.getAdminPassword()).andReturn(null).atLeastOnce(); - replay(node); - } + @BeforeMethod(groups = { "unit" }) + public void init() { + sshClient = createMock(SshClient.class); + sshFactory = new Function() { + @Override + public SshClient apply(@Nullable NodeMetadata nodeMetadata) { + return sshClient; + } + }; + node = createMock(NodeMetadata.class); + expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "notalot", null, false)).atLeastOnce(); + replay(node); + } - public void simpleTest() { - RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), - wrapInInitScript(false).runAsRoot(false)); + public void simpleTest() { + RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), + wrapInInitScript(false).runAsRoot(false)); - testMe.init(); + testMe.init(); - sshClient.connect(); - expect(sshClient.getUsername()).andReturn("tester"); - expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); - expect(sshClient.exec("echo $USER\n" + - "echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0)); - sshClient.disconnect(); - replay(sshClient); + sshClient.connect(); + expect(sshClient.getUsername()).andReturn("tester"); + expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); + expect(sshClient.exec("echo $USER\n" + "echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0)); + sshClient.disconnect(); + replay(sshClient); - testMe.call(); - } + testMe.call(); + } - public void simpleRootTest() { - RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), - wrapInInitScript(false).runAsRoot(true)); + public void simpleRootTest() { + RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), + wrapInInitScript(false).runAsRoot(true)); - testMe.init(); + testMe.init(); - sshClient.connect(); - expect(sshClient.getUsername()).andReturn("tester"); - expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); - expect(sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + - "echo $USER\n" + - "echo $USER\n" + - "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); - sshClient.disconnect(); - replay(sshClient); + sshClient.connect(); + expect(sshClient.getUsername()).andReturn("tester"); + expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); + expect( + sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "echo $USER\n" + "echo $USER\n" + + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); + sshClient.disconnect(); + replay(sshClient); - testMe.call(); - } + testMe.call(); + } - public void simpleRootTestWithSudoPassword() { - node = createMock(NodeMetadata.class); - expect(node.getCredentials()).andReturn(new Credentials("tester", "notalot")); - expect(node.getAdminPassword()).andReturn("testpassword!").atLeastOnce(); - replay(node); - RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), - wrapInInitScript(false).runAsRoot(true)); - testMe.init(); + public void simpleRootTestWithSudoPassword() { + node = createMock(NodeMetadata.class); + expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "testpassword!", null, true)) + .atLeastOnce(); + replay(node); + RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), + wrapInInitScript(false).runAsRoot(true)); + testMe.init(); - sshClient.connect(); - expect(sshClient.getUsername()).andReturn("tester"); - expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); - expect(sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + - "testpassword!\n" + - "echo $USER\n" + - "echo $USER\n" + - "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); - sshClient.disconnect(); - replay(sshClient); + sshClient.connect(); + expect(sshClient.getUsername()).andReturn("tester"); + expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); + expect( + sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "testpassword!\n" + "echo $USER\n" + + "echo $USER\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0)); + sshClient.disconnect(); + replay(sshClient); - testMe.call(); - } + testMe.call(); + } - public void testUserAddAsRoot() { - RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, - UserAdd.builder().login("testuser").build(), - wrapInInitScript(false).runAsRoot(true).overrideLoginCredentialWith("test")); + public void testUserAddAsRoot() { + RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, UserAdd.builder() + .login("testuser").build(), wrapInInitScript(false).runAsRoot(true).overrideLoginPassword("test")); - testMe.init(); + testMe.init(); - sshClient.connect(); - expect(sshClient.getUsername()).andReturn("tester"); - expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); - expect(sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + - "mkdir -p /home/users\n" + - "useradd -s /bin/bash -m -d /home/users/testuser testuser\n" + - "chown -R testuser /home/users/testuser\n" + - "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("done", null, 0)); - sshClient.disconnect(); - replay(sshClient); + sshClient.connect(); + expect(sshClient.getUsername()).andReturn("tester"); + expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); + expect( + sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "mkdir -p /home/users\n" + + "useradd -s /bin/bash -m -d /home/users/testuser testuser\n" + + "chown -R testuser /home/users/testuser\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn( + new ExecResponse("done", null, 0)); + sshClient.disconnect(); + replay(sshClient); - testMe.call(); - } + testMe.call(); + } } diff --git a/compute/src/test/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest.java b/compute/src/test/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest.java index 4dd84be3e5..f0b7777b97 100644 --- a/compute/src/test/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest.java +++ b/compute/src/test/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest.java @@ -28,6 +28,7 @@ import java.util.Map; import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; /** @@ -45,8 +46,10 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); expect(credstore.containsKey("image")).andReturn(false); - expect(config.apply("provider.login-user")).andReturn(null); - expect(config.apply("jclouds.login-user")).andReturn(null); + expect(config.apply("provider.image.login-user")).andReturn(null); + expect(config.apply("jclouds.image.login-user")).andReturn(null); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn(null); replay(config); replay(credstore); @@ -68,7 +71,9 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); expect(credstore.containsKey("image")).andReturn(false); - expect(config.apply("provider.login-user")).andReturn("ubuntu"); + expect(config.apply("provider.image.login-user")).andReturn("ubuntu"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn(null); expect(credstore.put("image", expected)).andReturn(null); replay(config); @@ -91,8 +96,10 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); expect(credstore.containsKey("image")).andReturn(false); - expect(config.apply("provider.login-user")).andReturn(null); - expect(config.apply("jclouds.login-user")).andReturn("ubuntu"); + expect(config.apply("provider.image.login-user")).andReturn(null); + expect(config.apply("jclouds.image.login-user")).andReturn("ubuntu"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn(null); expect(credstore.put("image", expected)).andReturn(null); replay(config); @@ -137,7 +144,9 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); expect(credstore.containsKey("image")).andReturn(false); - expect(config.apply("provider.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn(null); expect(credstore.put("image", expected)).andReturn(null); replay(config); @@ -160,8 +169,62 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); expect(credstore.containsKey("image")).andReturn(false); - expect(config.apply("provider.login-user")).andReturn(null); - expect(config.apply("jclouds.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.login-user")).andReturn(null); + expect(config.apply("jclouds.image.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn(null); + expect(credstore.put("image", expected)).andReturn(null); + + replay(config); + replay(credstore); + + GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull( + "provider", config, credstore); + assertEquals(fn.get(), expected); + + verify(config); + verify(credstore); + + } + + public void testWhenCredentialsNotPresentAndJcloudsPropertyHasUserAndPasswordAndSudo() { + @SuppressWarnings("unchecked") + Map credstore = createMock(Map.class); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").authenticateSudo(true) + .build(); + + ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); + + expect(credstore.containsKey("image")).andReturn(false); + expect(config.apply("provider.image.login-user")).andReturn(null); + expect(config.apply("jclouds.image.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn(null); + expect(config.apply("jclouds.image.authenticate-sudo")).andReturn("true"); + expect(credstore.put("image", expected)).andReturn(null); + + replay(config); + replay(credstore); + + GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull( + "provider", config, credstore); + assertEquals(fn.get(), expected); + + verify(config); + verify(credstore); + + } + + public void testWhenCredentialsNotPresentAndProviderPropertyHasUserAndPasswordAndSudo() { + @SuppressWarnings("unchecked") + Map credstore = createMock(Map.class); + LoginCredentials expected = LoginCredentials.builder().user("ubuntu").password("password").authenticateSudo(true) + .build(); + + ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); + + expect(credstore.containsKey("image")).andReturn(false); + expect(config.apply("provider.image.login-user")).andReturn("ubuntu:password"); + expect(config.apply("provider.image.authenticate-sudo")).andReturn("true"); expect(credstore.put("image", expected)).andReturn(null); replay(config); diff --git a/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java b/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java index bf67235d84..ac472de6d0 100644 --- a/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java +++ b/compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java @@ -33,6 +33,7 @@ import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.internal.PersistNodeCredentials; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.testng.annotations.Test; @@ -83,7 +84,7 @@ public class PersistNodeCredentialsTest { public void testRefreshCredentialsForNodeWhenStatementIsNullSameCredentialsAndDoesCache() { @SuppressWarnings("unchecked") Map credstore = createMock(Map.class); - Credentials credentials = createMock(Credentials.class); + LoginCredentials credentials = createMock(LoginCredentials.class); expect(credstore.put("node#id", credentials)).andReturn(null); @@ -102,7 +103,7 @@ public class PersistNodeCredentialsTest { Map credstore = createMock(Map.class); AdminAccess statement = createMock(AdminAccess.class); - Credentials credentials = createMock(Credentials.class); + LoginCredentials credentials = LoginCredentials.builder().user("foo").build(); expect(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce(); expect(credstore.put("node#id", credentials)).andReturn(null); @@ -125,7 +126,7 @@ public class PersistNodeCredentialsTest { Map credstore = createMock(Map.class); AdminAccess statement = createMock(AdminAccess.class); - Credentials credentials = createMock(Credentials.class); + LoginCredentials credentials = LoginCredentials.builder().user("foo").build(); expect(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce(); expect(credstore.put("node#id", credentials)).andReturn(null); expect(credstore.put("node#id", credentials)).andReturn(null); // TODO diff --git a/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java b/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java index 820c8b14c1..022c3d7f1a 100644 --- a/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java +++ b/compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java @@ -27,19 +27,19 @@ import static org.testng.Assert.assertEquals; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; /** * * @author Adrian Cole */ -@Test(groups = "unit", testName = "DefaultCredentialsFromImageOrOverridingCredentialsTest") +@Test(groups = "unit", testName = "DefaultLoginCredentialsFromImageOrOverridingLoginCredentialsTest") public class DefaultCredentialsFromImageOrOverridingCredentialsTest { private static final DefaultCredentialsFromImageOrOverridingCredentials fn = new DefaultCredentialsFromImageOrOverridingCredentials(); - public void testWhenCredentialsNotPresentInImageOrTemplateOptionsReturnNull() { - Credentials expected = null; + public void testWhenLoginCredentialsNotPresentInImageOrTemplateOptionsReturnNull() { + LoginCredentials expected = null; Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -58,15 +58,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { } - public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptions() { - Credentials expected = new Credentials("ubuntu", "password"); + public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() { + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); expect(image.getDefaultCredentials()).andReturn(null); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideCredentialsWith(expected)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); replay(template); replay(image); @@ -78,8 +78,8 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { } - public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImage() { - Credentials expected = new Credentials("ubuntu", "password"); + public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() { + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -98,15 +98,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { } - public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptions() { - Credentials expected = new Credentials("ubuntu", "password"); + public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() { + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new Credentials("user", "password")); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); + expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); replay(template); replay(image); @@ -118,15 +118,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest { } - public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptions() { - Credentials expected = new Credentials("ubuntu", "password"); + public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() { + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new Credentials("ubuntu", "password2")); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentialWith("password")); + expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password")); replay(template); replay(image); diff --git a/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java b/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java index 64dfb6e02d..017b6f90cf 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java @@ -29,6 +29,7 @@ import org.jclouds.compute.domain.Template; import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; /** @@ -61,7 +62,7 @@ public class PrioritizeCredentialsFromTemplateTest { } public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() { - Credentials expected = new Credentials("foo", "bar"); + LoginCredentials expected = new LoginCredentials("foo", "bar", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -81,19 +82,19 @@ public class PrioritizeCredentialsFromTemplateTest { } public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() { - Credentials expected = new Credentials("ubuntu", "password"); + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); expect(image.getDefaultCredentials()).andReturn(null); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideCredentialsWith(expected)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected)); replay(template); replay(image); - assertEquals(fn.apply(template, new Credentials("foo", "bar")), expected); + assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); verify(template); verify(image); @@ -108,12 +109,12 @@ public class PrioritizeCredentialsFromTemplateTest { expect(template.getImage()).andReturn(image); expect(image.getDefaultCredentials()).andReturn(null); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); replay(template); replay(image); - assertEquals(fn.apply(template, new Credentials("foo", "password")), expected); + assertEquals(fn.apply(template, new LoginCredentials("foo", "password", null, false)), expected); verify(template); verify(image); @@ -121,7 +122,7 @@ public class PrioritizeCredentialsFromTemplateTest { } public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() { - Credentials expected = new Credentials("ubuntu", "password"); + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); @@ -133,7 +134,7 @@ public class PrioritizeCredentialsFromTemplateTest { replay(template); replay(image); - assertEquals(fn.apply(template, new Credentials("foo", "bar")), expected); + assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); verify(template); verify(image); @@ -147,13 +148,13 @@ public class PrioritizeCredentialsFromTemplateTest { Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new Credentials("user", "password")); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); + expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu")); replay(template); replay(image); - assertEquals(fn.apply(template, new Credentials("foo", "bar")), expected); + assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); verify(template); verify(image); @@ -161,19 +162,19 @@ public class PrioritizeCredentialsFromTemplateTest { } public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() { - Credentials expected = new Credentials("ubuntu", "password"); + LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false); Image image = createMock(Image.class); Template template = createMock(Template.class); expect(template.getImage()).andReturn(image); - expect(image.getDefaultCredentials()).andReturn(new Credentials("ubuntu", "password2")); - expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentialWith("password")); + expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false)); + expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password")); replay(template); replay(image); - assertEquals(fn.apply(template, new Credentials("foo", "bar")), expected); + assertEquals(fn.apply(template, new LoginCredentials("foo", "bar", null, false)), expected); verify(template); verify(image); diff --git a/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java b/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java index 6a1b999435..0c10444334 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java @@ -28,6 +28,7 @@ import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.testng.annotations.Test; /** @@ -41,7 +42,7 @@ public class ReturnCredentialsBoundToImageTest { Image image = createMock(Image.class); replay(image); - Credentials creds = new Credentials("ubuntu", "foo"); + LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false); assertEquals(new ReturnCredentialsBoundToImage(creds).execute(image), creds); verify(image); diff --git a/core/src/main/java/org/jclouds/domain/Credentials.java b/core/src/main/java/org/jclouds/domain/Credentials.java index 4096ddc20c..abe296714c 100644 --- a/core/src/main/java/org/jclouds/domain/Credentials.java +++ b/core/src/main/java/org/jclouds/domain/Credentials.java @@ -35,8 +35,8 @@ public class Credentials { public static final Credentials NO_CREDENTIALS = new Credentials(null, null); public static class Builder { - private String identity; - private String credential; + protected String identity; + protected String credential; public Builder identity(String identity) { this.identity = identity; diff --git a/core/src/main/java/org/jclouds/domain/LoginCredentials.java b/core/src/main/java/org/jclouds/domain/LoginCredentials.java new file mode 100644 index 0000000000..be0b096fec --- /dev/null +++ b/core/src/main/java/org/jclouds/domain/LoginCredentials.java @@ -0,0 +1,178 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you 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.domain; + +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.util.CredentialUtils; + +/** + * @author Adrian Cole + */ +public class LoginCredentials extends Credentials { + + public static Builder builder(Credentials creds) { + if (creds == null) + return builder(); + if (creds instanceof LoginCredentials) + return LoginCredentials.class.cast(creds).toBuilder(); + else + return builder().identity(creds.identity).credential(creds.credential); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends Credentials.Builder { + + private boolean authenticateSudo; + private String password; + private String privateKey; + + public Builder identity(String identity) { + return Builder.class.cast(super.identity(identity)); + } + + public Builder user(String user) { + return identity(user); + } + + public Builder password(String password) { + this.password = password; + return this; + } + + public Builder privateKey(String privateKey) { + this.privateKey = privateKey; + return this; + } + + public Builder credential(String credential) { + if (CredentialUtils.isPrivateKeyCredential(credential)) + return privateKey(credential); + else if (credential != null) + return password(credential); + return this; + } + + public Builder authenticateSudo(boolean authenticateSudo) { + this.authenticateSudo = authenticateSudo; + return this; + } + + public LoginCredentials build() { + if (identity == null && password == null && privateKey == null && !authenticateSudo) + return null; + return new LoginCredentials(identity, password, privateKey, authenticateSudo); + } + } + + private final boolean authenticateSudo; + private final String password; + private final String privateKey; + + public LoginCredentials(String username, @Nullable String password, @Nullable String privateKey, + boolean authenticateSudo) { + super(username, CredentialUtils.isPrivateKeyCredential(privateKey) ? privateKey : password); + this.authenticateSudo = authenticateSudo; + this.password = password; + this.privateKey = privateKey; + } + + /** + * @return the login user + */ + public String getUser() { + return identity; + } + + /** + * @return the password of the login user or null + */ + @Nullable + public String getPassword() { + return password; + } + + /** + * @return the private ssh key of the user or null + */ + @Nullable + public String getPrivateKey() { + return privateKey; + } + + /** + * secures access to root requires a password. This password is required to + * access either the console or run sudo as root. + *

+ * ex. {@code echo 'password' |sudo -S command} + * + * @return if a password is required to access the root user + */ + public boolean shouldAuthenticateSudo() { + return authenticateSudo; + } + + @Override + public Builder toBuilder() { + return new Builder().user(identity).password(password).privateKey(privateKey).authenticateSudo(authenticateSudo); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (authenticateSudo ? 1231 : 1237); + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + ((privateKey == null) ? 0 : privateKey.hashCode()); + return result; + } + + @Override + public String toString() { + return "[user=" + getUser() + ", passwordPresent=" + (password != null) + ", privateKeyPresent=" + + (privateKey != null) + ", shouldAuthenticateSudo=" + authenticateSudo + "]"; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + LoginCredentials other = (LoginCredentials) obj; + if (authenticateSudo != other.authenticateSudo) + return false; + if (password == null) { + if (other.password != null) + return false; + } else if (!password.equals(other.password)) + return false; + if (privateKey == null) { + if (other.privateKey != null) + return false; + } else if (!privateKey.equals(other.privateKey)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java index 05d4b81737..cc5ffb3d4b 100644 --- a/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java +++ b/core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java @@ -30,6 +30,7 @@ import javax.inject.Singleton; import org.jclouds.collect.TransformingMap; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.io.CopyInputStreamInputSupplierMap; import org.jclouds.json.Json; import org.jclouds.logging.Logger; @@ -90,10 +91,28 @@ public class CredentialStoreModule extends AbstractModule { @Override public InputStream apply(Credentials from) { - return Strings2.toInputStream(json.toJson(checkNotNull(from))); + checkNotNull(from, "inputCredentials"); + if (from instanceof LoginCredentials) { + LoginCredentials login = LoginCredentials.class.cast(from); + JsonLoginCredentials val = new JsonLoginCredentials(); + val.user = login.getUser(); + val.password = login.getPassword(); + val.privateKey = login.getPrivateKey(); + if (login.shouldAuthenticateSudo()) + val.authenticateSudo = login.shouldAuthenticateSudo(); + return Strings2.toInputStream(json.toJson(val)); + } + return Strings2.toInputStream(json.toJson(from)); } } + static class JsonLoginCredentials { + private String user; + private String password; + private String privateKey; + private Boolean authenticateSudo; + } + @Singleton public static class CredentialsFromJsonInputStream implements Function { @Resource @@ -106,17 +125,17 @@ public class CredentialStoreModule extends AbstractModule { this.json = json; } - private static class PrivateCredentials { - String identity; - String credential; - } - @Override public Credentials apply(InputStream from) { try { - PrivateCredentials credentials = json.fromJson(Strings2.toStringAndClose(checkNotNull(from)), - PrivateCredentials.class); - return new Credentials(credentials.identity, credentials.credential); + String creds = Strings2.toStringAndClose(checkNotNull(from)); + if (creds.indexOf("\"user\":") == -1) { + return json.fromJson(creds, Credentials.class); + } else { + JsonLoginCredentials val = json.fromJson(creds, JsonLoginCredentials.class); + return LoginCredentials.builder().user(val.user).password(val.password).privateKey(val.privateKey) + .authenticateSudo(Boolean.TRUE.equals(val.authenticateSudo)).build(); + } } catch (Exception e) { logger.warn(e, "ignoring problem retrieving credentials"); return null; diff --git a/core/src/main/java/org/jclouds/util/CredentialUtils.java b/core/src/main/java/org/jclouds/util/CredentialUtils.java index f4e522cf6e..2732ac1de8 100644 --- a/core/src/main/java/org/jclouds/util/CredentialUtils.java +++ b/core/src/main/java/org/jclouds/util/CredentialUtils.java @@ -46,10 +46,12 @@ public class CredentialUtils { } public static boolean isPrivateKeyCredential(Credentials credentials) { - return credentials != null - && credentials.credential != null - && (credentials.credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credentials.credential - .startsWith(Pems.PRIVATE_PKCS8_MARKER)); + return credentials != null && isPrivateKeyCredential(credentials.credential); + } + + public static boolean isPrivateKeyCredential(String credential) { + return credential != null + && (credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credential.startsWith(Pems.PRIVATE_PKCS8_MARKER)); } public static boolean isPrivateKeyEncrypted(byte[] privateKey) { diff --git a/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java index 310ac1629e..86daa793cd 100644 --- a/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java +++ b/core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.ConcurrentHashMap; import org.jclouds.crypto.PemsTest; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.io.CopyInputStreamInputSupplierMap; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; @@ -60,7 +61,7 @@ public class CredentialStoreModuleTest { 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); + check(map, getStore(injector), "i-20312", new Credentials(identity, credential)); } public void testProvidedMapWithValue() throws IOException { @@ -68,8 +69,8 @@ public class CredentialStoreModuleTest { 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"); + checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass")); + checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass")); remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); } @@ -84,7 +85,7 @@ public class CredentialStoreModuleTest { Map store = getStore(injector); for (int i = 0; i < 10; i++) - check(map, store, "test" + i, "user" + i, "pass" + i); + check(map, store, "test" + i, new Credentials("user" + i, "pass" + i)); } @@ -92,9 +93,9 @@ public class CredentialStoreModuleTest { 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"); + put(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass")); + checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass")); + checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass")); remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); } @@ -102,13 +103,33 @@ public class CredentialStoreModuleTest { 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"); + put(map, getStore(createInjector()), "test", new Credentials("user", "pass")); + checkConsistent(map, getStore(createInjector()), "test", new Credentials("user", "pass")); + checkConsistent(map, getStore(createInjector()), "test", new Credentials("user", "pass")); remove(map, getStore(createInjector()), "test"); } + public void testLoginConsistentAcrossMultipleInjectorsAndLooksNice() throws IOException { + Map map = getMap(createInjector()); + LoginCredentials creds = LoginCredentials.builder().user("user").password("pass").build(); + put(map, getStore(createInjector()), "test", creds); + checkConsistent(map, getStore(createInjector()), "test", creds, "{\"user\":\"user\",\"password\":\"pass\"}"); + checkConsistent(map, getStore(createInjector()), "test", creds, "{\"user\":\"user\",\"password\":\"pass\"}"); + remove(map, getStore(createInjector()), "test"); + } + + public void testLoginConsistentAcrossMultipleInjectorsAndLooksNiceWithSudo() throws IOException { + Map map = getMap(createInjector()); + LoginCredentials creds = LoginCredentials.builder().user("user").password("pass").authenticateSudo(true).build(); + put(map, getStore(createInjector()), "test", creds); + checkConsistent(map, getStore(createInjector()), "test", creds, + "{\"user\":\"user\",\"password\":\"pass\",\"authenticateSudo\":true}"); + checkConsistent(map, getStore(createInjector()), "test", creds, + "{\"user\":\"user\",\"password\":\"pass\",\"authenticateSudo\":true}"); + remove(map, getStore(createInjector()), "test"); + } + protected Map getStore(Injector injector) { return injector.getInstance(Key.get(new TypeLiteral>() { })); @@ -127,10 +148,10 @@ public class CredentialStoreModuleTest { 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); + protected void check(Map map, Map store, String key, Credentials creds) + throws IOException { + put(map, store, key, creds); + checkConsistent(map, store, key, creds); remove(map, store, key); } @@ -143,26 +164,29 @@ public class CredentialStoreModuleTest { } protected void checkConsistent(Map map, Map store, String key, - String identity, String credential) throws IOException { + Credentials creds) throws IOException { + checkConsistent(map, store, key, creds, json.toJson(creds)); + } + + protected void checkConsistent(Map map, Map store, String key, + Credentials creds, String expected) 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)); + assertEquals(store.get(key), creds); + assertEquals(store.get(key), creds); // checkRepeatedRead - checkToJson(map, key, identity, credential); - checkToJson(map, key, identity, credential); + checkToJson(map, key, expected); + checkToJson(map, key, expected); } - protected void checkToJson(Map map, String key, String identity, String credential) - throws IOException { - assertEquals(Strings2.toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential))); + protected void checkToJson(Map map, String key, String expected) throws IOException { + assertEquals(Strings2.toStringAndClose(map.get(key)), expected); } - protected void put(Map map, Map store, String key, String identity, - String credential) { + protected void put(Map map, Map store, String key, Credentials creds) { assertEquals(store.size(), 0); assertEquals(map.size(), 0); - store.put(key, new Credentials(identity, credential)); + store.put(key, creds); } } \ No newline at end of file diff --git a/providers/aws-ec2/pom.xml b/providers/aws-ec2/pom.xml index 520a2f7b11..61d6067f62 100644 --- a/providers/aws-ec2/pom.xml +++ b/providers/aws-ec2/pom.xml @@ -39,7 +39,8 @@ ${test.aws.identity} ${test.aws.credential} - + + @@ -116,7 +117,8 @@ ${test.aws-ec2.identity} ${test.aws-ec2.credential} ${test.aws-ec2.image-id} - ${test.aws-ec2.login-user} + ${test.aws-ec2.image.login-user} + ${test.aws-ec2.image.authenticate-sudo} diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateOptions.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateOptions.java index c4914cb7c3..6538a59766 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateOptions.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateOptions.java @@ -29,6 +29,7 @@ import java.util.Set; import org.jclouds.aws.ec2.options.RequestSpotInstancesOptions; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.options.EC2TemplateOptions; import org.jclouds.ec2.domain.BlockDeviceMapping; import org.jclouds.io.Payload; @@ -176,6 +177,48 @@ public class AWSEC2TemplateOptions extends EC2TemplateOptions implements Cloneab } public static class Builder { + @Deprecated + public static AWSEC2TemplateOptions overrideLoginUserWith(String user) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginUserWith(user); + } + + public static AWSEC2TemplateOptions overrideLoginUser(String user) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginUser(user); + } + + public static AWSEC2TemplateOptions overrideLoginPassword(String password) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginPassword(password); + } + + public static AWSEC2TemplateOptions overrideLoginPrivateKey(String privateKey) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginPrivateKey(privateKey); + } + + public static AWSEC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideAuthenticateSudo(authenticateSudo); + } + + @Deprecated + public static AWSEC2TemplateOptions overrideLoginCredentialWith(String credential) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginCredentialWith(credential); + } + + @Deprecated + public static AWSEC2TemplateOptions overrideCredentialsWith(Credentials credentials) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideCredentialsWith(credentials); + } + + public static AWSEC2TemplateOptions overrideLoginCredentials(LoginCredentials credentials) { + AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); + return options.overrideLoginCredentials(credentials); + } /** * @see AWSEC2TemplateOptions#securityGroupIds(Iterable) @@ -363,7 +406,7 @@ public class AWSEC2TemplateOptions extends EC2TemplateOptions implements Cloneab AWSEC2TemplateOptions options = new AWSEC2TemplateOptions(); return options.spotOptions(spotOptions); } - + /** * @see TemplateOptions#userMetadata(Map) */ @@ -593,11 +636,70 @@ public class AWSEC2TemplateOptions extends EC2TemplateOptions implements Cloneab /** * {@inheritDoc} */ + @Deprecated @Override public AWSEC2TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { return AWSEC2TemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials)); } + /** + * {@inheritDoc} + */ + @Deprecated + @Override + public AWSEC2TemplateOptions overrideLoginUserWith(String loginUser) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginUserWith(loginUser)); + } + + /** + * {@inheritDoc} + */ + @Deprecated + @Override + public AWSEC2TemplateOptions overrideLoginCredentialWith(String loginCredential) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginCredentialWith(loginCredential)); + } + + /** + * {@inheritDoc} + */ + @Override + public AWSEC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials)); + } + + /** + * {@inheritDoc} + */ + @Override + public AWSEC2TemplateOptions overrideLoginPassword(String password) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginPassword(password)); + } + + /** + * {@inheritDoc} + */ + @Override + public AWSEC2TemplateOptions overrideLoginPrivateKey(String privateKey) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey)); + } + + /** + * {@inheritDoc} + */ + @Override + public AWSEC2TemplateOptions overrideLoginUser(String loginUser) { + return AWSEC2TemplateOptions.class.cast(super.overrideLoginUser(loginUser)); + } + + /** + * {@inheritDoc} + */ + @Override + public AWSEC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) { + return AWSEC2TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo)); + } + /** * @return placementGroup to use when running the instance or null, to * generate a placementGroup. diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadata.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadata.java index 626393c6aa..f1cbbc7098 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadata.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadata.java @@ -18,8 +18,9 @@ */ package org.jclouds.aws.ec2.compute.functions; -import static com.google.common.base.Predicates.*; -import static com.google.common.collect.Maps.*; +import static com.google.common.base.Predicates.equalTo; +import static com.google.common.base.Predicates.not; +import static com.google.common.collect.Maps.filterValues; import java.util.Map; import java.util.Set; @@ -35,6 +36,7 @@ import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata; import org.jclouds.ec2.domain.InstanceState; @@ -58,10 +60,12 @@ public class AWSRunningInstanceToNodeMetadata extends RunningInstanceToNodeMetad @Override protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) { - Credentials creds = credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId()); + LoginCredentials creds = LoginCredentials.builder( + credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId())).build(); String spotRequestId = AWSRunningInstance.class.cast(instance).getSpotInstanceRequestId(); if (creds == null && spotRequestId != null) { - creds = credentialStore.get("node#" + instance.getRegion() + "/" + spotRequestId); + creds = LoginCredentials.builder(credentialStore.get("node#" + instance.getRegion() + "/" + spotRequestId)) + .build(); if (creds != null) credentialStore.put("node#" + instance.getRegion() + "/" + instance.getId(), creds); } diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java index 4817bb3453..3e9907a386 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java @@ -54,7 +54,7 @@ import com.google.common.cache.Cache; */ @Singleton public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions extends - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions { @Resource @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; @@ -67,12 +67,12 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions @Inject public CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions( - Function makeKeyPair, ConcurrentMap credentialsMap, - @Named("SECURITY") Cache securityGroupMap, - Provider optionsProvider, - @Named("PLACEMENT") Cache placementGroupMap, - CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded, - Function importExistingKeyPair) { + Function makeKeyPair, ConcurrentMap credentialsMap, + @Named("SECURITY") Cache securityGroupMap, + Provider optionsProvider, + @Named("PLACEMENT") Cache placementGroupMap, + CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded, + Function importExistingKeyPair) { super(makeKeyPair, credentialsMap, securityGroupMap, optionsProvider); this.placementGroupMap = placementGroupMap; this.createPlacementGroupIfNeeded = createPlacementGroupIfNeeded; @@ -81,11 +81,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions public AWSRunInstancesOptions execute(String region, String group, Template template) { AWSRunInstancesOptions instanceOptions = AWSRunInstancesOptions.class - .cast(super.execute(region, group, template)); + .cast(super.execute(region, group, template)); String placementGroupName = template.getHardware().getId().startsWith("cc") ? createNewPlacementGroupUnlessUserSpecifiedOtherwise( - region, group, template.getOptions()) - : null; + region, group, template.getOptions()) : null; if (placementGroupName != null) instanceOptions.inPlacementGroup(placementGroupName); @@ -104,7 +103,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions placementGroupName = AWSEC2TemplateOptions.class.cast(options).getPlacementGroup(); if (placementGroupName == null) shouldAutomaticallyCreatePlacementGroup = AWSEC2TemplateOptions.class.cast(options) - .shouldAutomaticallyCreatePlacementGroup(); + .shouldAutomaticallyCreatePlacementGroup(); } if (placementGroupName == null && shouldAutomaticallyCreatePlacementGroup) { // placementGroupName must be unique within an account per @@ -125,12 +124,11 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions pair = importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, options.getPublicKey())); options.dontAuthorizePublicKey(); if (hasLoginCredential.apply(options)) - pair = pair.toBuilder().keyMaterial(options.getOverridingCredentials().credential).build(); + pair = pair.toBuilder().keyMaterial(options.getLoginPrivateKey()).build(); credentialsMap.put(key, pair); } else { if (hasPublicKeyMaterial.apply(options)) { - logger - .warn("to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)"); + logger.warn("to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)"); } return super.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options); } @@ -159,7 +157,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions @Override public boolean apply(TemplateOptions options) { - return options.getOverridingCredentials() != null && options.getOverridingCredentials().credential != null; + return options.getLoginPrivateKey() != null; } }; @@ -167,8 +165,8 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions @Override protected boolean userSpecifiedTheirOwnGroups(TemplateOptions options) { return options instanceof AWSEC2TemplateOptions - && AWSEC2TemplateOptions.class.cast(options).getGroupIds().size() > 0 - || super.userSpecifiedTheirOwnGroups(options); + && AWSEC2TemplateOptions.class.cast(options).getGroupIds().size() > 0 + || super.userSpecifiedTheirOwnGroups(options); } @Override diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceLiveTest.java index 6b4044e4c1..fe87ee2aae 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceLiveTest.java @@ -34,7 +34,7 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.predicates.NodePredicates; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.EC2Client; import org.jclouds.ec2.compute.EC2ComputeServiceLiveTest; import org.jclouds.ec2.domain.IpProtocol; @@ -123,7 +123,7 @@ public class AWSEC2ComputeServiceLiveTest extends EC2ComputeServiceLiveTest { // pass in the private key, so that we can run a script with it assert result.getKeyMaterial() != null : result; - options.overrideLoginCredentialWith(result.getKeyMaterial()); + options.overrideLoginPrivateKey(result.getKeyMaterial()); // an arbitrary command to run options.runScript(Statements.exec("find /usr")); @@ -172,8 +172,9 @@ public class AWSEC2ComputeServiceLiveTest extends EC2ComputeServiceLiveTest { assert secgroup.getIpPermissions().size() == 0 : secgroup; // try to run a script with the original keyPair - runScriptWithCreds(group, first.getOperatingSystem(), new Credentials(first.getCredentials().identity, result - .getKeyMaterial())); + runScriptWithCreds(group, first.getOperatingSystem(), + LoginCredentials.builder().user(first.getCredentials().identity).privateKey(result.getKeyMaterial()) + .build()); } finally { client.destroyNodesMatching(NodePredicates.inGroup(group)); diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java index c2b4ee6d0f..63ffd8b77a 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java @@ -28,10 +28,10 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.functions.EC2ImageParser; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.domain.Image; @@ -58,29 +58,40 @@ public class AWSEC2ImageParserTest { Set result = convertImages("/alestic_canonical.xml"); - assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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( + Iterables.get(result, 0), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("ubuntu", null, null, false)).id("us-east-1/ami-7e28ca17") + .providerId("ami-7e28ca17").location(defaultLocation).version("20091130") + .userMetadata(ImmutableMap.of("owner", "099720109477", "rootDeviceType", "instance-store")).build()); - assertEquals(Iterables.get(result, 4), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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()); + assertEquals( + Iterables.get(result, 4), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("ubuntu", null, null, false)).id("us-east-1/ami-c0fa1ea9") + .providerId("ami-c0fa1ea9").location(defaultLocation).version("20080905") + .userMetadata(ImmutableMap.of("owner", "063491364108", "rootDeviceType", "instance-store")).build()); - assertEquals(Iterables.get(result, 6), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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()); + assertEquals( + Iterables.get(result, 6), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("ubuntu", null, null, false)).id("us-east-1/ami-10f3a255") + .providerId("ami-10f3a255").location(defaultLocation).version("20100827") + .userMetadata(ImmutableMap.of("owner", "099720109477", "rootDeviceType", "ebs")).build()); } @@ -88,13 +99,17 @@ public class AWSEC2ImageParserTest { Set result = convertImages("/vostok.xml"); - assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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()); + assertEquals( + Iterables.get(result, 0), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("root", null, null, false)).id("us-east-1/ami-870de2ee") + .providerId("ami-870de2ee").location(defaultLocation).version("5622") + .userMetadata(ImmutableMap.of("owner", "133804938231", "rootDeviceType", "instance-store")).build()); } @@ -102,12 +117,16 @@ public class AWSEC2ImageParserTest { Set result = convertImages("/describe_images_cc.xml"); - assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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()); + assertEquals( + Iterables.get(result, 0), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("root", null, null, false)).id("us-east-1/ami-7ea24a17") + .providerId("ami-7ea24a17").location(defaultLocation) + .userMetadata(ImmutableMap.of("owner", "206029621532", "rootDeviceType", "ebs")).build()); } @@ -115,56 +134,67 @@ public class AWSEC2ImageParserTest { Set result = convertImages("/rightscale_images.xml"); - assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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( + Iterables.get(result, 0), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("root", null, null, false)).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\",\"tags\":[],\"providerId\":\"ami-c19db6b5\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"paravirtual\",\"hypervisor\":\"xen\"}}"); + 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\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-c19db6b5\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-c19db6b5\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"paravirtual\",\"hypervisor\":\"xen\"}}"); assertEquals( - new Gson().toJson(Iterables.get(result, 2)), - "{\"operatingSystem\":{\"family\":\"WINDOWS\",\"arch\":\"hvm\",\"version\":\"2003\",\"description\":\"411009282317/RightImage Windows_2003_i386_v5.4.3\",\"is64Bit\":false},\"version\":\"5.4.3\",\"description\":\"Built by RightScale\",\"defaultCredentials\":{\"identity\":\"root\"},\"id\":\"us-east-1/ami-710c2605\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-710c2605\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"hvm\",\"hypervisor\":\"xen\"}}"); + new Gson().toJson(Iterables.get(result, 2)), + "{\"operatingSystem\":{\"family\":\"WINDOWS\",\"arch\":\"hvm\",\"version\":\"2003\",\"description\":\"411009282317/RightImage Windows_2003_i386_v5.4.3\",\"is64Bit\":false},\"version\":\"5.4.3\",\"description\":\"Built by RightScale\",\"defaultCredentials\":{\"authenticateSudo\":false,\"identity\":\"root\"},\"id\":\"us-east-1/ami-710c2605\",\"type\":\"IMAGE\",\"tags\":[],\"providerId\":\"ami-710c2605\",\"location\":{\"scope\":\"REGION\",\"id\":\"us-east-1\",\"description\":\"us-east-1\",\"iso3166Codes\":[],\"metadata\":{}},\"userMetadata\":{\"owner\":\"411009282317\",\"rootDeviceType\":\"ebs\",\"virtualizationType\":\"hvm\",\"hypervisor\":\"xen\"}}"); } public void testParseAmznImage() { Set result = convertImages("/amzn_images.xml"); - assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( - new OperatingSystem.Builder().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, 0), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("ec2-user", null, null, false)).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 OperatingSystem.Builder().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()); + assertEquals( + Iterables.get(result, 3), + new ImageBuilder() + .operatingSystem( + new OperatingSystem.Builder().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 LoginCredentials("ec2-user", null, null, false)).id("us-east-1/ami-f2e4b5b7") + .providerId("ami-f2e4b5b7").location(defaultLocation).version("0.9.7-beta") + .userMetadata(ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); } - static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id("us-east-1").description( - "us-east-1").build(); + static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id("us-east-1") + .description("us-east-1").build(); public static Set convertImages(String resource) { Map> map = new BaseComputeServiceContextModule() { }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)); + .getInstance(Json.class)); Set result = DescribeImagesResponseHandlerTest.parseImages(resource); EC2ImageParser parser = new EC2ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(null), map, - Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), Suppliers - .ofInstance(defaultLocation), new AWSEC2ReviseParsedImage(map)); + Suppliers.> ofInstance(ImmutableSet. of(defaultLocation)), + Suppliers.ofInstance(defaultLocation), new AWSEC2ReviseParsedImage(map)); return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull())); } } diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java index 4781124029..c9eea64cd4 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java @@ -42,7 +42,7 @@ import org.jclouds.aws.ec2.options.AWSRunInstancesOptions; import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Template; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.EC2TemplateBuilderTest; import org.jclouds.ec2.compute.domain.EC2HardwareBuilder; import org.jclouds.ec2.compute.domain.RegionAndName; @@ -87,18 +87,18 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class); Template template = createMock(Template.class); @@ -109,7 +109,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getSubnetId()).andReturn(null); @@ -124,9 +124,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", generatedGroup, "KeyName", systemGeneratedKeyPairName) - .entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", + generatedGroup, "KeyName", systemGeneratedKeyPairName).entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -149,18 +150,18 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class); Template template = createMock(Template.class); @@ -171,9 +172,9 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - generatedGroup); + generatedGroup); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getSubnetId()).andReturn(null); @@ -188,9 +189,11 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", generatedGroup, "KeyName", systemGeneratedKeyPairName, - "Placement.GroupName", generatedGroup).entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", + generatedGroup, "KeyName", systemGeneratedKeyPairName, "Placement.GroupName", generatedGroup) + .entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -213,18 +216,18 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class); Template template = createMock(Template.class); @@ -235,9 +238,9 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - generatedGroup); + generatedGroup); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getSubnetId()).andReturn(null); @@ -252,9 +255,11 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", generatedGroup, "KeyName", systemGeneratedKeyPairName, - "Placement.GroupName", generatedGroup).entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", + generatedGroup, "KeyName", systemGeneratedKeyPairName, "Placement.GroupName", generatedGroup) + .entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -275,18 +280,18 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class); Template template = createMock(Template.class); @@ -297,7 +302,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getSubnetId()).andReturn("1"); expect(options.getUserData()).andReturn(null); @@ -311,8 +316,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SubnetId", "1", "KeyName", systemGeneratedKeyPairName).entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SubnetId", "1", "KeyName", + systemGeneratedKeyPairName).entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -335,18 +342,18 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getOptionsProvider"), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( - "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, - TemplateOptions.class), - CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class - .getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, - TemplateOptions.class) }); + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class, + new Method[] { + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class + .getDeclaredMethod("getOptionsProvider"), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "createNewPlacementGroupUnlessUserSpecifiedOtherwise", String.class, String.class, + TemplateOptions.class), + CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( + "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) }); AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class); Template template = createMock(Template.class); @@ -357,7 +364,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(template.getOptions()).andReturn(options).atLeastOnce(); expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet. of()).atLeastOnce(); expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn( - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); expect(strategy.getSecurityGroupsForTagAndOptions(region, group, options)).andReturn(generatedGroups); expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getSubnetId()).andReturn(null); @@ -372,9 +379,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run RunInstancesOptions customize = strategy.execute(region, group, template); assertEquals(customize.buildQueryParameters(), ImmutableMultimap. of()); - assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap. of("InstanceType", - size.getProviderId(), "SecurityGroup.1", "group", "KeyName", systemGeneratedKeyPairName, "UserData", - Base64.encodeBytes("hello".getBytes())).entries()); + assertEquals( + customize.buildFormParameters().entries(), + ImmutableMultimap. of("InstanceType", size.getProviderId(), "SecurityGroup.1", "group", + "KeyName", systemGeneratedKeyPairName, "UserData", Base64.encodeBytes("hello".getBytes())).entries()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap. of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap. of()); assertEquals(customize.buildStringPayload(), null); @@ -400,7 +408,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getPublicKey()).andReturn(null).times(2); - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); @@ -432,7 +440,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // setup expectations expect(options.getPublicKey()).andReturn(null).times(2); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true); @@ -463,11 +471,11 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // we specify we have a public key we want to use for authentication expect(options.getPublicKey()).andReturn("ssh-rsa").times(2); - expect(options.getOverridingCredentials()).andReturn(CREDENTIALS).atLeastOnce(); + expect(options.getLoginPrivateKey()).andReturn(CREDENTIALS.getPrivateKey()).atLeastOnce(); // Here, we import the keypair and place it into the cache expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, "ssh-rsa"))) - .andReturn(KEYPAIR); + .andReturn(KEYPAIR); expect(options.dontAuthorizePublicKey()).andReturn(options); expect(strategy.credentialsMap.put(new RegionAndName(region, group), KEYPAIR)).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); @@ -494,17 +502,17 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // create mocks CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); - AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey("ssh-rsa").overrideCredentialsWith( - new Credentials("foo", CREDENTIALS.credential)); + AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey("ssh-rsa").overrideLoginCredentials( + LoginCredentials.builder().user("foo").privateKey(CREDENTIALS.credential).build()); KeyPair keyPair = new KeyPair(region, group, "//TODO", null, null); // setup expectations expect( - strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, - CREDENTIALS.credential))).andReturn(keyPair); + strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, + CREDENTIALS.credential))).andReturn(keyPair); expect( - strategy.credentialsMap.put(new RegionAndName(region, group), keyPair.toBuilder().keyMaterial( - CREDENTIALS.credential).build())).andReturn(null); + strategy.credentialsMap.put(new RegionAndName(region, group), + keyPair.toBuilder().keyMaterial(CREDENTIALS.credential).build())).andReturn(null); // replay mocks replayStrategy(strategy); @@ -530,7 +538,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // setup expectations expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, "ssh-rsa"))) - .andReturn(keyPair); + .andReturn(keyPair); expect(strategy.credentialsMap.put(new RegionAndName(region, group), keyPair)).andReturn(null); // replay mocks @@ -572,7 +580,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); // verify mocks verify(options); @@ -592,12 +600,12 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT KeyPair keyPair = createMock(KeyPair.class); // setup expectations - expect(options.getOverridingCredentials()).andReturn(null); + expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo hello")); expect(options.getPublicKey()).andReturn(null).times(2); expect(options.getKeyPair()).andReturn(systemGeneratedKeyPairName); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, systemGeneratedKeyPairName))) - .andReturn(true); + .andReturn(true); // replay mocks replay(options); @@ -606,7 +614,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), - systemGeneratedKeyPairName); + systemGeneratedKeyPairName); // verify mocks verify(options); @@ -666,7 +674,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getGroups()).andReturn(groupNames).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(group); // replay mocks @@ -700,7 +708,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getGroups()).andReturn(groupNames).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup); // replay mocks @@ -734,7 +742,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getGroups()).andReturn(groupNames).atLeastOnce(); expect(options.getInboundPorts()).andReturn(ports).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup); // replay mocks @@ -768,10 +776,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getGroupIds()).andReturn(ImmutableSet. of()); expect(options.getGroups()).andReturn(groupNames).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)) - .andReturn(groupExisted ? "group" : null); + .andReturn(groupExisted ? "group" : null); // replay mocks replay(options); @@ -804,10 +812,10 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getGroupIds()).andReturn(ImmutableSet. of("group1", "group2")); expect(options.getGroups()).andReturn(groupNames).atLeastOnce(); RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup, - ports, shouldAuthorizeSelf); + ports, shouldAuthorizeSelf); expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)) - .andReturn(groupExisted ? "group" : null); + .andReturn(groupExisted ? "group" : null); // replay mocks replay(options); @@ -842,7 +850,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run assertEquals(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options), - userSuppliedPlacementGroup); + userSuppliedPlacementGroup); // verify mocks verify(options); @@ -866,7 +874,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT expect(options.getPlacementGroup()).andReturn(userSuppliedPlacementGroup); expect(options.shouldAutomaticallyCreatePlacementGroup()).andReturn(shouldAutomaticallyCreatePlacementGroup); expect(strategy.placementGroupMap.getUnchecked(new RegionAndName(region, generatedMarkerGroup))).andReturn( - generatedMarkerGroup); + generatedMarkerGroup); // replay mocks replay(options); @@ -874,7 +882,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT // run assertEquals(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options), - generatedMarkerGroup); + generatedMarkerGroup); // verify mocks verify(options); @@ -886,7 +894,8 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedPlacementGroup = null; - boolean shouldAutomaticallyCreatePlacementGroup = false; // here's the important + boolean shouldAutomaticallyCreatePlacementGroup = false; // here's the + // important // part! // create mocks @@ -931,8 +940,7 @@ public class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsT CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded = createMock(CreatePlacementGroupIfNeeded.class); return new CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions(makeKeyPair, credentialsMap, - securityGroupMap, OPTIONS_PROVIDER, placementGroupMap, createPlacementGroupIfNeeded, - importExistingKeyPair); + securityGroupMap, OPTIONS_PROVIDER, placementGroupMap, createPlacementGroupIfNeeded, importExistingKeyPair); } private void replayStrategy(CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy) { diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/AWSKeyPairClientLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/AWSKeyPairClientLiveTest.java index 15c3a81d71..c084279627 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/AWSKeyPairClientLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/AWSKeyPairClientLiveTest.java @@ -48,7 +48,7 @@ import org.jclouds.compute.ComputeTestUtils; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.domain.KeyPair; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.rest.RestContext; @@ -141,12 +141,12 @@ public class AWSKeyPairClientLiveTest { assertEquals(instance.getKeyName(), "jclouds#" + group); Map responses = computeContext.getComputeService() - .runScriptOnNodesMatching( - runningInGroup(group), - exec("echo hello"), - overrideCredentialsWith( - new Credentials(first.getCredentials().identity, keyPair.get("private"))) - .wrapInInitScript(false).runAsRoot(false)); + .runScriptOnNodesMatching( + runningInGroup(group), + exec("echo hello"), + overrideCredentialsWith( + LoginCredentials.builder().user(first.getCredentials().identity) + .privateKey(keyPair.get("private")).build()).wrapInInitScript(false).runAsRoot(false)); ExecResponse hello = getOnlyElement(responses.values()); assertEquals(hello.getOutput().trim(), "hello"); @@ -223,7 +223,7 @@ public class AWSKeyPairClientLiveTest { protected void checkKeyPair(String keyName, KeyPair keyPair) { assertNotNull(keyPair); - assertNotNull(keyPair.getKeyFingerprint()); + assertNotNull(keyPair.getSha1OfPrivateKey()); assertEquals(keyPair.getKeyName(), keyName); Set twoResults = client.describeKeyPairsInRegion(null, keyName); @@ -231,7 +231,7 @@ public class AWSKeyPairClientLiveTest { assertEquals(twoResults.size(), 1); KeyPair listPair = twoResults.iterator().next(); assertEquals(listPair.getKeyName(), keyPair.getKeyName()); - assertEquals(listPair.getKeyFingerprint(), keyPair.getKeyFingerprint()); + assertEquals(listPair.getSha1OfPrivateKey(), keyPair.getSha1OfPrivateKey()); } protected AWSRunningInstance getInstance(AWSInstanceClient instanceClient, String id) { diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java index 5af5c33030..2be773d658 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java @@ -96,7 +96,12 @@ public class TagClientLiveTest { new Log4JLoggingModule(), new SshjSshClientModule()), overrides); context = computeContext.getProviderSpecificContext(); client = context.getApi().getTagServices(); - testGroup = context.getApi().getSecurityGroupServices().createSecurityGroupInRegionAndReturnId(null, "test-group", "test-group"); + try { + testGroup = context.getApi().getSecurityGroupServices() + .createSecurityGroupInRegionAndReturnId(null, "test-group", "test-group"); + } catch (IllegalStateException e) { + // already exists + } } @AfterGroups(groups = { "live" }) diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstancesHandlerTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstancesHandlerTest.java index 4bcbc54b80..9477abfbf4 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstancesHandlerTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstancesHandlerTest.java @@ -18,9 +18,10 @@ */ package org.jclouds.aws.ec2.xml; -import static org.easymock.EasyMock.*; -import static org.easymock.classextension.EasyMock.*; -import static org.testng.Assert.*; +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.Map; @@ -39,9 +40,7 @@ import org.testng.annotations.Test; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; import com.google.inject.AbstractModule; import com.google.inject.Guice; diff --git a/providers/bluelock-vcloud-zone01/pom.xml b/providers/bluelock-vcloud-zone01/pom.xml index c70c2132a0..a71d30af90 100644 --- a/providers/bluelock-vcloud-zone01/pom.xml +++ b/providers/bluelock-vcloud-zone01/pom.xml @@ -39,7 +39,8 @@ FIXME_IDENTITY FIXME_CREDENTIAL - + + @@ -105,7 +106,8 @@ ${test.bluelock-vcloud-zone01.identity} ${test.bluelock-vcloud-zone01.credential} ${test.bluelock-vcloud-zone01.image-id} - ${test.bluelock-vcloud-zone01.login-user} + ${test.bluelock-vcloud-zone01.image.login-user} + ${test.bluelock-vcloud-zone01.image.authenticate-sudo} diff --git a/providers/cloudservers-uk/pom.xml b/providers/cloudservers-uk/pom.xml index 4f9edcf3ea..22ead7c37c 100644 --- a/providers/cloudservers-uk/pom.xml +++ b/providers/cloudservers-uk/pom.xml @@ -39,7 +39,8 @@ ${test.rackspace-uk.identity} ${test.rackspace-uk.credential} - + + @@ -110,7 +111,8 @@ ${test.cloudservers-uk.identity} ${test.cloudservers-uk.credential} ${test.cloudservers-uk.image-id} - ${test.cloudservers-uk.login-user} + ${test.cloudservers-uk.image.login-user} + ${test.cloudservers-uk.image.authenticate-sudo} diff --git a/providers/cloudservers-us/pom.xml b/providers/cloudservers-us/pom.xml index 12313e3015..6c9e4d2881 100644 --- a/providers/cloudservers-us/pom.xml +++ b/providers/cloudservers-us/pom.xml @@ -39,7 +39,8 @@ ${test.rackspace-us.identity} ${test.rackspace-us.credential} - + + @@ -111,7 +112,8 @@ ${test.cloudservers-us.identity} ${test.cloudservers-us.credential} ${test.cloudservers-us.image-id} - ${test.cloudservers-us.login-user} + ${test.cloudservers-us.image.login-user} + ${test.cloudservers-us.image.authenticate-sudo} diff --git a/providers/cloudsigma-lvs/pom.xml b/providers/cloudsigma-lvs/pom.xml index 842ba6d7b5..492fe13433 100644 --- a/providers/cloudsigma-lvs/pom.xml +++ b/providers/cloudsigma-lvs/pom.xml @@ -39,7 +39,8 @@ FIXME FIXME - + + @@ -105,7 +106,8 @@ ${test.cloudsigma-lvs.identity} ${test.cloudsigma-lvs.credential} ${test.cloudsigma-lvs.image-id} - ${test.cloudsigma-lvs.login-user} + ${test.cloudsigma-lvs.image.login-user} + ${test.cloudsigma-lvs.image.authenticate-sudo} diff --git a/providers/cloudsigma-zrh/pom.xml b/providers/cloudsigma-zrh/pom.xml index 8323616e6b..2efb74f244 100644 --- a/providers/cloudsigma-zrh/pom.xml +++ b/providers/cloudsigma-zrh/pom.xml @@ -39,7 +39,8 @@ FIXME FIXME - + + @@ -105,7 +106,8 @@ ${test.cloudsigma-zrh.identity} ${test.cloudsigma-zrh.credential} ${test.cloudsigma-zrh.image-id} - ${test.cloudsigma-zrh.login-user} + ${test.cloudsigma-zrh.image.login-user} + ${test.cloudsigma-zrh.image.authenticate-sudo} diff --git a/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java b/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java index 73ed76c365..e39f70ffc4 100644 --- a/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java +++ b/providers/eucalyptus-partnercloud-ec2/src/test/java/org/jclouds/epc/compute/strategy/EucalyptusPartnerCloudReviseParsedImageTest.java @@ -28,10 +28,10 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.ec2.compute.functions.EC2ImageParser; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.domain.Image; @@ -60,32 +60,53 @@ public class EucalyptusPartnerCloudReviseParsedImageTest { Set result = convertImages("/eucalyptus_images.xml"); assertEquals(result.size(), 3); - assertEquals(Iterables.get(result, 0).toString(), new ImageBuilder().operatingSystem( - OperatingSystem.builder().family(OsFamily.DEBIAN).arch("paravirtual").version("6.0").description( - "debian-6.0-x86_64/debian.6-0.x86-64.img.manifest.xml").is64Bit(true).build()).description( - "debian-6.0-x86_64/debian.6-0.x86-64.img.manifest.xml") - .defaultCredentials(new Credentials("root", null)).id("us-east-1/emi-892C130F").providerId( - "emi-892C130F").location(defaultLocation).userMetadata( + assertEquals( + Iterables.get(result, 0).toString(), + new ImageBuilder() + .operatingSystem( + OperatingSystem.builder().family(OsFamily.DEBIAN).arch("paravirtual").version("6.0") + .description("debian-6.0-x86_64/debian.6-0.x86-64.img.manifest.xml").is64Bit(true) + .build()) + .description("debian-6.0-x86_64/debian.6-0.x86-64.img.manifest.xml") + .defaultCredentials(new LoginCredentials("root", null, null, false)) + .id("us-east-1/emi-892C130F") + .providerId("emi-892C130F") + .location(defaultLocation) + .userMetadata( ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + "paravirtual", "hypervisor", "xen")).build().toString()); - assertEquals(Iterables.get(result, 1).toString(), new ImageBuilder().operatingSystem( - OperatingSystem.builder().family(OsFamily.CENTOS).arch("paravirtual").version("5.5").description( - "centos-5.5-x86_64/centos.5-5.x86-64.img.manifest.xml").is64Bit(true).build()).description( - "centos-5.5-x86_64/centos.5-5.x86-64.img.manifest.xml") - .defaultCredentials(new Credentials("root", null)).id("us-east-1/emi-9B751369").providerId( - "emi-9B751369").location(defaultLocation).userMetadata( + assertEquals( + Iterables.get(result, 1).toString(), + new ImageBuilder() + .operatingSystem( + OperatingSystem.builder().family(OsFamily.CENTOS).arch("paravirtual").version("5.5") + .description("centos-5.5-x86_64/centos.5-5.x86-64.img.manifest.xml").is64Bit(true) + .build()) + .description("centos-5.5-x86_64/centos.5-5.x86-64.img.manifest.xml") + .defaultCredentials(new LoginCredentials("root", null, null, false)) + .id("us-east-1/emi-9B751369") + .providerId("emi-9B751369") + .location(defaultLocation) + .userMetadata( ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + "paravirtual", "hypervisor", "xen")).build().toString()); - assertEquals(Iterables.get(result, 2).toString(), new ImageBuilder().operatingSystem( - OperatingSystem.builder().family(OsFamily.UBUNTU).arch("paravirtual").version("10.04").description( - "ubuntu-10.04-x86_64/ubuntu.10-04.x86-64.img.manifest.xml").is64Bit(true).build()).description( - "ubuntu-10.04-x86_64/ubuntu.10-04.x86-64.img.manifest.xml").defaultCredentials( - new Credentials("root", null)).id("us-east-1/emi-E0641459").providerId("emi-E0641459").location( - defaultLocation).userMetadata( - ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", - "paravirtual", "hypervisor", "xen")).build().toString()); + assertEquals( + Iterables.get(result, 2).toString(), + new ImageBuilder() + .operatingSystem( + OperatingSystem.builder().family(OsFamily.UBUNTU).arch("paravirtual").version("10.04") + .description("ubuntu-10.04-x86_64/ubuntu.10-04.x86-64.img.manifest.xml").is64Bit(true) + .build()) + .description("ubuntu-10.04-x86_64/ubuntu.10-04.x86-64.img.manifest.xml") + .defaultCredentials(new LoginCredentials("root", null, null, false)) + .id("us-east-1/emi-E0641459") + .providerId("emi-E0641459") + .location(defaultLocation) + .userMetadata( + ImmutableMap.of("owner", "admin", "rootDeviceType", "instance-store", "virtualizationType", + "paravirtual", "hypervisor", "xen")).build().toString()); } diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridContextBuilder.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridContextBuilder.java index 6aae3dc9ca..d0c16ce5e9 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridContextBuilder.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridContextBuilder.java @@ -26,7 +26,6 @@ import org.jclouds.compute.ComputeServiceContextBuilder; import org.jclouds.compute.internal.ComputeServiceContextImpl; import org.jclouds.gogrid.compute.config.GoGridComputeServiceContextModule; import org.jclouds.gogrid.config.GoGridRestClientModule; -import org.jclouds.gogrid.config.internal.GoGridResolveImagesModule; import com.google.inject.Key; import com.google.inject.Module; @@ -52,11 +51,6 @@ public class GoGridContextBuilder extends modules.add(new GoGridComputeServiceContextModule()); } - @Override - protected void addImageResolutionModule() { - modules.add(new GoGridResolveImagesModule()); - } - @Override public ComputeServiceContext buildComputeServiceContext() { return this diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java index 8e0e905776..ae0abcc9ef 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java @@ -35,7 +35,6 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.ServerState; @@ -59,7 +58,6 @@ public class ServerToNodeMetadata implements Function { private final Supplier> images; private final Supplier> hardwares; private final Supplier> locations; - private final Map credentialStore; static class FindImageForServer implements Predicate { private final Server instance; @@ -92,11 +90,10 @@ public class ServerToNodeMetadata implements Function { } @Inject - ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, - @Memoized Supplier> images, @Memoized Supplier> hardwares, - Supplier> locations) { + ServerToNodeMetadata(Map serverStateToNodeState, + @Memoized Supplier> images, @Memoized Supplier> hardwares, + Supplier> locations) { this.serverStateToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); this.hardwares = checkNotNull(hardwares, "hardwares"); this.locations = checkNotNull(locations, "locations"); @@ -118,7 +115,6 @@ public class ServerToNodeMetadata implements Function { builder.state(serverStateToNodeState.get(from.getState())); builder.publicAddresses(ImmutableSet.of(from.getIp().getIp())); - builder.credentials(credentialStore.get("node#" + from.getId())); return builder.build(); } diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java index 0c8525e3dc..3e50067bfb 100644 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java +++ b/providers/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridImageSupplier.java @@ -77,7 +77,7 @@ public class GoGridImageSupplier implements Supplier> { builder.ids(from.getId() + ""); builder.name(from.getFriendlyName()); builder.description(from.getDescription()); - builder.defaultCredentials(authenticator.execute(from)); + builder.defaultCredentials(authenticator.apply(from)); builder.operatingSystem(parseOs(from)); images.add(builder.build()); } diff --git a/providers/gogrid/src/main/java/org/jclouds/gogrid/config/internal/GoGridResolveImagesModule.java b/providers/gogrid/src/main/java/org/jclouds/gogrid/config/internal/GoGridResolveImagesModule.java deleted file mode 100644 index abe3a5c742..0000000000 --- a/providers/gogrid/src/main/java/org/jclouds/gogrid/config/internal/GoGridResolveImagesModule.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.gogrid.config.internal; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.compute.config.ResolvesImages; -import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; -import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; -import org.jclouds.domain.Credentials; -import org.jclouds.javax.annotation.Nullable; - -import com.google.inject.AbstractModule; - -/** - * @author Oleksiy Yarmula - */ -@ResolvesImages -public class GoGridResolveImagesModule extends AbstractModule { - @Override - protected void configure() { - bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to( - GoGridPopulateDefaultLoginCredentialsForImageStrategy.class); - } - - @Singleton - public static class GoGridPopulateDefaultLoginCredentialsForImageStrategy extends ReturnCredentialsBoundToImage { - @Inject - public GoGridPopulateDefaultLoginCredentialsForImageStrategy(@Nullable @Named("image") Credentials creds) { - super(creds); - } - - @Override - public Credentials execute(Object resourceToAuthenticate) { - if (creds != null) - return creds; - return new Credentials("root", null); - } - } - -} diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java index 517bf0e43d..eca8e81480 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java @@ -323,7 +323,7 @@ public class GoGridLiveTestDisabled { */ @Test(enabled = true) public void testImageLifecycle() { - GetImageListOptions options = new GetImageListOptions.Builder().publicDatabaseServers(); + GetImageListOptions options = GetImageListOptions.Builder.publicDatabaseServers(); Set images = client.getImageServices().getImageList(options); Predicate isDatabaseServer = new Predicate() { diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java index 40c3abb8c9..f9cc4892fa 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java @@ -24,7 +24,6 @@ import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import static org.testng.Assert.assertEquals; -import java.net.UnknownHostException; import java.util.Map; import java.util.Set; @@ -33,7 +32,6 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; @@ -58,7 +56,7 @@ public class ServerToNodeMetadataTest { @SuppressWarnings("unchecked") @Test - public void testApplySetsTagFromNameAndCredentialsFromName() throws UnknownHostException { + public void testApplySetsTagFromNameAndCredentialsFromName() { Map serverStateToNodeState = createMock(Map.class); org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class); @@ -77,9 +75,6 @@ public class ServerToNodeMetadataTest { Location location = new LocationBuilder().scope(LocationScope.ZONE).id("1").description("US-West-1").build(); Map locations = ImmutableMap. of("1", location); - Map credentialsMap = createMock(Map.class); - expect(credentialsMap.get("node#1000")).andReturn(new Credentials("user", "pass")); - expect(server.getIp()).andReturn(new Ip("127.0.0.1")); ServerImage image = createMock(ServerImage.class); @@ -95,9 +90,8 @@ public class ServerToNodeMetadataTest { replay(server); replay(image); replay(jcImage); - replay(credentialsMap); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, credentialsMap, Suppliers + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, Suppliers .> ofInstance(images), Suppliers .> ofInstance(GoGridHardwareSupplier.H_ALL), Suppliers .> ofInstance(locations)); @@ -106,11 +100,9 @@ public class ServerToNodeMetadataTest { assertEquals(metadata.getLocation(), location); assertEquals(metadata.getImageId(), "2000"); assertEquals(metadata.getGroup(), "group"); - assertEquals(metadata.getCredentials(), new Credentials("user", "pass")); verify(serverStateToNodeState); verify(image); - verify(credentialsMap); verify(server); verify(jcImage); diff --git a/providers/ninefold-compute/pom.xml b/providers/ninefold-compute/pom.xml index 68e6b9dccc..1ce8128f7c 100644 --- a/providers/ninefold-compute/pom.xml +++ b/providers/ninefold-compute/pom.xml @@ -39,7 +39,8 @@ FIXME_IDENTITY FIXME_CREDENTIAL 575 - user:Password01 + user:Password01 + user:Password01 @@ -106,7 +107,8 @@ ${test.ninefold-compute.identity} ${test.ninefold-compute.credential} ${test.ninefold-compute.image-id} - ${test.ninefold-compute.login-user} + ${test.ninefold-compute.image.login-user} + ${test.ninefold-compute.image.authenticate-sudo} diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java index 6222c7bfab..9d07e215b1 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/functions/ServerToNodeMetadata.java @@ -35,7 +35,6 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.logging.Logger; import org.jclouds.rimuhosting.miro.domain.Server; @@ -55,7 +54,6 @@ public class ServerToNodeMetadata implements Function { @Resource protected Logger logger = Logger.NULL; - protected final Map credentialStore; protected final Supplier> locations; protected final Function> getPublicAddresses; protected final Map runningStateToNodeState; @@ -73,18 +71,17 @@ 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, - @Memoized Supplier> locations, Map credentialStore, - Map runningStateToNodeState, @Memoized Supplier> images) { + @Memoized Supplier> locations, Map runningStateToNodeState, + @Memoized Supplier> images) { this.getPublicAddresses = checkNotNull(getPublicAddresses, "serverStateToNodeState"); this.locations = checkNotNull(locations, "locations"); - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.runningStateToNodeState = checkNotNull(runningStateToNodeState, "serverStateToNodeState"); this.images = checkNotNull(images, "images"); } @@ -102,12 +99,11 @@ public class ServerToNodeMetadata implements Function { builder.operatingSystem(parseOperatingSystem(from, location)); builder.hardware(null);// TODO if (from.getBillingData() != null && from.getBillingData().getDateCancelled() != null - && RunningState.NOTRUNNING == from.getState()) + && RunningState.NOTRUNNING == from.getState()) builder.state(NodeState.TERMINATED); else builder.state(runningStateToNodeState.get(from.getState())); builder.publicAddresses(getPublicAddresses.apply(from)); - builder.credentials(credentialStore.get("node#" + from.getId())); return builder.build(); } diff --git a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java index f4f62fe7dc..050b5f88be 100644 --- a/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java +++ b/providers/rimuhosting/src/main/java/org/jclouds/rimuhosting/miro/compute/suppliers/RimuHostingImageSupplier.java @@ -32,7 +32,6 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; import org.jclouds.rimuhosting.miro.RimuHostingClient; @@ -67,7 +66,6 @@ public class RimuHostingImageSupplier implements Supplier> 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()); diff --git a/providers/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java b/providers/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java index 37ff839b1c..3936278c51 100644 --- a/providers/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java +++ b/providers/savvis-symphonyvpdc/src/main/java/org/jclouds/savvis/vpdc/compute/functions/VMToNodeMetadata.java @@ -35,7 +35,6 @@ import org.jclouds.compute.domain.CIMOperatingSystem; 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.domain.Location; import org.jclouds.savvis.vpdc.domain.VM; import org.jclouds.savvis.vpdc.util.Utils; @@ -59,11 +58,9 @@ public class VMToNodeMetadata implements Function { NodeState.SUSPENDED).put(VM.Status.UNRESOLVED, NodeState.PENDING).build(); private final FindLocationForVM findLocationForVM; - private final Map credentialStore; @Inject - VMToNodeMetadata(Map credentialStore, FindLocationForVM findLocationForVM) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + VMToNodeMetadata(FindLocationForVM findLocationForVM) { this.findLocationForVM = checkNotNull(findLocationForVM, "findLocationForVM"); } @@ -85,7 +82,6 @@ public class VMToNodeMetadata implements Function { Set addresses = Utils.getIpsFromVM(from); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); - builder.credentials(credentialStore.get(from.getHref().toASCIIString())); return builder.build(); } diff --git a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java index 5c62c97853..4bf3162c46 100644 --- a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java +++ b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SliceToNodeMetadata.java @@ -38,6 +38,7 @@ import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import org.jclouds.slicehost.domain.Slice; @@ -125,7 +126,7 @@ public class SliceToNodeMetadata implements Function { } })); - builder.credentials(credentialStore.get("node#" + from.getId())); + builder.credentials(LoginCredentials.builder(credentialStore.get("node#" + from.getId())).build()); return builder.build(); } diff --git a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java index 28b4e1a687..feeffddb53 100644 --- a/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java +++ b/providers/slicehost/src/main/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImage.java @@ -24,7 +24,7 @@ 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 org.jclouds.domain.LoginCredentials; import com.google.common.base.Function; @@ -47,7 +47,7 @@ public class SlicehostImageToImage implements Function sliceStateToNodeState = SlicehostComputeServiceDependenciesModule.sliceStatusToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); diff --git a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java index b97c0afcd2..202a64c0cb 100644 --- a/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java +++ b/providers/slicehost/src/test/java/org/jclouds/slicehost/compute/functions/SlicehostImageToImageTest.java @@ -28,10 +28,10 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.domain.LoginCredentials; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; import org.jclouds.slicehost.xml.ImageHandlerTest; @@ -48,20 +48,27 @@ public class SlicehostImageToImageTest { @Test public void test() throws UnknownHostException { - assertEquals(convertImage(), new ImageBuilder().name("CentOS 5.2").operatingSystem( - new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit( - true).build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)).ids( - "2").build()); + assertEquals( + convertImage(), + new ImageBuilder() + .name("CentOS 5.2") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2") + .is64Bit(true).build()).description("CentOS 5.2") + .defaultCredentials(LoginCredentials.builder().user("root").build()).ids("2").build()); } @Test public void test32() throws UnknownHostException { - assertEquals(convertImage("/test_get_image32.xml"), new ImageBuilder().name("Ubuntu 10.10 (maverick) 32-bit") - .operatingSystem( - new OperatingSystem.Builder().family(OsFamily.UBUNTU).version("10.10").description( - "Ubuntu 10.10 (maverick) 32-bit").build()).description( - "Ubuntu 10.10 (maverick) 32-bit").defaultCredentials(new Credentials("root", null)).ids("70") - .build()); + assertEquals( + convertImage("/test_get_image32.xml"), + new ImageBuilder() + .name("Ubuntu 10.10 (maverick) 32-bit") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.UBUNTU).version("10.10") + .description("Ubuntu 10.10 (maverick) 32-bit").build()) + .description("Ubuntu 10.10 (maverick) 32-bit") + .defaultCredentials(LoginCredentials.builder().user("root").build()).ids("70").build()); } public static Image convertImage() { @@ -72,9 +79,9 @@ public class SlicehostImageToImageTest { org.jclouds.slicehost.domain.Image image = ImageHandlerTest.parseImage(resource); SlicehostImageToImage parser = new SlicehostImageToImage(new SlicehostImageToOperatingSystem( - new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice - .createInjector(new GsonModule()).getInstance(Json.class)))); + new BaseComputeServiceContextModule() { + }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) + .getInstance(Json.class)))); return parser.apply(image); } diff --git a/providers/softlayer/pom.xml b/providers/softlayer/pom.xml index e4c8182b91..ebffd1bd99 100644 --- a/providers/softlayer/pom.xml +++ b/providers/softlayer/pom.xml @@ -53,7 +53,8 @@ FIXME FIXME - + + @@ -110,7 +111,8 @@ ${test.softlayer.identity} ${test.softlayer.credential} ${test.softlayer.image-id} - ${test.softlayer.login-user} + ${test.softlayer.image.login-user} + ${test.softlayer.image.authenticate-sudo} diff --git a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/ProductItemToImage.java b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/ProductItemToImage.java index a99fc65fd5..e931e57759 100644 --- a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/ProductItemToImage.java +++ b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/ProductItemToImage.java @@ -33,7 +33,6 @@ import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; import org.jclouds.logging.Logger; import org.jclouds.softlayer.domain.ProductItem; import org.jclouds.softlayer.domain.ProductItemPrice; @@ -76,7 +75,6 @@ public class ProductItemToImage implements Function { return new ImageBuilder() .ids(imageId().apply(productItem)) .description(productItem.getDescription()) - .defaultCredentials(new Credentials("root", null)) .operatingSystem(os) .build(); } diff --git a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java index be376a5a3f..496cd49eb0 100644 --- a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java +++ b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java @@ -34,7 +34,6 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.softlayer.SoftLayerClient; import org.jclouds.softlayer.domain.Datacenter; @@ -56,20 +55,17 @@ import com.google.common.collect.Iterables; public class VirtualGuestToNodeMetadata implements Function { public static final Map serverStateToNodeState = ImmutableMap - . builder().put(VirtualGuest.State.HALTED, NodeState.PENDING).put( - VirtualGuest.State.PAUSED, NodeState.SUSPENDED).put(VirtualGuest.State.RUNNING, NodeState.RUNNING) - .put(VirtualGuest.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); + . builder().put(VirtualGuest.State.HALTED, NodeState.PENDING) + .put(VirtualGuest.State.PAUSED, NodeState.SUSPENDED).put(VirtualGuest.State.RUNNING, NodeState.RUNNING) + .put(VirtualGuest.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); - private final Map credentialStore; private final FindLocationForVirtualGuest findLocationForVirtualGuest; private final GetHardwareForVirtualGuest getHardwareForVirtualGuest; private final GetImageForVirtualGuest getImageForVirtualGuest; @Inject - VirtualGuestToNodeMetadata(Map credentialStore, - FindLocationForVirtualGuest findLocationForVirtualGuest, - GetHardwareForVirtualGuest getHardwareForVirtualGuest, GetImageForVirtualGuest getImageForVirtualGuest) { - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + VirtualGuestToNodeMetadata(FindLocationForVirtualGuest findLocationForVirtualGuest, + GetHardwareForVirtualGuest getHardwareForVirtualGuest, GetImageForVirtualGuest getImageForVirtualGuest) { this.findLocationForVirtualGuest = checkNotNull(findLocationForVirtualGuest, "findLocationForVirtualGuest"); this.getHardwareForVirtualGuest = checkNotNull(getHardwareForVirtualGuest, "getHardwareForVirtualGuest"); this.getImageForVirtualGuest = checkNotNull(getImageForVirtualGuest, "getImageForVirtualGuest"); @@ -102,8 +98,6 @@ public class VirtualGuestToNodeMetadata implements Function of(from.getPrimaryIpAddress())); if (from.getPrimaryBackendIpAddress() != null) builder.privateAddresses(ImmutableSet. of(from.getPrimaryBackendIpAddress())); - - builder.credentials(credentialStore.get("node#" + from.getId())); return builder.build(); } @@ -132,7 +126,7 @@ public class VirtualGuestToNodeMetadata implements Function, Hardware> productItemsToHardware) { + Function, Hardware> productItemsToHardware) { this.client = checkNotNull(client, "client"); this.productItemsToHardware = checkNotNull(productItemsToHardware, "productItemsToHardware"); diff --git a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/strategy/SoftLayerComputeServiceAdapter.java b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/strategy/SoftLayerComputeServiceAdapter.java index a9c3b4c1c8..528f334b5e 100644 --- a/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/strategy/SoftLayerComputeServiceAdapter.java +++ b/providers/softlayer/src/main/java/org/jclouds/softlayer/compute/strategy/SoftLayerComputeServiceAdapter.java @@ -46,7 +46,7 @@ import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.domain.Template; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.softlayer.SoftLayerClient; @@ -141,8 +141,8 @@ public class SoftLayerComputeServiceAdapter implements result = client.getVirtualGuestClient().getVirtualGuest(result.getId()); Password pw = get(result.getOperatingSystem().getPasswords(), 0); - return new NodeAndInitialCredentials(result, result.getId() + "", new Credentials(pw.getUsername(), - pw.getPassword())); + return new NodeAndInitialCredentials(result, result.getId() + "", LoginCredentials.builder().user(pw.getUsername()).password( + pw.getPassword()).build()); } private Iterable getPrices(Template template) { diff --git a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java index 09da8652a5..94eb341b4d 100644 --- a/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java +++ b/providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java @@ -21,8 +21,6 @@ package org.jclouds.softlayer.compute.functions; import static org.easymock.classextension.EasyMock.createNiceMock; import static org.testng.Assert.assertEquals; -import java.net.UnknownHostException; -import java.util.Map; import java.util.Set; import org.jclouds.compute.domain.Hardware; @@ -33,11 +31,9 @@ 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.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.softlayer.SoftLayerClient; import org.jclouds.softlayer.compute.functions.VirtualGuestToNodeMetadata.FindLocationForVirtualGuest; -import org.jclouds.softlayer.domain.Password; import org.jclouds.softlayer.domain.VirtualGuest; import org.jclouds.softlayer.parse.ParseBadVirtualGuest; import org.jclouds.softlayer.parse.ParseVirtualGuestHaltedTest; @@ -49,9 +45,7 @@ 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.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; /** * @author Adrian Cole @@ -60,166 +54,139 @@ import com.google.common.collect.Iterables; public class VirtualGuestToNodeMetadataTest { @Test - public void testApplyWhereVirtualGuestWithNoPassword() throws UnknownHostException { + public void testApplyWhereVirtualGuestWithNoPassword() { // notice if we've already parsed this properly here, we can rely on it. VirtualGuest guest = new ParseVirtualGuestWithNoPasswordTest().expected(); - // note we are testing when no credentials are here. otherwise would be ("node#416696", new - // Credentials("root", "password")) - Map credentialStore = ImmutableMap. of(); - // setup so that we have an expected Location to be parsed from the guest. Location expectedLocation = DatacenterToLocationTest.function.apply(guest.getDatacenter()); Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of(expectedLocation)); + . of(expectedLocation)); - VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(credentialStore, - new FindLocationForVirtualGuest(locationSupplier),new GetHardwareForVirtualGuestMock(),new GetImageForVirtualGuestMock()); + VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(new FindLocationForVirtualGuest( + locationSupplier), new GetHardwareForVirtualGuestMock(), new GetImageForVirtualGuestMock()); NodeMetadata node = parser.apply(guest); - assertEquals(node, new NodeMetadataBuilder().ids("416788") - .name("node1000360500").hostname("node1000360500") - .location(expectedLocation).state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("173.192.29.186")).privateAddresses(ImmutableSet.of("10.37.102.194")) - .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) - .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) - .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()) - .build()); + assertEquals( + node, + new NodeMetadataBuilder().ids("416788").name("node1000360500").hostname("node1000360500") + .location(expectedLocation).state(NodeState.PENDING) + .publicAddresses(ImmutableSet.of("173.192.29.186")) + .privateAddresses(ImmutableSet.of("10.37.102.194")) + .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) + .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) + .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()).build()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), null); } @Test - public void testApplyWhereVirtualIsBad() throws UnknownHostException { + public void testApplyWhereVirtualIsBad() { // notice if we've already parsed this properly here, we can rely on it. VirtualGuest guest = new ParseBadVirtualGuest().expected(); - // note we are testing when no credentials are here. otherwise would be ("node#416696", new - // Credentials("root", "password")) - Map credentialStore = ImmutableMap. of(); - // no location here Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of()); + . of()); - VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(credentialStore, - new FindLocationForVirtualGuest(locationSupplier),new GetHardwareForVirtualGuestMock(),new GetImageForVirtualGuestMock()); + VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(new FindLocationForVirtualGuest( + locationSupplier), new GetHardwareForVirtualGuestMock(), new GetImageForVirtualGuestMock()); NodeMetadata node = parser.apply(guest); - assertEquals(node, new NodeMetadataBuilder().ids("413348") - .name("foo-ef4").hostname("foo-ef4").group("foo") - .state(NodeState.PENDING) - .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) - .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) - .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()) - .build()); + assertEquals( + node, + new NodeMetadataBuilder().ids("413348").name("foo-ef4").hostname("foo-ef4").group("foo") + .state(NodeState.PENDING).hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) + .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) + .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()).build()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), null); } @Test - public void testApplyWhereVirtualGuestIsHalted() throws UnknownHostException { + public void testApplyWhereVirtualGuestIsHalted() { // notice if we've already parsed this properly here, we can rely on it. VirtualGuest guest = new ParseVirtualGuestHaltedTest().expected(); - Password password = Iterables.get(guest.getOperatingSystem().getPasswords(), 0); - Credentials credentials = new Credentials(password.getUsername(),password.getPassword()); - Map credentialStore = ImmutableMap. of("node#416700",credentials); - // setup so that we have an expected Location to be parsed from the guest. Location expectedLocation = DatacenterToLocationTest.function.apply(guest.getDatacenter()); Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of(expectedLocation)); + . of(expectedLocation)); - VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(credentialStore, - new FindLocationForVirtualGuest(locationSupplier),new GetHardwareForVirtualGuestMock(),new GetImageForVirtualGuestMock()); + VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(new FindLocationForVirtualGuest( + locationSupplier), new GetHardwareForVirtualGuestMock(), new GetImageForVirtualGuestMock()); NodeMetadata node = parser.apply(guest); - assertEquals(node, new NodeMetadataBuilder().ids("416700") - .name("node1703810489").hostname("node1703810489") - .location(expectedLocation).state(NodeState.PENDING).credentials(credentials) - .publicAddresses(ImmutableSet.of("173.192.29.187")).privateAddresses(ImmutableSet.of("10.37.102.195")) - .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) - .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) - .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()) - .build()); + assertEquals( + node, + new NodeMetadataBuilder().ids("416700").name("node1703810489").hostname("node1703810489") + .location(expectedLocation).state(NodeState.PENDING) + .publicAddresses(ImmutableSet.of("173.192.29.187")) + .privateAddresses(ImmutableSet.of("10.37.102.195")) + .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) + .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) + .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()).build()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), credentials); } @Test - public void testApplyWhereVirtualGuestIsPaused() throws UnknownHostException { + public void testApplyWhereVirtualGuestIsPaused() { // notice if we've already parsed this properly here, we can rely on it. VirtualGuest guest = new ParseVirtualGuestPausedTest().expected(); - Password password = Iterables.get(guest.getOperatingSystem().getPasswords(),0); - Credentials credentials = new Credentials(password.getUsername(),password.getPassword()); - Map credentialStore = ImmutableMap. of("node#416700",credentials); - // setup so that we have an expected Location to be parsed from the guest. Location expectedLocation = DatacenterToLocationTest.function.apply(guest.getDatacenter()); Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of(expectedLocation)); + . of(expectedLocation)); - VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(credentialStore, - new FindLocationForVirtualGuest(locationSupplier),new GetHardwareForVirtualGuestMock(),new GetImageForVirtualGuestMock()); + VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(new FindLocationForVirtualGuest( + locationSupplier), new GetHardwareForVirtualGuestMock(), new GetImageForVirtualGuestMock()); NodeMetadata node = parser.apply(guest); - assertEquals(node, new NodeMetadataBuilder().ids("416700") - .name("node1703810489").hostname("node1703810489") - .location(expectedLocation).state(NodeState.SUSPENDED).credentials(credentials) - .publicAddresses(ImmutableSet.of("173.192.29.187")).privateAddresses(ImmutableSet.of("10.37.102.195")) - .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) - .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) - .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()) - .build()); + assertEquals( + node, + new NodeMetadataBuilder().ids("416700").name("node1703810489").hostname("node1703810489") + .location(expectedLocation).state(NodeState.SUSPENDED) + .publicAddresses(ImmutableSet.of("173.192.29.187")) + .privateAddresses(ImmutableSet.of("10.37.102.195")) + .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) + .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) + .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()).build()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), credentials); } @Test - public void testApplyWhereVirtualGuestIsRunning() throws UnknownHostException { + public void testApplyWhereVirtualGuestIsRunning() { // notice if we've already parsed this properly here, we can rely on it. VirtualGuest guest = new ParseVirtualGuestRunningTest().expected(); - Password password = Iterables.get(guest.getOperatingSystem().getPasswords(),0); - Credentials credentials = new Credentials(password.getUsername(),password.getPassword()); - Map credentialStore = ImmutableMap. of("node#416700",credentials); - // setup so that we have an expected Location to be parsed from the guest. Location expectedLocation = DatacenterToLocationTest.function.apply(guest.getDatacenter()); Supplier> locationSupplier = Suppliers.> ofInstance(ImmutableSet - . of(expectedLocation)); + . of(expectedLocation)); - VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(credentialStore, - new FindLocationForVirtualGuest(locationSupplier),new GetHardwareForVirtualGuestMock(),new GetImageForVirtualGuestMock()); + VirtualGuestToNodeMetadata parser = new VirtualGuestToNodeMetadata(new FindLocationForVirtualGuest( + locationSupplier), new GetHardwareForVirtualGuestMock(), new GetImageForVirtualGuestMock()); NodeMetadata node = parser.apply(guest); - assertEquals(node, new NodeMetadataBuilder().ids("416700") - .name("node1703810489").hostname("node1703810489") - .location(expectedLocation).state(NodeState.RUNNING).credentials(credentials) - .publicAddresses(ImmutableSet.of("173.192.29.187")).privateAddresses(ImmutableSet.of("10.37.102.195")) - .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) - .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) - .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()) - .build()); + assertEquals( + node, + new NodeMetadataBuilder().ids("416700").name("node1703810489").hostname("node1703810489") + .location(expectedLocation).state(NodeState.RUNNING) + .publicAddresses(ImmutableSet.of("173.192.29.187")) + .privateAddresses(ImmutableSet.of("10.37.102.195")) + .hardware(new GetHardwareForVirtualGuestMock().getHardware(guest)) + .imageId(new GetImageForVirtualGuestMock().getImage(guest).getId()) + .operatingSystem(new GetImageForVirtualGuestMock().getImage(guest).getOperatingSystem()).build()); - // because it wasn't present in the credential store. - assertEquals(node.getCredentials(), credentials); } private static class GetHardwareForVirtualGuestMock extends VirtualGuestToNodeMetadata.GetHardwareForVirtualGuest { @@ -242,8 +209,7 @@ public class VirtualGuestToNodeMetadataTest { @Override public Image getImage(VirtualGuest guest) { return new ImageBuilder().ids("123").description("mocked image") - .operatingSystem(OperatingSystem.builder().description("foo os").build()) - .build(); + .operatingSystem(OperatingSystem.builder().description("foo os").build()).build(); } } } diff --git a/providers/trmk-ecloud/src/test/java/org/jclouds/trmk/ecloud/compute/TerremarkECloudComputeServiceLiveTest.java b/providers/trmk-ecloud/src/test/java/org/jclouds/trmk/ecloud/compute/TerremarkECloudComputeServiceLiveTest.java index b6f34f8bbe..351be4df25 100644 --- a/providers/trmk-ecloud/src/test/java/org/jclouds/trmk/ecloud/compute/TerremarkECloudComputeServiceLiveTest.java +++ b/providers/trmk-ecloud/src/test/java/org/jclouds/trmk/ecloud/compute/TerremarkECloudComputeServiceLiveTest.java @@ -31,7 +31,6 @@ import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.domain.Credentials; import org.jclouds.rest.RestContext; import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient; diff --git a/sandbox-apis/virtualbox/pom.xml b/sandbox-apis/virtualbox/pom.xml index 6162b39169..70a26d282b 100644 --- a/sandbox-apis/virtualbox/pom.xml +++ b/sandbox-apis/virtualbox/pom.xml @@ -39,7 +39,8 @@ administrator 12345 - + + @@ -144,7 +145,8 @@ ${test.virtualbox.identity} ${test.virtualbox.credential} ${test.virtualbox.image-id} - ${test.virtualbox.login-user} + ${test.virtualbox.image.login-user} + ${test.virtualbox.image.authenticate-sudo} diff --git a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index 808b30efa5..ee7d74eaa3 100644 --- a/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/sandbox-apis/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -98,11 +98,6 @@ public class IMachineToNodeMetadata implements Function // nodeMetadataBuilder.imageId(""); // nodeMetadataBuilder.group(""); - String provider = "virtualbox"; - String identity = System.getProperty("test." + provider + ".identity", "administrator"); - String credential = System.getProperty("test." + provider + ".credential", "12345"); - - nodeMetadataBuilder.credentials(new Credentials(identity, credential)); nodeMetadataBuilder.id(vm.getId()); return nodeMetadataBuilder.build(); } diff --git a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerToNodeMetadata.java b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerToNodeMetadata.java index ee3642ba6f..51d17cbb72 100644 --- a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerToNodeMetadata.java +++ b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerToNodeMetadata.java @@ -36,6 +36,7 @@ import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeState; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; +import org.jclouds.domain.LoginCredentials; import org.jclouds.servermanager.Server; import com.google.common.base.Function; @@ -86,7 +87,7 @@ public class ServerToNodeMetadata implements Function { builder.state(serverStatusToNodeState.get(from.status)); builder.publicAddresses(ImmutableSet. of(from.publicAddress)); builder.privateAddresses(ImmutableSet. of(from.privateAddress)); - builder.credentials(credentialStore.get(from.id + "")); + builder.credentials(LoginCredentials.builder(credentialStore.get(from.id + "")).build()); return builder.build(); } diff --git a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/strategy/ServerManagerComputeServiceAdapter.java b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/strategy/ServerManagerComputeServiceAdapter.java index 4289750ef4..9e5b0b619e 100644 --- a/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/strategy/ServerManagerComputeServiceAdapter.java +++ b/skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/strategy/ServerManagerComputeServiceAdapter.java @@ -26,7 +26,7 @@ import javax.inject.Singleton; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.domain.Template; -import org.jclouds.domain.Credentials; +import org.jclouds.domain.LoginCredentials; import org.jclouds.servermanager.Datacenter; import org.jclouds.servermanager.Hardware; import org.jclouds.servermanager.Image; @@ -55,7 +55,8 @@ public class ServerManagerComputeServiceAdapter implements ComputeServiceAdapter Server from = client.createServerInDC(template.getLocation().getId(), name, Integer.parseInt(template.getImage().getProviderId()), Integer.parseInt(template.getHardware().getProviderId())); - return new NodeAndInitialCredentials(from, from.id + "", new Credentials(from.loginUser, from.password)); + return new NodeAndInitialCredentials(from, from.id + "", LoginCredentials.builder().user(from.loginUser) + .password(from.password).build()); } @Override