brooklyn-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From henev...@apache.org
Subject [13/21] incubator-brooklyn git commit: review comments addressed, cleaning up password check, and more logging
Date Tue, 27 Jan 2015 17:45:20 GMT
review comments addressed, cleaning up password check, and more logging

only thing left to do is tidy the statics (unless there are more review comments!)


Project: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/commit/0781c36a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/tree/0781c36a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/diff/0781c36a

Branch: refs/heads/master
Commit: 0781c36ab36df62d122c68e42a13b38c4fee147b
Parents: ce458d5
Author: Alex Heneveld <alex.heneveld@cloudsoftcorp.com>
Authored: Mon Jan 26 11:07:05 2015 +0000
Committer: Alex Heneveld <alex.heneveld@cloudsoftcorp.com>
Committed: Mon Jan 26 12:26:19 2015 +0000

----------------------------------------------------------------------
 .../location/basic/LocationConfigUtils.java     |  3 +-
 .../brooklyn/util/crypto/FluentKeySigner.java   | 31 ++++----
 .../java/brooklyn/util/crypto/SecureKeys.java   | 15 ++--
 .../location/basic/LocationConfigUtilsTest.java | 10 +--
 .../location/jclouds/JcloudsLocation.java       | 78 ++++++++++----------
 pom.xml                                         |  1 +
 6 files changed, 70 insertions(+), 68 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java b/core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java
