Issue 441: added new type: LoginCredentials, and (jclouds|provider).image.(login-user|authenticate-sudo) context properties

This commit is contained in:
Adrian Cole 2011-11-21 10:57:58 +02:00
parent 1b2a221744
commit 4a5af1e7a5
139 changed files with 2558 additions and 1693 deletions

View File

@ -42,6 +42,8 @@ import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.LoginCredentials.Builder;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.util.Strings2; import org.jclouds.util.Strings2;
@ -92,24 +94,25 @@ public class NodeToNodeMetadata implements Function<Node, NodeMetadata> {
builder.publicAddresses(ImmutableSet.<String> of(from.getHostname())); builder.publicAddresses(ImmutableSet.<String> of(from.getHostname()));
if (from.getUsername() != null) { if (from.getUsername() != null) {
Credentials creds = null; Builder credBuilder = LoginCredentials.builder().user(from.getUsername());
if (from.getCredentialUrl() != null) { if (from.getCredentialUrl() != null) {
try { try {
creds = new Credentials(from.getUsername(), Strings2.toStringAndClose(slurp.apply(from credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl())));
.getCredentialUrl())));
} catch (IOException e) { } catch (IOException e) {
logger.error(e, "URI could not be read: %s", from.getCredentialUrl()); logger.error(e, "URI could not be read: %s", from.getCredentialUrl());
} }
} else if (from.getCredential() != null) { } else if (from.getCredential() != null) {
creds = new Credentials(from.getUsername(), from.getCredential()); credBuilder.credential(from.getCredential());
} }
if (creds != null) if (from.getSudoPassword() != null){
credBuilder.password(from.getSudoPassword());
credBuilder.authenticateSudo(true);
}
LoginCredentials creds = credBuilder.build();
builder.credentials(creds); builder.credentials(creds);
credentialStore.put("node#" + from.getId(), creds); credentialStore.put("node#" + from.getId(), creds);
} }
if (from.getSudoPassword() != null)
builder.adminPassword(from.getSudoPassword());
return builder.build(); return builder.build();
} }

View File

@ -30,13 +30,16 @@ import org.jclouds.byon.config.CacheNodeStoreModule;
import org.jclouds.byon.functions.NodesFromYamlTest; import org.jclouds.byon.functions.NodesFromYamlTest;
import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.cache.Cache; import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Module; import com.google.inject.Module;
/** /**
@ -83,8 +86,8 @@ public class BYONComputeServiceTest {
assertEquals(supplier.get().asMap(), assertEquals(supplier.get().asMap(),
ImmutableMap.<String, Node> of(NodesFromYamlTest.TEST1.getId(), NodesFromYamlTest.TEST1)); ImmutableMap.<String, Node> of(NodesFromYamlTest.TEST1.getId(), NodesFromYamlTest.TEST1));
assertEquals(context.getComputeService().listNodes(), assertEquals(context.getComputeService().listNodes().toString(),
ImmutableSet.of(expectedNodeMetadataFromResource(endpoint))); ImmutableSet.of(expectedNodeMetadataFromResource(endpoint)).toString());
assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(providerLocation)); assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(providerLocation));
} finally { } finally {
if (context != null) if (context != null)
@ -98,8 +101,8 @@ public class BYONComputeServiceTest {
String endpoint = "file://" + getClass().getResource("/test_location.yaml").getPath(); String endpoint = "file://" + getClass().getResource("/test_location.yaml").getPath();
Properties props = new Properties(); Properties props = new Properties();
props.setProperty("byon.endpoint", endpoint); props.setProperty("byon.endpoint", endpoint);
context = new ComputeServiceContextFactory().createContext("byon", "foo", "bar", context = new ComputeServiceContextFactory().createContext("byon", "foo", "bar", ImmutableSet.<Module> of(),
ImmutableSet.<Module> of(), props); props);
assertEquals(context.getProviderSpecificContext().getEndpoint(), URI.create(endpoint)); assertEquals(context.getProviderSpecificContext().getEndpoint(), URI.create(endpoint));
@ -115,9 +118,26 @@ public class BYONComputeServiceTest {
Location virginia = zoneCalled("virginia", providerLocation); Location virginia = zoneCalled("virginia", providerLocation);
Location maryland = zoneCalled("maryland", providerLocation); Location maryland = zoneCalled("maryland", providerLocation);
assertEquals(context.getComputeService().listNodes(), ImmutableSet.of( assertEquals(
expectedNodeMetadataFromResource(1, endpoint, virginia), context.getComputeService().listNodes().toString(),
expectedNodeMetadataFromResource(2, endpoint, maryland, 2022))); 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)); assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(virginia, maryland));
} finally { } finally {

View File

@ -34,6 +34,7 @@ import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
@ -86,11 +87,15 @@ public class NodeToNodeMetadataTest {
.hostname("cluster-" + id + ".mydomain.com") .hostname("cluster-" + id + ".mydomain.com")
.location(location) .location(location)
.userMetadata(ImmutableMap.of("Name", "foo")) .userMetadata(ImmutableMap.of("Name", "foo"))
.tags(ImmutableSet.of("vanilla"))
.state(NodeState.RUNNING) .state(NodeState.RUNNING)
.operatingSystem( .operatingSystem(
OperatingSystem.builder().description("redhat").family(OsFamily.RHEL).arch("x86").version("5.3") OperatingSystem.builder().description("redhat").family(OsFamily.RHEL).arch("x86").version("5.3")
.build()).publicAddresses(ImmutableSet.of("cluster-" + id + ".mydomain.com")) .build())
.credentials(new Credentials("myUser", NodesFromYamlTest.key)).adminPassword("happy bear").build(); .publicAddresses(ImmutableSet.of("cluster-" + id + ".mydomain.com"))
.credentials(
LoginCredentials.builder().user("myUser").privateKey(NodesFromYamlTest.key).password("happy bear")
.authenticateSudo(true).build()).build();
} }
@Test @Test

View File

@ -40,7 +40,8 @@
<test.cloudservers.identity>${test.rackspace.identity}</test.cloudservers.identity> <test.cloudservers.identity>${test.rackspace.identity}</test.cloudservers.identity>
<test.cloudservers.credential>${test.rackspace.credential}</test.cloudservers.credential> <test.cloudservers.credential>${test.rackspace.credential}</test.cloudservers.credential>
<test.cloudservers.image-id></test.cloudservers.image-id> <test.cloudservers.image-id></test.cloudservers.image-id>
<test.cloudservers.login-user></test.cloudservers.login-user> <test.cloudservers.image.login-user></test.cloudservers.image.login-user>
<test.cloudservers.image.authenticate-sudo></test.cloudservers.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -111,7 +112,8 @@
<test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity> <test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity>
<test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential> <test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential>
<test.cloudstack.image-id>${test.cloudstack.image-id}</test.cloudstack.image-id> <test.cloudstack.image-id>${test.cloudstack.image-id}</test.cloudstack.image-id>
<test.cloudstack.login-user>${test.cloudstack.login-user}</test.cloudstack.login-user> <test.cloudstack.image.login-user>${test.cloudstack.image.login-user}</test.cloudstack.image.login-user>
<test.cloudstack.image.authenticate-sudo>${test.cloudstack.image.authenticate-sudo}</test.cloudstack.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -39,7 +39,8 @@
<test.cloudsigma.identity>FIXME</test.cloudsigma.identity> <test.cloudsigma.identity>FIXME</test.cloudsigma.identity>
<test.cloudsigma.credential>FIXME</test.cloudsigma.credential> <test.cloudsigma.credential>FIXME</test.cloudsigma.credential>
<test.cloudsigma.image-id></test.cloudsigma.image-id> <test.cloudsigma.image-id></test.cloudsigma.image-id>
<test.cloudsigma.login-user></test.cloudsigma.login-user> <test.cloudsigma.image.login-user></test.cloudsigma.image.login-user>
<test.cloudsigma.image.authenticate-sudo></test.cloudsigma.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -97,7 +98,8 @@
<test.cloudsigma.identity>${test.cloudsigma.identity}</test.cloudsigma.identity> <test.cloudsigma.identity>${test.cloudsigma.identity}</test.cloudsigma.identity>
<test.cloudsigma.credential>${test.cloudsigma.credential}</test.cloudsigma.credential> <test.cloudsigma.credential>${test.cloudsigma.credential}</test.cloudsigma.credential>
<test.cloudsigma.image-id>${test.cloudsigma.image-id}</test.cloudsigma.image-id> <test.cloudsigma.image-id>${test.cloudsigma.image-id}</test.cloudsigma.image-id>
<test.cloudsigma.login-user>${test.cloudsigma.login-user}</test.cloudsigma.login-user> <test.cloudsigma.image.login-user>${test.cloudsigma.image.login-user}</test.cloudsigma.image.login-user>
<test.cloudsigma.image.authenticate-sudo>${test.cloudsigma.image.authenticate-sudo}</test.cloudsigma.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -50,8 +50,8 @@ import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.location.suppliers.JustProvider; import org.jclouds.location.suppliers.JustProvider;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -126,8 +126,8 @@ public class CloudSigmaComputeServiceAdapter implements
logger.debug("<< created server(%s)", from.getUuid()); logger.debug("<< created server(%s)", from.getUuid());
logger.debug(">> starting server(%s)", from.getUuid()); logger.debug(">> starting server(%s)", from.getUuid());
client.startServer(from.getUuid()); client.startServer(from.getUuid());
return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), LoginCredentials.builder()
new Credentials("root", defaultVncPassword)); .password(defaultVncPassword).authenticateSudo(true).build());
} }
@Override @Override

View File

@ -27,8 +27,8 @@ import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OperatingSystem.Builder; import org.jclouds.compute.domain.OperatingSystem.Builder;
import org.jclouds.compute.domain.OsFamilyVersion64Bit; import org.jclouds.compute.domain.OsFamilyVersion64Bit;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
@ -59,9 +59,10 @@ public class PreinstalledDiskToImage implements Function<DriveInfo, Image> {
builder.name(drive.getName()).description(description) builder.name(drive.getName()).description(description)
.is64Bit(drive.getBits() != null ? drive.getBits() == 64 : parsed.is64Bit).version(parsed.version) .is64Bit(drive.getBits() != null ? drive.getBits() == 64 : parsed.is64Bit).version(parsed.version)
.family(parsed.family); .family(parsed.family);
return new ImageBuilder().ids(drive.getUuid()).adminPassword("cloudsigma") return new ImageBuilder().ids(drive.getUuid())
.userMetadata(ImmutableMap.<String, String> of("size", drive.getSize() / 1024 / 1024 / 1024 + "")) .userMetadata(ImmutableMap.<String, String> of("size", drive.getSize() / 1024 / 1024 / 1024 + ""))
.defaultCredentials(new Credentials("cloudsigma", null)).location(locationSupplier.get()) .defaultCredentials(new LoginCredentials("cloudsigma", "cloudsigma", null, true))
.name(drive.getName()).description(description).operatingSystem(builder.build()).version("").build(); .location(locationSupplier.get()).name(drive.getName()).description(description)
.operatingSystem(builder.build()).version("").build();
} }
} }

View File

@ -44,7 +44,6 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder; import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -73,15 +72,12 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
private final Function<Server, String> getImageIdFromServer; private final Function<Server, String> getImageIdFromServer;
private final Function<String, Image> findImageForId; private final Function<String, Image> findImageForId;
private final Map<String, Credentials> credentialStore;
private final Supplier<Location> locationSupplier; private final Supplier<Location> locationSupplier;
private final Function<Device, Volume> deviceToVolume; private final Function<Device, Volume> deviceToVolume;
@Inject @Inject
ServerInfoToNodeMetadata(Map<String, Credentials> credentialStore, Function<Server, String> getImageIdFromServer, ServerInfoToNodeMetadata(Function<Server, String> getImageIdFromServer, Function<String, Image> findImageForId,
Function<String, Image> findImageForId, Function<Device, Volume> deviceToVolume, Function<Device, Volume> deviceToVolume, Supplier<Location> locationSupplier) {
Supplier<Location> locationSupplier) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier"); this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier");
this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume"); this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume");
this.findImageForId = checkNotNull(findImageForId, "findImageForId"); this.findImageForId = checkNotNull(findImageForId, "findImageForId");
@ -102,7 +98,6 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
Image image = findImageForId.apply(imageId); Image image = findImageForId.apply(imageId);
if (image != null) { if (image != null) {
builder.operatingSystem(image.getOperatingSystem()); builder.operatingSystem(image.getOperatingSystem());
builder.adminPassword(image.getAdminPassword());
} }
} }
builder.hardware(new HardwareBuilder().ids(from.getUuid()) builder.hardware(new HardwareBuilder().ids(from.getUuid())
@ -111,7 +106,6 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
builder.state(serverStatusToNodeState.get(from.getStatus())); builder.state(serverStatusToNodeState.get(from.getStatus()));
builder.publicAddresses(ImmutableSet.<String> of(from.getVnc().getIp())); builder.publicAddresses(ImmutableSet.<String> of(from.getVnc().getIp()));
builder.privateAddresses(ImmutableSet.<String> of()); builder.privateAddresses(ImmutableSet.<String> of());
builder.credentials(credentialStore.get("node#"+ from.getUuid()));
return builder.build(); return builder.build();
} }
@ -144,8 +138,8 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
} }
/** /**
* When we create the boot drive of the server, by convention we set the name to the image it * When we create the boot drive of the server, by convention we set the name
* came from. * to the image it came from.
* *
* @author Adrian Cole * @author Adrian Cole
* *

View File

@ -55,7 +55,8 @@
<test.cloudstack.domainAdminIdentity></test.cloudstack.domainAdminIdentity> <test.cloudstack.domainAdminIdentity></test.cloudstack.domainAdminIdentity>
<test.cloudstack.domainAdminCredential></test.cloudstack.domainAdminCredential> <test.cloudstack.domainAdminCredential></test.cloudstack.domainAdminCredential>
<test.cloudstack.image-id></test.cloudstack.image-id> <test.cloudstack.image-id></test.cloudstack.image-id>
<test.cloudstack.login-user></test.cloudstack.login-user> <test.cloudstack.image.login-user></test.cloudstack.image.login-user>
<test.cloudstack.image.authenticate-sudo></test.cloudstack.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -119,7 +120,8 @@
<test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity> <test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity>
<test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential> <test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential>
<test.cloudstack.image-id>${test.cloudstack.image-id}</test.cloudstack.image-id> <test.cloudstack.image-id>${test.cloudstack.image-id}</test.cloudstack.image-id>
<test.cloudstack.login-user>${test.cloudstack.login-user}</test.cloudstack.login-user> <test.cloudstack.image.login-user>${test.cloudstack.image.login-user}</test.cloudstack.image.login-user>
<test.cloudstack.image.authenticate-sudo>${test.cloudstack.image.authenticate-sudo}</test.cloudstack.image.authenticate-sudo>
<test.cloudstack.domainAdminIdentity>${test.cloudstack.domainAdminIdentity}</test.cloudstack.domainAdminIdentity> <test.cloudstack.domainAdminIdentity>${test.cloudstack.domainAdminIdentity}</test.cloudstack.domainAdminIdentity>
<test.cloudstack.domainAdminCredential>${test.cloudstack.domainAdminCredential}</test.cloudstack.domainAdminCredential> <test.cloudstack.domainAdminCredential>${test.cloudstack.domainAdminCredential}</test.cloudstack.domainAdminCredential>
</systemPropertyVariables> </systemPropertyVariables>

View File

@ -36,7 +36,6 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import org.jclouds.util.InetAddresses2; import org.jclouds.util.InetAddresses2;
@ -68,19 +67,16 @@ public class VirtualMachineToNodeMetadata implements Function<VirtualMachine, No
.put(VirtualMachine.State.SHUTDOWNED, NodeState.PENDING) .put(VirtualMachine.State.SHUTDOWNED, NodeState.PENDING)
.put(VirtualMachine.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build(); .put(VirtualMachine.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).build();
private final Map<String, Credentials> credentialStore;
private final FindLocationForVirtualMachine findLocationForVirtualMachine; private final FindLocationForVirtualMachine findLocationForVirtualMachine;
private final FindHardwareForVirtualMachine findHardwareForVirtualMachine; private final FindHardwareForVirtualMachine findHardwareForVirtualMachine;
private final FindImageForVirtualMachine findImageForVirtualMachine; private final FindImageForVirtualMachine findImageForVirtualMachine;
private final Cache<Long, IPForwardingRule> getIPForwardingRuleByVirtualMachine; private final Cache<Long, IPForwardingRule> getIPForwardingRuleByVirtualMachine;
@Inject @Inject
VirtualMachineToNodeMetadata(Map<String, Credentials> credentialStore, VirtualMachineToNodeMetadata(FindLocationForVirtualMachine findLocationForVirtualMachine,
FindLocationForVirtualMachine findLocationForVirtualMachine,
FindHardwareForVirtualMachine findHardwareForVirtualMachine, FindHardwareForVirtualMachine findHardwareForVirtualMachine,
FindImageForVirtualMachine findImageForVirtualMachine, FindImageForVirtualMachine findImageForVirtualMachine,
Cache<Long, IPForwardingRule> getIPForwardingRuleByVirtualMachine) { Cache<Long, IPForwardingRule> getIPForwardingRuleByVirtualMachine) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.findLocationForVirtualMachine = checkNotNull(findLocationForVirtualMachine, "findLocationForVirtualMachine"); this.findLocationForVirtualMachine = checkNotNull(findLocationForVirtualMachine, "findLocationForVirtualMachine");
this.findHardwareForVirtualMachine = checkNotNull(findHardwareForVirtualMachine, "findHardwareForVirtualMachine"); this.findHardwareForVirtualMachine = checkNotNull(findHardwareForVirtualMachine, "findHardwareForVirtualMachine");
this.findImageForVirtualMachine = checkNotNull(findImageForVirtualMachine, "findImageForVirtualMachine"); this.findImageForVirtualMachine = checkNotNull(findImageForVirtualMachine, "findImageForVirtualMachine");
@ -127,7 +123,6 @@ public class VirtualMachineToNodeMetadata implements Function<VirtualMachine, No
throw e; throw e;
} }
} }
builder.credentials(credentialStore.get("node#" + from.getId()));
return builder.build(); return builder.build();
} }

View File

@ -55,6 +55,7 @@ import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceAdapter; import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
@ -161,12 +162,12 @@ public class CloudStackComputeServiceAdapter implements
private static final long serialVersionUID = 4371112085613620239L; private static final long serialVersionUID = 4371112085613620239L;
}); });
VirtualMachine vm = jobWithResult.getResult(); VirtualMachine vm = jobWithResult.getResult();
Credentials credentials = null; LoginCredentials credentials = null;
if (vm.isPasswordEnabled()) { if (vm.isPasswordEnabled()) {
assert vm.getPassword() != null : vm; assert vm.getPassword() != null : vm;
credentials = new Credentials(null, vm.getPassword()); credentials = LoginCredentials.builder().password(vm.getPassword()).build();
} else { } else {
credentials = credentialStore.get("keypair#" + templateOptions.getKeyPair()); credentials = LoginCredentials.builder(credentialStore.get("keypair#" + templateOptions.getKeyPair())).build();
} }
if (templateOptions.shouldSetupStaticNat()) { if (templateOptions.shouldSetupStaticNat()) {
// TODO: possibly not all network ids, do we want to do this // TODO: possibly not all network ids, do we want to do this

View File

@ -19,14 +19,12 @@
package org.jclouds.cloudstack.compute; package org.jclouds.cloudstack.compute;
import static com.google.common.collect.Iterables.concat; import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.get; import static com.google.common.collect.Iterables.get;
import static com.google.common.collect.Sets.newTreeSet; import static com.google.common.collect.Sets.newTreeSet;
import static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.vlan; import static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.vlan;
import static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.specifyVLAN; import static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.specifyVLAN;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set; import java.util.Set;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;

View File

@ -21,7 +21,6 @@ package org.jclouds.cloudstack.compute.functions;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Map;
import java.util.Set; import java.util.Set;
import org.jclouds.cloudstack.compute.functions.VirtualMachineToNodeMetadata.FindHardwareForVirtualMachine; import org.jclouds.cloudstack.compute.functions.VirtualMachineToNodeMetadata.FindHardwareForVirtualMachine;
@ -35,7 +34,6 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -44,7 +42,6 @@ import com.google.common.base.Supplier;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -57,11 +54,6 @@ public class VirtualMachineToNodeMetadataTest {
@Test @Test
public void testApplyWhereVirtualMachineWithIPForwardingRule() throws UnknownHostException { public void testApplyWhereVirtualMachineWithIPForwardingRule() throws UnknownHostException {
// note we are testing when no credentials are here. otherwise would be
// ("node#416696", new
// Credentials("root", "password"))
Map<String, Credentials> credentialStore = ImmutableMap.<String, Credentials> of();
Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(ZoneToLocationTest.one, ZoneToLocationTest.two)); .<Location> of(ZoneToLocationTest.one, ZoneToLocationTest.two));
@ -70,9 +62,9 @@ public class VirtualMachineToNodeMetadataTest {
Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(TemplateToImageTest.one, TemplateToImageTest.two)); .<Image> of(TemplateToImageTest.one, TemplateToImageTest.two));
VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore, VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(new FindLocationForVirtualMachine(
new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), new FindImageForVirtualMachine(
new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder().<Long, IPForwardingRule> build( imageSupplier), CacheBuilder.newBuilder().<Long, IPForwardingRule> build(
new CacheLoader<Long, IPForwardingRule>() { new CacheLoader<Long, IPForwardingRule>() {
@Override @Override
@ -89,24 +81,17 @@ public class VirtualMachineToNodeMetadataTest {
assertEquals( assertEquals(
node.toString(), node.toString(),
new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3").location(ZoneToLocationTest.one) new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3")
.state(NodeState.PENDING).privateAddresses(ImmutableSet.of("10.1.1.18")) .location(ZoneToLocationTest.one).state(NodeState.PENDING)
.publicAddresses(ImmutableSet.of("1.1.1.1")).hardware(ServiceOfferingToHardwareTest.one) .privateAddresses(ImmutableSet.of("10.1.1.18")).publicAddresses(ImmutableSet.of("1.1.1.1"))
.imageId(TemplateToImageTest.one.getId()) .hardware(ServiceOfferingToHardwareTest.one).imageId(TemplateToImageTest.one.getId())
.operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString());
// because it wasn't present in the credential store.
assertEquals(node.getCredentials(), null);
} }
@Test @Test
public void testApplyWhereVirtualMachineWithNoPassword() throws UnknownHostException { public void testApplyWhereVirtualMachineWithNoPassword() throws UnknownHostException {
// note we are testing when no credentials are here. otherwise would be
// ("node#416696", new
// Credentials("root", "password"))
Map<String, Credentials> credentialStore = ImmutableMap.<String, Credentials> of();
Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(ZoneToLocationTest.one, ZoneToLocationTest.two)); .<Location> of(ZoneToLocationTest.one, ZoneToLocationTest.two));
@ -115,9 +100,9 @@ public class VirtualMachineToNodeMetadataTest {
Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(TemplateToImageTest.one, TemplateToImageTest.two)); .<Image> of(TemplateToImageTest.one, TemplateToImageTest.two));
VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore, VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(new FindLocationForVirtualMachine(
new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier), new FindImageForVirtualMachine(
new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder().<Long, IPForwardingRule> build( imageSupplier), CacheBuilder.newBuilder().<Long, IPForwardingRule> build(
new CacheLoader<Long, IPForwardingRule>() { new CacheLoader<Long, IPForwardingRule>() {
@Override @Override
@ -134,55 +119,11 @@ public class VirtualMachineToNodeMetadataTest {
assertEquals( assertEquals(
node.toString(), node.toString(),
new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3").location(ZoneToLocationTest.one) new NodeMetadataBuilder().id("54").providerId("54").name("i-3-54-VM").group("i-3")
.state(NodeState.PENDING).privateAddresses(ImmutableSet.of("10.1.1.18")) .location(ZoneToLocationTest.one).state(NodeState.PENDING)
.hardware(ServiceOfferingToHardwareTest.one).imageId(TemplateToImageTest.one.getId()) .privateAddresses(ImmutableSet.of("10.1.1.18")).hardware(ServiceOfferingToHardwareTest.one)
.imageId(TemplateToImageTest.one.getId())
.operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString()); .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<String, Credentials> credentialStore = ImmutableMap.<String, Credentials> of("node#54", new Credentials(
"root", "password"));
Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet
.<Location> of(ZoneToLocationTest.one, ZoneToLocationTest.two));
Supplier<Set<? extends Hardware>> hardwareSupplier = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(ServiceOfferingToHardwareTest.one, ServiceOfferingToHardwareTest.two));
Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet
.<Image> of(TemplateToImageTest.one, TemplateToImageTest.two));
VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(credentialStore,
new FindLocationForVirtualMachine(locationSupplier), new FindHardwareForVirtualMachine(hardwareSupplier),
new FindImageForVirtualMachine(imageSupplier), CacheBuilder.newBuilder().<Long, IPForwardingRule> build(
new CacheLoader<Long, IPForwardingRule>() {
@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"));
}
} }

View File

@ -53,7 +53,8 @@
<test.deltacloud.identity>mockuser</test.deltacloud.identity> <test.deltacloud.identity>mockuser</test.deltacloud.identity>
<test.deltacloud.credential>mockpassword</test.deltacloud.credential> <test.deltacloud.credential>mockpassword</test.deltacloud.credential>
<test.deltacloud.image-id></test.deltacloud.image-id> <test.deltacloud.image-id></test.deltacloud.image-id>
<test.deltacloud.login-user></test.deltacloud.login-user> <test.deltacloud.image.login-user></test.deltacloud.image.login-user>
<test.deltacloud.image.authenticate-sudo></test.deltacloud.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -110,7 +111,8 @@
<test.deltacloud.identity>${test.deltacloud.identity}</test.deltacloud.identity> <test.deltacloud.identity>${test.deltacloud.identity}</test.deltacloud.identity>
<test.deltacloud.credential>${test.deltacloud.credential}</test.deltacloud.credential> <test.deltacloud.credential>${test.deltacloud.credential}</test.deltacloud.credential>
<test.deltacloud.image-id>${test.deltacloud.image-id}</test.deltacloud.image-id> <test.deltacloud.image-id>${test.deltacloud.image-id}</test.deltacloud.image-id>
<test.deltacloud.login-user>${test.deltacloud.login-user}</test.deltacloud.login-user> <test.deltacloud.image.login-user>${test.deltacloud.image.login-user}</test.deltacloud.image.login-user>
<test.deltacloud.image.authenticate-sudo>${test.deltacloud.image.authenticate-sudo}</test.deltacloud.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -39,7 +39,6 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.deltacloud.domain.Instance; import org.jclouds.deltacloud.domain.Instance;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -56,16 +55,15 @@ import com.google.common.collect.Iterables;
public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata> { public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata> {
public static final Map<Instance.State, NodeState> instanceToNodeState = ImmutableMap public static final Map<Instance.State, NodeState> instanceToNodeState = ImmutableMap
.<Instance.State, NodeState> builder().put(Instance.State.STOPPED, NodeState.SUSPENDED).put( .<Instance.State, NodeState> builder().put(Instance.State.STOPPED, NodeState.SUSPENDED)
Instance.State.RUNNING, NodeState.RUNNING).put(Instance.State.PENDING, NodeState.PENDING).put( .put(Instance.State.RUNNING, NodeState.RUNNING).put(Instance.State.PENDING, NodeState.PENDING)
Instance.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, .put(Instance.State.UNRECOGNIZED, NodeState.UNRECOGNIZED).put(Instance.State.SHUTTING_DOWN, NodeState.PENDING)
NodeState.PENDING).put(Instance.State.START, NodeState.PENDING).build(); .put(Instance.State.START, NodeState.PENDING).build();
@Resource @Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
protected final Map<String, Credentials> credentialStore;
protected final Supplier<Set<? extends Location>> locations; protected final Supplier<Set<? extends Location>> locations;
protected final Supplier<Set<? extends Image>> images; protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwares; protected final Supplier<Set<? extends Hardware>> hardwares;
@ -137,10 +135,8 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
} }
@Inject @Inject
InstanceToNodeMetadata(Map<String, Credentials> credentialStore, InstanceToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,
@Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares) {
@Memoized Supplier<Set<? extends Hardware>> hardwares) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.locations = checkNotNull(locations, "locations"); this.locations = checkNotNull(locations, "locations");
this.hardwares = checkNotNull(hardwares, "hardwares"); this.hardwares = checkNotNull(hardwares, "hardwares");
@ -159,7 +155,6 @@ public class InstanceToNodeMetadata implements Function<Instance, NodeMetadata>
builder.state(instanceToNodeState.get(from.getState())); builder.state(instanceToNodeState.get(from.getState()));
builder.publicAddresses(from.getPublicAddresses()); builder.publicAddresses(from.getPublicAddresses());
builder.privateAddresses(from.getPrivateAddresses()); builder.privateAddresses(from.getPrivateAddresses());
builder.credentials(credentialStore.get(from.getHref().toASCIIString()));
return builder.build(); return builder.build();
} }
} }

View File

@ -43,7 +43,7 @@ import org.jclouds.deltacloud.domain.TransitionOnAction;
import org.jclouds.deltacloud.options.CreateInstanceOptions; import org.jclouds.deltacloud.options.CreateInstanceOptions;
import org.jclouds.deltacloud.predicates.InstanceFinished; import org.jclouds.deltacloud.predicates.InstanceFinished;
import org.jclouds.deltacloud.predicates.InstanceRunning; import org.jclouds.deltacloud.predicates.InstanceRunning;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
@ -86,7 +86,7 @@ public class DeltacloudComputeServiceAdapter implements
Template template) { Template template) {
Instance instance = client.createInstance(template.getImage().getProviderId(), CreateInstanceOptions.Builder Instance instance = client.createInstance(template.getImage().getProviderId(), CreateInstanceOptions.Builder
.named(name).hardwareProfile(template.getHardware().getId()).realm(template.getLocation().getId())); .named(name).hardwareProfile(template.getHardware().getId()).realm(template.getLocation().getId()));
Credentials creds = null; LoginCredentials creds = null;
if (instance.getAuthentication() != null && instance.getAuthentication() instanceof PasswordAuthentication) { if (instance.getAuthentication() != null && instance.getAuthentication() instanceof PasswordAuthentication) {
creds = PasswordAuthentication.class.cast(instance.getAuthentication()).getLoginCredentials(); creds = PasswordAuthentication.class.cast(instance.getAuthentication()).getLoginCredentials();
} }

View File

@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.io.Serializable; 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 */ /** The serialVersionUID */
private static final long serialVersionUID = 7669076186483470376L; 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"); this.login = checkNotNull(login, "login");
} }
public Credentials getLoginCredentials() { public LoginCredentials getLoginCredentials() {
return login; return login;
} }

View File

@ -27,10 +27,11 @@ import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.jclouds.deltacloud.domain.Instance; import org.jclouds.deltacloud.domain.Instance;
import org.jclouds.deltacloud.domain.Instance.Authentication;
import org.jclouds.deltacloud.domain.KeyAuthentication; import org.jclouds.deltacloud.domain.KeyAuthentication;
import org.jclouds.deltacloud.domain.PasswordAuthentication; import org.jclouds.deltacloud.domain.PasswordAuthentication;
import org.jclouds.deltacloud.domain.Instance.Authentication; import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials.Builder;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -67,7 +68,7 @@ public class InstanceHandler extends ParseSax.HandlerWithResult<Instance> {
private Instance instance; private Instance instance;
private Credentials.Builder<Credentials> credentialsBuilder = new Credentials.Builder<Credentials>(); private Builder credentialsBuilder = LoginCredentials.builder();
private String keyName; private String keyName;
private Authentication authentication; private Authentication authentication;
@ -125,19 +126,19 @@ public class InstanceHandler extends ParseSax.HandlerWithResult<Instance> {
} else if (qName.equalsIgnoreCase("keyname")) { } else if (qName.equalsIgnoreCase("keyname")) {
this.keyName = currentOrNull(currentText); this.keyName = currentOrNull(currentText);
} else if (qName.equalsIgnoreCase("username")) { } else if (qName.equalsIgnoreCase("username")) {
this.credentialsBuilder.identity(currentOrNull(currentText)); this.credentialsBuilder.user(currentOrNull(currentText));
} else if (qName.equalsIgnoreCase("password")) { } else if (qName.equalsIgnoreCase("password")) {
this.credentialsBuilder.credential(currentOrNull(currentText)); this.credentialsBuilder.password(currentOrNull(currentText));
} else if (qName.equalsIgnoreCase("authentication")) { } else if (qName.equalsIgnoreCase("authentication")) {
if (keyName != null) { if (keyName != null) {
this.authentication = new KeyAuthentication(keyName); this.authentication = new KeyAuthentication(keyName);
} else { } else {
Credentials creds = credentialsBuilder.build(); LoginCredentials creds = credentialsBuilder.build();
if (creds.identity != null) if (creds != null && creds.identity != null)
this.authentication = new PasswordAuthentication(creds); this.authentication = new PasswordAuthentication(creds);
} }
this.keyName = null; this.keyName = null;
this.credentialsBuilder = new Credentials.Builder<Credentials>(); this.credentialsBuilder = LoginCredentials.builder();
} else if (qName.equalsIgnoreCase("state")) { } else if (qName.equalsIgnoreCase("state")) {
this.state = Instance.State.fromValue(currentOrNull(currentText)); this.state = Instance.State.fromValue(currentOrNull(currentText));
} else if (qName.equalsIgnoreCase("address")) { } else if (qName.equalsIgnoreCase("address")) {

View File

@ -24,10 +24,10 @@ import java.io.InputStream;
import java.net.URI; import java.net.URI;
import org.jclouds.deltacloud.domain.Instance; import org.jclouds.deltacloud.domain.Instance;
import org.jclouds.deltacloud.domain.Instance.Authentication;
import org.jclouds.deltacloud.domain.KeyAuthentication; import org.jclouds.deltacloud.domain.KeyAuthentication;
import org.jclouds.deltacloud.domain.PasswordAuthentication; import org.jclouds.deltacloud.domain.PasswordAuthentication;
import org.jclouds.deltacloud.domain.Instance.Authentication; import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.config.SaxParserModule; import org.jclouds.http.functions.config.SaxParserModule;
@ -68,7 +68,8 @@ public class InstanceHandlerTest {
} }
public void testWithPasswordAuthentication() { 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()); assertEquals(parseInstance("/test_get_instance_pw.xml").toString(), expects.toString());
} }
@ -84,15 +85,15 @@ public class InstanceHandlerTest {
private Instance instanceWithAuthentication(Authentication authentication) { private Instance instanceWithAuthentication(Authentication authentication) {
return new Instance(URI.create("http://fancycloudprovider.com/api/instances/inst1"), "inst1", "larry", 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 "Production JBoss Instance", URI.create("http://fancycloudprovider.com/api/images/img3"),
.create("http://fancycloudprovider.com/api/hardware_profiles/m1-small"), URI URI.create("http://fancycloudprovider.com/api/hardware_profiles/m1-small"),
.create("http://fancycloudprovider.com/api/realms/us"), Instance.State.RUNNING, ImmutableMap URI.create("http://fancycloudprovider.com/api/realms/us"), Instance.State.RUNNING, ImmutableMap.of(
.of(Instance.Action.REBOOT, new HttpRequest("POST", URI Instance.Action.REBOOT,
.create("http://fancycloudprovider.com/api/instances/inst1/reboot")), new HttpRequest("POST", URI.create("http://fancycloudprovider.com/api/instances/inst1/reboot")),
Instance.Action.STOP, new HttpRequest("POST", URI Instance.Action.STOP,
.create("http://fancycloudprovider.com/api/instances/inst1/stop"))), new HttpRequest("POST", URI.create("http://fancycloudprovider.com/api/instances/inst1/stop"))),
authentication, ImmutableSet.of("inst1.larry.fancycloudprovider.com"), ImmutableSet authentication, ImmutableSet.of("inst1.larry.fancycloudprovider.com"),
.of("inst1.larry.internal")); ImmutableSet.of("inst1.larry.internal"));
} }
} }

View File

@ -39,7 +39,8 @@
<test.ec2.identity>${test.aws.identity}</test.ec2.identity> <test.ec2.identity>${test.aws.identity}</test.ec2.identity>
<test.ec2.credential>${test.aws.credential}</test.ec2.credential> <test.ec2.credential>${test.aws.credential}</test.ec2.credential>
<test.ec2.image-id></test.ec2.image-id> <test.ec2.image-id></test.ec2.image-id>
<test.ec2.login-user></test.ec2.login-user> <test.ec2.image.login-user></test.ec2.image.login-user>
<test.ec2.image.authenticate-sudo></test.ec2.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -105,7 +106,8 @@
<test.ec2.identity>${test.ec2.identity}</test.ec2.identity> <test.ec2.identity>${test.ec2.identity}</test.ec2.identity>
<test.ec2.credential>${test.ec2.credential}</test.ec2.credential> <test.ec2.credential>${test.ec2.credential}</test.ec2.credential>
<test.ec2.image-id>${test.ec2.image-id}</test.ec2.image-id> <test.ec2.image-id>${test.ec2.image-id}</test.ec2.image-id>
<test.ec2.login-user>${test.ec2.login-user}</test.ec2.login-user> <test.ec2.image.login-user>${test.ec2.image.login-user}</test.ec2.image.login-user>
<test.ec2.image.authenticate-sudo>${test.ec2.image.authenticate-sudo}</test.ec2.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -102,7 +102,7 @@ public class EC2ImageParser implements Function<org.jclouds.ec2.domain.Image, Im
reviseParsedImage.reviseParsedImage(from, builder, family, osBuilder); reviseParsedImage.reviseParsedImage(from, builder, family, osBuilder);
builder.defaultCredentials(credentialProvider.execute(from)); builder.defaultCredentials(credentialProvider.apply(from));
try { try {
builder.location(Iterables.find(locations.get(), new Predicate<Location>() { builder.location(Iterables.find(locations.get(), new Predicate<Location>() {

View File

@ -41,6 +41,7 @@ import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.compute.domain.RegionAndName;
import org.jclouds.ec2.domain.BlockDevice; import org.jclouds.ec2.domain.BlockDevice;
import org.jclouds.ec2.domain.InstanceState; import org.jclouds.ec2.domain.InstanceState;
@ -125,7 +126,7 @@ public class RunningInstanceToNodeMetadata implements Function<RunningInstance,
} }
protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) { protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) {
builder.credentials(credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId())); builder.credentials(LoginCredentials.builder(credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId())).build());
} }
protected Hardware parseHardware(final RunningInstance instance) { protected Hardware parseHardware(final RunningInstance instance) {

View File

@ -28,6 +28,7 @@ import java.util.Set;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.domain.BlockDeviceMapping; import org.jclouds.ec2.domain.BlockDeviceMapping;
import org.jclouds.ec2.domain.BlockDeviceMapping.MapEBSSnapshotToDevice; import org.jclouds.ec2.domain.BlockDeviceMapping.MapEBSSnapshotToDevice;
import org.jclouds.ec2.domain.BlockDeviceMapping.MapEphemeralDeviceToDevice; import org.jclouds.ec2.domain.BlockDeviceMapping.MapEphemeralDeviceToDevice;
@ -299,13 +300,49 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
return EC2TemplateOptions.class.cast(options.userMetadata(userMetadata)); return EC2TemplateOptions.class.cast(options.userMetadata(userMetadata));
} }
/** @Deprecated
* @see TemplateOptions#userMetadata(String, String) public static EC2TemplateOptions overrideLoginUserWith(String user) {
*/
public static EC2TemplateOptions userMetadata(String key, String value) {
EC2TemplateOptions options = new EC2TemplateOptions(); EC2TemplateOptions options = new EC2TemplateOptions();
return EC2TemplateOptions.class.cast(options.userMetadata(key, value)); return options.overrideLoginUserWith(user);
} }
public static EC2TemplateOptions overrideLoginUser(String user) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideLoginUser(user);
}
public static EC2TemplateOptions overrideLoginPassword(String password) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideLoginPassword(password);
}
public static EC2TemplateOptions overrideLoginPrivateKey(String privateKey) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideLoginPrivateKey(privateKey);
}
public static EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideAuthenticateSudo(authenticateSudo);
}
@Deprecated
public static EC2TemplateOptions overrideLoginCredentialWith(String credential) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideLoginCredentialWith(credential);
}
@Deprecated
public static EC2TemplateOptions overrideCredentialsWith(Credentials credentials) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideCredentialsWith(credentials);
}
public static EC2TemplateOptions overrideLoginCredentials(LoginCredentials credentials) {
EC2TemplateOptions options = new EC2TemplateOptions();
return options.overrideLoginCredentials(credentials);
}
} }
// methods that only facilitate returning the correct object type // methods that only facilitate returning the correct object type
@ -420,11 +457,70 @@ public class EC2TemplateOptions extends TemplateOptions implements Cloneable {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Deprecated
@Override @Override
public EC2TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) { public EC2TemplateOptions overrideCredentialsWith(Credentials overridingCredentials) {
return EC2TemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials)); return EC2TemplateOptions.class.cast(super.overrideCredentialsWith(overridingCredentials));
} }
/**
* {@inheritDoc}
*/
@Deprecated
@Override
public EC2TemplateOptions overrideLoginUserWith(String loginUser) {
return EC2TemplateOptions.class.cast(super.overrideLoginUserWith(loginUser));
}
/**
* {@inheritDoc}
*/
@Deprecated
@Override
public EC2TemplateOptions overrideLoginCredentialWith(String loginCredential) {
return EC2TemplateOptions.class.cast(super.overrideLoginCredentialWith(loginCredential));
}
/**
* {@inheritDoc}
*/
@Override
public EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {
return EC2TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));
}
/**
* {@inheritDoc}
*/
@Override
public EC2TemplateOptions overrideLoginPassword(String password) {
return EC2TemplateOptions.class.cast(super.overrideLoginPassword(password));
}
/**
* {@inheritDoc}
*/
@Override
public EC2TemplateOptions overrideLoginPrivateKey(String privateKey) {
return EC2TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));
}
/**
* {@inheritDoc}
*/
@Override
public EC2TemplateOptions overrideLoginUser(String loginUser) {
return EC2TemplateOptions.class.cast(super.overrideLoginUser(loginUser));
}
/**
* {@inheritDoc}
*/
@Override
public EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {
return EC2TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */

View File

@ -122,8 +122,8 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions {
if (keyPairName == null && shouldAutomaticallyCreateKeyPair) { if (keyPairName == null && shouldAutomaticallyCreateKeyPair) {
keyPairName = createOrImportKeyPair(region, group, options); keyPairName = createOrImportKeyPair(region, group, options);
} else if (keyPairName != null) { } else if (keyPairName != null) {
if (options.getOverridingCredentials() != null && options.getOverridingCredentials().credential != null) { if (options.getLoginPrivateKey() != null) {
String pem = options.getOverridingCredentials().credential; String pem = options.getLoginPrivateKey();
KeyPair keyPair = KeyPair.builder().region(region).keyName(keyPairName).fingerprint( KeyPair keyPair = KeyPair.builder().region(region).keyName(keyPairName).fingerprint(
fingerprintPrivateKey(pem)).sha1OfPrivateKey(sha1PrivateKey(pem)).keyMaterial(pem).build(); fingerprintPrivateKey(pem)).sha1OfPrivateKey(sha1PrivateKey(pem)).keyMaterial(pem).build();
RegionAndName key = new RegionAndName(region, keyPairName); RegionAndName key = new RegionAndName(region, keyPairName);

View File

@ -25,7 +25,8 @@ import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.domain.LoginCredentials.Builder;
import org.jclouds.ec2.domain.Image; import org.jclouds.ec2.domain.Image;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
@ -39,15 +40,15 @@ public class EC2PopulateDefaultLoginCredentialsForImageStrategy extends ReturnCr
} }
@Inject @Inject
public EC2PopulateDefaultLoginCredentialsForImageStrategy(@Nullable @Named("image") Credentials creds) { public EC2PopulateDefaultLoginCredentialsForImageStrategy(@Nullable @Named("image") LoginCredentials creds) {
super(creds); super(creds);
} }
@Override @Override
public Credentials execute(Object resourceToAuthenticate) { public LoginCredentials apply(Object resourceToAuthenticate) {
if (creds != null) if (creds != null)
return creds; return creds;
Credentials credentials = new Credentials("root", null); Builder credentials = LoginCredentials.builder().user("root");
if (resourceToAuthenticate != null) { if (resourceToAuthenticate != null) {
String owner = null; String owner = null;
if (resourceToAuthenticate instanceof Image) { if (resourceToAuthenticate instanceof Image) {
@ -58,12 +59,12 @@ public class EC2PopulateDefaultLoginCredentialsForImageStrategy extends ReturnCr
checkArgument(owner != null, "Resource must be an image (for EC2)"); checkArgument(owner != null, "Resource must be an image (for EC2)");
// canonical/alestic images use the ubuntu user to login // canonical/alestic images use the ubuntu user to login
if (owner.matches("063491364108|099720109477")) { if (owner.matches("063491364108|099720109477")) {
credentials = new Credentials("ubuntu", null); credentials.user("ubuntu");
// http://typepad.com/2010/09/introducing-amazon-linux-ami.html // http://typepad.com/2010/09/introducing-amazon-linux-ami.html
} else if (owner.equals("137112412989")) { } else if (owner.equals("137112412989")) {
credentials = new Credentials("ec2-user", null); credentials.user("ec2-user");
} }
} }
return credentials; return credentials.build();
} }
} }

View File

@ -165,7 +165,7 @@ public class CloudApplicationArchitecturesEC2ClientLiveTest {
keyPair = client.getKeyPairServices().createKeyPairInRegion(null, keyName); keyPair = client.getKeyPairServices().createKeyPairInRegion(null, keyName);
assertNotNull(keyPair); assertNotNull(keyPair);
assertNotNull(keyPair.getKeyMaterial()); assertNotNull(keyPair.getKeyMaterial());
assertNotNull(keyPair.getKeyFingerprint()); assertNotNull(keyPair.getSha1OfPrivateKey());
assertEquals(keyPair.getKeyName(), keyName); assertEquals(keyPair.getKeyName(), keyName);
} }

View File

@ -212,7 +212,7 @@ public class EBSBootEC2ClientLiveTest {
keyPair = client.getKeyPairServices().createKeyPairInRegion(null, keyName); keyPair = client.getKeyPairServices().createKeyPairInRegion(null, keyName);
assertNotNull(keyPair); assertNotNull(keyPair);
assertNotNull(keyPair.getKeyMaterial()); assertNotNull(keyPair.getKeyMaterial());
assertNotNull(keyPair.getKeyFingerprint()); assertNotNull(keyPair.getSha1OfPrivateKey());
assertEquals(keyPair.getKeyName(), keyName); assertEquals(keyPair.getKeyName(), keyName);
} }

View File

@ -30,9 +30,9 @@ import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.predicates.NodePredicates; import org.jclouds.compute.predicates.NodePredicates;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.EC2Client; import org.jclouds.ec2.EC2Client;
import org.jclouds.ec2.compute.options.EC2TemplateOptions; import org.jclouds.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.ec2.domain.BlockDevice; import org.jclouds.ec2.domain.BlockDevice;
@ -123,7 +123,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
// pass in the private key, so that we can run a script with it // pass in the private key, so that we can run a script with it
assert result.getKeyMaterial() != null : result; assert result.getKeyMaterial() != null : result;
options.overrideLoginCredentialWith(result.getKeyMaterial()); options.overrideLoginPrivateKey(result.getKeyMaterial());
// an arbitrary command to run // an arbitrary command to run
options.runScript(Statements.exec("find /usr")); options.runScript(Statements.exec("find /usr"));
@ -149,8 +149,9 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
assert secgroup.getIpPermissions().size() == 0 : secgroup; assert secgroup.getIpPermissions().size() == 0 : secgroup;
// try to run a script with the original keyPair // try to run a script with the original keyPair
runScriptWithCreds(group, first.getOperatingSystem(), new Credentials(first.getCredentials().identity, result runScriptWithCreds(group, first.getOperatingSystem(),
.getKeyMaterial())); LoginCredentials.builder().user(first.getCredentials().identity).privateKey(result.getKeyMaterial())
.build());
} finally { } finally {
client.destroyNodesMatching(NodePredicates.inGroup(group)); client.destroyNodesMatching(NodePredicates.inGroup(group));

View File

@ -48,10 +48,10 @@ import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.internal.TemplateBuilderImpl; import org.jclouds.compute.domain.internal.TemplateBuilderImpl;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -153,11 +153,11 @@ public class EC2TemplateBuilderTest {
Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of( Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(
new ImageBuilder().providerId("cc-image").name("image").id("us-east-1/cc-image").location(location) 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)) .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") .build(), new ImageBuilder().providerId("normal-image").name("image").id("us-east-1/cc-image")
.location(location).operatingSystem( .location(location).operatingSystem(
new OperatingSystem(OsFamily.UBUNTU, null, "1.0", "paravirtual", "ubuntu", true)) 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())); .build()));
Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet
.<Hardware> of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(), .<Hardware> of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(),