index cae2edd..eb9e96d 100644
--- a/core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java
+++ b/core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java
@@ -126,7 +126,7 @@ public class LocationConfigUtils {
         
         /** returns either the key or password or null; if both a key and a password this
prefers the key unless otherwise set
          * via {@link #preferPassword()} */
-        public synchronized String get() {
+        public synchronized String getPreferredCredential() {
             infer();
             
             if (isUsingPassword()) return password;
@@ -324,6 +324,7 @@ public class LocationConfigUtils {
                 }
             } catch (PassphraseProblem e) {
                 if (doKeyValidation) {
+                    log.debug("Encountered error handling key "+label+": "+e, e);
                     if (Strings.isBlank(passphrase))
                         addWarning("Passphrase required for key '"+label+"'");
                     else

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java b/core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java
index 2dfbe98..674fb7f 100644
--- a/core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java
+++ b/core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java
@@ -29,20 +29,17 @@ import java.util.Date;
 
 import javax.security.auth.x500.X500Principal;
 
+import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
 import org.bouncycastle.asn1.x509.X509Extension;
-import org.bouncycastle.asn1.x509.X509Name;
 import org.bouncycastle.jce.X509Principal;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.bouncycastle.x509.X509V3CertificateGenerator;
-import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure;
-import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure;
 
 import brooklyn.util.exceptions.Exceptions;
 
 /** A fluent API which simplifies generating certificates (signed keys) */
-/* we use deprecated X509V3CertificateGenerator for now because official replacement,
- * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
-@SuppressWarnings("deprecation")
+/* NB - re deprecation - we use deprecated X509V3CertificateGenerator still
+ * because the official replacement, X509v3CertificateBuilder, 
+ * drags in an add'l dependency (bcmail) and is harder to use. */
 public class FluentKeySigner {
 
     static { Security.addProvider(new BouncyCastleProvider()); }
@@ -56,7 +53,7 @@ public class FluentKeySigner {
     protected BigInteger serialNumber;
     
     protected String signatureAlgorithm = "MD5WithRSAEncryption";
-    protected AuthorityKeyIdentifierStructure authorityKeyIdentifier;
+    protected AuthorityKeyIdentifier authorityKeyIdentifier;
     protected X509Certificate authorityCertificate;
 
     public FluentKeySigner(X500Principal issuerPrincipal, KeyPair issuerKey) {
@@ -86,8 +83,11 @@ public class FluentKeySigner {
         return issuerPrincipal;
     }
     
+    @SuppressWarnings("deprecation")
     public String getCommonName() {
-        return (String) new X509Principal(issuerPrincipal.getName()).getValues(X509Name.CN).elementAt(0);
+//        TODO see deprecation note at top of file
+        // for modernising, would RFC4519Style.cn work ?
+        return (String) new X509Principal(issuerPrincipal.getName()).getValues(org.bouncycastle.asn1.x509.X509Name.CN).elementAt(0);
     }
     
     public X509Certificate getAuthorityCertificate() {
@@ -123,9 +123,10 @@ public class FluentKeySigner {
         return this;
     }
 
+    @SuppressWarnings("deprecation")
     public FluentKeySigner authorityCertificate(X509Certificate certificate) {
         try {
-            authorityKeyIdentifier(new AuthorityKeyIdentifierStructure(certificate));
+            authorityKeyIdentifier(new org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure(certificate));
             this.authorityCertificate = certificate;
             return this;
         } catch (CertificateParsingException e) {
@@ -133,7 +134,7 @@ public class FluentKeySigner {
         }
     }
 
-    public FluentKeySigner authorityKeyIdentifier(AuthorityKeyIdentifierStructure authorityKeyIdentifier)
{
+    public FluentKeySigner authorityKeyIdentifier(AuthorityKeyIdentifier authorityKeyIdentifier)
{
         this.authorityKeyIdentifier = authorityKeyIdentifier;
         return this;
     }
@@ -143,10 +144,12 @@ public class FluentKeySigner {
         authorityCertificate(newCertificateFor(getCommonName(), getKey()));
         return this;
     }
-    
+
+    // TODO see note re deprecation at start of file
+    @SuppressWarnings("deprecation")
     public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify)
{
         try {
-            X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
+            org.bouncycastle.x509.X509V3CertificateGenerator v3CertGen = new org.bouncycastle.x509.X509V3CertificateGenerator();
 
             v3CertGen.setSerialNumber(
                     serialNumber != null ? serialNumber :
@@ -161,7 +164,7 @@ public class FluentKeySigner {
             v3CertGen.setPublicKey(keyToCertify);  
 
             v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false,
-                    new SubjectKeyIdentifierStructure(keyToCertify));
+                    new org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure(keyToCertify));
 
             if (authorityKeyIdentifier!=null)
                 v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false,

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/core/src/main/java/brooklyn/util/crypto/SecureKeys.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/util/crypto/SecureKeys.java b/core/src/main/java/brooklyn/util/crypto/SecureKeys.java
index 0c9acc8..5e12ad3 100644
--- a/core/src/main/java/brooklyn/util/crypto/SecureKeys.java
+++ b/core/src/main/java/brooklyn/util/crypto/SecureKeys.java
@@ -35,7 +35,6 @@ import org.bouncycastle.openssl.PEMDecryptorProvider;
 import org.bouncycastle.openssl.PEMEncryptedKeyPair;
 import org.bouncycastle.openssl.PEMKeyPair;
 import org.bouncycastle.openssl.PEMParser;
-import org.bouncycastle.openssl.PEMReader;
 import org.bouncycastle.openssl.PEMWriter;
 import org.bouncycastle.openssl.PasswordFinder;
 import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
@@ -60,8 +59,8 @@ public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
     public static class PassphraseProblem extends IllegalStateException {
         private static final long serialVersionUID = -3382824813899223447L;
-        public PassphraseProblem() { super("Passphrase problem with this key"); }
         public PassphraseProblem(String message) { super("Passphrase problem with this key:
"+message); }
+        public PassphraseProblem(String message, Exception cause) { super("Passphrase problem
with this key: "+message, cause); }
     }
     
     private SecureKeys() {}
@@ -74,7 +73,7 @@ public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting
also the public key if possible
      * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if
that is the problem */
     public static KeyPair readPem(InputStream input, final String passphrase) {
-        // TODO cache is only for fallback "reader" strategy 
+        // TODO cache is only for fallback "reader" strategy (2015-01); delete when Parser
confirmed working
         byte[] cache = Streams.readFully(input);
         input = new ByteArrayInputStream(cache);
 
@@ -95,7 +94,7 @@ public class SecureKeys extends SecureKeysWithoutBouncyCastle {
                     kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
                 } catch (Exception e) {
                     Exceptions.propagateIfFatal(e);
-                    throw new PassphraseProblem("wrong passphrase");
+                    throw new PassphraseProblem("wrong passphrase", e);
                 }
             } else  if (object instanceof PEMKeyPair) {
                 kp = converter.getKeyPair((PEMKeyPair) object);
@@ -118,17 +117,19 @@ public class SecureKeys extends SecureKeysWithoutBouncyCastle {
             input = new ByteArrayInputStream(cache);
             try {
                 Security.addProvider(new BouncyCastleProvider());
-                PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder()
{
+                @SuppressWarnings("deprecation")
+                org.bouncycastle.openssl.PEMReader pr = new org.bouncycastle.openssl.PEMReader(new
InputStreamReader(input), new PasswordFinder() {
                     public char[] getPassword() {
                         return passphrase!=null ? passphrase.toCharArray() : new char[0];
                     }
                 });
+                @SuppressWarnings("deprecation")
                 KeyPair result = (KeyPair) pr.readObject();
                 pr.close();
                 if (result==null)
                     throw Exceptions.propagate(e);
                 
-                log.warn("PEMParser failed when PEMReader succeeded, with "+result+"; had:
"+e);
+                log.warn("PEMParser failed when deprecated PEMReader succeeded, with "+result+";
had: "+e);
 
                 return result;
 
@@ -141,7 +142,7 @@ public class SecureKeys extends SecureKeysWithoutBouncyCastle {
 
     /** because KeyPair.equals is not implemented :( */
     public static boolean equal(KeyPair k1, KeyPair k2) {
-        return Objects.equal(k2.getPrivate(), k1.getPrivate()) && Objects.equal(k2.getPrivate(),
k1.getPrivate());
+        return Objects.equal(k2.getPrivate(), k1.getPrivate()) && Objects.equal(k2.getPublic(),
k1.getPublic());
     }
 
     /** returns the PEM (base64, ie for id_rsa) string for the private key / key pair;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java b/core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java
index 4c2cc37..6f9178c 100644
--- a/core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java
+++ b/core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java
@@ -73,7 +73,7 @@ public class LocationConfigUtilsTest {
         OsCredential creds = LocationConfigUtils.getOsCredential(config);
         String data = creds.getPublicKeyData();
         assertEquals(data, "mydata");
-        Assert.assertNull(creds.get());
+        Assert.assertNull(creds.getPreferredCredential());
         Assert.assertFalse(creds.hasPassword());
         Assert.assertFalse(creds.hasKey());
         // and not even any warnings here
@@ -86,7 +86,7 @@ public class LocationConfigUtilsTest {
         config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);
 
         // don't mind if it has a passphrase
-        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).get();
+        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPreferredCredential();
         assertTrue(data != null && data.length() > 0);
     }
     
@@ -96,7 +96,7 @@ public class LocationConfigUtilsTest {
         config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE);
 
         OsCredential cred = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
-        String data = cred.get();
+        String data = cred.getPreferredCredential();
         assertTrue(data != null && data.length() > 0);
         Assert.assertFalse(data.isEmpty());
         
@@ -122,7 +122,7 @@ public class LocationConfigUtilsTest {
         ConfigBag config = ConfigBag.newInstance();
         config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "/path/does/not/exist:"+SSH_PRIVATE_KEY_FILE);
         
-        String data = LocationConfigUtils.getOsCredential(config).get();
+        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
         assertTrue(data != null && data.length() > 0);
     }
     
@@ -130,7 +130,7 @@ public class LocationConfigUtilsTest {
         ConfigBag config = ConfigBag.newInstance();
         config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE+":/path/does/not/exist");
 
-        String data = LocationConfigUtils.getOsCredential(config).get();
+        String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
         assertTrue(data != null && data.length() > 0);
     }
     

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
index 2547422..1059891 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
@@ -73,7 +73,6 @@ import org.jclouds.ec2.compute.options.EC2TemplateOptions;
 import org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;
 import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
 import org.jclouds.rest.AuthorizationException;
-import org.jclouds.scriptbuilder.ScriptBuilder;
 import org.jclouds.scriptbuilder.domain.LiteralStatement;
 import org.jclouds.scriptbuilder.domain.Statement;
 import org.jclouds.scriptbuilder.domain.StatementList;
@@ -115,7 +114,6 @@ import brooklyn.management.AccessController;
 import brooklyn.util.ResourceUtils;
 import brooklyn.util.collections.MutableList;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.collections.MutableSet;
 import brooklyn.util.config.ConfigBag;
 import brooklyn.util.crypto.SecureKeys;
 import brooklyn.util.exceptions.CompoundRuntimeException;
@@ -306,13 +304,11 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
     }
 
     public String getEndpoint() {
-        return LocationConfigUtils.getConfigCheckingDeprecatedAlternatives(getAllConfigBag(),

-                CLOUD_ENDPOINT, JCLOUDS_KEY_ENDPOINT);
+        return (String) getAllConfigBag().getWithDeprecation(CLOUD_ENDPOINT, JCLOUDS_KEY_ENDPOINT);
     }
 
     public String getUser(ConfigBag config) {
-        return LocationConfigUtils.getConfigCheckingDeprecatedAlternatives(config, 
-                USER, JCLOUDS_KEY_USERNAME);
+        return (String) config.getWithDeprecation(USER, JCLOUDS_KEY_USERNAME);
     }
     
     protected Semaphore getMachineCreationSemaphore() {
@@ -334,9 +330,12 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
     }
     
     protected Collection<JcloudsLocationCustomizer> getCustomizers(ConfigBag setup)
{
+        @SuppressWarnings("deprecation")
         JcloudsLocationCustomizer customizer = setup.get(JCLOUDS_LOCATION_CUSTOMIZER);
         Collection<JcloudsLocationCustomizer> customizers = setup.get(JCLOUDS_LOCATION_CUSTOMIZERS);
+        @SuppressWarnings("deprecation")
         String customizerType = setup.get(JCLOUDS_LOCATION_CUSTOMIZER_TYPE);
+        @SuppressWarnings("deprecation")
         String customizersSupplierType = setup.get(JCLOUDS_LOCATION_CUSTOMIZERS_SUPPLIER_TYPE);
 
         ClassLoader catalogClassLoader = getManagementContext().getCatalog().getRootClassLoader();
@@ -738,6 +737,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                 if (setup.get(OPEN_IPTABLES)) {
                     customisationForLogging.add("open iptables");
                     
+                    @SuppressWarnings("unchecked")
                     List<String> iptablesRules = createIptablesRulesForNetworkInterface((Iterable<Integer>)
setup.get(INBOUND_PORTS));
                     iptablesRules.add(IptablesCommands.saveIptablesRules());
                     List<String> batch = Lists.newArrayList();
@@ -770,7 +770,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                         extraKeyDataToAuth.add(ResourceUtils.create().getResourceAsString(keyUrl));
                     }
                     sshMachineLocation.execCommands("Authorizing ssh keys", 
-                        MutableList.of(new AuthorizeRSAPublicKeys(extraKeyDataToAuth).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX)));
+                        ImmutableList.of(new AuthorizeRSAPublicKeys(extraKeyDataToAuth).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX)));
                 }
 
             } else {
@@ -901,7 +901,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                             ((EC2TemplateOptions)t).securityGroups(securityGroups);
                         } else if (t instanceof NovaTemplateOptions) {
                             String[] securityGroups = toStringArray(v);
-                            ((NovaTemplateOptions)t).securityGroupNames(securityGroups);
+                            ((NovaTemplateOptions)t).securityGroups(securityGroups);
                         } else if (t instanceof SoftLayerTemplateOptions) {
                             String[] securityGroups = toStringArray(v);
                             ((SoftLayerTemplateOptions)t).securityGroups(securityGroups);
@@ -1358,9 +1358,9 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                 LOG.info("Not creating user {}, and not installing its password or authorizing
keys (assuming it exists)", user);
 
                 if (credential.isUsingPassword()) {
-                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
+                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.getPassword()).build();
                 } else if (credential.hasKey()) {
-                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
+                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                 }
             }
             
@@ -1372,10 +1372,11 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
             }
 
             // Using the pre-existing loginUser; setup the publicKey/password so can login
as expected
-            if (Strings.isNonBlank(passwordToSet)) {
-                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user,
passwordToSet));
-                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
-            }
+            
+            // *Always* change the password (unless dontCreateUser was specified) 
+            statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
+            createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
+            
             if (Strings.isNonBlank(credential.getPublicKeyData())) {
                 statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
                 if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData()))
{
@@ -1387,7 +1388,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
             String pubKey = credential.getPublicKeyData();
             String privKey = credential.getPrivateKeyData();
             
-            if (credential.get()==null) {
+            if (credential.isEmpty()) {
                 if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE))
{
                     loggedSshKeysHint = true;
                     LOG.info("Default SSH keys not found or not usable; will create new keys
for each machine. "
@@ -1400,7 +1401,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                 privKey = SecureKeys.toPem(newKeyPair);
                 LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+"
is:\n"+privKey);
             }
-            // ensure credential is not used any more, as we have extracted al useful info
+            // ensure credential is not used any more, as we have extracted all useful info
             credential = null;
             
             // Create the user
@@ -1409,14 +1410,13 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                     .adminUsername(user)
                     .grantSudoToAdminUser(grantUserSudo);
             
-            Boolean useKey = null;
-            if (passwordToSet!=null) {
-                adminBuilder.adminPassword(passwordToSet);
-                useKey = false;
-            } else {
-                // will be using a key, so set the password to something obscure (and forget
it)
-                adminBuilder.adminPassword(Identifiers.makeRandomId(12));
-            }
+            boolean useKey = Strings.isNonBlank(pubKey);
+            
+            // always set this password; if not supplied, it will be a random string
+            adminBuilder.adminPassword(passwordToSet);
+            // log the password also, in case we need it
+            LOG.debug("Password '"+passwordToSet+"' being created for user '"+user+"' at
the machine we are about to provision in "+this+"; "+
+                (useKey ? "however a key will be used to access it" : "this will be the only
way to log in"));
             
             if (grantUserSudo && config.get(JcloudsLocationConfig.DISABLE_ROOT_AND_PASSWORD_SSH))
{
                 // the default - set root password which we forget, because we have sudo
acct
@@ -1428,17 +1428,12 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
                 adminBuilder.loginPassword(Identifiers.makeRandomId(12)+"-ignored");    
           
             }
             
-            if (Strings.isNonBlank(pubKey)) {
+            if (useKey) {
                 adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(pubKey);
-                if (privKey!=null) useKey = true;
             } else {
                 adminBuilder.authorizeAdminPublicKey(false).adminPublicKey(Identifiers.makeRandomId(12)+"-ignored");
             }
             
-            if (useKey==null) {
-                throw new IllegalStateException("Misconfiguration: neither a key or password
known for the user being created");
-            }
-            
             // jclouds wants us to give it the private key, otherwise it might refuse to
authorize the public key
             // (in AdminAccess.build, if adminUsername != null && adminPassword !=
null);
             // we don't want to give it the private key, but we *do* want the public key
authorized;
@@ -1451,20 +1446,22 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
             adminBuilder.lockSsh(useKey && grantUserSudo && !config.get(JcloudsLocationConfig.DISABLE_ROOT_AND_PASSWORD_SSH));
             
             statements.add(adminBuilder.build());
-            
+
             if (useKey) {
                 createdUserCreds = LoginCredentials.builder().user(user).privateKey(privKey).build();
             } else if (passwordToSet!=null) {
                 createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
             }
-
         }
         
         String customTemplateOptionsScript = config.get(CUSTOM_TEMPLATE_OPTIONS_SCRIPT_CONTENTS);
         if (Strings.isNonBlank(customTemplateOptionsScript)) {
             statements.add(new LiteralStatement(customTemplateOptionsScript));
         }
-        
+
+        LOG.debug("Machine we are about to create in "+this+" will be customized with: "+
+            statements);
+
         return new UserCreation(createdUserCreds, statements);
     }
 
@@ -1474,7 +1471,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
     public JcloudsSshMachineLocation rebindMachine(NodeMetadata metadata) throws NoMachinesAvailableException
{
         return rebindMachine(MutableMap.of(), metadata);
     }
-    public JcloudsSshMachineLocation rebindMachine(Map flags, NodeMetadata metadata) throws
NoMachinesAvailableException {
+    public JcloudsSshMachineLocation rebindMachine(Map<?,?> flags, NodeMetadata metadata)
throws NoMachinesAvailableException {
         ConfigBag setup = ConfigBag.newInstanceExtending(getAllConfigBag(), flags);
         if (!setup.containsKey("id")) setup.putStringKey("id", metadata.getId());
         setHostnameUpdatingCredentials(setup, metadata);
@@ -1556,7 +1553,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
         }
     }
 
-    public JcloudsSshMachineLocation rebindMachine(Map flags) throws NoMachinesAvailableException
{
+    public JcloudsSshMachineLocation rebindMachine(Map<?,?> flags) throws NoMachinesAvailableException
{
         ConfigBag setup = ConfigBag.newInstanceExtending(getAllConfigBag(), flags);
         return rebindMachine(setup);
     }
@@ -1663,8 +1660,8 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
     protected Map<String,Object> extractSshConfig(ConfigBag setup, NodeMetadata node)
{
         ConfigBag nodeConfig = new ConfigBag();
         if (node!=null && node.getCredentials() != null) {
-            nodeConfig.putIfNotNull(PASSWORD, node.getCredentials().getPassword());
-            nodeConfig.putIfNotNull(PRIVATE_KEY_DATA, node.getCredentials().getPrivateKey());
+            nodeConfig.putIfNotNull(PASSWORD, node.getCredentials().getOptionalPassword().orNull());
+            nodeConfig.putIfNotNull(PRIVATE_KEY_DATA, node.getCredentials().getOptionalPrivateKey().orNull());
         }
         return extractSshConfig(setup, nodeConfig).getAllConfig();
     }
@@ -1723,7 +1720,6 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
         String instanceId = node.getId();
         LOG.info("Releasing node {} in {}, instance id {}", new Object[] {node, this, instanceId});
         
-        ComputeService computeService = null;
         try {
             releaseNode(instanceId);
         } catch (Exception e) {
@@ -1883,9 +1879,9 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation
im
         }
         
         LoginCredentials credentials = metadata.getCredentials();
-        if (groovyTruth(credentials)) {
-            if (groovyTruth(credentials.getUser())) setup.put(USER, credentials.getUser());
-            if (groovyTruth(credentials.getPrivateKey())) setup.put(PRIVATE_KEY_DATA, credentials.getPrivateKey());
+        if (credentials!=null) {
+            if (Strings.isNonBlank(credentials.getUser())) setup.put(USER, credentials.getUser());
+            if (Strings.isNonBlank(credentials.getOptionalPrivateKey().orNull())) setup.put(PRIVATE_KEY_DATA,
credentials.getOptionalPrivateKey().orNull());
             if (setHostname(setup, metadata, false)) {
                 if (originalUser!=null && !originalUser.equals(getUser(setup))) {
                     LOG.warn("Switching to cloud-specified user at "+metadata+" as "+getUser(setup)+"
(failed to connect using: "+usersTried+")");

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/0781c36a/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 286ad96..6b99236 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1200,6 +1200,7 @@
                   <exclude>**/MANIFEST.MF</exclude>
                   <exclude>**/test-output/**</exclude>
                   <exclude>**/*.pem.pub</exclude>
+                  <exclude>**/*.pem</exclude>
                   <exclude>**/*_rsa.pub</exclude>
                   <exclude>**/*_rsa</exclude>
                   <exclude>**/*.svg</exclude>


Mime
View raw message