View File

@ -28,10 +28,10 @@ import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.ec2.compute.strategy.ReviseParsedImage; import org.jclouds.ec2.compute.strategy.ReviseParsedImage;
import org.jclouds.ec2.domain.Image; import org.jclouds.ec2.domain.Image;
@ -61,14 +61,14 @@ public class EC2ImageParserTest {
assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem( assertEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem(
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description(
"137112412989/amzn-ami-0.9.7-beta.i386-ebs").is64Bit(false).build()).description("Amazon") "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( "ami-82e4b5c7").location(defaultLocation).userMetadata(
ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build());
assertEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem( assertEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem(
new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch("paravirtual").version("").description( 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()) "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( "us-east-1/ami-f2e4b5b7").providerId("ami-f2e4b5b7").location(defaultLocation).userMetadata(
ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build()); ImmutableMap.of("owner", "137112412989", "rootDeviceType", "ebs")).build());
} }

View File

@ -36,6 +36,7 @@ import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule; import org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;
import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.compute.domain.RegionAndName;
import org.jclouds.ec2.domain.InstanceState; import org.jclouds.ec2.domain.InstanceState;
@ -75,7 +76,7 @@ public class RunningInstanceToNodeMetadataTest {
@Test @Test
public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound() public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound()
throws UnknownHostException { throws UnknownHostException {
Credentials creds = new Credentials("root", "abdce"); LoginCredentials creds = LoginCredentials.builder().user("root").password("abdce").build();
RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet
.<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of( .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of(

View File

@ -35,7 +35,7 @@ import org.jclouds.aws.domain.Region;
import org.jclouds.compute.domain.Hardware; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions; 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.EC2HardwareBuilder;
import org.jclouds.ec2.compute.domain.RegionAndName; import org.jclouds.ec2.compute.domain.RegionAndName;
import org.jclouds.ec2.compute.domain.RegionNameAndIngressRules; import org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;
@ -58,7 +58,10 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit", singleThreaded = true, testName = "CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest") @Test(groups = "unit", singleThreaded = true, testName = "CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest")
public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest { public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
public static final Credentials CREDENTIALS = new Credentials(null, "-----BEGIN RSA PRIVATE KEY-----\n" public static final LoginCredentials CREDENTIALS = LoginCredentials
.builder()
.privateKey(
"-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\n" + "MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\n"
+ "W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\n" + "W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\n"
+ "EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\n" + "EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\n"
@ -80,11 +83,11 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
+ "rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\n" + "rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\n"
+ "3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\n" + "3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\n"
+ "DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\n" + "DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\n"
+ "-----END RSA PRIVATE KEY-----"); + "-----END RSA PRIVATE KEY-----").build();
public static final KeyPair KEYPAIR = KeyPair.builder().region(Region.AP_SOUTHEAST_1).keyName("myKeyPair") 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( .sha1OfPrivateKey("13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32")
"60:15:d1:f1:d9:e2:3c:e2:ee:a9:64:6a:42:a7:34:0c").keyMaterial(CREDENTIALS.credential).build(); .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<RunInstancesOptions> OPTIONS_PROVIDER = new javax.inject.Provider<RunInstancesOptions>() { private static final Provider<RunInstancesOptions> OPTIONS_PROVIDER = new javax.inject.Provider<RunInstancesOptions>() {
@ -106,15 +109,15 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// create mocks // create mocks
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock(
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class,
new Method[] {
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class
.getDeclaredMethod("getOptionsProvider"), .getDeclaredMethod("getOptionsProvider"),
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(
"createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class,
TemplateOptions.class), TemplateOptions.class),
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(
.getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) });
TemplateOptions.class) });
EC2TemplateOptions options = createMock(EC2TemplateOptions.class); EC2TemplateOptions options = createMock(EC2TemplateOptions.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -137,9 +140,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// run // run
RunInstancesOptions customize = strategy.execute(region, group, template); RunInstancesOptions customize = strategy.execute(region, group, template);
assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap.<String, String> of("InstanceType", assertEquals(
size.getProviderId(), "SecurityGroup.1", generatedGroup, "KeyName", systemGeneratedKeyPairName) customize.buildFormParameters().entries(),
.entries()); ImmutableMultimap.<String, String> of("InstanceType", size.getProviderId(), "SecurityGroup.1",
generatedGroup, "KeyName", systemGeneratedKeyPairName).entries());
assertEquals(customize.buildMatrixParameters(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildStringPayload(), null); assertEquals(customize.buildStringPayload(), null);
@ -161,15 +165,15 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// create mocks // create mocks
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock( CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = createMock(
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class, new Method[] { CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class,
new Method[] {
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class
.getDeclaredMethod("getOptionsProvider"), .getDeclaredMethod("getOptionsProvider"),
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod( CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(
"createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class, "createNewKeyPairUnlessUserSpecifiedOtherwise", String.class, String.class,
TemplateOptions.class), TemplateOptions.class),
CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(
.getDeclaredMethod("getSecurityGroupsForTagAndOptions", String.class, String.class, "getSecurityGroupsForTagAndOptions", String.class, String.class, TemplateOptions.class) });
TemplateOptions.class) });
EC2TemplateOptions options = createMock(EC2TemplateOptions.class); EC2TemplateOptions options = createMock(EC2TemplateOptions.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -192,9 +196,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// run // run
RunInstancesOptions customize = strategy.execute(region, group, template); RunInstancesOptions customize = strategy.execute(region, group, template);
assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildFormParameters().entries(), ImmutableMultimap.<String, String> of("InstanceType", assertEquals(
size.getProviderId(), "SecurityGroup.1", "group", "KeyName", systemGeneratedKeyPairName, "UserData", customize.buildFormParameters().entries(),
Base64.encodeBytes("hello".getBytes())).entries()); ImmutableMultimap.<String, String> of("InstanceType", size.getProviderId(), "SecurityGroup.1", "group",
"KeyName", systemGeneratedKeyPairName, "UserData", Base64.encodeBytes("hello".getBytes())).entries());
assertEquals(customize.buildMatrixParameters(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildMatrixParameters(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of()); assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());
assertEquals(customize.buildStringPayload(), null); assertEquals(customize.buildStringPayload(), null);
@ -218,7 +223,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// setup expectations // setup expectations
expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);
expect(options.getOverridingCredentials()).andReturn(null); expect(options.getLoginPrivateKey()).andReturn(null);
expect(options.getRunScript()).andReturn(null); expect(options.getRunScript()).andReturn(null);
// replay mocks // replay mocks
@ -249,7 +254,10 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// setup expectations // setup expectations
expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); 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(options.getRunScript()).andReturn(Statements.exec("echo foo"));
expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false);
@ -281,7 +289,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// setup expectations // setup expectations
expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);
expect(options.getOverridingCredentials()).andReturn(null); expect(options.getLoginPrivateKey()).andReturn(null);
expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(options.getRunScript()).andReturn(Statements.exec("echo foo"));
expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true);
@ -313,7 +321,7 @@ public class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {
// setup expectations // setup expectations
expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); 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 // Notice that the fingerprint and sha1 generated
expect(strategy.credentialsMap.put(new RegionAndName(region, userSuppliedKeyPair), KEYPAIR)).andReturn(null); expect(strategy.credentialsMap.put(new RegionAndName(region, userSuppliedKeyPair), KEYPAIR)).andReturn(null);

View File

@ -121,7 +121,7 @@ public class KeyPairClientLiveTest {
KeyPair result = client.createKeyPairInRegion(null, keyName); KeyPair result = client.createKeyPairInRegion(null, keyName);
assertNotNull(result); assertNotNull(result);
assertNotNull(result.getKeyMaterial()); assertNotNull(result.getKeyMaterial());
assertNotNull(result.getKeyFingerprint()); assertNotNull(result.getSha1OfPrivateKey());
assertEquals(result.getKeyName(), keyName); assertEquals(result.getKeyName(), keyName);
Set<KeyPair> twoResults = Sets.newLinkedHashSet(client.describeKeyPairsInRegion(null, keyName)); Set<KeyPair> twoResults = Sets.newLinkedHashSet(client.describeKeyPairsInRegion(null, keyName));
@ -129,7 +129,7 @@ public class KeyPairClientLiveTest {
assertEquals(twoResults.size(), 1); assertEquals(twoResults.size(), 1);
KeyPair listPair = twoResults.iterator().next(); KeyPair listPair = twoResults.iterator().next();
assertEquals(listPair.getKeyName(), result.getKeyName()); assertEquals(listPair.getKeyName(), result.getKeyName());
assertEquals(listPair.getKeyFingerprint(), result.getKeyFingerprint()); assertEquals(listPair.getSha1OfPrivateKey(), result.getSha1OfPrivateKey());
} }
@AfterTest @AfterTest

View File

@ -53,7 +53,8 @@
<test.elasticstack.identity>FIXME</test.elasticstack.identity> <test.elasticstack.identity>FIXME</test.elasticstack.identity>
<test.elasticstack.credential>FIXME</test.elasticstack.credential> <test.elasticstack.credential>FIXME</test.elasticstack.credential>
<test.elasticstack.image-id></test.elasticstack.image-id> <test.elasticstack.image-id></test.elasticstack.image-id>
<test.elasticstack.login-user></test.elasticstack.login-user> <test.elasticstack.image.login-user></test.elasticstack.image.login-user>
<test.elasticstack.image.authenticate-sudo></test.elasticstack.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
@ -110,7 +111,8 @@
<test.elasticstack.identity>${test.elasticstack.identity}</test.elasticstack.identity> <test.elasticstack.identity>${test.elasticstack.identity}</test.elasticstack.identity>
<test.elasticstack.credential>${test.elasticstack.credential}</test.elasticstack.credential> <test.elasticstack.credential>${test.elasticstack.credential}</test.elasticstack.credential>
<test.elasticstack.image-id>${test.elasticstack.image-id}</test.elasticstack.image-id> <test.elasticstack.image-id>${test.elasticstack.image-id}</test.elasticstack.image-id>
<test.elasticstack.login-user>${test.elasticstack.login-user}</test.elasticstack.login-user> <test.elasticstack.image.login-user>${test.elasticstack.image.login-user}</test.elasticstack.image.login-user>
<test.elasticstack.image.authenticate-sudo>${test.elasticstack.image.authenticate-sudo}</test.elasticstack.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -44,8 +44,8 @@ import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.domain.internal.VolumeImpl;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.elasticstack.ElasticStackClient; import org.jclouds.elasticstack.ElasticStackClient;
import org.jclouds.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.Device;
import org.jclouds.elasticstack.domain.Drive; import org.jclouds.elasticstack.domain.Drive;
@ -126,7 +126,8 @@ public class ElasticStackComputeServiceAdapter implements
ServerInfo from = client.createServer(toCreate); ServerInfo from = client.createServer(toCreate);
client.startServer(from.getUuid()); client.startServer(from.getUuid());
from = client.getServerInfo(from.getUuid()); from = client.getServerInfo(from.getUuid());
return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), new Credentials(null, defaultVncPassword)); return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), LoginCredentials.builder()
.password(defaultVncPassword).build());
} }
@Override @Override

View File

@ -39,7 +39,6 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Processor; import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.VolumeBuilder; import org.jclouds.compute.domain.VolumeBuilder;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.elasticstack.domain.Device; import org.jclouds.elasticstack.domain.Device;
import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.elasticstack.domain.DriveInfo;
@ -73,15 +72,12 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
private final Function<Server, String> getImageIdFromServer; private final Function<Server, String> getImageIdFromServer;
private final Function<String, Image> findImageForId; private final Function<String, Image> findImageForId;
private final Map<String, Credentials> credentialStore;
private final Supplier<Location> locationSupplier; private final Supplier<Location> locationSupplier;
private final Function<Device, Volume> deviceToVolume; private final Function<Device, Volume> deviceToVolume;
@Inject @Inject
ServerInfoToNodeMetadata(Map<String, Credentials> credentialStore, Function<Server, String> getImageIdFromServer, ServerInfoToNodeMetadata(Function<Server, String> getImageIdFromServer, Function<String, Image> findImageForId,
Function<String, Image> findImageForId, Function<Device, Volume> deviceToVolume, Function<Device, Volume> deviceToVolume, Supplier<Location> locationSupplier) {
Supplier<Location> locationSupplier) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier"); this.locationSupplier = checkNotNull(locationSupplier, "locationSupplier");
this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume"); this.deviceToVolume = checkNotNull(deviceToVolume, "deviceToVolume");
this.findImageForId = checkNotNull(findImageForId, "findImageForId"); this.findImageForId = checkNotNull(findImageForId, "findImageForId");
@ -110,7 +106,6 @@ public class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetada
builder.state(serverStatusToNodeState.get(from.getStatus())); builder.state(serverStatusToNodeState.get(from.getStatus()));
builder.publicAddresses(ImmutableSet.<String> of(from.getNics().get(0).getDhcp())); builder.publicAddresses(ImmutableSet.<String> of(from.getNics().get(0).getDhcp()));
builder.privateAddresses(ImmutableSet.<String> of()); builder.privateAddresses(ImmutableSet.<String> of());
builder.credentials(credentialStore.get("node#" + from.getUuid()));
return builder.build(); return builder.build();
} }

View File

@ -26,8 +26,8 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.elasticstack.domain.DriveInfo; import org.jclouds.elasticstack.domain.DriveInfo;
import org.jclouds.elasticstack.domain.WellKnownImage; import org.jclouds.elasticstack.domain.WellKnownImage;
@ -52,13 +52,18 @@ public class WellKnownImageToImage implements Function<DriveInfo, Image> {
@Override @Override
public Image apply(DriveInfo drive) { public Image apply(DriveInfo drive) {
WellKnownImage input = preinstalledImages.get(drive.getUuid()); WellKnownImage input = preinstalledImages.get(drive.getUuid());
return new ImageBuilder().ids(drive.getUuid()).userMetadata( return new ImageBuilder()
.ids(drive.getUuid())
.userMetadata(
ImmutableMap.<String, String> builder().putAll(drive.getUserMetadata()) ImmutableMap.<String, String> builder().putAll(drive.getUserMetadata())
.put("size", input.getSize() + "").build()).defaultCredentials( .put("size", input.getSize() + "").build())
new Credentials(input.getLoginUser(), null)).location(locationSupplier.get()).name( .defaultCredentials(LoginCredentials.builder().user(input.getLoginUser()).build())
input.getDescription()).description(drive.getName()).operatingSystem( .location(locationSupplier.get())
new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion()).name( .name(input.getDescription())
input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build()).version( .description(drive.getName())
"").build(); .operatingSystem(
new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion())
.name(input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build())
.version("").build();
} }
} }

View File

@ -39,7 +39,8 @@
<test.eucalyptus.identity>FIXME_IDENTITY</test.eucalyptus.identity> <test.eucalyptus.identity>FIXME_IDENTITY</test.eucalyptus.identity>
<test.eucalyptus.credential>FIXME_CREDENTIAL</test.eucalyptus.credential> <test.eucalyptus.credential>FIXME_CREDENTIAL</test.eucalyptus.credential>
<test.eucalyptus.image-id></test.eucalyptus.image-id> <test.eucalyptus.image-id></test.eucalyptus.image-id>
<test.eucalyptus.login-user></test.eucalyptus.login-user> <test.eucalyptus.image.login-user></test.eucalyptus.image.login-user>
<test.eucalyptus.image.authenticate-sudo></test.eucalyptus.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -105,7 +106,8 @@
<test.eucalyptus.identity>${test.eucalyptus.identity}</test.eucalyptus.identity> <test.eucalyptus.identity>${test.eucalyptus.identity}</test.eucalyptus.identity>
<test.eucalyptus.credential>${test.eucalyptus.credential}</test.eucalyptus.credential> <test.eucalyptus.credential>${test.eucalyptus.credential}</test.eucalyptus.credential>
<test.eucalyptus.image-id>${test.eucalyptus.image-id}</test.eucalyptus.image-id> <test.eucalyptus.image-id>${test.eucalyptus.image-id}</test.eucalyptus.image-id>
<test.eucalyptus.login-user>${test.eucalyptus.login-user}</test.eucalyptus.login-user> <test.eucalyptus.image.login-user>${test.eucalyptus.image.login-user}</test.eucalyptus.image.login-user>
<test.eucalyptus.image.authenticate-sudo>${test.eucalyptus.image.authenticate-sudo}</test.eucalyptus.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -38,6 +38,7 @@ import java.util.Properties;
import java.util.Set; import java.util.Set;
import junit.framework.Assert; import junit.framework.Assert;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobRequestSigner;
@ -46,7 +47,6 @@ import org.jclouds.blobstore.BlobStoreContext;
import org.jclouds.blobstore.BlobStoreContextFactory; import org.jclouds.blobstore.BlobStoreContextFactory;
import org.jclouds.blobstore.ContainerNotFoundException; import org.jclouds.blobstore.ContainerNotFoundException;
import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.Blob;
import org.jclouds.blobstore.domain.BlobBuilder;
import org.jclouds.blobstore.domain.BlobMetadata; import org.jclouds.blobstore.domain.BlobMetadata;
import org.jclouds.blobstore.domain.MutableBlobMetadata; import org.jclouds.blobstore.domain.MutableBlobMetadata;
import org.jclouds.blobstore.domain.PageSet; import org.jclouds.blobstore.domain.PageSet;
@ -66,6 +66,7 @@ import org.testng.annotations.DataProvider;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.inject.CreationException; import com.google.inject.CreationException;
import com.google.inject.Module;
/** /**
* Test class for {@link FilesystemAsyncBlobStore} class * Test class for {@link FilesystemAsyncBlobStore} class
@ -95,7 +96,7 @@ public class FilesystemAsyncBlobStoreTest {
// create context for filesystem container // create context for filesystem container
Properties prop = new Properties(); Properties prop = new Properties();
prop.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR); 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.<Module>emptyList(), prop);
// create a container in the default location // create a container in the default location
blobStore = context.getBlobStore(); blobStore = context.getBlobStore();

View File

@ -39,7 +39,8 @@
<test.nova.identity>FIXME_IDENTITY</test.nova.identity> <test.nova.identity>FIXME_IDENTITY</test.nova.identity>
<test.nova.credential>FIXME_CREDENTIALS</test.nova.credential> <test.nova.credential>FIXME_CREDENTIALS</test.nova.credential>
<test.nova.image-id></test.nova.image-id> <test.nova.image-id></test.nova.image-id>
<test.nova.login-user></test.nova.login-user> <test.nova.image.login-user></test.nova.image.login-user>
<test.nova.image.authenticate-sudo></test.nova.image.authenticate-sudo>
<test.ssh.keyfile.public></test.ssh.keyfile.public> <test.ssh.keyfile.public></test.ssh.keyfile.public>
<test.ssh.keyfile.private></test.ssh.keyfile.private> <test.ssh.keyfile.private></test.ssh.keyfile.private>
</properties> </properties>
@ -130,7 +131,8 @@
<test.nova.identity>${test.nova.identity}</test.nova.identity> <test.nova.identity>${test.nova.identity}</test.nova.identity>
<test.nova.credential>${test.nova.credential}</test.nova.credential> <test.nova.credential>${test.nova.credential}</test.nova.credential>
<test.nova.image-id>${test.nova.image-id}</test.nova.image-id> <test.nova.image-id>${test.nova.image-id}</test.nova.image-id>
<test.nova.login-user>${test.nova.login-user}</test.nova.login-user> <test.nova.image.login-user>${test.nova.image.login-user}</test.nova.image.login-user>
<test.nova.image.authenticate-sudo>${test.nova.image.authenticate-sudo}</test.nova.image.authenticate-sudo>
<test.ssh.keyfile.public>${test.ssh.keyfile.public}</test.ssh.keyfile.public> <test.ssh.keyfile.public>${test.ssh.keyfile.public}</test.ssh.keyfile.public>
<test.ssh.keyfile.private>${test.ssh.keyfile.private}</test.ssh.keyfile.private> <test.ssh.keyfile.private>${test.ssh.keyfile.private}</test.ssh.keyfile.private>
</systemPropertyVariables> </systemPropertyVariables>

View File

@ -20,10 +20,9 @@ package org.jclouds.openstack.nova;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.ws.rs.PathParam;
import org.jclouds.concurrent.Timeout; import org.jclouds.concurrent.Timeout;
import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Addresses;
import org.jclouds.openstack.nova.domain.Flavor; 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.openstack.nova.options.RebuildServerOptions;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
import java.util.concurrent.Future;
/** /**
* Provides access to OpenStack Nova via their REST API. * Provides access to OpenStack Nova via their REST API.
* <p/> * <p/>

View File

@ -24,7 +24,6 @@ import javax.inject.Singleton;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials;
import com.google.common.base.Function; import com.google.common.base.Function;
@ -48,7 +47,6 @@ public class NovaImageToImage implements Function<org.jclouds.openstack.nova.dom
builder.description(from.getName() != null ? from.getName() : "unspecified"); builder.description(from.getName() != null ? from.getName() : "unspecified");
builder.version(from.getUpdated() != null ? from.getUpdated().getTime() + "" : "-1"); builder.version(from.getUpdated() != null ? from.getUpdated().getTime() + "" : "-1");
builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type builder.operatingSystem(imageToOs.apply(from)); //image name may not represent the OS type
builder.defaultCredentials(new Credentials("root", null));
builder.uri(from.getURI()); builder.uri(from.getURI());
Image image = builder.build(); Image image = builder.build();
return image; return image;

View File

@ -18,14 +18,25 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; package org.jclouds.openstack.nova.compute.functions;
import com.google.common.base.Function; import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Predicate; import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables; import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.collect.Memoized; import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.*; import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
@ -34,16 +45,10 @@ import org.jclouds.openstack.nova.domain.Address;
import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.Server;
import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.openstack.nova.domain.ServerStatus;
import javax.annotation.Resource; import com.google.common.base.Function;
import javax.inject.Inject; import com.google.common.base.Predicate;
import javax.inject.Named; import com.google.common.base.Supplier;
import javax.inject.Singleton; import com.google.common.collect.Iterables;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -55,7 +60,6 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
protected final Supplier<Location> location; protected final Supplier<Location> location;
protected final Map<String, Credentials> credentialStore;
protected final Map<ServerStatus, NodeState> serverToNodeState; protected final Map<ServerStatus, NodeState> serverToNodeState;
protected final Supplier<Set<? extends Image>> images; protected final Supplier<Set<? extends Image>> images;
protected final Supplier<Set<? extends Hardware>> hardwares; protected final Supplier<Set<? extends Hardware>> hardwares;
@ -87,11 +91,10 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
} }
@Inject @Inject
ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState, Map<String, Credentials> credentialStore, ServerToNodeMetadata(Map<ServerStatus, NodeState> serverStateToNodeState,
@Memoized Supplier<Set<? extends Image>> images, Supplier<Location> location, @Memoized Supplier<Set<? extends Image>> images, Supplier<Location> location,
@Memoized Supplier<Set<? extends Hardware>> hardwares) { @Memoized Supplier<Set<? extends Hardware>> hardwares) {
this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState");
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.images = checkNotNull(images, "images"); this.images = checkNotNull(images, "images");
this.location = checkNotNull(location, "location"); this.location = checkNotNull(location, "location");
this.hardwares = checkNotNull(hardwares, "hardwares"); this.hardwares = checkNotNull(hardwares, "hardwares");
@ -115,7 +118,6 @@ public class ServerToNodeMetadata implements Function<Server, NodeMetadata> {
builder.state(serverToNodeState.get(from.getStatus())); builder.state(serverToNodeState.get(from.getStatus()));
builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction())); builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction()));
builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction())); builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction()));
builder.credentials(credentialStore.get("node#" + from.getId()));
builder.uri(from.getURI()); builder.uri(from.getURI());
return builder.build(); return builder.build();
} }

View File

@ -30,6 +30,7 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName; import org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.openstack.nova.NovaClient; import org.jclouds.openstack.nova.NovaClient;
import org.jclouds.openstack.nova.domain.Server; 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) { public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {
Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId(), Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId(),
withMetadata(template.getOptions().getUserMetadata())); 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); return serverToNodeMetadata.apply(from);
} }

View File

@ -18,24 +18,22 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; 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.config.BaseComputeServiceContextModule;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder; import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.net.URI; import com.google.inject.Guice;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import static org.testng.Assert.assertEquals;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -44,13 +42,13 @@ import static org.testng.Assert.assertEquals;
public class NovaImageToImageTest { public class NovaImageToImageTest {
@Test @Test
public void testApplyWhereImageNotFound() throws UnknownHostException, URISyntaxException { public void testApplyWhereImageNotFound() {
Image image = new ImageBuilder() Image image = new ImageBuilder()
.name("CentOS 5.2") .name("CentOS 5.2")
.operatingSystem( .operatingSystem(
new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2")
.build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) .is64Bit(true).build()).description("CentOS 5.2").ids("2").version("1286712000000")
.ids("2").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); .uri(URI.create("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build();
Image parsedImage = convertImage(); Image parsedImage = convertImage();
assertEquals(parsedImage, image); assertEquals(parsedImage, image);
@ -59,7 +57,8 @@ public class NovaImageToImageTest {
public static Image convertImage() { public static Image convertImage() {
org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage();
NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(
new BaseComputeServiceContextModule() {
}.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
.getInstance(Json.class)))); .getInstance(Json.class))));

View File

@ -18,12 +18,25 @@
*/ */
package org.jclouds.openstack.nova.compute.functions; package org.jclouds.openstack.nova.compute.functions;
import com.google.common.base.Suppliers; import static org.testng.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import java.net.URI;
import com.google.common.collect.ImmutableSet; import java.net.URISyntaxException;
import org.jclouds.compute.domain.*; import java.net.UnknownHostException;
import org.jclouds.domain.Credentials; 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.Location;
import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
@ -33,13 +46,10 @@ import org.jclouds.openstack.nova.domain.ServerStatus;
import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.net.URI; import com.google.common.base.Suppliers;
import java.net.URISyntaxException; import com.google.common.collect.ImmutableList;
import java.net.UnknownHostException; import com.google.common.collect.ImmutableMap;
import java.util.Map; import com.google.common.collect.ImmutableSet;
import java.util.Set;
import static org.testng.Assert.assertEquals;
/** /**
* @author Adrian Cole * @author Adrian Cole
@ -49,35 +59,16 @@ public class ServerToNodeMetadataTest {
Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build();
@Test @Test
public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException,
Credentials creds = new Credentials("root", "abdce"); ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(); Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer(); Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
.<String, Credentials>of("node#1234", creds), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers.ofInstance(provider),
Suppliers.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares)); Suppliers.<Set<? extends Hardware>> 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<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of();
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
@ -95,75 +86,67 @@ public class ServerToNodeMetadataTest {
.id("1234") .id("1234")
.providerId("1234") .providerId("1234")
.name("sample-server") .name("sample-server")
.location(new LocationBuilder() .location(
.scope(LocationScope.HOST) new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0")
.id("e4d909c290d0fb1ca068ffaddf22cbd0") .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build())
.description("e4d909c290d0fb1ca068ffaddf22cbd0")
.parent(provider).build())
.userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1"))
.uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); .uri(new URI("http://servers.api.openstack.org/1234/servers/1234"));
} }
@Test @Test
public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException,
ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage();
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(); Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of();
Server server = ParseServerFromJsonResponseTest.parseServer(); Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers.ofInstance(provider),
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares)); Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder() NodeMetadata constructedMetadata = newNodeMetadataBuilder()
.imageId("2") .imageId("2")
.operatingSystem(new OperatingSystem.Builder() .operatingSystem(
.family(OsFamily.CENTOS) new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
.description("CentOS 5.2") .is64Bit(true).build()).build();
.version("5.2")
.is64Bit(true).build())
.build();
assertEquals(metadata, constructedMetadata); assertEquals(metadata, constructedMetadata);
} }
@Test @Test
public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException,
ClassNotFoundException, URISyntaxException {
Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Map<ServerStatus, NodeState> serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState;
Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage()); Set<org.jclouds.compute.domain.Image> images = ImmutableSet.of(NovaImageToImageTest.convertImage());
Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); Set<org.jclouds.compute.domain.Hardware> hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor());
Server server = ParseServerFromJsonResponseTest.parseServer(); Server server = ParseServerFromJsonResponseTest.parseServer();
ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState,
.<String, Credentials>of(), Suppliers.<Set<? extends Image>>ofInstance(images), Suppliers Suppliers.<Set<? extends Image>> ofInstance(images), Suppliers.ofInstance(provider),
.ofInstance(provider), Suppliers.<Set<? extends Hardware>>ofInstance(hardwares)); Suppliers.<Set<? extends Hardware>> ofInstance(hardwares));
NodeMetadata metadata = parser.apply(server); NodeMetadata metadata = parser.apply(server);
NodeMetadata constructedMetadata = newNodeMetadataBuilder() NodeMetadata constructedMetadata = newNodeMetadataBuilder()
.imageId("2") .imageId("2")
.operatingSystem(new OperatingSystem.Builder() .operatingSystem(
.family(OsFamily.CENTOS) new OperatingSystem.Builder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2")
.description("CentOS 5.2")
.version("5.2")
.is64Bit(true).build()) .is64Bit(true).build())
.hardware(new HardwareBuilder() .hardware(
new HardwareBuilder()
.ids("1") .ids("1")
.name("256 MB Server") .name("256 MB Server")
.processors(ImmutableList.of(new Processor(1.0, 1.0))) .processors(ImmutableList.of(new Processor(1.0, 1.0)))
.ram(256) .ram(256)
.volumes(ImmutableList.of(new VolumeBuilder() .volumes(
.type(Volume.Type.LOCAL) ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true)
.size(10.0f)
.durable(true)
.bootDevice(true).build())) .bootDevice(true).build()))
.uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")).build()).build();
.build())
.build();
assertEquals(metadata, constructedMetadata); assertEquals(metadata, constructedMetadata);
} }

View File

@ -18,10 +18,13 @@
*/ */
package org.jclouds.openstack.nova.functions; package org.jclouds.openstack.nova.functions;
import com.google.inject.Guice; import static org.testng.Assert.assertEquals;
import com.google.inject.Injector; import static org.testng.Assert.assertTrue;
import com.google.inject.Key;
import com.google.inject.TypeLiteral; import java.io.InputStream;
import java.net.UnknownHostException;
import java.text.ParseException;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads; 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.jclouds.openstack.nova.domain.ServerStatus;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.io.InputStream; import com.google.inject.Guice;
import java.net.UnknownHostException; import com.google.inject.Injector;
import java.text.ParseException; import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Test(groups = "unit") @Test(groups = "unit")
public class ParseServerFromJsonNoAddressesResponseTest { public class ParseServerFromJsonNoAddressesResponseTest {

View File

@ -18,13 +18,16 @@
*/ */
package org.jclouds.openstack.nova.functions; package org.jclouds.openstack.nova.functions;
import com.google.common.collect.ImmutableList; import static org.testng.Assert.assertEquals;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables; import java.io.InputStream;
import com.google.inject.Guice; import java.net.URI;
import com.google.inject.Injector; import java.text.SimpleDateFormat;
import com.google.inject.Key; import java.util.HashSet;
import com.google.inject.TypeLiteral; import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.io.Payloads; 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.jclouds.openstack.nova.domain.ServerStatus;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.io.InputStream; import com.google.common.collect.ImmutableList;
import java.net.URI; import com.google.common.collect.ImmutableMap;
import java.net.UnknownHostException; import com.google.common.collect.Iterables;
import java.text.ParseException; import com.google.inject.Guice;
import java.text.SimpleDateFormat; import com.google.inject.Injector;
import java.util.HashSet; import com.google.inject.Key;
import java.util.List; import com.google.inject.TypeLiteral;
import java.util.Locale;
import java.util.SimpleTimeZone;
import static org.testng.Assert.assertEquals;
/** /**
* Tests behavior of {@code ParseServerFromJsonResponse} for the transitional nova api 1.1 in the Diablo release * Tests behavior of {@code ParseServerFromJsonResponse} for the transitional nova api 1.1 in the Diablo release

View File

@ -18,22 +18,7 @@
*/ */
package org.jclouds.openstack.nova.functions; package org.jclouds.openstack.nova.functions;
import com.google.common.collect.ImmutableList; import static org.testng.Assert.assertEquals;
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 java.io.InputStream; import java.io.InputStream;
import java.net.UnknownHostException; import java.net.UnknownHostException;
@ -44,7 +29,23 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.SimpleTimeZone; 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} * Tests behavior of {@code ParseServerFromJsonResponse}

View File

@ -70,6 +70,7 @@ import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.scriptbuilder.domain.Statements;
@ -93,27 +94,25 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
private static String group = "compute service test group"; private static String group = "compute service test group";
protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String tag) throws IOException { protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String tag) throws IOException {
for (NodeMetadata node : nodes) { for (NodeMetadata node : nodes) {
assertNotNull(node.getProviderId()); assertNotNull(node.getProviderId());
assertNotNull(node.getGroup()); assertNotNull(node.getGroup());
assertEquals(node.getGroup(), group); assertEquals(node.getGroup(), group);
//assertEquals(node.getState(), NodeState.RUNNING); // assertEquals(node.getState(), NodeState.RUNNING);
Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); Credentials fromStore = context.getCredentialStore().get("node#" + node.getId());
assertEquals(fromStore, node.getCredentials()); assertEquals(fromStore, node.getCredentials());
assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node;
// assertNotNull(node.getCredentials()); // assertNotNull(node.getCredentials());
// if (node.getCredentials().identity != null) { // if (node.getCredentials().identity != null) {
// assertNotNull(node.getCredentials().identity); // assertNotNull(node.getCredentials().identity);
// assertNotNull(node.getCredentials().credential); // assertNotNull(node.getCredentials().credential);
// doCheckJavaIsInstalledViaSsh(node); // doCheckJavaIsInstalledViaSsh(node);
// } // }
assertEquals(node.getLocation().getScope(), LocationScope.HOST); assertEquals(node.getLocation().getScope(), LocationScope.HOST);
} }
} }
@BeforeTest @BeforeTest
@Override @Override
public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException { public void before() throws IOException, ExecutionException, TimeoutException, InterruptedException {
@ -128,8 +127,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
properties.remove(provider + ".identity"); properties.remove(provider + ".identity");
ComputeServiceContext context = null; ComputeServiceContext context = null;
try { try {
context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA", ImmutableSet context = new ComputeServiceContextFactory().createContext(provider, "MOMMA", "MIA",
.<Module>of(new SLF4JLoggingModule()), properties); ImmutableSet.<Module> of(new SLF4JLoggingModule()), properties);
context.getComputeService().listNodes(); context.getComputeService().listNodes();
} finally { } finally {
if (context != null) if (context != null)
@ -148,8 +147,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
@Test(enabled = true, expectedExceptions = NoSuchElementException.class, timeOut = 60000) @Test(enabled = true, expectedExceptions = NoSuchElementException.class, timeOut = 60000)
public void testCorrectExceptionRunningNodesNotFound() throws Exception { public void testCorrectExceptionRunningNodesNotFound() throws Exception {
computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"),
.family(OsFamily.UBUNTU).description("ffoo").build())); buildScript(new OperatingSystem.Builder().family(OsFamily.UBUNTU).description("ffoo").build()));
} }
@Test(expectedExceptions = UserAuthException.class, timeOut = 240000) @Test(expectedExceptions = UserAuthException.class, timeOut = 240000)
@ -160,35 +159,38 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
OperatingSystem os = node.getOperatingSystem(); OperatingSystem os = node.getOperatingSystem();
try { try {
@SuppressWarnings("unused") @SuppressWarnings("unused")
Map<? extends NodeMetadata, ExecResponse> responses = runJavaInstallationScriptWithCreds(group, os, new Credentials( Map<? extends NodeMetadata, ExecResponse> responses = runJavaInstallationScriptWithCreds(group, os,
"root", "romeo")); LoginCredentials.builder().user("root").password("romeo").build());
} catch (RunScriptOnNodesException e) { } catch (RunScriptOnNodesException e) {
throw e.getNodeErrors().values().iterator().next().getCause(); throw e.getNodeErrors().values().iterator().next().getCause();
} }
} }
@Test(timeOut = 240000) @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); NodeMetadata node = getDefaultNodeImmediately(group);
String address = awaitForStartup(node.getId()); String address = awaitForStartup(node.getId());
awaitForSshPort(address, new Credentials("root", keyPair.get("private"))); awaitForSshPort(address, new Credentials("root", keyPair.get("private")));
for (Map.Entry<? extends NodeMetadata, ExecResponse> response : computeService.runScriptOnNodesMatching( for (Map.Entry<? extends NodeMetadata, ExecResponse> response : computeService.runScriptOnNodesMatching(
runningInGroup(group), Statements.exec("echo hello"), runningInGroup(group),
overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet()) Statements.exec("echo hello"),
assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " overrideCredentialsWith(LoginCredentials.builder().user("root").privateKey(keyPair.get("private")).build())
+ response.getValue(); .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 runJavaInstallationScriptWithCreds(group, os, new
//TODO no response? if os is null (ZYPPER) // Credentials("root", keyPair.get("private")));
// TODO no response? if os is null (ZYPPER)
node = computeService.getNodeMetadata(node.getId()); node = computeService.getNodeMetadata(node.getId());
checkNodes(Sets.newHashSet(node), group); checkNodes(Sets.newHashSet(node), group);
@SuppressWarnings("unused") @SuppressWarnings("unused")
Credentials good = node.getCredentials(); Credentials good = node.getCredentials();
//TODO check good is being private key .overrideCredentialsWith // TODO check good is being private key .overrideCredentialsWith
//TODO test for .blockOnPort // TODO test for .blockOnPort
} }
@Test(timeOut = 60000) @Test(timeOut = 60000)
@ -198,9 +200,9 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assertEquals(toMatch.getImage(), template.getImage()); assertEquals(toMatch.getImage(), template.getImage());
} }
// protected void checkHttpGet(NodeMetadata node) { // protected void checkHttpGet(NodeMetadata node) {
// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); // ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080);
// } // }
@Test(timeOut = 60000) @Test(timeOut = 60000)
public void testCreateTwoNodesWithRunScript() throws Exception { public void testCreateTwoNodesWithRunScript() throws Exception {
@ -219,18 +221,21 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assertLocationSameOrChild(node2.getLocation(), template.getLocation()); assertLocationSameOrChild(node2.getLocation(), template.getLocation());
assertEquals(node1.getImageId(), template.getImage().getId()); assertEquals(node1.getImageId(), template.getImage().getId());
assertEquals(node2.getImageId(), template.getImage().getId()); assertEquals(node2.getImageId(), template.getImage().getId());
// checkOsMatchesTemplate(node1); // checkOsMatchesTemplate(node1);
// checkOsMatchesTemplate(node2); // checkOsMatchesTemplate(node2);
//TODO add with script; // TODO add with script;
} }
// protected void checkOsMatchesTemplate(NodeMetadata node) { // protected void checkOsMatchesTemplate(NodeMetadata node) {
// if (node.getOperatingSystem() != null) // if (node.getOperatingSystem() != null)
// assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String // assert
// .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node // node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily())
// .getOperatingSystem()); // : String
// } // .format("expecting family %s but got %s",
// getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(),
// node
// .getOperatingSystem());
// }
@Test(timeOut = 60000) @Test(timeOut = 60000)
public void testCreateAnotherNodeWithNewContextToEnsureSharedMemIsntRequired() throws Exception { public void testCreateAnotherNodeWithNewContextToEnsureSharedMemIsntRequired() throws Exception {
@ -238,9 +243,9 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
initializeContextAndComputeService(overrides); initializeContextAndComputeService(overrides);
NodeMetadata node = createDefaultNode(TemplateOptions.Builder.blockUntilRunning(true), group); NodeMetadata node = createDefaultNode(TemplateOptions.Builder.blockUntilRunning(true), group);
checkNodes(Sets.<NodeMetadata>newHashSet(node), group); checkNodes(Sets.<NodeMetadata> newHashSet(node), group);
assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation()); assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation());
// checkOsMatchesTemplate(node); // checkOsMatchesTemplate(node);
} }
@Test(timeOut = 60000) @Test(timeOut = 60000)
@ -254,14 +259,13 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId();
} }
protected Map<? extends NodeMetadata, ExecResponse> runJavaInstallationScriptWithCreds(final String group, OperatingSystem os, protected Map<? extends NodeMetadata, ExecResponse> runJavaInstallationScriptWithCreds(final String group,
Credentials creds) throws RunScriptOnNodesException { OperatingSystem os, LoginCredentials creds) throws RunScriptOnNodesException {
return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os),
.nameTask("runJavaInstallationScriptWithCreds")); overrideCredentialsWith(creds).nameTask("runJavaInstallationScriptWithCreds"));
} }
protected Template buildTemplate(TemplateBuilder templateBuilder) { protected Template buildTemplate(TemplateBuilder templateBuilder) {
return templateBuilder.build(); return templateBuilder.build();
} }
@ -269,8 +273,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
@Test(timeOut = 120000) @Test(timeOut = 120000)
public void testGetNodeMetadata() throws Exception { public void testGetNodeMetadata() throws Exception {
Set<NodeMetadata> nodes = Sets.newHashSet(getDefaultNodeImmediately(group)); Set<NodeMetadata> nodes = Sets.newHashSet(getDefaultNodeImmediately(group));
Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueIndex(
.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))),
new Function<NodeMetadata, String>() { new Function<NodeMetadata, String>() {
@Override @Override
@ -288,7 +292,7 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assertEquals(nodeMetadata.getGroup(), node.getGroup()); assertEquals(nodeMetadata.getGroup(), node.getGroup());
assertLocationSameOrChild(nodeMetadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); assertLocationSameOrChild(nodeMetadata.getLocation(), getDefaultTemplateBuilder().build().getLocation());
assertEquals(nodeMetadata.getImageId(), getDefaultTemplateBuilder().build().getImage().getId()); assertEquals(nodeMetadata.getImageId(), getDefaultTemplateBuilder().build().getImage().getId());
// checkOsMatchesTemplate(metadata); // checkOsMatchesTemplate(metadata);
assertEquals(nodeMetadata.getState(), NodeState.RUNNING); assertEquals(nodeMetadata.getState(), NodeState.RUNNING);
// due to DHCP the addresses can actually change in-between runs. // due to DHCP the addresses can actually change in-between runs.
assertTrue(nodeMetadata.getPrivateAddresses().size() > 0); assertTrue(nodeMetadata.getPrivateAddresses().size() > 0);
@ -297,13 +301,11 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assertNodeZero(metadataMap.values(), nodes); assertNodeZero(metadataMap.values(), nodes);
} }
protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet, Set<NodeMetadata> nodes) { protected void assertNodeZero(Collection<? extends NodeMetadata> metadataSet, Set<NodeMetadata> nodes) {
assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]",
metadataSet, nodes); metadataSet, nodes);
} }
@Test(timeOut = 60000) @Test(timeOut = 60000)
public void testListNodes() throws Exception { public void testListNodes() throws Exception {
for (ComputeMetadata node : computeService.listNodes()) { for (ComputeMetadata node : computeService.listNodes()) {
@ -323,7 +325,8 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
// nullable // nullable
// assert nodeMetadata.getImage() != null : node; // assert nodeMetadata.getImage() != null : node;
// user specified name is not always supported // user specified name is not always supported
// assert nodeMetadata.getName().parseGroupFromName() != null : nodeMetadata; // assert nodeMetadata.getName().parseGroupFromName() != null :
// nodeMetadata;
if (node.getState() == NodeState.RUNNING) { if (node.getState() == NodeState.RUNNING) {
assert node.getPublicAddresses() != null : node; assert node.getPublicAddresses() != null : node;
@ -344,13 +347,12 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
} }
} }
@Test(timeOut = 60000) @Test(timeOut = 60000)
public void testCreateAndRunService() throws Exception { public void testCreateAndRunService() throws Exception {
@SuppressWarnings("unused") @SuppressWarnings("unused")
NodeMetadata node = getDefaultNodeImmediately(group); NodeMetadata node = getDefaultNodeImmediately(group);
//TODO .inboundPorts // TODO .inboundPorts
//checkHttpGet(node); // checkHttpGet(node);
} }
public void testListImages() throws Exception { public void testListImages() throws Exception {
@ -394,10 +396,12 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
} }
public void testOptionToNotBlock() throws Exception { public void testOptionToNotBlock() throws Exception {
//TODO no inbound ports // TODO no inbound ports
//TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); // TemplateOptions options =
// computeService.templateOptions().blockUntilRunning(false).inboundPorts();
long time = System.currentTimeMillis(); 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; assert node.getState() != NodeState.RUNNING;
long duration = System.currentTimeMillis() - time; long duration = System.currentTimeMillis() - time;
assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; 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) @Test(timeOut = 60000, enabled = false)
public void testListHardwareProfiles() throws Exception { 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()) { for (Hardware hardware : computeService.listHardwareProfiles()) {
assert hardware.getProviderId() != null; assert hardware.getProviderId() != null;
assert getCores(hardware) > 0; assert getCores(hardware) > 0;
@ -420,7 +424,6 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
} }
} }
@Test(timeOut = 60000) @Test(timeOut = 60000)
public void testCompareSizes() throws Exception { public void testCompareSizes() throws Exception {
TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); TemplateBuilder templateBuilder = getDefaultTemplateBuilder();
@ -447,7 +450,6 @@ public class NovaComputeServiceLiveTest extends ComputeBase {
assert getCores(fastest) >= getCores(smallest); assert getCores(fastest) >= getCores(smallest);
} }
protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException {
SshClient ssh = context.utils().sshForNode().apply(node); SshClient ssh = context.utils().sshForNode().apply(node);

View File

@ -18,23 +18,31 @@
*/ */
package org.jclouds.openstack.nova.live.novaclient; 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.domain.Credentials;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.net.IPSocket; 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.openstack.nova.options.RebuildServerOptions;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
import org.jclouds.util.Strings2; import org.jclouds.util.Strings2;
import org.testng.annotations.AfterTest; import org.testng.annotations.AfterTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.io.IOException; import com.google.common.collect.Iterables;
import java.util.Set;
import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails;
import static org.testng.Assert.*;
/** /**
* Tests behavior of {@code NovaClient} * Tests behavior of {@code NovaClient}

View File

@ -39,7 +39,8 @@
<test.vcloud.identity>FIXME</test.vcloud.identity> <test.vcloud.identity>FIXME</test.vcloud.identity>
<test.vcloud.credential>FIXME</test.vcloud.credential> <test.vcloud.credential>FIXME</test.vcloud.credential>
<test.vcloud.image-id></test.vcloud.image-id> <test.vcloud.image-id></test.vcloud.image-id>
<test.vcloud.login-user></test.vcloud.login-user> <test.vcloud.image.login-user></test.vcloud.image.login-user>
<test.vcloud.image.authenticate-sudo></test.vcloud.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -108,7 +109,8 @@
<test.vcloud.identity>${test.vcloud.identity}</test.vcloud.identity> <test.vcloud.identity>${test.vcloud.identity}</test.vcloud.identity>
<test.vcloud.credential>${test.vcloud.credential}</test.vcloud.credential> <test.vcloud.credential>${test.vcloud.credential}</test.vcloud.credential>
<test.vcloud.image-id>${test.vcloud.image-id}</test.vcloud.image-id> <test.vcloud.image-id>${test.vcloud.image-id}</test.vcloud.image-id>
<test.vcloud.login-user>${test.vcloud.login-user}</test.vcloud.login-user> <test.vcloud.image.login-user>${test.vcloud.image.login-user}</test.vcloud.image.login-user>
<test.vcloud.image.authenticate-sudo>${test.vcloud.image.authenticate-sudo}</test.vcloud.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

View File

@ -65,7 +65,7 @@ public class ImageForVAppTemplate implements Function<VAppTemplate, Image> {
builder.description(from.getDescription() != null ? from.getDescription() : from.getName()); builder.description(from.getDescription() != null ? from.getDescription() : from.getName());
Envelope ovf = client.getVAppTemplateClient().getOvfEnvelopeForVAppTemplate(from.getHref()); Envelope ovf = client.getVAppTemplateClient().getOvfEnvelopeForVAppTemplate(from.getHref());
builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf)); builder.operatingSystem(CIMOperatingSystem.toComputeOs(ovf));
builder.defaultCredentials(credentialsProvider.execute(from)); builder.defaultCredentials(credentialsProvider.apply(from));
return builder.build(); return builder.build();
} }

View File

@ -38,6 +38,7 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.util.InetAddresses2.IsPrivateIPAddress; import org.jclouds.util.InetAddresses2.IsPrivateIPAddress;
import org.jclouds.vcloud.domain.Status; import org.jclouds.vcloud.domain.Status;
@ -80,11 +81,11 @@ public class VAppToNodeMetadata implements Function<VApp, NodeMetadata> {
Set<String> addresses = getIpsFromVApp(from); Set<String> addresses = getIpsFromVApp(from);
builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE))); builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE)));
builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE)); builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE));
builder.credentials(getCredentialsFrom(from));
Credentials fromApi = getCredentialsFrom(from); Credentials fromApi = getCredentialsFrom(from);
if (fromApi != null && !credentialStore.containsKey("node#" + from.getHref().toASCIIString())) if (fromApi != null && !credentialStore.containsKey("node#" + from.getHref().toASCIIString()))
credentialStore.put("node#" + from.getHref().toASCIIString(), fromApi); 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(); return builder.build();
} }
} }

View File

@ -27,7 +27,7 @@ import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; 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.javax.annotation.Nullable;
import org.jclouds.vcloud.domain.VAppTemplate; import org.jclouds.vcloud.domain.VAppTemplate;
@ -37,12 +37,12 @@ import org.jclouds.vcloud.domain.VAppTemplate;
@Singleton @Singleton
public class GetLoginCredentialsFromGuestConfiguration extends ReturnCredentialsBoundToImage { public class GetLoginCredentialsFromGuestConfiguration extends ReturnCredentialsBoundToImage {
@Inject @Inject
public GetLoginCredentialsFromGuestConfiguration(@Nullable @Named("image") Credentials creds) { public GetLoginCredentialsFromGuestConfiguration(@Nullable @Named("image") LoginCredentials creds) {
super(creds); super(creds);
} }
@Override @Override
public Credentials execute(Object resourceToAuthenticate) { public LoginCredentials apply(Object resourceToAuthenticate) {
if (creds != null) if (creds != null)
return creds; return creds;
checkNotNull(resourceToAuthenticate); checkNotNull(resourceToAuthenticate);

View File

@ -27,7 +27,7 @@ import org.jclouds.cim.ResourceAllocationSettingData;
import org.jclouds.cim.ResourceAllocationSettingData.ResourceType; import org.jclouds.cim.ResourceAllocationSettingData.ResourceType;
import org.jclouds.compute.domain.CIMOperatingSystem; import org.jclouds.compute.domain.CIMOperatingSystem;
import org.jclouds.compute.domain.OperatingSystem; 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.NetworkConnection;
import org.jclouds.vcloud.domain.VApp; import org.jclouds.vcloud.domain.VApp;
import org.jclouds.vcloud.domain.VAppTemplate; import org.jclouds.vcloud.domain.VAppTemplate;
@ -35,8 +35,8 @@ import org.jclouds.vcloud.domain.Vm;
import org.jclouds.vcloud.domain.ovf.VCloudNetworkAdapter; import org.jclouds.vcloud.domain.ovf.VCloudNetworkAdapter;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableSet.Builder; import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Iterables;
/** /**
* *
@ -67,23 +67,23 @@ public class VCloudComputeUtils {
return null; 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; 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; return vApp.getChildren().size() > 0 ? getCredentialsFrom(Iterables.get(vApp.getChildren(), 0)) : null;
} }
public static Credentials getCredentialsFrom(Vm vm) { public static LoginCredentials getCredentialsFrom(Vm vm) {
String user = "root"; LoginCredentials.Builder builder = LoginCredentials.builder();
builder.user("root");
if (vm.getOperatingSystemSection() != null && vm.getOperatingSystemSection().getDescription() != null if (vm.getOperatingSystemSection() != null && vm.getOperatingSystemSection().getDescription() != null
&& vm.getOperatingSystemSection().getDescription().indexOf("Windows") >= 0) && vm.getOperatingSystemSection().getDescription().indexOf("Windows") >= 0)
user = "Administrator"; builder.user("Administrator");
String password = null;
if (vm.getGuestCustomizationSection() != null) if (vm.getGuestCustomizationSection() != null)
password = vm.getGuestCustomizationSection().getAdminPassword(); builder.password(vm.getGuestCustomizationSection().getAdminPassword());
return new Credentials(user, password); return builder.build();
} }
public static Set<String> getIpsFromVApp(VApp vApp) { public static Set<String> getIpsFromVApp(VApp vApp) {

View File

@ -18,13 +18,10 @@
*/ */
package org.jclouds.vcloud.internal; package org.jclouds.vcloud.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import org.jclouds.Constants;
import org.jclouds.compute.BaseVersionedServiceLiveTest; import org.jclouds.compute.BaseVersionedServiceLiveTest;
import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContextFactory;
@ -33,7 +30,6 @@ import org.jclouds.rest.RestContextFactory;
import org.jclouds.sshj.config.SshjSshClientModule; import org.jclouds.sshj.config.SshjSshClientModule;
import org.jclouds.vcloud.VCloudClient; import org.jclouds.vcloud.VCloudClient;
import org.testng.annotations.AfterGroups; import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;

View File

@ -29,7 +29,6 @@ import java.util.Map.Entry;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
@ -40,6 +39,8 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient; import org.jclouds.trmk.vcloud_0_8.TerremarkVCloudClient;
import org.jclouds.trmk.vcloud_0_8.domain.InternetService; import org.jclouds.trmk.vcloud_0_8.domain.InternetService;
@ -134,7 +135,7 @@ public class TerremarkVCloudComputeClient {
password = passwordGenerator.get(); password = passwordGenerator.get();
options.getProperties().put("password", password); options.getProperties().put("password", password);
} }
Credentials defaultCredentials = credentialsProvider.execute(template); LoginCredentials defaultCredentials = credentialsProvider.apply(template);
checkNotNull(options, "options"); checkNotNull(options, "options");
logger.debug(">> instantiating vApp vDC(%s) template(%s) name(%s) options(%s) ", VDC, templateId, name, options); logger.debug(">> instantiating vApp vDC(%s) template(%s) name(%s) options(%s) ", VDC, templateId, name, options);

View File

@ -31,7 +31,7 @@ import javax.inject.Singleton;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; 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.javax.annotation.Nullable;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate; import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate;
@ -42,7 +42,7 @@ import org.jclouds.trmk.vcloud_0_8.domain.VAppTemplate;
@Singleton @Singleton
public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends ReturnCredentialsBoundToImage { public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends ReturnCredentialsBoundToImage {
@Inject @Inject
public ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(@Nullable @Named("image") Credentials creds) { public ParseVAppTemplateDescriptionToGetDefaultLoginCredentials(@Nullable @Named("image") LoginCredentials creds) {
super(creds); super(creds);
} }
@ -54,7 +54,7 @@ public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends Re
.compile(".*[Uu]sername: ([a-z]+) ?.*\n[Pp]assword: ([^ \n\r]+) ?\r?\n.*"); .compile(".*[Uu]sername: ([a-z]+) ?.*\n[Pp]assword: ([^ \n\r]+) ?\r?\n.*");
@Override @Override
public Credentials execute(Object resourceToAuthenticate) { public LoginCredentials apply(Object resourceToAuthenticate) {
if (creds != null) if (creds != null)
return creds; return creds;
checkNotNull(resourceToAuthenticate); checkNotNull(resourceToAuthenticate);
@ -62,11 +62,11 @@ public class ParseVAppTemplateDescriptionToGetDefaultLoginCredentials extends Re
VAppTemplate template = (VAppTemplate) resourceToAuthenticate; VAppTemplate template = (VAppTemplate) resourceToAuthenticate;
String search = template.getDescription() != null ? template.getDescription() : template.getName(); String search = template.getDescription() != null ? template.getDescription() : template.getName();
if (search.indexOf("Windows") >= 0) { if (search.indexOf("Windows") >= 0) {
return new Credentials("Administrator", null); return LoginCredentials.builder().user("Administrator").build();
} else { } else {
Matcher matcher = USER_PASSWORD_PATTERN.matcher(search); Matcher matcher = USER_PASSWORD_PATTERN.matcher(search);
if (matcher.find()) { 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 { } else {
logger.warn("could not parse username/password for image: " + template.getHref() + "\n" + search); logger.warn("could not parse username/password for image: " + template.getHref() + "\n" + search);
return null; return null;

View File

@ -18,8 +18,6 @@
*/ */
package org.jclouds.trmk.vcloud_0_8.internal; package org.jclouds.trmk.vcloud_0_8.internal;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;

View File

@ -21,7 +21,7 @@ package org.jclouds.compute;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
/** /**
@ -66,9 +66,9 @@ public interface ComputeServiceAdapter<N, H, I, L> {
public static class NodeAndInitialCredentials<N> { public static class NodeAndInitialCredentials<N> {
private final N node; private final N node;
private final String nodeId; 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.node = checkNotNull(node, "node");
this.nodeId = checkNotNull(nodeId, "nodeId"); this.nodeId = checkNotNull(nodeId, "nodeId");
this.credentials = credentials; this.credentials = credentials;
@ -96,7 +96,7 @@ public interface ComputeServiceAdapter<N, H, I, L> {
* information is not available * information is not available
*/ */
@Nullable @Nullable
public Credentials getCredentials() { public LoginCredentials getCredentials() {
return credentials; return credentials;
} }
} }

View File

@ -31,6 +31,7 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.scriptbuilder.InitBuilder; import org.jclouds.scriptbuilder.InitBuilder;
import org.jclouds.scriptbuilder.domain.AdminAccessVisitor; import org.jclouds.scriptbuilder.domain.AdminAccessVisitor;
@ -106,8 +107,8 @@ public class RunScriptOnNodeAsInitScriptUsingSsh extends SudoAwareInitManager im
if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) { if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) {
ssh.disconnect(); ssh.disconnect();
logger.debug(">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress()); logger.debug(">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress());
ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node).adminPassword(null).credentials( ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(LoginCredentials.builder(
input.getAdminCredentials()).build()); input.getAdminCredentials()).build()).build());
ssh.connect(); ssh.connect();
setupLinkToInitFile(); setupLinkToInitFile();
} }

View File

@ -94,8 +94,8 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode {
protected ExecResponse runCommand(String command) { protected ExecResponse runCommand(String command) {
ExecResponse returnVal; ExecResponse returnVal;
logger.debug(">> running [%s] as %s@%s", command.replace(node.getAdminPassword() != null ? node logger.debug(">> running [%s] as %s@%s", command.replace(node.getCredentials().getPassword() != null ? node
.getAdminPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress()); .getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh.getHostAddress());
returnVal = ssh.exec(command); returnVal = ssh.exec(command);
return returnVal; return returnVal;
} }
@ -103,8 +103,8 @@ public class RunScriptOnNodeUsingSsh implements RunScriptOnNode {
@VisibleForTesting @VisibleForTesting
public String execAsRoot(String command) { public String execAsRoot(String command) {
if (node.getCredentials().identity.equals("root")) { if (node.getCredentials().identity.equals("root")) {
} else if (node.getAdminPassword() != null) { } else if (node.getCredentials().shouldAuthenticateSudo()) {
command = String.format("sudo -S sh <<'%s'\n%s\n%s%s\n", MARKER, node.getAdminPassword(), command, MARKER); command = String.format("sudo -S sh <<'%s'\n%s\n%s%s\n", MARKER, node.getCredentials().getPassword(), command, MARKER);
} else { } 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);
} }

View File

@ -94,8 +94,8 @@ public class SudoAwareInitManager {
ExecResponse runCommand(String command) { ExecResponse runCommand(String command) {
String statement = String.format(">> running [%s] as %s@%s", command.replace( String statement = String.format(">> running [%s] as %s@%s", command.replace(
node.getAdminPassword() != null ? node.getAdminPassword() : "XXXXX", "XXXXX"), ssh.getUsername(), ssh node.getCredentials().getPassword() != null ? node.getCredentials().getPassword() : "XXXXX", "XXXXX"), ssh
.getHostAddress()); .getUsername(), ssh.getHostAddress());
if (command.endsWith("status")) if (command.endsWith("status"))
logger.trace(statement); logger.trace(statement);
else else
@ -108,8 +108,9 @@ public class SudoAwareInitManager {
String command; String command;
if (node.getCredentials().identity.equals("root")) { if (node.getCredentials().identity.equals("root")) {
command = "./" + init.getInstanceName() + " " + action; command = "./" + init.getInstanceName() + " " + action;
} else if (node.getAdminPassword() != null) { } else if (node.getCredentials().shouldAuthenticateSudo()) {
command = String.format("echo '%s'|sudo -S ./%s %s", node.getAdminPassword(), init.getInstanceName(), action); command = String.format("echo '%s'|sudo -S ./%s %s", node.getCredentials().getPassword(),
init.getInstanceName(), action);
} else { } else {
command = "sudo ./" + init.getInstanceName() + " " + action; command = "sudo ./" + init.getInstanceName() + " " + action;
} }
@ -126,8 +127,8 @@ public class SudoAwareInitManager {
@Override @Override
public String toString() { public String toString() {
return Objects.toStringHelper(this).add("node", node).add("name", init.getInstanceName()).add("runAsRoot", return Objects.toStringHelper(this).add("node", node).add("name", init.getInstanceName())
runAsRoot).toString(); .add("runAsRoot", runAsRoot).toString();
} }
public InitBuilder getStatement() { public InitBuilder getStatement() {

View File

@ -52,7 +52,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap; import org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;
import org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap; import org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.location.Provider; import org.jclouds.location.Provider;
import org.jclouds.location.config.LocationModule; import org.jclouds.location.config.LocationModule;
@ -87,9 +87,9 @@ public abstract class BaseComputeServiceContextModule extends AbstractModule {
}).to(CreateSshClientOncePortIsListeningOnNode.class); }).to(CreateSshClientOncePortIsListeningOnNode.class);
bind(new TypeLiteral<Function<TemplateOptions, Statement>>() { bind(new TypeLiteral<Function<TemplateOptions, Statement>>() {
}).to(TemplateOptionsToStatement.class); }).to(TemplateOptionsToStatement.class);
bind(Credentials.class).annotatedWith(Names.named("image")).toProvider( bind(LoginCredentials.class).annotatedWith(Names.named("image")).toProvider(
GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.class); GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.class);
bind(new TypeLiteral<Function<Template, Credentials>>() { bind(new TypeLiteral<Function<Template, LoginCredentials>>() {
}).to(DefaultCredentialsFromImageOrOverridingCredentials.class); }).to(DefaultCredentialsFromImageOrOverridingCredentials.class);
install(new FactoryModuleBuilder() install(new FactoryModuleBuilder()

View File

@ -39,8 +39,8 @@ import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy; import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies; import org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Functions; import com.google.common.base.Functions;
@ -126,7 +126,7 @@ public class ComputeServiceAdapterContextModule<S, A, N, H, I, L> extends BaseCo
@Override @Override
public Image apply(Image arg0) { 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; return credentials != null ? ImageBuilder.fromImage(arg0).defaultCredentials(credentials).build() : arg0;
} }

View File

@ -26,6 +26,8 @@ import javax.inject.Singleton;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.domain.Credentials; 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.javax.annotation.Nullable;
import org.jclouds.location.Provider; import org.jclouds.location.Provider;
@ -36,7 +38,7 @@ import com.google.inject.Inject;
*/ */
@Singleton @Singleton
public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull implements public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull implements
javax.inject.Provider<Credentials> { javax.inject.Provider<LoginCredentials> {
private final ValueOfConfigurationKeyOrNull config; private final ValueOfConfigurationKeyOrNull config;
private final String provider; private final String provider;
private final Map<String, Credentials> credentialStore; private final Map<String, Credentials> credentialStore;
@ -51,22 +53,33 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull im
@Override @Override
@Nullable @Nullable
public Credentials get() { public LoginCredentials get() {
if (credentialStore.containsKey("image")) if (credentialStore.containsKey("image")) {
return credentialStore.get("image"); return LoginCredentials.builder(credentialStore.get("image")).build();
Credentials creds = null; }
String loginUser = config.apply(provider + ".login-user"); Builder builder = LoginCredentials.builder();
String loginUser = config.apply(provider + ".image.login-user");
if (loginUser == null) if (loginUser == null)
loginUser = config.apply("jclouds.login-user"); loginUser = config.apply("jclouds.image.login-user");
if (loginUser != null) { if (loginUser != null) {
int pos = loginUser.indexOf(':'); int pos = loginUser.indexOf(':');
if (pos != -1) { 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 } else
creds = new Credentials(loginUser, null); builder.user(loginUser);
credentialStore.put("image", creds);
}
return creds;
} }
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;
}
} }

View File

@ -20,12 +20,12 @@ package org.jclouds.compute.config;
import java.util.Map; import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.internal.PersistNodeCredentials; import org.jclouds.compute.internal.PersistNodeCredentials;
import org.jclouds.domain.Credentials; 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.domain.Statement;
import org.jclouds.scriptbuilder.functions.CredentialsFromAdminAccess; import org.jclouds.scriptbuilder.functions.CredentialsFromAdminAccess;
@ -60,7 +60,8 @@ public class PersistNodeCredentialsModule extends AbstractModule {
return input; return input;
Credentials credentials = CredentialsFromAdminAccess.INSTANCE.apply(statement); Credentials credentials = CredentialsFromAdminAccess.INSTANCE.apply(statement);
if (credentials != null) { 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()); credentialStore.put("node#" + input.getId(), input.getCredentials());
} }
return input; return input;

View File

@ -18,10 +18,9 @@
*/ */
package org.jclouds.compute.domain; package org.jclouds.compute.domain;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.ImageImpl; 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.common.annotations.Beta;
import com.google.inject.ImplementedBy; import com.google.inject.ImplementedBy;
@ -50,19 +49,24 @@ public interface Image extends ComputeMetadata {
String getDescription(); String getDescription();
/** /**
* <h4>will be removed in jclouds 1.4.0</h4>
*
* secures access to root with a password. This password is required to access either the console * secures access to root with a password. This password is required to access either the console
* or run sudo as root. * or run sudo as root.
* <p/> * <p/>
* ex. {@code echo 'password' |sudo -S command} * ex. {@code echo 'password' |sudo -S command}
* *
*
* @return root or console password, if configured, or null. * @return root or console password, if configured, or null.
* @see LoginCredentials#shouldAuthenticateSudo
*/ */
@Nullable @Nullable
@Deprecated
String getAdminPassword(); String getAdminPassword();
/** /**
* Default credentials for the current image * Default credentials for the current image
*/ */
Credentials getDefaultCredentials(); LoginCredentials getDefaultCredentials();
} }

View File

@ -23,11 +23,12 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.ImageImpl; import org.jclouds.compute.domain.internal.ImageImpl;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; 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 * @author Adrian Cole
@ -36,9 +37,7 @@ public class ImageBuilder extends ComputeMetadataBuilder {
private OperatingSystem operatingSystem; private OperatingSystem operatingSystem;
private String version; private String version;
private String description; private String description;
@Nullable private LoginCredentials defaultLoginCredentials;
private String adminPassword;
private Credentials defaultCredentials;
public ImageBuilder() { public ImageBuilder() {
super(ComputeType.IMAGE); super(ComputeType.IMAGE);
@ -59,13 +58,30 @@ public class ImageBuilder extends ComputeMetadataBuilder {
return this; return this;
} }
/**
* <h4>will be removed in jclouds 1.4.0</h4>
*
* @see LoginCredentials#shouldAuthenticateSudo
*/
@Deprecated
public ImageBuilder adminPassword(@Nullable String adminPassword) { 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; return this;
} }
public ImageBuilder defaultCredentials(@Nullable Credentials defaultCredentials) { @Deprecated
this.defaultCredentials = defaultCredentials; public ImageBuilder defaultCredentials(@Nullable Credentials defaultLoginCredentials) {
return defaultCredentials(LoginCredentials.builder(defaultLoginCredentials).build());
}
public ImageBuilder defaultCredentials(@Nullable LoginCredentials defaultLoginCredentials) {
this.defaultLoginCredentials = defaultLoginCredentials;
return this; return this;
} }
@ -110,15 +126,15 @@ public class ImageBuilder extends ComputeMetadataBuilder {
@Override @Override
public Image build() { public Image build() {
return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, description, version, return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, description,
adminPassword, defaultCredentials); version, defaultLoginCredentials);
} }
public static ImageBuilder fromImage(Image image) { public static ImageBuilder fromImage(Image image) {
return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()).location( return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId())
image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()).tags(image.getTags()).version( .location(image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata())
image.getVersion()).description(image.getDescription()).operatingSystem(image.getOperatingSystem()) .tags(image.getTags()).version(image.getVersion()).description(image.getDescription())
.adminPassword(image.getAdminPassword()).defaultCredentials(image.getDefaultCredentials()); .operatingSystem(image.getOperatingSystem()).defaultCredentials(image.getDefaultCredentials());
} }
} }

View File

@ -20,10 +20,9 @@ package org.jclouds.compute.domain;
import java.util.Set; import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.NodeMetadataImpl; 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; import com.google.inject.ImplementedBy;
@ -92,21 +91,25 @@ public interface NodeMetadata extends ComputeMetadata {
int getLoginPort(); int getLoginPort();
/** /**
* <h4>will be removed in jclouds 1.4.0</h4>
*
* secures access to root with a password. This password is required to access either the console * secures access to root with a password. This password is required to access either the console
* or run sudo as root. * or run sudo as root.
* <p/> * <p/>
* ex. {@code echo 'password' |sudo -S command} * ex. {@code echo 'password' |sudo -S command}
* *
* @return root or console password, if configured, or null. * @return root or console password, if configured, or null.
* @see LoginCredentials#shouldAuthenticateSudo
*/ */
@Nullable @Nullable
@Deprecated
String getAdminPassword(); String getAdminPassword();
/** /**
* If possible, these are returned upon all detail requests. However, it is often the case that * If possible, these are returned upon all detail requests. However, it is often the case that
* credentials are only available at "run" time. * credentials are only available at "run" time.
*/ */
Credentials getCredentials(); LoginCredentials getCredentials();
/** /**
* All public IP addresses, potentially including shared ips. * All public IP addresses, potentially including shared ips.

View File

@ -29,6 +29,8 @@ import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.internal.NodeMetadataImpl; import org.jclouds.compute.domain.internal.NodeMetadataImpl;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; 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.ImmutableSet;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@ -41,9 +43,7 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
private Set<String> publicAddresses = Sets.newLinkedHashSet(); private Set<String> publicAddresses = Sets.newLinkedHashSet();
private Set<String> privateAddresses = Sets.newLinkedHashSet(); private Set<String> privateAddresses = Sets.newLinkedHashSet();
@Nullable @Nullable
private String adminPassword; private LoginCredentials credentials;
@Nullable
private Credentials credentials;
@Nullable @Nullable
private String group; private String group;
private int loginPort = 22; private int loginPort = 22;
@ -80,15 +80,33 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
return this; return this;
} }
/**
* <h4>will be removed in jclouds 1.4.0</h4>
*
* @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) { public NodeMetadataBuilder credentials(@Nullable Credentials credentials) {
return credentials(LoginCredentials.builder(credentials).build());
}
public NodeMetadataBuilder credentials(@Nullable LoginCredentials credentials) {
this.credentials = credentials; this.credentials = credentials;
return this; return this;
} }
public NodeMetadataBuilder adminPassword(@Nullable String adminPassword) {
this.adminPassword = adminPassword;
return this;
}
public NodeMetadataBuilder group(@Nullable String group) { public NodeMetadataBuilder group(@Nullable String group) {
this.group = group; this.group = group;
@ -158,7 +176,7 @@ public class NodeMetadataBuilder extends ComputeMetadataBuilder {
@Override @Override
public NodeMetadata build() { public NodeMetadata build() {
return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tags, group, hardware, imageId, 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) { 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.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tags(node.getTags()).group(
node.getGroup()).hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem( node.getGroup()).hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem(
node.getOperatingSystem()).state(node.getState()).loginPort(node.getLoginPort()).publicAddresses( node.getOperatingSystem()).state(node.getState()).loginPort(node.getLoginPort()).publicAddresses(
node.getPublicAddresses()).privateAddresses(node.getPrivateAddresses()).adminPassword( node.getPublicAddresses()).privateAddresses(node.getPrivateAddresses()).credentials(node.getCredentials()).hostname(node.getHostname());
node.getAdminPassword()).credentials(node.getCredentials()).hostname(node.getHostname());
} }
} }

View File

@ -24,13 +24,14 @@ import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.compute.domain.ComputeType; import org.jclouds.compute.domain.ComputeType;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; 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 * @author Adrian Cole
@ -43,10 +44,12 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
private final OperatingSystem operatingSystem; private final OperatingSystem operatingSystem;
private final String version; private final String version;
private final String description; private final String description;
@Nullable private final LoginCredentials defaultCredentials;
private final String adminPassword;
private final Credentials defaultCredentials;
/**
* <h4>will be removed in jclouds 1.4.0</h4>
*/
@Deprecated
public ImageImpl(String providerId, String name, String id, Location location, URI uri, public ImageImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, Set<String> tags, OperatingSystem operatingSystem, String description, Map<String, String> userMetadata, Set<String> tags, OperatingSystem operatingSystem, String description,
@Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) { @Nullable String version, @Nullable String adminPassword, @Nullable Credentials defaultCredentials) {
@ -54,7 +57,21 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem"); this.operatingSystem = checkNotNull(operatingSystem, "operatingSystem");
this.version = version; this.version = version;
this.description = checkNotNull(description, "description"); this.description = checkNotNull(description, "description");
this.adminPassword = adminPassword; 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<String, String> userMetadata, Set<String> 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.defaultCredentials = defaultCredentials; this.defaultCredentials = defaultCredentials;
} }
@ -86,7 +103,7 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Credentials getDefaultCredentials() { public LoginCredentials getDefaultCredentials() {
return defaultCredentials; return defaultCredentials;
} }
@ -94,8 +111,10 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
@Deprecated
public String getAdminPassword() { public String getAdminPassword() {
return adminPassword; return (defaultCredentials != null && defaultCredentials.shouldAuthenticateSudo()) ? defaultCredentials
.getPassword() : null;
} }
@Override @Override
@ -110,7 +129,6 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = super.hashCode(); int result = super.hashCode();
result = prime * result + ((adminPassword == null) ? 0 : adminPassword.hashCode());
result = prime * result + ((defaultCredentials == null) ? 0 : defaultCredentials.hashCode()); result = prime * result + ((defaultCredentials == null) ? 0 : defaultCredentials.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode()); result = prime * result + ((operatingSystem == null) ? 0 : operatingSystem.hashCode());
@ -127,11 +145,6 @@ public class ImageImpl extends ComputeMetadataImpl implements Image {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
ImageImpl other = (ImageImpl) obj; 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 (defaultCredentials == null) {
if (other.defaultCredentials != null) if (other.defaultCredentials != null)
return false; return false;

View File

@ -33,6 +33,8 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; 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.ImmutableSet;
@ -50,9 +52,7 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
private final Set<String> publicAddresses; private final Set<String> publicAddresses;
private final Set<String> privateAddresses; private final Set<String> privateAddresses;
@Nullable @Nullable
private final String adminPassword; private final LoginCredentials credentials;
@Nullable
private final Credentials credentials;
@Nullable @Nullable
private final String group; private final String group;
@Nullable @Nullable
@ -64,6 +64,10 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
@Nullable @Nullable
private final String hostname; private final String hostname;
/**
* <h4>will be removed in jclouds 1.4.0</h4>
*/
@Deprecated
public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri, public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri,
Map<String, String> userMetadata, Set<String> tags, @Nullable String group, @Nullable Hardware hardware, Map<String, String> userMetadata, Set<String> tags, @Nullable String group, @Nullable Hardware hardware,
@Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort, @Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort,
@ -78,7 +82,29 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
this.loginPort = loginPort; this.loginPort = loginPort;
this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses")); this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, "publicAddresses"));
this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses")); this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, "privateAddresses"));
this.adminPassword = adminPassword; 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<String, String> userMetadata, Set<String> tags, @Nullable String group, @Nullable Hardware hardware,
@Nullable String imageId, @Nullable OperatingSystem os, NodeState state, int loginPort,
Iterable<String> publicAddresses, Iterable<String> privateAddresses, @Nullable LoginCredentials 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.credentials = credentials; this.credentials = credentials;
this.hostname = hostname; this.hostname = hostname;
} }
@ -111,15 +137,16 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
@Deprecated
public String getAdminPassword() { public String getAdminPassword() {
return adminPassword; return (credentials != null && credentials.shouldAuthenticateSudo()) ? credentials.getPassword() : null;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Credentials getCredentials() { public LoginCredentials getCredentials() {
return credentials; return credentials;
} }
@ -201,7 +228,6 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
result = prime * result + ((imageId == null) ? 0 : imageId.hashCode()); result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());
result = prime * result + ((hardware == null) ? 0 : hardware.hashCode()); result = prime * result + ((hardware == null) ? 0 : hardware.hashCode());
result = prime * result + ((os == null) ? 0 : os.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()); result = prime * result + ((credentials == null) ? 0 : credentials.hashCode());
return result; return result;
} }
@ -252,11 +278,6 @@ public class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadat
return false; return false;
} else if (!os.equals(other.os)) } else if (!os.equals(other.os))
return false; return false;
if (adminPassword == null) {
if (other.adminPassword != null)
return false;
} else if (!adminPassword.equals(other.adminPassword))
return false;
if (credentials == null) { if (credentials == null) {
if (other.credentials != null) if (other.credentials != null)
return false; return false;

View File

@ -18,13 +18,12 @@
*/ */
package org.jclouds.compute.functions; package org.jclouds.compute.functions;
import static org.jclouds.domain.Credentials.NO_CREDENTIALS;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions; 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; import com.google.common.base.Function;
@ -33,21 +32,21 @@ import com.google.common.base.Function;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class DefaultCredentialsFromImageOrOverridingCredentials implements Function<Template, Credentials> { public class DefaultCredentialsFromImageOrOverridingCredentials implements Function<Template, LoginCredentials> {
@Override @Override
public Credentials apply(Template template) { public LoginCredentials apply(Template template) {
TemplateOptions options = template.getOptions(); TemplateOptions options = template.getOptions();
Credentials creds = template.getImage().getDefaultCredentials(); Builder builder = LoginCredentials.builder(template.getImage().getDefaultCredentials());
Credentials overridingCredentials = options.getOverridingCredentials(); if (options.getLoginUser() != null)
Credentials overrideCreds = (overridingCredentials != null) ? overridingCredentials : NO_CREDENTIALS; builder.user(options.getLoginUser());
if (creds == null) if (options.getLoginPassword() != null)
creds = overrideCreds; builder.password(options.getLoginPassword());
if (overrideCreds.identity != null) if (options.getLoginPrivateKey() != null)
creds = creds.toBuilder().identity(overrideCreds.identity).build(); builder.privateKey(options.getLoginPrivateKey());
if (overrideCreds.credential != null) if (options.shouldAuthenticateSudo() != null)
creds = creds.toBuilder().credential(overrideCreds.credential).build(); builder.authenticateSudo(true);
return creds.equals(NO_CREDENTIALS) ? null : creds; return builder.build();
} }
} }

View File

@ -80,7 +80,8 @@ import org.jclouds.compute.strategy.RunScriptOnNodeAndAddToGoodMapOrPutException
import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; 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.io.Payload;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
@ -139,14 +140,12 @@ public class BaseComputeService implements ComputeService {
@Inject @Inject
protected BaseComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore, protected BaseComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
@Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy, @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy, CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy,
CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy, RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy, ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy,
SuspendNodeStrategy suspendNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning, @Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated, @Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended, @Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended,
@ -502,8 +501,8 @@ public class BaseComputeService implements ComputeService {
public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript, public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<NodeMetadata> filter, Payload runScript,
RunScriptOptions options) throws RunScriptOnNodesException { RunScriptOptions options) throws RunScriptOnNodesException {
try { try {
return runScriptOnNodesMatching(filter, Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript, return runScriptOnNodesMatching(filter,
"runScript").getInput())), options); Statements.exec(Strings2.toStringAndClose(checkNotNull(runScript, "runScript").getInput())), options);
} catch (IOException e) { } catch (IOException e) {
Throwables.propagate(e); Throwables.propagate(e);
return null; return null;
@ -643,7 +642,8 @@ public class BaseComputeService implements ComputeService {
private Iterable<? extends RunScriptOnNode> transformNodesIntoInitializedScriptRunners( private Iterable<? extends RunScriptOnNode> transformNodesIntoInitializedScriptRunners(
Iterable<? extends NodeMetadata> nodes, Statement script, RunScriptOptions options, Iterable<? extends NodeMetadata> nodes, Statement script, RunScriptOptions options,
Map<NodeMetadata, Exception> badNodes) { Map<NodeMetadata, Exception> badNodes) {
return filter(transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes), return filter(
transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes),
executor, null, logger, "initialize script runners"), notNull()); executor, null, logger, "initialize script runners"), notNull());
} }
@ -658,21 +658,16 @@ public class BaseComputeService implements ComputeService {
protected NodeMetadata updateNodeWithCredentialsIfPresent(NodeMetadata node, RunScriptOptions options) { protected NodeMetadata updateNodeWithCredentialsIfPresent(NodeMetadata node, RunScriptOptions options) {
checkNotNull(node, "node"); checkNotNull(node, "node");
if (options.getOverridingCredentials() != null) { Builder builder = LoginCredentials.builder(node.getCredentials());
Builder<? extends Credentials> builder = node.getCredentials() != null ? node.getCredentials().toBuilder() if (options.getLoginUser() != null)
: new Credentials.Builder<Credentials>(); builder.user(options.getLoginUser());
if (options.getOverridingCredentials().identity != null) if (options.getLoginPassword() != null)
builder.identity(options.getOverridingCredentials().identity); builder.password(options.getLoginPassword());
if (options.getOverridingCredentials().credential != null) { if (options.getLoginPrivateKey() != null)
// custom credentials are related to the input builder.privateKey(options.getLoginPrivateKey());
builder = options.getOverridingCredentials().toBuilder(); if (options.shouldAuthenticateSudo() != null)
Credentials cred = builder.build(); builder.authenticateSudo(true);
builder.identity(cred.identity); return NodeMetadataBuilder.fromNodeMetadata(node).credentials(builder.build()).build();
builder.credential(options.getOverridingCredentials().credential);
}
node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(builder.build()).build();
}
return node;
} }
private final class TransformNodesIntoInitializedScriptRunners implements private final class TransformNodesIntoInitializedScriptRunners implements

View File

@ -22,6 +22,9 @@ import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import org.jclouds.domain.Credentials; 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. * Enables additional options for running a script.
@ -52,12 +55,6 @@ public class RunScriptOptions {
return delegate.toString(); return delegate.toString();
} }
@Override
public Credentials getOverridingCredentials() {
return delegate.getOverridingCredentials();
}
@Override @Override
public boolean shouldRunAsRoot() { public boolean shouldRunAsRoot() {
return delegate.shouldRunAsRoot(); return delegate.shouldRunAsRoot();
@ -80,11 +77,62 @@ public class RunScriptOptions {
throw new IllegalArgumentException("blockOnComplete is immutable"); 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 @Override
public RunScriptOptions overrideLoginUserWith(String loginUser) { public RunScriptOptions overrideLoginUserWith(String loginUser) {
throw new IllegalArgumentException("loginUser is immutable"); throw new IllegalArgumentException("loginUser is immutable");
} }
@Override
public RunScriptOptions overrideLoginUser(String loginUser) {
throw new IllegalArgumentException("loginUser is immutable");
}
@Override @Override
public RunScriptOptions overrideLoginCredentialWith(String loginCredential) { public RunScriptOptions overrideLoginCredentialWith(String loginCredential) {
throw new IllegalArgumentException("loginCredential is immutable"); throw new IllegalArgumentException("loginCredential is immutable");
@ -95,6 +143,7 @@ public class RunScriptOptions {
throw new IllegalArgumentException("wrapInInitScript is immutable"); throw new IllegalArgumentException("wrapInInitScript is immutable");
} }
@Deprecated
@Override @Override
public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) { public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) {
throw new IllegalArgumentException("overridingCredentials is immutable"); throw new IllegalArgumentException("overridingCredentials is immutable");
@ -129,36 +178,72 @@ public class RunScriptOptions {
protected int port = -1; protected int port = -1;
protected int seconds = -1; protected int seconds = -1;
protected String taskName; protected String taskName;
protected Credentials overridingCredentials;
protected boolean runAsRoot = true; protected boolean runAsRoot = true;
protected boolean blockOnComplete = true; protected boolean blockOnComplete = true;
protected boolean wrapInInitScript = true; protected boolean wrapInInitScript = true;
protected String loginUser;
protected Boolean authenticateSudo;
protected String loginPassword;
protected String loginPrivateKey;
@Deprecated
public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) { public RunScriptOptions overrideCredentialsWith(Credentials overridingCredentials) {
return overrideLoginCredentials(LoginCredentials.builder(overridingCredentials).build());
}
public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {
checkNotNull(overridingCredentials, "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; return this;
} }
@Deprecated
public RunScriptOptions overrideLoginUserWith(String loginUser) { public RunScriptOptions overrideLoginUserWith(String loginUser) {
return overrideLoginUser(loginUser);
}
public RunScriptOptions overrideLoginUser(String loginUser) {
checkNotNull(loginUser, "loginUser"); checkNotNull(loginUser, "loginUser");
org.jclouds.domain.Credentials.Builder<? extends Credentials> builder = overridingCredentials != null ? overridingCredentials this.loginUser = loginUser;
.toBuilder() : new Credentials.Builder<Credentials>();
this.overridingCredentials = builder.identity(loginUser).build();
return this; return this;
} }
@Deprecated
public RunScriptOptions overrideLoginCredentialWith(String loginCredential) { public RunScriptOptions overrideLoginCredentialWith(String loginCredential) {
checkNotNull(loginCredential, "loginCredential"); checkNotNull(loginCredential, "loginCredential");
org.jclouds.domain.Credentials.Builder<? extends Credentials> builder = overridingCredentials != null ? overridingCredentials if (CredentialUtils.isPrivateKeyCredential(loginCredential)) {
.toBuilder() : new Credentials.Builder<Credentials>(); this.loginPrivateKey = loginCredential;
this.overridingCredentials = builder.credential(loginCredential).build(); } 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 this;
} }
/** /**
* @return What to call the task relating to this script; default * @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) { public RunScriptOptions nameTask(String name) {
@ -176,8 +261,9 @@ public class RunScriptOptions {
* <p/> * <p/>
* *
* @param wrapInInitScript * @param wrapInInitScript
* if the command is long-running, use this option to ensure it is wrapInInitScripted * if the command is long-running, use this option to ensure it is
* properly. (ex. have jclouds wrap it an init script, nohup, etc) * wrapInInitScripted properly. (ex. have jclouds wrap it an init
* script, nohup, etc)
* @return * @return
*/ */
public RunScriptOptions wrapInInitScript(boolean wrapInInitScript) { 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 * As of version 1.1.0, we cannot kick off a script unless a node is in
* RUNNING state. * RUNNING state.
* *
* @param blockOnComplete (default true) * @param blockOnComplete
* false means kick off the script in the background, but don't * (default true) false means kick off the script in the
* wait for it to finish. (as of version 1.1.0, implemented as * background, but don't wait for it to finish. (as of version
* nohup) * 1.1.0, implemented as nohup)
*/ */
public RunScriptOptions blockOnComplete(boolean blockOnComplete) { public RunScriptOptions blockOnComplete(boolean blockOnComplete) {
this.blockOnComplete = 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() { @Nullable
return overridingCredentials; 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 * @return value
*/ */
@ -264,21 +385,49 @@ public class RunScriptOptions {
return options.nameTask(name); return options.nameTask(name);
} }
@Deprecated
public static RunScriptOptions overrideLoginUserWith(String user) { public static RunScriptOptions overrideLoginUserWith(String user) {
RunScriptOptions options = new RunScriptOptions(); RunScriptOptions options = new RunScriptOptions();
return options.overrideLoginUserWith(user); 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) { public static RunScriptOptions overrideLoginCredentialWith(String credential) {
RunScriptOptions options = new RunScriptOptions(); RunScriptOptions options = new RunScriptOptions();
return options.overrideLoginCredentialWith(credential); return options.overrideLoginCredentialWith(credential);
} }
@Deprecated
public static RunScriptOptions overrideCredentialsWith(Credentials credentials) { public static RunScriptOptions overrideCredentialsWith(Credentials credentials) {
RunScriptOptions options = new RunScriptOptions(); RunScriptOptions options = new RunScriptOptions();
return options.overrideCredentialsWith(credentials); return options.overrideCredentialsWith(credentials);
} }
public static RunScriptOptions overrideLoginCredentials(LoginCredentials credentials) {
RunScriptOptions options = new RunScriptOptions();
return options.overrideLoginCredentials(credentials);
}
public static RunScriptOptions runAsRoot(boolean value) { public static RunScriptOptions runAsRoot(boolean value) {
RunScriptOptions options = new RunScriptOptions(); RunScriptOptions options = new RunScriptOptions();
return options.runAsRoot(value); return options.runAsRoot(value);
@ -306,9 +455,74 @@ public class RunScriptOptions {
@Override @Override
public String toString() { public String toString() {
return "[overridingCredentials=" + (overridingCredentials != null) + ", port:seconds=" + port + ":" + seconds return "[loginUser=" + loginUser + ", loginPasswordPresent=" + (loginPassword != null)
+ ", runAsRoot=" + runAsRoot + ", blockOnComplete=" + blockOnComplete + ", wrapInInitScript=" + ", loginPrivateKeyPresent=" + (loginPrivateKey != null) + ", shouldAuthenticateSudo=" + authenticateSudo
+ wrapInInitScript + "]"; + ", 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;
} }
} }

View File

@ -28,6 +28,7 @@ import java.util.Set;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.io.Payload; import org.jclouds.io.Payload;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.scriptbuilder.domain.Statements;
@ -82,8 +83,14 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
to.blockUntilRunning(false); to.blockUntilRunning(false);
if (!this.shouldBlockOnComplete()) if (!this.shouldBlockOnComplete())
to.blockOnComplete(false); to.blockOnComplete(false);
if (this.getOverridingCredentials() != null) if (this.getLoginUser() != null)
to.overrideCredentialsWith(this.getOverridingCredentials()); 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) if (this.getTaskName() != null)
to.nameTask(this.getTaskName()); to.nameTask(this.getTaskName());
} }
@ -113,11 +120,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
return delegate.getSeconds(); return delegate.getSeconds();
} }
@Override
public Credentials getOverridingCredentials() {
return delegate.getOverridingCredentials();
}
@Override @Override
public boolean shouldRunAsRoot() { public boolean shouldRunAsRoot() {
return delegate.shouldRunAsRoot(); return delegate.shouldRunAsRoot();
@ -191,21 +193,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
throw new IllegalArgumentException("runAsRoot is immutable"); 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 @Override
public TemplateOptions wrapInInitScript(boolean wrapInInitScript) { public TemplateOptions wrapInInitScript(boolean wrapInInitScript) {
throw new IllegalArgumentException("wrapInInitScript is immutable"); throw new IllegalArgumentException("wrapInInitScript is immutable");
@ -216,6 +203,68 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
throw new IllegalArgumentException("blockOnComplete is immutable"); 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 @Override
public <T extends TemplateOptions> T as(Class<T> clazz) { public <T extends TemplateOptions> T as(Class<T> clazz) {
return delegate.as(clazz); return delegate.as(clazz);
@ -465,21 +514,49 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
return options.nameTask(name); return options.nameTask(name);
} }
@Deprecated
public static TemplateOptions overrideLoginUserWith(String user) { public static TemplateOptions overrideLoginUserWith(String user) {
TemplateOptions options = new TemplateOptions(); TemplateOptions options = new TemplateOptions();
return options.overrideLoginUserWith(user); 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) { public static TemplateOptions overrideLoginCredentialWith(String credential) {
TemplateOptions options = new TemplateOptions(); TemplateOptions options = new TemplateOptions();
return options.overrideLoginCredentialWith(credential); return options.overrideLoginCredentialWith(credential);
} }
@Deprecated
public static TemplateOptions overrideCredentialsWith(Credentials credentials) { public static TemplateOptions overrideCredentialsWith(Credentials credentials) {
TemplateOptions options = new TemplateOptions(); TemplateOptions options = new TemplateOptions();
return options.overrideCredentialsWith(credentials); return options.overrideCredentialsWith(credentials);
} }
public static TemplateOptions overrideLoginCredentials(LoginCredentials credentials) {
TemplateOptions options = new TemplateOptions();
return options.overrideLoginCredentials(credentials);
}
public static TemplateOptions runAsRoot(boolean value) { public static TemplateOptions runAsRoot(boolean value) {
TemplateOptions options = new TemplateOptions(); TemplateOptions options = new TemplateOptions();
return options.runAsRoot(value); return options.runAsRoot(value);
@ -736,21 +813,6 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
return TemplateOptions.class.cast(super.runAsRoot(runAsRoot)); 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 @Override
public TemplateOptions wrapInInitScript(boolean wrapInInitScript) { public TemplateOptions wrapInInitScript(boolean wrapInInitScript) {
return TemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript)); return TemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript));
@ -760,4 +822,48 @@ public class TemplateOptions extends RunScriptOptions implements Cloneable {
public TemplateOptions blockOnComplete(boolean blockOnComplete) { public TemplateOptions blockOnComplete(boolean blockOnComplete) {
return TemplateOptions.class.cast(super.blockOnComplete(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));
}
} }

View File

@ -20,26 +20,39 @@ package org.jclouds.compute.strategy;
import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage; import org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import com.google.common.base.Function;
import com.google.inject.ImplementedBy; import com.google.inject.ImplementedBy;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@ImplementedBy(ReturnCredentialsBoundToImage.class) @ImplementedBy(ReturnCredentialsBoundToImage.class)
public interface PopulateDefaultLoginCredentialsForImageStrategy { public interface PopulateDefaultLoginCredentialsForImageStrategy extends Function<Object, LoginCredentials> {
/** /**
* <h4>will be removed in jclouds 1.4.0</h4> <br/>
*
* Processes the resource to determine credentials. * Processes the resource to determine credentials.
* *
* @param resourceToAuthenticate * @param resourceToAuthenticate
* this can be any resource, such as an image, * this can be any resource, such as an image, running server
* running server instance or other. It's the * instance or other. It's the responsibility of an implementation
* responsibility of an implementation to apply * to apply the cloud-specific logic.
* the cloud-specific logic. * @return credentials object. Note: the key may not be set, but the identity
* @return credentials object. Note: the key * must be set
* may not be set, but the identity must be set
*/ */
@Deprecated
Credentials execute(Object resourceToAuthenticate); 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);
} }

View File

@ -19,13 +19,13 @@
package org.jclouds.compute.strategy; package org.jclouds.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.domain.Credentials.NO_CREDENTIALS;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.compute.domain.Template; 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; import com.google.common.base.Function;
@ -35,25 +35,29 @@ import com.google.common.base.Function;
*/ */
@Singleton @Singleton
public class PrioritizeCredentialsFromTemplate { public class PrioritizeCredentialsFromTemplate {
private final Function<Template, Credentials> credentialsFromImageOrTemplateOptions; private final Function<Template, LoginCredentials> credentialsFromImageOrTemplateOptions;
@Inject @Inject
public PrioritizeCredentialsFromTemplate(Function<Template, Credentials> credentialsFromImageOrTemplateOptions) { public PrioritizeCredentialsFromTemplate(Function<Template, LoginCredentials> credentialsFromImageOrTemplateOptions) {
this.credentialsFromImageOrTemplateOptions = checkNotNull(credentialsFromImageOrTemplateOptions, this.credentialsFromImageOrTemplateOptions = checkNotNull(credentialsFromImageOrTemplateOptions,
"credentialsFromImageOrTemplateOptions"); "credentialsFromImageOrTemplateOptions");
} }
public Credentials apply(Template template, Credentials fromNode) { public LoginCredentials apply(Template template, LoginCredentials fromNode) {
Credentials creds = (fromNode != null) ? fromNode : NO_CREDENTIALS; LoginCredentials creds = fromNode;
Credentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template); LoginCredentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template);
if (credsFromParameters != null) { if (credsFromParameters != null) {
if (credsFromParameters.identity != null) Builder builder = LoginCredentials.builder(creds);
creds = creds.toBuilder().identity(credsFromParameters.identity).build(); if (credsFromParameters.getUser() != null)
if (credsFromParameters.credential != null) builder.user(credsFromParameters.getUser());
creds = creds.toBuilder().credential(credsFromParameters.credential).build(); 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; return creds;
} }

View File

@ -32,6 +32,7 @@ import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;
import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.predicates.NodePredicates; 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.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy; import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -76,9 +79,25 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements CreateNodeW
this.prioritizeCredentialsFromTemplate = checkNotNull(prioritizeCredentialsFromTemplate, this.prioritizeCredentialsFromTemplate = checkNotNull(prioritizeCredentialsFromTemplate,
"prioritizeCredentialsFromTemplate"); "prioritizeCredentialsFromTemplate");
this.client = checkNotNull(client, "client"); this.client = checkNotNull(client, "client");
this.nodeMetadataAdapter = checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter"); this.nodeMetadataAdapter = Functions.compose(addLoginCredentials,
checkNotNull(nodeMetadataAdapter, "nodeMetadataAdapter"));
} }
private final Function<NodeMetadata, NodeMetadata> addLoginCredentials = new Function<NodeMetadata, NodeMetadata>() {
@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 @Override
public Iterable<? extends ComputeMetadata> listNodes() { public Iterable<? extends ComputeMetadata> listNodes() {
return listDetailsOnNodesMatching(NodePredicates.all()); return listDetailsOnNodesMatching(NodePredicates.all());
@ -92,7 +111,9 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements CreateNodeW
@Override @Override
public NodeMetadata getNode(String id) { public NodeMetadata getNode(String id) {
N node = client.getNode(checkNotNull(id, "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 @Override
@ -141,8 +162,8 @@ public class AdaptingComputeServiceStrategies<N, H, I, L> implements CreateNodeW
checkState(template != null, "template must be specified"); checkState(template != null, "template must be specified");
NodeAndInitialCredentials<N> from = client.createNodeWithGroupEncodedIntoName(group, name, template); NodeAndInitialCredentials<N> from = client.createNodeWithGroupEncodedIntoName(group, name, template);
Credentials fromNode = from.getCredentials(); LoginCredentials fromNode = from.getCredentials();
Credentials creds = prioritizeCredentialsFromTemplate.apply(template, fromNode); LoginCredentials creds = prioritizeCredentialsFromTemplate.apply(template, fromNode);
if (creds != null) if (creds != null)
credentialStore.put("node#" + from.getNodeId(), creds); credentialStore.put("node#" + from.getNodeId(), creds);
NodeMetadata node = nodeMetadataAdapter.apply(from.getNode()); NodeMetadata node = nodeMetadataAdapter.apply(from.getNode());

View File

@ -28,6 +28,7 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy; import org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.javax.annotation.Nullable; import org.jclouds.javax.annotation.Nullable;
/** /**
@ -36,23 +37,28 @@ import org.jclouds.javax.annotation.Nullable;
@Singleton @Singleton
public class ReturnCredentialsBoundToImage implements PopulateDefaultLoginCredentialsForImageStrategy { public class ReturnCredentialsBoundToImage implements PopulateDefaultLoginCredentialsForImageStrategy {
protected final Credentials creds; protected final LoginCredentials creds;
@Inject @Inject
public ReturnCredentialsBoundToImage(@Nullable @Named("image") Credentials creds) { public ReturnCredentialsBoundToImage(@Nullable @Named("image") LoginCredentials creds) {
this.creds = creds; this.creds = creds;
} }
@Override @Override
public Credentials execute(Object resourceToAuthenticate) { public LoginCredentials apply(Object resourceToAuthenticate) {
checkState(resourceToAuthenticate instanceof Image, "this is only valid for images"); checkState(resourceToAuthenticate instanceof Image, "this is only valid for images");
if (creds != null) if (creds != null)
return creds; return creds;
Image image = Image.class.cast(resourceToAuthenticate); Image image = Image.class.cast(resourceToAuthenticate);
if (image.getOperatingSystem() != null && OsFamily.WINDOWS.equals(image.getOperatingSystem().getFamily())) { if (image.getOperatingSystem() != null && OsFamily.WINDOWS.equals(image.getOperatingSystem().getFamily())) {
return new Credentials("Administrator", null); return LoginCredentials.builder().user("Administrator").build();
} else { } else {
return new Credentials("root", null); return LoginCredentials.builder().user("root").build();
} }
} }
@Override
public Credentials execute(Object resourceToAuthenticate) {
return apply(resourceToAuthenticate);
}
} }

View File

@ -38,8 +38,8 @@ import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.location.suppliers.JustProvider; import org.jclouds.location.suppliers.JustProvider;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
@ -63,14 +63,12 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
private final String passwordPrefix; private final String passwordPrefix;
private final Supplier<Set<? extends Location>> locationSupplier; private final Supplier<Set<? extends Location>> locationSupplier;
private final Map<OsFamily, Map<String, String>> osToVersionMap; private final Map<OsFamily, Map<String, String>> osToVersionMap;
private final Map<String, Credentials> credentialStore;
@Inject @Inject
public StubComputeServiceAdapter(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location, public StubComputeServiceAdapter(ConcurrentMap<String, NodeMetadata> nodes, Supplier<Location> location,
@Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix, @Named("NODE_ID") Provider<Integer> idProvider, @Named("PUBLIC_IP_PREFIX") String publicIpPrefix,
@Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix, @Named("PRIVATE_IP_PREFIX") String privateIpPrefix, @Named("PASSWORD_PREFIX") String passwordPrefix,
JustProvider locationSupplier, Map<OsFamily, Map<String, String>> osToVersionMap, JustProvider locationSupplier, Map<OsFamily, Map<String, String>> osToVersionMap) {
Map<String, Credentials> credentialStore) {
this.nodes = nodes; this.nodes = nodes;
this.location = location; this.location = location;
this.idProvider = idProvider; this.idProvider = idProvider;
@ -79,7 +77,6 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
this.passwordPrefix = passwordPrefix; this.passwordPrefix = passwordPrefix;
this.locationSupplier = locationSupplier; this.locationSupplier = locationSupplier;
this.osToVersionMap = osToVersionMap; this.osToVersionMap = osToVersionMap;
this.credentialStore = credentialStore;
} }
@Override @Override
@ -99,9 +96,8 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
builder.state(NodeState.PENDING); builder.state(NodeState.PENDING);
builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id)); builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));
builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id)); builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));
builder.credentials(new Credentials(null, passwordPrefix + id)); builder.credentials(LoginCredentials.builder().user("root").password(passwordPrefix + id).build());
NodeMetadata node = builder.build(); NodeMetadata node = builder.build();
credentialStore.put("node#" + node.getId(), node.getCredentials());
nodes.put(node.getId(), node); nodes.put(node.getId(), node);
StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100); StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100);
return new NodeWithInitialCredentials(node); return new NodeWithInitialCredentials(node);
@ -116,7 +112,6 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
@Override @Override
public Iterable<Image> listImages() { public Iterable<Image> listImages() {
Credentials defaultCredentials = new Credentials("root", null);
// initializing as a List, as ImmutableSet does not allow you to put // initializing as a List, as ImmutableSet does not allow you to put
// duplicates // duplicates
Builder<Image> images = ImmutableList.<Image> builder(); Builder<Image> images = ImmutableList.<Image> builder();
@ -127,7 +122,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
String desc = String.format("stub %s %s", osVersions.getKey(), is64Bit); String desc = String.format("stub %s %s", osVersions.getKey(), is64Bit);
images.add(new ImageBuilder().ids(id++ + "").name(osVersions.getKey().name()).location(location.get()) images.add(new ImageBuilder().ids(id++ + "").name(osVersions.getKey().name()).location(location.get())
.operatingSystem(new OperatingSystem(osVersions.getKey(), desc, version, null, desc, is64Bit)) .operatingSystem(new OperatingSystem(osVersions.getKey(), desc, version, null, desc, is64Bit))
.description(desc).defaultCredentials(defaultCredentials).build()); .description(desc).build());
} }
} }
return images.build(); return images.build();
@ -146,9 +141,7 @@ public class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAda
@Override @Override
public NodeMetadata getNode(String id) { public NodeMetadata getNode(String id) {
NodeMetadata node = nodes.get(id); return nodes.get(id);
return node == null ? null : NodeMetadataBuilder.fromNodeMetadata(node)
.credentials(credentialStore.get("node#" + node.getId())).build();
} }
@Override @Override

View File

@ -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.nameTask;
import static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript; 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.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.options.TemplateOptions.Builder.runAsRoot;
import static org.jclouds.compute.predicates.NodePredicates.TERMINATED; import static org.jclouds.compute.predicates.NodePredicates.TERMINATED;
import static org.jclouds.compute.predicates.NodePredicates.all; 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.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.net.IPSocket; import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
@ -228,13 +229,13 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv
try { try {
Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, options); Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, options);
NodeMetadata node = get(nodes, 0); NodeMetadata node = get(nodes, 0);
Credentials good = node.getCredentials(); LoginCredentials good = node.getCredentials();
assert good.identity != null : nodes; assert good.identity != null : nodes;
assert good.credential != null : nodes; assert good.credential != null : nodes;
for (Entry<? extends NodeMetadata, ExecResponse> response : client.runScriptOnNodesMatching( for (Entry<? extends NodeMetadata, ExecResponse> response : client.runScriptOnNodesMatching(
runningInGroup(group), Statements.exec("hostname"), runningInGroup(group), Statements.exec("hostname"),
wrapInInitScript(false).runAsRoot(false).overrideCredentialsWith(good)).entrySet()) { wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(good)).entrySet()) {
checkResponseEqualsHostname(response.getValue(), response.getKey()); checkResponseEqualsHostname(response.getValue(), response.getKey());
} }
@ -281,10 +282,12 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv
@Test(enabled = false) @Test(enabled = false)
protected void tryBadPassword(String group, Credentials good) throws AssertionError { protected void tryBadPassword(String group, Credentials good) throws AssertionError {
try { try {
Map<? extends NodeMetadata, ExecResponse> responses = client.runScriptOnNodesMatching(runningInGroup(group), Map<? extends NodeMetadata, ExecResponse> responses = client.runScriptOnNodesMatching(
runningInGroup(group),
"echo I put a bad password", "echo I put a bad password",
wrapInInitScript(false).runAsRoot(false) wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(
.overrideCredentialsWith(new Credentials(good.identity, "romeo"))); 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; assert responses.size() == 0 : "shouldn't pass with a bad password\n" + responses;
} catch (AssertionError e) { } catch (AssertionError e) {
throw e; throw e;
@ -433,8 +436,8 @@ public abstract class BaseComputeServiceLiveTest extends BaseVersionedServiceLiv
} }
protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String group, OperatingSystem os, protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String group, OperatingSystem os,
Credentials creds) throws RunScriptOnNodesException { LoginCredentials creds) throws RunScriptOnNodesException {
return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideLoginCredentials(creds)
.nameTask("runScriptWithCreds")); .nameTask("runScriptWithCreds"));
} }

View File

@ -37,9 +37,9 @@ import org.jclouds.compute.domain.OsFamilyVersion64Bit;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.domain.LocationScope; import org.jclouds.domain.LocationScope;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule;
@ -257,8 +257,8 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi
@Test @Test
public void testTemplateBuilderWithLoginUserSpecified() throws IOException { public void testTemplateBuilderWithLoginUserSpecified() throws IOException {
tryOverrideUsingPropertyKey("jclouds.login-user"); tryOverrideUsingPropertyKey("jclouds");
tryOverrideUsingPropertyKey(provider + ".login-user"); tryOverrideUsingPropertyKey(provider);
} }
protected void tryOverrideUsingPropertyKey(String propertyKey) { protected void tryOverrideUsingPropertyKey(String propertyKey) {
@ -266,7 +266,9 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi
try { try {
Properties overrides = setupProperties(); Properties overrides = setupProperties();
String login = loginUser != null ? loginUser : "foo:bar"; 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, context = new ComputeServiceContextFactory().createContext(provider,
ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides); ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides);
@ -275,7 +277,7 @@ public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLi
String user = Iterables.get(userPass, 0); String user = Iterables.get(userPass, 0);
String pass = Iterables.size(userPass) > 1 ? Iterables.get(userPass, 1) : null; String pass = Iterables.size(userPass) > 1 ? Iterables.get(userPass, 1) : null;
assertEquals(context.getComputeService().templateBuilder().build().getImage().getDefaultCredentials(), assertEquals(context.getComputeService().templateBuilder().build().getImage().getDefaultCredentials(),
new Credentials(user, pass)); LoginCredentials.builder().user(user).password(pass).authenticateSudo(auth).build());
} finally { } finally {
if (context != null) if (context != null)
context.close(); context.close();

View File

@ -41,6 +41,7 @@ public abstract class BaseVersionedServiceLiveTest {
protected String apiversion; protected String apiversion;
protected String imageId; protected String imageId;
protected String loginUser; protected String loginUser;
protected String authenticateSudo;
protected Properties setupRestProperties() { protected Properties setupRestProperties() {
return RestContextFactory.getPropertiesFromResource("/rest.properties"); return RestContextFactory.getPropertiesFromResource("/rest.properties");
@ -68,7 +69,9 @@ public abstract class BaseVersionedServiceLiveTest {
if (imageId != null) if (imageId != null)
overrides.setProperty(provider + ".image-id", imageId); overrides.setProperty(provider + ".image-id", imageId);
if (loginUser != null) 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; return overrides;
} }
@ -80,7 +83,8 @@ public abstract class BaseVersionedServiceLiveTest {
endpoint = System.getProperty("test." + provider + ".endpoint"); endpoint = System.getProperty("test." + provider + ".endpoint");
apiversion = System.getProperty("test." + provider + ".apiversion"); apiversion = System.getProperty("test." + provider + ".apiversion");
imageId = System.getProperty("test." + provider + ".image-id"); 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");
} }
} }

View File

@ -35,7 +35,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.MoreExecutors;
import org.jclouds.concurrent.config.ExecutorServiceModule; 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.InitBuilder;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
@ -84,7 +84,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testWithoutInitThrowsIllegalStateException() { public void testWithoutInitThrowsIllegalStateException() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -101,7 +101,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testDefault() { public void testDefault() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -150,7 +150,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testWithSudoPassword() { public void testWithSudoPassword() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -169,7 +169,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0)); expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0));
// since there's an adminPassword we must pass this in // 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 // signal the command completed
expect(sshClient.exec("./jclouds-script-0 status")).andReturn(new ExecResponse("", "", 1)); expect(sshClient.exec("./jclouds-script-0 status")).andReturn(new ExecResponse("", "", 1));
@ -198,7 +198,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {
public void testNotRoot() { public void testNotRoot() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);

View File

@ -30,7 +30,7 @@ import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.options.RunScriptOptions; 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.InitBuilder;
import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.OsFamily;
import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.Statement;
@ -51,7 +51,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest {
public void testWithoutInitThrowsIllegalStateException() { public void testWithoutInitThrowsIllegalStateException() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -67,7 +67,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest {
public void testDefault() { public void testDefault() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -108,7 +108,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest {
public void testWithSudoPassword() { public void testWithSudoPassword() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);
@ -126,7 +126,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest {
expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0)); expect(sshClient.exec("./jclouds-script-0 init")).andReturn(new ExecResponse("", "", 0));
// since there's an adminPassword we must pass this in // 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(); sshClient.disconnect();
@ -150,7 +150,7 @@ public class RunScriptOnNodeAsInitScriptUsingSshTest {
public void testNotRoot() { public void testNotRoot() {
Statement command = exec("doFoo"); Statement command = exec("doFoo");
NodeMetadata node = new NodeMetadataBuilder().ids("id").state(NodeState.RUNNING).credentials( 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); SshClient sshClient = createMock(SshClient.class);

View File

@ -26,7 +26,7 @@ import static org.jclouds.scriptbuilder.domain.Statements.exec;
import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.NodeMetadata; 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.javax.annotation.Nullable;
import org.jclouds.scriptbuilder.statements.login.UserAdd; import org.jclouds.scriptbuilder.statements.login.UserAdd;
import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshClient;
@ -38,13 +38,13 @@ import com.google.common.base.Function;
/** /**
* @author Adam Lowe * @author Adam Lowe
*/ */
@Test(groups={"unit"}, singleThreaded = true) @Test(groups = { "unit" }, singleThreaded = true)
public class RunScriptOnNodeUsingSshTest { public class RunScriptOnNodeUsingSshTest {
private SshClient sshClient; private SshClient sshClient;
private NodeMetadata node; private NodeMetadata node;
private Function<NodeMetadata, SshClient> sshFactory; private Function<NodeMetadata, SshClient> sshFactory;
@BeforeMethod(groups={"unit"}) @BeforeMethod(groups = { "unit" })
public void init() { public void init() {
sshClient = createMock(SshClient.class); sshClient = createMock(SshClient.class);
sshFactory = new Function<NodeMetadata, SshClient>() { sshFactory = new Function<NodeMetadata, SshClient>() {
@ -54,8 +54,7 @@ public class RunScriptOnNodeUsingSshTest {
} }
}; };
node = createMock(NodeMetadata.class); node = createMock(NodeMetadata.class);
expect(node.getCredentials()).andReturn(new Credentials("tester", "notalot")); expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "notalot", null, false)).atLeastOnce();
expect(node.getAdminPassword()).andReturn(null).atLeastOnce();
replay(node); replay(node);
} }
@ -68,8 +67,7 @@ public class RunScriptOnNodeUsingSshTest {
sshClient.connect(); sshClient.connect();
expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getUsername()).andReturn("tester");
expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com");
expect(sshClient.exec("echo $USER\n" + expect(sshClient.exec("echo $USER\n" + "echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0));
"echo $USER\n")).andReturn(new ExecResponse("tester\ntester\n", null, 0));
sshClient.disconnect(); sshClient.disconnect();
replay(sshClient); replay(sshClient);
@ -85,10 +83,9 @@ public class RunScriptOnNodeUsingSshTest {
sshClient.connect(); sshClient.connect();
expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getUsername()).andReturn("tester");
expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com");
expect(sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + expect(
"echo $USER\n" + sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "echo $USER\n" + "echo $USER\n"
"echo $USER\n" + + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0));
"RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0));
sshClient.disconnect(); sshClient.disconnect();
replay(sshClient); replay(sshClient);
@ -97,8 +94,8 @@ public class RunScriptOnNodeUsingSshTest {
public void simpleRootTestWithSudoPassword() { public void simpleRootTestWithSudoPassword() {
node = createMock(NodeMetadata.class); node = createMock(NodeMetadata.class);
expect(node.getCredentials()).andReturn(new Credentials("tester", "notalot")); expect(node.getCredentials()).andReturn(new LoginCredentials("tester", "testpassword!", null, true))
expect(node.getAdminPassword()).andReturn("testpassword!").atLeastOnce(); .atLeastOnce();
replay(node); replay(node);
RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"), RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, exec("echo $USER\necho $USER"),
wrapInInitScript(false).runAsRoot(true)); wrapInInitScript(false).runAsRoot(true));
@ -107,11 +104,9 @@ public class RunScriptOnNodeUsingSshTest {
sshClient.connect(); sshClient.connect();
expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getUsername()).andReturn("tester");
expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com");
expect(sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + expect(
"testpassword!\n" + sshClient.exec("sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + "testpassword!\n" + "echo $USER\n"
"echo $USER\n" + + "echo $USER\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0));
"echo $USER\n" +
"RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("root\nroot\n", null, 0));
sshClient.disconnect(); sshClient.disconnect();
replay(sshClient); replay(sshClient);
@ -119,20 +114,19 @@ public class RunScriptOnNodeUsingSshTest {
} }
public void testUserAddAsRoot() { public void testUserAddAsRoot() {
RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, node, UserAdd.builder()
UserAdd.builder().login("testuser").build(), .login("testuser").build(), wrapInInitScript(false).runAsRoot(true).overrideLoginPassword("test"));
wrapInInitScript(false).runAsRoot(true).overrideLoginCredentialWith("test"));
testMe.init(); testMe.init();
sshClient.connect(); sshClient.connect();
expect(sshClient.getUsername()).andReturn("tester"); expect(sshClient.getUsername()).andReturn("tester");
expect(sshClient.getHostAddress()).andReturn("somewhere.example.com"); expect(sshClient.getHostAddress()).andReturn("somewhere.example.com");
expect(sshClient.exec("sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\n" + expect(
"mkdir -p /home/users\n" + 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" + + "useradd -s /bin/bash -m -d /home/users/testuser testuser\n"
"chown -R testuser /home/users/testuser\n" + + "chown -R testuser /home/users/testuser\n" + "RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(
"RUN_SCRIPT_AS_ROOT_SSH\n")).andReturn(new ExecResponse("done", null, 0)); new ExecResponse("done", null, 0));
sshClient.disconnect(); sshClient.disconnect();
replay(sshClient); replay(sshClient);

View File

@ -28,6 +28,7 @@ import java.util.Map;
import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.config.ValueOfConfigurationKeyOrNull;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@ -45,8 +46,10 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes
ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);
expect(credstore.containsKey("image")).andReturn(false); expect(credstore.containsKey("image")).andReturn(false);
expect(config.apply("provider.login-user")).andReturn(null); expect(config.apply("provider.image.login-user")).andReturn(null);
expect(config.apply("jclouds.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(config);
replay(credstore); replay(credstore);
@ -68,7 +71,9 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes
ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);
expect(credstore.containsKey("image")).andReturn(false); 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); expect(credstore.put("image", expected)).andReturn(null);
replay(config); replay(config);
@ -91,8 +96,10 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes
ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);
expect(credstore.containsKey("image")).andReturn(false); expect(credstore.containsKey("image")).andReturn(false);
expect(config.apply("provider.login-user")).andReturn(null); expect(config.apply("provider.image.login-user")).andReturn(null);
expect(config.apply("jclouds.login-user")).andReturn("ubuntu"); 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); expect(credstore.put("image", expected)).andReturn(null);
replay(config); replay(config);
@ -137,7 +144,9 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes
ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);
expect(credstore.containsKey("image")).andReturn(false); 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); expect(credstore.put("image", expected)).andReturn(null);
replay(config); replay(config);
@ -160,8 +169,62 @@ public class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTes
ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class); ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);
expect(credstore.containsKey("image")).andReturn(false); expect(credstore.containsKey("image")).andReturn(false);
expect(config.apply("provider.login-user")).andReturn(null); expect(config.apply("provider.image.login-user")).andReturn(null);
expect(config.apply("jclouds.login-user")).andReturn("ubuntu:password"); 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<String, Credentials> 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<String, Credentials> 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); expect(credstore.put("image", expected)).andReturn(null);
replay(config); replay(config);

View File

@ -33,6 +33,7 @@ import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState; import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.internal.PersistNodeCredentials; import org.jclouds.compute.internal.PersistNodeCredentials;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.scriptbuilder.statements.login.AdminAccess; import org.jclouds.scriptbuilder.statements.login.AdminAccess;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -83,7 +84,7 @@ public class PersistNodeCredentialsTest {
public void testRefreshCredentialsForNodeWhenStatementIsNullSameCredentialsAndDoesCache() { public void testRefreshCredentialsForNodeWhenStatementIsNullSameCredentialsAndDoesCache() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Credentials> credstore = createMock(Map.class); Map<String, Credentials> credstore = createMock(Map.class);
Credentials credentials = createMock(Credentials.class); LoginCredentials credentials = createMock(LoginCredentials.class);
expect(credstore.put("node#id", credentials)).andReturn(null); expect(credstore.put("node#id", credentials)).andReturn(null);
@ -102,7 +103,7 @@ public class PersistNodeCredentialsTest {
Map<String, Credentials> credstore = createMock(Map.class); Map<String, Credentials> credstore = createMock(Map.class);
AdminAccess statement = createMock(AdminAccess.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(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce();
expect(credstore.put("node#id", credentials)).andReturn(null); expect(credstore.put("node#id", credentials)).andReturn(null);
@ -125,7 +126,7 @@ public class PersistNodeCredentialsTest {
Map<String, Credentials> credstore = createMock(Map.class); Map<String, Credentials> credstore = createMock(Map.class);
AdminAccess statement = createMock(AdminAccess.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(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce();
expect(credstore.put("node#id", credentials)).andReturn(null); expect(credstore.put("node#id", credentials)).andReturn(null);
expect(credstore.put("node#id", credentials)).andReturn(null); // TODO expect(credstore.put("node#id", credentials)).andReturn(null); // TODO

View File

@ -27,19 +27,19 @@ import static org.testng.Assert.assertEquals;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials; import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "DefaultCredentialsFromImageOrOverridingCredentialsTest") @Test(groups = "unit", testName = "DefaultLoginCredentialsFromImageOrOverridingLoginCredentialsTest")
public class DefaultCredentialsFromImageOrOverridingCredentialsTest { public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
private static final DefaultCredentialsFromImageOrOverridingCredentials fn = new DefaultCredentialsFromImageOrOverridingCredentials(); private static final DefaultCredentialsFromImageOrOverridingCredentials fn = new DefaultCredentialsFromImageOrOverridingCredentials();
public void testWhenCredentialsNotPresentInImageOrTemplateOptionsReturnNull() { public void testWhenLoginCredentialsNotPresentInImageOrTemplateOptionsReturnNull() {
Credentials expected = null; LoginCredentials expected = null;
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -58,15 +58,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
} }
public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptions() { public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideCredentialsWith(expected)); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
replay(template); replay(template);
replay(image); replay(image);
@ -78,8 +78,8 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
} }
public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImage() { public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -98,15 +98,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
} }
public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptions() { public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(new Credentials("user", "password")); expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false));
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template);
replay(image); replay(image);
@ -118,15 +118,15 @@ public class DefaultCredentialsFromImageOrOverridingCredentialsTest {
} }
public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptions() { public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(new Credentials("ubuntu", "password2")); expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false));
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentialWith("password")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
replay(template); replay(template);
replay(image); replay(image);

View File

@ -29,6 +29,7 @@ import org.jclouds.compute.domain.Template;
import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials; import org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@ -61,7 +62,7 @@ public class PrioritizeCredentialsFromTemplateTest {
} }
public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() { public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() {
Credentials expected = new Credentials("foo", "bar"); LoginCredentials expected = new LoginCredentials("foo", "bar", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -81,19 +82,19 @@ public class PrioritizeCredentialsFromTemplateTest {
} }
public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() { public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideCredentialsWith(expected)); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));
replay(template); replay(template);
replay(image); 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(template);
verify(image); verify(image);
@ -108,12 +109,12 @@ public class PrioritizeCredentialsFromTemplateTest {
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(null); expect(image.getDefaultCredentials()).andReturn(null);
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template);
replay(image); 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(template);
verify(image); verify(image);
@ -121,7 +122,7 @@ public class PrioritizeCredentialsFromTemplateTest {
} }
public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() { public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
@ -133,7 +134,7 @@ public class PrioritizeCredentialsFromTemplateTest {
replay(template); replay(template);
replay(image); 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(template);
verify(image); verify(image);
@ -147,13 +148,13 @@ public class PrioritizeCredentialsFromTemplateTest {
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(new Credentials("user", "password")); expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("user", "password", null, false));
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUserWith("ubuntu")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser("ubuntu"));
replay(template); replay(template);
replay(image); 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(template);
verify(image); verify(image);
@ -161,19 +162,19 @@ public class PrioritizeCredentialsFromTemplateTest {
} }
public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() { public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() {
Credentials expected = new Credentials("ubuntu", "password"); LoginCredentials expected = new LoginCredentials("ubuntu", "password", null, false);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Template template = createMock(Template.class); Template template = createMock(Template.class);
expect(template.getImage()).andReturn(image); expect(template.getImage()).andReturn(image);
expect(image.getDefaultCredentials()).andReturn(new Credentials("ubuntu", "password2")); expect(image.getDefaultCredentials()).andReturn(new LoginCredentials("ubuntu", "password2", null, false));
expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentialWith("password")); expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword("password"));
replay(template); replay(template);
replay(image); 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(template);
verify(image); verify(image);

View File

@ -28,6 +28,7 @@ import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.domain.OsFamily;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.testng.annotations.Test; import org.testng.annotations.Test;
/** /**
@ -41,7 +42,7 @@ public class ReturnCredentialsBoundToImageTest {
Image image = createMock(Image.class); Image image = createMock(Image.class);
replay(image); replay(image);
Credentials creds = new Credentials("ubuntu", "foo"); LoginCredentials creds = new LoginCredentials("ubuntu", "foo", null, false);
assertEquals(new ReturnCredentialsBoundToImage(creds).execute(image), creds); assertEquals(new ReturnCredentialsBoundToImage(creds).execute(image), creds);
verify(image); verify(image);

View File

@ -35,8 +35,8 @@ public class Credentials {
public static final Credentials NO_CREDENTIALS = new Credentials(null, null); public static final Credentials NO_CREDENTIALS = new Credentials(null, null);
public static class Builder<T extends Credentials> { public static class Builder<T extends Credentials> {
private String identity; protected String identity;
private String credential; protected String credential;
public Builder<T> identity(String identity) { public Builder<T> identity(String identity) {
this.identity = identity; this.identity = identity;

View File

@ -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<LoginCredentials> {
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.
* <p/>
* 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;
}
}

View File

@ -30,6 +30,7 @@ import javax.inject.Singleton;
import org.jclouds.collect.TransformingMap; import org.jclouds.collect.TransformingMap;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.io.CopyInputStreamInputSupplierMap; import org.jclouds.io.CopyInputStreamInputSupplierMap;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -90,8 +91,26 @@ public class CredentialStoreModule extends AbstractModule {
@Override @Override
public InputStream apply(Credentials from) { 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 @Singleton
@ -106,17 +125,17 @@ public class CredentialStoreModule extends AbstractModule {
this.json = json; this.json = json;
} }
private static class PrivateCredentials {
String identity;
String credential;
}
@Override @Override
public Credentials apply(InputStream from) { public Credentials apply(InputStream from) {
try { try {
PrivateCredentials credentials = json.fromJson(Strings2.toStringAndClose(checkNotNull(from)), String creds = Strings2.toStringAndClose(checkNotNull(from));
PrivateCredentials.class); if (creds.indexOf("\"user\":") == -1) {
return new Credentials(credentials.identity, credentials.credential); 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) { } catch (Exception e) {
logger.warn(e, "ignoring problem retrieving credentials"); logger.warn(e, "ignoring problem retrieving credentials");
return null; return null;

View File

@ -46,10 +46,12 @@ public class CredentialUtils {
} }
public static boolean isPrivateKeyCredential(Credentials credentials) { public static boolean isPrivateKeyCredential(Credentials credentials) {
return credentials != null return credentials != null && isPrivateKeyCredential(credentials.credential);
&& credentials.credential != null }
&& (credentials.credential.startsWith(Pems.PRIVATE_PKCS1_MARKER) || credentials.credential
.startsWith(Pems.PRIVATE_PKCS8_MARKER)); 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) { public static boolean isPrivateKeyEncrypted(byte[] privateKey) {

View File

@ -28,6 +28,7 @@ import java.util.concurrent.ConcurrentHashMap;
import org.jclouds.crypto.PemsTest; import org.jclouds.crypto.PemsTest;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.io.CopyInputStreamInputSupplierMap; import org.jclouds.io.CopyInputStreamInputSupplierMap;
import org.jclouds.json.Json; import org.jclouds.json.Json;
import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule;
@ -60,7 +61,7 @@ public class CredentialStoreModuleTest {
public void deleteObject(String identity, String credential) throws InterruptedException, IOException { public void deleteObject(String identity, String credential) throws InterruptedException, IOException {
Injector injector = createInjector(); Injector injector = createInjector();
Map<String, InputStream> map = getMap(injector); Map<String, InputStream> 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 { public void testProvidedMapWithValue() throws IOException {
@ -68,8 +69,8 @@ public class CredentialStoreModuleTest {
new ConcurrentHashMap<String, InputSupplier<InputStream>>()); new ConcurrentHashMap<String, InputSupplier<InputStream>>());
map.put("test", new ByteArrayInputStream(json.toJson(new Credentials("user", "pass")).getBytes())); 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", new Credentials("user", "pass"));
checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass"); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass"));
remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); remove(map, getStore(createInjectorWithProvidedMap(map)), "test");
} }
@ -84,7 +85,7 @@ public class CredentialStoreModuleTest {
Map<String, Credentials> store = getStore(injector); Map<String, Credentials> store = getStore(injector);
for (int i = 0; i < 10; i++) 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<String, InputStream> map = new CopyInputStreamInputSupplierMap( Map<String, InputStream> map = new CopyInputStreamInputSupplierMap(
new ConcurrentHashMap<String, InputSupplier<InputStream>>()); new ConcurrentHashMap<String, InputSupplier<InputStream>>());
put(map, getStore(createInjectorWithProvidedMap(map)), "test", "user", "pass"); put(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("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", "user", "pass"); checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), "test", new Credentials("user", "pass"));
remove(map, getStore(createInjectorWithProvidedMap(map)), "test"); remove(map, getStore(createInjectorWithProvidedMap(map)), "test");
} }
@ -102,13 +103,33 @@ public class CredentialStoreModuleTest {
public void testDefaultConsistentAcrossMultipleInjectors() throws IOException { public void testDefaultConsistentAcrossMultipleInjectors() throws IOException {
Map<String, InputStream> map = getMap(createInjector()); Map<String, InputStream> map = getMap(createInjector());
put(map, getStore(createInjector()), "test", "user", "pass"); put(map, getStore(createInjector()), "test", new Credentials("user", "pass"));
checkConsistent(map, getStore(createInjector()), "test", "user", "pass"); checkConsistent(map, getStore(createInjector()), "test", new Credentials("user", "pass"));
checkConsistent(map, getStore(createInjector()), "test", "user", "pass"); checkConsistent(map, getStore(createInjector()), "test", new Credentials("user", "pass"));
remove(map, getStore(createInjector()), "test"); remove(map, getStore(createInjector()), "test");
} }
public void testLoginConsistentAcrossMultipleInjectorsAndLooksNice() throws IOException {
Map<String, InputStream> 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<String, InputStream> 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<String, Credentials> getStore(Injector injector) { protected Map<String, Credentials> getStore(Injector injector) {
return injector.getInstance(Key.get(new TypeLiteral<Map<String, Credentials>>() { return injector.getInstance(Key.get(new TypeLiteral<Map<String, Credentials>>() {
})); }));
@ -127,10 +148,10 @@ public class CredentialStoreModuleTest {
return Guice.createInjector(new CredentialStoreModule(), new GsonModule()); return Guice.createInjector(new CredentialStoreModule(), new GsonModule());
} }
protected void check(Map<String, InputStream> map, Map<String, Credentials> store, String key, String identity, protected void check(Map<String, InputStream> map, Map<String, Credentials> store, String key, Credentials creds)
String credential) throws IOException { throws IOException {
put(map, store, key, identity, credential); put(map, store, key, creds);
checkConsistent(map, store, key, identity, credential); checkConsistent(map, store, key, creds);
remove(map, store, key); remove(map, store, key);
} }
@ -143,26 +164,29 @@ public class CredentialStoreModuleTest {
} }
protected void checkConsistent(Map<String, InputStream> map, Map<String, Credentials> store, String key, protected void checkConsistent(Map<String, InputStream> map, Map<String, Credentials> 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<String, InputStream> map, Map<String, Credentials> store, String key,
Credentials creds, String expected) throws IOException {
assertEquals(store.size(), 1); assertEquals(store.size(), 1);
assertEquals(map.size(), 1); assertEquals(map.size(), 1);
// checkRepeatedRead // checkRepeatedRead
assertEquals(store.get(key), new Credentials(identity, credential)); assertEquals(store.get(key), creds);
assertEquals(store.get(key), new Credentials(identity, credential)); assertEquals(store.get(key), creds);
// checkRepeatedRead // checkRepeatedRead
checkToJson(map, key, identity, credential); checkToJson(map, key, expected);
checkToJson(map, key, identity, credential); checkToJson(map, key, expected);
} }
protected void checkToJson(Map<String, InputStream> map, String key, String identity, String credential) protected void checkToJson(Map<String, InputStream> map, String key, String expected) throws IOException {
throws IOException { assertEquals(Strings2.toStringAndClose(map.get(key)), expected);
assertEquals(Strings2.toStringAndClose(map.get(key)), json.toJson(new Credentials(identity, credential)));
} }
protected void put(Map<String, InputStream> map, Map<String, Credentials> store, String key, String identity, protected void put(Map<String, InputStream> map, Map<String, Credentials> store, String key, Credentials creds) {
String credential) {
assertEquals(store.size(), 0); assertEquals(store.size(), 0);
assertEquals(map.size(), 0); assertEquals(map.size(), 0);
store.put(key, new Credentials(identity, credential)); store.put(key, creds);
} }
} }

View File

@ -39,7 +39,8 @@
<test.aws-ec2.identity>${test.aws.identity}</test.aws-ec2.identity> <test.aws-ec2.identity>${test.aws.identity}</test.aws-ec2.identity>
<test.aws-ec2.credential>${test.aws.credential}</test.aws-ec2.credential> <test.aws-ec2.credential>${test.aws.credential}</test.aws-ec2.credential>
<test.aws-ec2.image-id></test.aws-ec2.image-id> <test.aws-ec2.image-id></test.aws-ec2.image-id>
<test.aws-ec2.login-user></test.aws-ec2.login-user> <test.aws-ec2.image.login-user></test.aws-ec2.image.login-user>
<test.aws-ec2.image.authenticate-sudo></test.aws-ec2.image.authenticate-sudo>
</properties> </properties>
<dependencies> <dependencies>
@ -116,7 +117,8 @@
<test.aws-ec2.identity>${test.aws-ec2.identity}</test.aws-ec2.identity> <test.aws-ec2.identity>${test.aws-ec2.identity}</test.aws-ec2.identity>
<test.aws-ec2.credential>${test.aws-ec2.credential}</test.aws-ec2.credential> <test.aws-ec2.credential>${test.aws-ec2.credential}</test.aws-ec2.credential>
<test.aws-ec2.image-id>${test.aws-ec2.image-id}</test.aws-ec2.image-id> <test.aws-ec2.image-id>${test.aws-ec2.image-id}</test.aws-ec2.image-id>
<test.aws-ec2.login-user>${test.aws-ec2.login-user}</test.aws-ec2.login-user> <test.aws-ec2.image.login-user>${test.aws-ec2.image.login-user}</test.aws-ec2.image.login-user>
<test.aws-ec2.image.authenticate-sudo>${test.aws-ec2.image.authenticate-sudo}</test.aws-ec2.image.authenticate-sudo>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</execution> </execution>

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