You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by wi...@apache.org on 2015/07/08 21:19:36 UTC

[01/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Repository: cloudstack
Updated Branches:
  refs/heads/reporter 5c9978471 -> 28300b5d0 (forced update)


Making possible to update KVM hosts password in the database via the API

   - Make sure the doUpdateHostPassword() method returns the result from the answer, not always true
   - Added the LibvirtUpdateHostPasswordCommandWrapper class, which will handle the changes in the KVM agent
     That's will be further implemented in the future. The command will avoid the agent to complain about Unsupported command
   - Added a test to make sure the current implementation of the comment works
     - If changes in the future, it will also require changes. In that way, we make sure nobody will break it

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

This closes #527


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/527d6ee7
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/527d6ee7
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/527d6ee7

Branch: refs/heads/reporter
Commit: 527d6ee77b6b202a5af00984a5e8a6a79ffa457a
Parents: b8ab3cd
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Jun 25 14:32:51 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Mon Jun 29 09:59:12 2015 +0200

----------------------------------------------------------------------
 ...LibvirtUpdateHostPasswordCommandWrapper.java | 35 ++++++++++++++++++++
 .../resource/LibvirtComputingResourceTest.java  | 15 +++++++++
 .../com/cloud/resource/ResourceManagerImpl.java |  2 +-
 3 files changed, 51 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/527d6ee7/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
new file mode 100644
index 0000000..5b7c7da
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.UpdateHostPasswordCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  UpdateHostPasswordCommand.class)
+public final class LibvirtUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final UpdateHostPasswordCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        return new Answer(command, true, null);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/527d6ee7/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index d3c8824..d5ce9bf 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -127,6 +127,7 @@ import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
 import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UnPlugNicCommand;
+import com.cloud.agent.api.UpdateHostPasswordCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.check.CheckSshCommand;
@@ -5072,4 +5073,18 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testUpdateHostPasswordCommand() {
+        final String username = "root";
+        final String newPassword = "password";
+        final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/527d6ee7/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index c1a7dbc..df6071c 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2235,7 +2235,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
         final String password = nv.getValue();
         final UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password);
         final Answer answer = _agentMgr.easySend(hostId, cmd);
-        return answer != null;
+        return answer.getResult();
     }
 
     @Override


[40/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
findbugs: impossible cast(s) fixed by changing field types

Signed-off-by: Daan Hoogland <da...@gmail.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/e34389a6
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/e34389a6
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/e34389a6

Branch: refs/heads/reporter
Commit: e34389a612ab0931cf3ae3d36c47047dc91b170e
Parents: 31c6b14
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jun 29 15:07:34 2015 +0200
Committer: Daan Hoogland <da...@gmail.com>
Committed: Mon Jul 6 16:22:19 2015 +0200

----------------------------------------------------------------------
 .../api/command/admin/vpc/CreateVPCOfferingCmd.java   | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e34389a6/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java
index 13e4c0e..99c1719 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java
@@ -64,10 +64,10 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd {
 
     @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. "
         + "If not specified, the provider for the service will be mapped to the default provider on the physical network")
-    private Map<String, String> serviceProviderList;
+    private Map<String, ? extends Map<String, String>> serviceProviderList;
 
     @Parameter(name = ApiConstants.SERVICE_CAPABILITY_LIST, type = CommandType.MAP, description = "desired service capabilities as part of vpc offering", since = "4.4")
-    private Map serviceCapabilitystList;
+    private Map<String, List<String>> serviceCapabilitystList;
 
     @Parameter(name = ApiConstants.SERVICE_OFFERING_ID,
                type = CommandType.UUID,
@@ -95,10 +95,14 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd {
         Map<String, List<String>> serviceProviderMap = null;
         if (serviceProviderList != null && !serviceProviderList.isEmpty()) {
             serviceProviderMap = new HashMap<String, List<String>>();
-            Collection servicesCollection = serviceProviderList.values();
-            Iterator iter = servicesCollection.iterator();
+            Collection<? extends Map<String, String>> servicesCollection = serviceProviderList.values();
+            Iterator<? extends Map<String, String>> iter = servicesCollection.iterator();
             while (iter.hasNext()) {
-                HashMap<String, String> services = (HashMap<String, String>)iter.next();
+                Map<String, String> obj = iter.next();
+                if (s_logger.isTraceEnabled()) {
+                    s_logger.trace("service provider entry specified: " + obj);
+                }
+                HashMap<String, String> services = (HashMap<String, String>)obj;
                 String service = services.get("service");
                 String provider = services.get("provider");
                 List<String> providerList = null;


[06/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
database: fix upgrade paths from 4.5.2 to 4.6.0

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3ff92e88
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3ff92e88
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3ff92e88

Branch: refs/heads/reporter
Commit: 3ff92e883ef982eadb86840dff5d6792b54586a2
Parents: 107595a
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Mon Jun 29 12:35:18 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon Jun 29 12:58:47 2015 +0200

----------------------------------------------------------------------
 .../cloud/upgrade/DatabaseUpgradeChecker.java   | 127 +++---
 .../com/cloud/upgrade/dao/Upgrade451to452.java  |  67 ++++
 .../com/cloud/upgrade/dao/Upgrade451to460.java  | 149 -------
 .../com/cloud/upgrade/dao/Upgrade452to460.java  | 149 +++++++
 .../cloudstack/api/command/ListIdpsCmd.java     |   4 +-
 setup/db/db/schema-451to460-cleanup.sql         |  20 -
 setup/db/db/schema-451to460.sql                 | 400 -------------------
 setup/db/db/schema-452to460-cleanup.sql         |  20 +
 setup/db/db/schema-452to460.sql                 | 400 +++++++++++++++++++
 9 files changed, 702 insertions(+), 634 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
index 4bc54b1..f3cbdea 100644
--- a/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
+++ b/engine/schema/src/com/cloud/upgrade/DatabaseUpgradeChecker.java
@@ -16,25 +16,6 @@
 // under the License.
 package com.cloud.upgrade;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.TreeMap;
-
-import javax.ejb.Local;
-import javax.inject.Inject;
-
-import org.apache.log4j.Logger;
-
 import com.cloud.maint.Version;
 import com.cloud.upgrade.dao.DbUpgrade;
 import com.cloud.upgrade.dao.Upgrade217to218;
@@ -74,7 +55,8 @@ import com.cloud.upgrade.dao.Upgrade442to450;
 import com.cloud.upgrade.dao.Upgrade443to450;
 import com.cloud.upgrade.dao.Upgrade444to450;
 import com.cloud.upgrade.dao.Upgrade450to451;
-import com.cloud.upgrade.dao.Upgrade451to460;
+import com.cloud.upgrade.dao.Upgrade451to452;
+import com.cloud.upgrade.dao.Upgrade452to460;
 import com.cloud.upgrade.dao.UpgradeSnapshot217to224;
 import com.cloud.upgrade.dao.UpgradeSnapshot223to224;
 import com.cloud.upgrade.dao.VersionDao;
@@ -86,6 +68,23 @@ import com.cloud.utils.db.GlobalLock;
 import com.cloud.utils.db.ScriptRunner;
 import com.cloud.utils.db.TransactionLegacy;
 import com.cloud.utils.exception.CloudRuntimeException;
+import org.apache.log4j.Logger;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.TreeMap;
 
 @Local(value = {SystemIntegrityChecker.class})
 public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
@@ -105,7 +104,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
             new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
             new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
             new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(),
-            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.1.8", new DbUpgrade[] {new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(),
             new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(),
@@ -113,7 +112,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
             new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
             new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(),
             new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.1.9", new DbUpgrade[] {new Upgrade218to22(), new Upgrade221to222(), new UpgradeSnapshot217to224(),
             new Upgrade222to224(), new Upgrade218to224DomainVlans(), new Upgrade224to225(), new Upgrade225to226(),
@@ -121,147 +120,149 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
             new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
             new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(),
             new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(),
-            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.1", new DbUpgrade[] {new Upgrade221to222(), new UpgradeSnapshot223to224(), new Upgrade222to224(),
             new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(),
             new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
             new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(),
             new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(),
-            new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.2", new DbUpgrade[] {new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(),
             new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
             new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
             new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.3", new DbUpgrade[] {new Upgrade222to224(), new UpgradeSnapshot223to224(), new Upgrade224to225(),
             new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
             new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
             new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.4", new DbUpgrade[] {new Upgrade224to225(), new Upgrade225to226(), new Upgrade227to228(),
             new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(),
             new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
             new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.5", new DbUpgrade[] {new Upgrade225to226(), new Upgrade227to228(), new Upgrade228to229(),
             new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
             new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
             new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(),
-            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.6", new DbUpgrade[] {new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
             new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(),
             new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(),
             new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.7", new DbUpgrade[] {new Upgrade227to228(), new Upgrade228to229(), new Upgrade229to2210(),
             new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
             new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(),
             new Upgrade410to420(),
             new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(),
-            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.8", new DbUpgrade[] {new Upgrade228to229(), new Upgrade229to2210(), new Upgrade2210to2211(),
             new Upgrade2211to2212(), new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30()
             , new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.9", new DbUpgrade[] {new Upgrade229to2210(), new Upgrade2210to2211(), new Upgrade2211to2212(),
             new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
             new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.10", new DbUpgrade[] {new Upgrade2210to2211(), new Upgrade2211to2212(), new Upgrade2212to2213(),
             new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(),
             new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(),
-            new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.12", new DbUpgrade[] {new Upgrade2212to2213(), new Upgrade2213to2214(), new Upgrade2214to30(),
             new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(),
-            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.13", new DbUpgrade[] {new Upgrade2213to2214(), new Upgrade2214to30(), new Upgrade30to301(),
             new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.14", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
             new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(),
-            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.0", new DbUpgrade[] {new Upgrade30to301(), new Upgrade301to302(), new Upgrade302to40(),
             new Upgrade40to41(), new Upgrade410to420(),
-            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.1", new DbUpgrade[] {new Upgrade301to302(), new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.2", new DbUpgrade[] {new Upgrade302to40(), new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(),
-            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
+
+        _upgradeMap.put("4.0.0", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.0.0", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.0.1", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.0.1", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.0.2", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.0.2", new DbUpgrade[] {new Upgrade40to41(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.1.0", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.1.0", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.1.1", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.1.1", new DbUpgrade[] {new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.2.0", new DbUpgrade[] {new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.2.0", new DbUpgrade[] {new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.2.1", new DbUpgrade[] {new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.2.1", new DbUpgrade[] {new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.3.0", new DbUpgrade[] {new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.3.0", new DbUpgrade[] {new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.3.1", new DbUpgrade[] {new Upgrade431to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.3.1", new DbUpgrade[] {new Upgrade431to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.3.2", new DbUpgrade[] {new Upgrade432to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.3.2", new DbUpgrade[] {new Upgrade432to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.4.0", new DbUpgrade[] {new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.4.0", new DbUpgrade[] {new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.4.1", new DbUpgrade[] {new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460() });
 
-        _upgradeMap.put("4.4.1", new DbUpgrade[] {new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460() });
+        _upgradeMap.put("4.4.2", new DbUpgrade[] {new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.4.2", new DbUpgrade[] {new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.4.3", new DbUpgrade[] {new Upgrade443to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.4.3", new DbUpgrade[] {new Upgrade443to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.4.4", new DbUpgrade[] {new Upgrade444to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.4.4", new DbUpgrade[] {new Upgrade444to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.5.0", new DbUpgrade[] {new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.5.0", new DbUpgrade[] {new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("4.5.1", new DbUpgrade[] {new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("4.5.1", new DbUpgrade[] {new Upgrade451to460()});
+        _upgradeMap.put("4.5.2", new DbUpgrade[] {new Upgrade452to460()});
 
         //CP Upgrades
         _upgradeMap.put("3.0.3", new DbUpgrade[] {new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(),
-            new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.4", new DbUpgrade[] {new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(),
-            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.5", new DbUpgrade[] {new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to421(),
-            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("3.0.6", new DbUpgrade[] {new Upgrade306to307(), new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(),
-            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
-        _upgradeMap.put("3.0.7", new DbUpgrade[] {new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+        _upgradeMap.put("3.0.7", new DbUpgrade[] {new Upgrade307to410(), new Upgrade410to420(), new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.15", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
             new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(),
             new Upgrade410to420(),
-            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
 
         _upgradeMap.put("2.2.16", new DbUpgrade[] {new Upgrade2214to30(), new Upgrade30to301(), new Upgrade301to302(),
             new Upgrade302to303(), new Upgrade303to304(), new Upgrade304to305(), new Upgrade305to306(), new Upgrade306to307(), new Upgrade307to410(),
             new Upgrade410to420(),
-            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to460()});
+            new Upgrade420to421(), new Upgrade421to430(), new Upgrade430to440(), new Upgrade440to441(), new Upgrade441to442(), new Upgrade442to450(), new Upgrade450to451(), new Upgrade451to452(), new Upgrade452to460()});
     }
 
     protected void runScript(Connection conn, File file) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to452.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to452.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to452.java
new file mode 100644
index 0000000..870e534
--- /dev/null
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to452.java
@@ -0,0 +1,67 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.upgrade.dao;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+import org.apache.log4j.Logger;
+
+import java.io.File;
+import java.sql.Connection;
+
+public class Upgrade451to452 implements DbUpgrade {
+    final static Logger s_logger = Logger.getLogger(Upgrade451to452.class);
+
+    @Override
+    public String[] getUpgradableVersionRange() {
+        return new String[] {"4.5.1", "4.5.2"};
+    }
+
+    @Override
+    public String getUpgradedVersion() {
+        return "4.5.2";
+    }
+
+    @Override
+    public boolean supportsRollingUpgrade() {
+        return false;
+    }
+
+    @Override
+    public File[] getPrepareScripts() {
+        String script = Script.findScript("", "db/schema-451to452.sql");
+        if (script == null) {
+            throw new CloudRuntimeException("Unable to find db/schema-451to452.sql");
+        }
+        return new File[] {new File(script)};
+    }
+
+    @Override
+    public void performDataMigration(Connection conn) {
+    }
+
+    @Override
+    public File[] getCleanupScripts() {
+        String script = Script.findScript("", "db/schema-451to452-cleanup.sql");
+        if (script == null) {
+            throw new CloudRuntimeException("Unable to find db/schema-451to452-cleanup.sql");
+        }
+
+        return new File[] {new File(script)};
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to460.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to460.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to460.java
deleted file mode 100644
index 383654f..0000000
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade451to460.java
+++ /dev/null
@@ -1,149 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF 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 com.cloud.upgrade.dao;
-
-import java.io.File;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import org.apache.log4j.Logger;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.script.Script;
-
-public class Upgrade451to460 implements DbUpgrade {
-    final static Logger s_logger = Logger.getLogger(Upgrade451to460.class);
-
-    @Override
-    public String[] getUpgradableVersionRange() {
-        return new String[] { "4.5.1", "4.6.0" };
-    }
-
-    @Override
-    public String getUpgradedVersion() {
-        return "4.6.0";
-    }
-
-    @Override
-    public boolean supportsRollingUpgrade() {
-        return false;
-    }
-
-    @Override
-    public File[] getPrepareScripts() {
-        final String script = Script.findScript("", "db/schema-451to460.sql");
-        if (script == null) {
-            throw new CloudRuntimeException("Unable to find db/schema-451to460.sql");
-        }
-
-        return new File[] { new File(script) };
-    }
-
-    @Override
-    public void performDataMigration(final Connection conn) {
-        updateVMInstanceUserId(conn);
-    }
-
-    public void updateVMInstanceUserId(final Connection conn) {
-        // For schemas before this, copy first user from an account_id which
-        // deployed already running VMs
-        s_logger.debug("Updating vm_instance column user_id using first user in vm_instance's account_id");
-        final String vmInstanceSql = "SELECT id, account_id FROM `cloud`.`vm_instance`";
-        final String userSql = "SELECT id FROM `cloud`.`user` where account_id=?";
-        final String userIdUpdateSql = "update `cloud`.`vm_instance` set user_id=? where id=?";
-        try (PreparedStatement selectStatement = conn.prepareStatement(vmInstanceSql)) {
-            final ResultSet results = selectStatement.executeQuery();
-            while (results.next()) {
-                final long vmId = results.getLong(1);
-                final long accountId = results.getLong(2);
-                try (PreparedStatement selectUserStatement = conn.prepareStatement(userSql)) {
-                    selectUserStatement.setLong(1, accountId);
-                    final ResultSet userResults = selectUserStatement.executeQuery();
-                    if (userResults.next()) {
-                        final long userId = userResults.getLong(1);
-                        try (PreparedStatement updateStatement = conn.prepareStatement(userIdUpdateSql)) {
-                            updateStatement.setLong(1, userId);
-                            updateStatement.setLong(2, vmId);
-                            updateStatement.executeUpdate();
-                        } catch (final SQLException e) {
-                            throw new CloudRuntimeException("Unable to update user ID " + userId + " on vm_instance id=" + vmId, e);
-                        }
-                    }
-
-                } catch (final SQLException e) {
-                    throw new CloudRuntimeException("Unable to update user ID using accountId " + accountId + " on vm_instance id=" + vmId, e);
-                }
-            }
-        } catch (final SQLException e) {
-            throw new CloudRuntimeException("Unable to update user Ids for previously deployed VMs", e);
-        }
-        s_logger.debug("Done updating user Ids for previously deployed VMs");
-        addRedundancyForNwAndVpc(conn);
-        removeBumPriorityColumn(conn);
-    }
-
-    private void addRedundancyForNwAndVpc(final Connection conn) {
-        ResultSet rs = null;
-        try (PreparedStatement addRedundantColToVpcOfferingPstmt = conn
-                .prepareStatement("ALTER TABLE `cloud`.`vpc_offerings` ADD COLUMN `redundant_router_service` tinyint(1) DEFAULT 0");
-                PreparedStatement addRedundantColToVpcPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vpc` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
-                PreparedStatement addRedundantColToNwPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`networks` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
-
-                // The redundancy of the networks must be based on the
-                // redundancy of their network offerings
-                PreparedStatement redundancyPerNwPstmt = conn.prepareStatement("select distinct nw.network_offering_id from networks nw join network_offerings off "
-                        + "on nw.network_offering_id = off.id where off.redundant_router_service = 1");
-                PreparedStatement updateNwRedundancyPstmt = conn.prepareStatement("update networks set redundant = 1 where network_offering_id = ?");) {
-            addRedundantColToVpcPstmt.executeUpdate();
-            addRedundantColToVpcOfferingPstmt.executeUpdate();
-            addRedundantColToNwPstmt.executeUpdate();
-
-            rs = redundancyPerNwPstmt.executeQuery();
-            while (rs.next()) {
-                final long nwOfferingId = rs.getLong("nw.network_offering_id");
-                updateNwRedundancyPstmt.setLong(1, nwOfferingId);
-                updateNwRedundancyPstmt.executeUpdate();
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new CloudRuntimeException("Adding redundancy to vpc, networks and vpc_offerings failed", e);
-        }
-    }
-
-    private void removeBumPriorityColumn(final Connection conn) {
-        try (PreparedStatement removeBumPriorityColumnPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`domain_router` DROP COLUMN `is_priority_bumpup`");) {
-            removeBumPriorityColumnPstmt.executeUpdate();
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new CloudRuntimeException("Adding redundancy to vpc, networks and vpc_offerings failed", e);
-        }
-    }
-
-    @Override
-    public File[] getCleanupScripts() {
-        final String script = Script.findScript("", "db/schema-451to460-cleanup.sql");
-        if (script == null) {
-            throw new CloudRuntimeException("Unable to find db/schema-451to460-cleanup.sql");
-        }
-
-        return new File[] { new File(script) };
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
new file mode 100644
index 0000000..9c2b1e3
--- /dev/null
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
@@ -0,0 +1,149 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.upgrade.dao;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+
+public class Upgrade452to460 implements DbUpgrade {
+    final static Logger s_logger = Logger.getLogger(Upgrade452to460.class);
+
+    @Override
+    public String[] getUpgradableVersionRange() {
+        return new String[] { "4.5.2", "4.6.0" };
+    }
+
+    @Override
+    public String getUpgradedVersion() {
+        return "4.6.0";
+    }
+
+    @Override
+    public boolean supportsRollingUpgrade() {
+        return false;
+    }
+
+    @Override
+    public File[] getPrepareScripts() {
+        final String script = Script.findScript("", "db/schema-452to460.sql");
+        if (script == null) {
+            throw new CloudRuntimeException("Unable to find db/schema-452to460.sql");
+        }
+
+        return new File[] { new File(script) };
+    }
+
+    @Override
+    public void performDataMigration(final Connection conn) {
+        updateVMInstanceUserId(conn);
+    }
+
+    public void updateVMInstanceUserId(final Connection conn) {
+        // For schemas before this, copy first user from an account_id which
+        // deployed already running VMs
+        s_logger.debug("Updating vm_instance column user_id using first user in vm_instance's account_id");
+        final String vmInstanceSql = "SELECT id, account_id FROM `cloud`.`vm_instance`";
+        final String userSql = "SELECT id FROM `cloud`.`user` where account_id=?";
+        final String userIdUpdateSql = "update `cloud`.`vm_instance` set user_id=? where id=?";
+        try (PreparedStatement selectStatement = conn.prepareStatement(vmInstanceSql)) {
+            final ResultSet results = selectStatement.executeQuery();
+            while (results.next()) {
+                final long vmId = results.getLong(1);
+                final long accountId = results.getLong(2);
+                try (PreparedStatement selectUserStatement = conn.prepareStatement(userSql)) {
+                    selectUserStatement.setLong(1, accountId);
+                    final ResultSet userResults = selectUserStatement.executeQuery();
+                    if (userResults.next()) {
+                        final long userId = userResults.getLong(1);
+                        try (PreparedStatement updateStatement = conn.prepareStatement(userIdUpdateSql)) {
+                            updateStatement.setLong(1, userId);
+                            updateStatement.setLong(2, vmId);
+                            updateStatement.executeUpdate();
+                        } catch (final SQLException e) {
+                            throw new CloudRuntimeException("Unable to update user ID " + userId + " on vm_instance id=" + vmId, e);
+                        }
+                    }
+
+                } catch (final SQLException e) {
+                    throw new CloudRuntimeException("Unable to update user ID using accountId " + accountId + " on vm_instance id=" + vmId, e);
+                }
+            }
+        } catch (final SQLException e) {
+            throw new CloudRuntimeException("Unable to update user Ids for previously deployed VMs", e);
+        }
+        s_logger.debug("Done updating user Ids for previously deployed VMs");
+        addRedundancyForNwAndVpc(conn);
+        removeBumPriorityColumn(conn);
+    }
+
+    private void addRedundancyForNwAndVpc(final Connection conn) {
+        ResultSet rs = null;
+        try (PreparedStatement addRedundantColToVpcOfferingPstmt = conn
+                .prepareStatement("ALTER TABLE `cloud`.`vpc_offerings` ADD COLUMN `redundant_router_service` tinyint(1) DEFAULT 0");
+                PreparedStatement addRedundantColToVpcPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vpc` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
+                PreparedStatement addRedundantColToNwPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`networks` ADD COLUMN `redundant` tinyint(1) DEFAULT 0");
+
+                // The redundancy of the networks must be based on the
+                // redundancy of their network offerings
+                PreparedStatement redundancyPerNwPstmt = conn.prepareStatement("select distinct nw.network_offering_id from networks nw join network_offerings off "
+                        + "on nw.network_offering_id = off.id where off.redundant_router_service = 1");
+                PreparedStatement updateNwRedundancyPstmt = conn.prepareStatement("update networks set redundant = 1 where network_offering_id = ?");) {
+            addRedundantColToVpcPstmt.executeUpdate();
+            addRedundantColToVpcOfferingPstmt.executeUpdate();
+            addRedundantColToNwPstmt.executeUpdate();
+
+            rs = redundancyPerNwPstmt.executeQuery();
+            while (rs.next()) {
+                final long nwOfferingId = rs.getLong("nw.network_offering_id");
+                updateNwRedundancyPstmt.setLong(1, nwOfferingId);
+                updateNwRedundancyPstmt.executeUpdate();
+            }
+        } catch (final SQLException e) {
+            e.printStackTrace();
+            throw new CloudRuntimeException("Adding redundancy to vpc, networks and vpc_offerings failed", e);
+        }
+    }
+
+    private void removeBumPriorityColumn(final Connection conn) {
+        try (PreparedStatement removeBumPriorityColumnPstmt = conn.prepareStatement("ALTER TABLE `cloud`.`domain_router` DROP COLUMN `is_priority_bumpup`");) {
+            removeBumPriorityColumnPstmt.executeUpdate();
+        } catch (final SQLException e) {
+            e.printStackTrace();
+            throw new CloudRuntimeException("Adding redundancy to vpc, networks and vpc_offerings failed", e);
+        }
+    }
+
+    @Override
+    public File[] getCleanupScripts() {
+        final String script = Script.findScript("", "db/schema-452to460-cleanup.sql");
+        if (script == null) {
+            throw new CloudRuntimeException("Unable to find db/schema-452to460-cleanup.sql");
+        }
+
+        return new File[] { new File(script) };
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
index 7d7c95e..0592425 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
@@ -36,6 +36,7 @@ import javax.inject.Inject;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
+import java.net.InetAddress;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -71,8 +72,7 @@ public class ListIdpsCmd extends BaseCmd implements APIAuthenticator {
     }
 
     @Override
-    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
-        auditTrailSb.append("=== SAML List IdPs ===");
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, InetAddress remoteAddress, String responseType, StringBuilder auditTrailSb, HttpServletRequest req, HttpServletResponse resp) throws ServerApiException {
         ListResponse<IdpResponse> response = new ListResponse<IdpResponse>();
         List<IdpResponse> idpResponseList = new ArrayList<IdpResponse>();
         for (SAMLProviderMetadata metadata: _samlAuthManager.getAllIdPMetadata()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/setup/db/db/schema-451to460-cleanup.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-451to460-cleanup.sql b/setup/db/db/schema-451to460-cleanup.sql
deleted file mode 100644
index 4bbaa95..0000000
--- a/setup/db/db/schema-451to460-cleanup.sql
+++ /dev/null
@@ -1,20 +0,0 @@
--- Licensed to the Apache Software Foundation (ASF) under one
--- or more contributor license agreements.  See the NOTICE file
--- distributed with this work for additional information
--- regarding copyright ownership.  The ASF 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.
-
---
--- Schema cleanup from 4.5.1 to 4.6.0
---

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/setup/db/db/schema-451to460.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-451to460.sql b/setup/db/db/schema-451to460.sql
deleted file mode 100644
index 0abd4f8..0000000
--- a/setup/db/db/schema-451to460.sql
+++ /dev/null
@@ -1,400 +0,0 @@
--- Licensed to the Apache Software Foundation (ASF) under one
--- or more contributor license agreements.  See the NOTICE file
--- distributed with this work for additional information
--- regarding copyright ownership.  The ASF 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.
-
---
--- Schema upgrade from 4.5.1 to 4.6.0
---
-
-ALTER TABLE `cloud`.`snapshots` ADD COLUMN `min_iops` bigint(20) unsigned COMMENT 'Minimum IOPS';
-ALTER TABLE `cloud`.`snapshots` ADD COLUMN `max_iops` bigint(20) unsigned COMMENT 'Maximum IOPS';
-
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Advanced", 'DEFAULT', 'management-server', "stats.output.uri", "", "URI to additionally send StatsCollector statistics to", "", NULL, NULL, 0);
-
-DROP VIEW IF EXISTS `cloud`.`domain_view`;
-CREATE VIEW `cloud`.`domain_view` AS
-    select
-        domain.id id,
-        domain.parent parent,
-        domain.name name,
-        domain.uuid uuid,
-        domain.owner owner,
-        domain.path path,
-        domain.level level,
-        domain.child_count child_count,
-        domain.next_child_seq next_child_seq,
-        domain.removed removed,
-        domain.state state,
-        domain.network_domain network_domain,
-        domain.type type,
-        vmlimit.max vmLimit,
-        vmcount.count vmTotal,
-        iplimit.max ipLimit,
-        ipcount.count ipTotal,
-        volumelimit.max volumeLimit,
-        volumecount.count volumeTotal,
-        snapshotlimit.max snapshotLimit,
-        snapshotcount.count snapshotTotal,
-        templatelimit.max templateLimit,
-        templatecount.count templateTotal,
-        vpclimit.max vpcLimit,
-        vpccount.count vpcTotal,
-        projectlimit.max projectLimit,
-        projectcount.count projectTotal,
-        networklimit.max networkLimit,
-        networkcount.count networkTotal,
-        cpulimit.max cpuLimit,
-        cpucount.count cpuTotal,
-        memorylimit.max memoryLimit,
-        memorycount.count memoryTotal,
-        primary_storage_limit.max primaryStorageLimit,
-        primary_storage_count.count primaryStorageTotal,
-        secondary_storage_limit.max secondaryStorageLimit,
-        secondary_storage_count.count secondaryStorageTotal
-    from
-        `cloud`.`domain`
-            left join
-        `cloud`.`resource_limit` vmlimit ON domain.id = vmlimit.domain_id
-            and vmlimit.type = 'user_vm'
-            left join
-        `cloud`.`resource_count` vmcount ON domain.id = vmcount.domain_id
-            and vmcount.type = 'user_vm'
-            left join
-        `cloud`.`resource_limit` iplimit ON domain.id = iplimit.domain_id
-            and iplimit.type = 'public_ip'
-            left join
-        `cloud`.`resource_count` ipcount ON domain.id = ipcount.domain_id
-            and ipcount.type = 'public_ip'
-            left join
-        `cloud`.`resource_limit` volumelimit ON domain.id = volumelimit.domain_id
-            and volumelimit.type = 'volume'
-            left join
-        `cloud`.`resource_count` volumecount ON domain.id = volumecount.domain_id
-            and volumecount.type = 'volume'
-            left join
-        `cloud`.`resource_limit` snapshotlimit ON domain.id = snapshotlimit.domain_id
-            and snapshotlimit.type = 'snapshot'
-            left join
-        `cloud`.`resource_count` snapshotcount ON domain.id = snapshotcount.domain_id
-            and snapshotcount.type = 'snapshot'
-            left join
-        `cloud`.`resource_limit` templatelimit ON domain.id = templatelimit.domain_id
-            and templatelimit.type = 'template'
-            left join
-        `cloud`.`resource_count` templatecount ON domain.id = templatecount.domain_id
-            and templatecount.type = 'template'
-            left join
-        `cloud`.`resource_limit` vpclimit ON domain.id = vpclimit.domain_id
-            and vpclimit.type = 'vpc'
-            left join
-        `cloud`.`resource_count` vpccount ON domain.id = vpccount.domain_id
-            and vpccount.type = 'vpc'
-            left join
-        `cloud`.`resource_limit` projectlimit ON domain.id = projectlimit.domain_id
-            and projectlimit.type = 'project'
-            left join
-        `cloud`.`resource_count` projectcount ON domain.id = projectcount.domain_id
-            and projectcount.type = 'project'
-            left join
-        `cloud`.`resource_limit` networklimit ON domain.id = networklimit.domain_id
-            and networklimit.type = 'network'
-            left join
-        `cloud`.`resource_count` networkcount ON domain.id = networkcount.domain_id
-            and networkcount.type = 'network'
-            left join
-        `cloud`.`resource_limit` cpulimit ON domain.id = cpulimit.domain_id
-            and cpulimit.type = 'cpu'
-            left join
-        `cloud`.`resource_count` cpucount ON domain.id = cpucount.domain_id
-            and cpucount.type = 'cpu'
-            left join
-        `cloud`.`resource_limit` memorylimit ON domain.id = memorylimit.domain_id
-            and memorylimit.type = 'memory'
-            left join
-        `cloud`.`resource_count` memorycount ON domain.id = memorycount.domain_id
-            and memorycount.type = 'memory'
-            left join
-        `cloud`.`resource_limit` primary_storage_limit ON domain.id = primary_storage_limit.domain_id
-            and primary_storage_limit.type = 'primary_storage'
-            left join
-        `cloud`.`resource_count` primary_storage_count ON domain.id = primary_storage_count.domain_id
-            and primary_storage_count.type = 'primary_storage'
-            left join
-        `cloud`.`resource_limit` secondary_storage_limit ON domain.id = secondary_storage_limit.domain_id
-            and secondary_storage_limit.type = 'secondary_storage'
-            left join
-        `cloud`.`resource_count` secondary_storage_count ON domain.id = secondary_storage_count.domain_id
-            and secondary_storage_count.type = 'secondary_storage';
-
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.user.vms','-1','The default maximum number of user VMs that can be deployed for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.public.ips','-1','The default maximum number of public IPs that can be consumed by a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.templates','-1','The default maximum number of templates that can be deployed for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.snapshots','-1','The default maximum number of snapshots that can be created for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.volumes','-1','The default maximum number of volumes that can be created for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.networks', '-1', 'The default maximum number of networks that can be created for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.vpcs', '-1', 'The default maximum number of vpcs that can be created for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.cpus', '-1', 'The default maximum number of cpu cores that can be used for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.memory', '-1', 'The default maximum memory (in MiB) that can be used for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.primary.storage', '-1', 'The default maximum primary storage space (in GiB) that can be used for a domain', '-1', NULL, NULL, 0);
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.secondary.storage', '-1', 'The default maximum secondary storage space (in GiB) that can be used for a domain', '-1', NULL, NULL, 0);
-
-ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `user_id` bigint unsigned NOT NULL DEFAULT 1 COMMENT 'user id of VM deployer';
-
-DROP VIEW IF EXISTS `cloud`.`user_vm_view`;
-CREATE VIEW `cloud`.`user_vm_view` AS
-    select
-        vm_instance.id id,
-        vm_instance.name name,
-        user_vm.display_name display_name,
-        user_vm.user_data user_data,
-        account.id account_id,
-        account.uuid account_uuid,
-        account.account_name account_name,
-        account.type account_type,
-        domain.id domain_id,
-        domain.uuid domain_uuid,
-        domain.name domain_name,
-        domain.path domain_path,
-        projects.id project_id,
-        projects.uuid project_uuid,
-        projects.name project_name,
-        instance_group.id instance_group_id,
-        instance_group.uuid instance_group_uuid,
-        instance_group.name instance_group_name,
-        vm_instance.uuid uuid,
-        vm_instance.user_id user_id,
-        vm_instance.last_host_id last_host_id,
-        vm_instance.vm_type type,
-        vm_instance.limit_cpu_use limit_cpu_use,
-        vm_instance.created created,
-        vm_instance.state state,
-        vm_instance.removed removed,
-        vm_instance.ha_enabled ha_enabled,
-        vm_instance.hypervisor_type hypervisor_type,
-        vm_instance.instance_name instance_name,
-        vm_instance.guest_os_id guest_os_id,
-        vm_instance.display_vm display_vm,
-        guest_os.uuid guest_os_uuid,
-        vm_instance.pod_id pod_id,
-        host_pod_ref.uuid pod_uuid,
-        vm_instance.private_ip_address private_ip_address,
-        vm_instance.private_mac_address private_mac_address,
-        vm_instance.vm_type vm_type,
-        data_center.id data_center_id,
-        data_center.uuid data_center_uuid,
-        data_center.name data_center_name,
-        data_center.is_security_group_enabled security_group_enabled,
-        data_center.networktype data_center_type,
-        host.id host_id,
-        host.uuid host_uuid,
-        host.name host_name,
-        vm_template.id template_id,
-        vm_template.uuid template_uuid,
-        vm_template.name template_name,
-        vm_template.display_text template_display_text,
-        vm_template.enable_password password_enabled,
-        iso.id iso_id,
-        iso.uuid iso_uuid,
-        iso.name iso_name,
-        iso.display_text iso_display_text,
-        service_offering.id service_offering_id,
-        svc_disk_offering.uuid service_offering_uuid,
-        disk_offering.uuid disk_offering_uuid,
-        disk_offering.id disk_offering_id,
-        Case
-             When (`cloud`.`service_offering`.`cpu` is null) then (`custom_cpu`.`value`)
-             Else ( `cloud`.`service_offering`.`cpu`)
-        End as `cpu`,
-        Case
-            When (`cloud`.`service_offering`.`speed` is null) then (`custom_speed`.`value`)
-            Else ( `cloud`.`service_offering`.`speed`)
-        End as `speed`,
-        Case
-            When (`cloud`.`service_offering`.`ram_size` is null) then (`custom_ram_size`.`value`)
-            Else ( `cloud`.`service_offering`.`ram_size`)
-        END as `ram_size`,
-        svc_disk_offering.name service_offering_name,
-        disk_offering.name disk_offering_name,
-        storage_pool.id pool_id,
-        storage_pool.uuid pool_uuid,
-        storage_pool.pool_type pool_type,
-        volumes.id volume_id,
-        volumes.uuid volume_uuid,
-        volumes.device_id volume_device_id,
-        volumes.volume_type volume_type,
-        security_group.id security_group_id,
-        security_group.uuid security_group_uuid,
-        security_group.name security_group_name,
-        security_group.description security_group_description,
-        nics.id nic_id,
-        nics.uuid nic_uuid,
-        nics.network_id network_id,
-        nics.ip4_address ip_address,
-        nics.ip6_address ip6_address,
-        nics.ip6_gateway ip6_gateway,
-        nics.ip6_cidr ip6_cidr,
-        nics.default_nic is_default_nic,
-        nics.gateway gateway,
-        nics.netmask netmask,
-        nics.mac_address mac_address,
-        nics.broadcast_uri broadcast_uri,
-        nics.isolation_uri isolation_uri,
-        vpc.id vpc_id,
-        vpc.uuid vpc_uuid,
-        networks.uuid network_uuid,
-        networks.name network_name,
-        networks.traffic_type traffic_type,
-        networks.guest_type guest_type,
-        user_ip_address.id public_ip_id,
-        user_ip_address.uuid public_ip_uuid,
-        user_ip_address.public_ip_address public_ip_address,
-        ssh_keypairs.keypair_name keypair_name,
-        resource_tags.id tag_id,
-        resource_tags.uuid tag_uuid,
-        resource_tags.key tag_key,
-        resource_tags.value tag_value,
-        resource_tags.domain_id tag_domain_id,
-        resource_tags.account_id tag_account_id,
-        resource_tags.resource_id tag_resource_id,
-        resource_tags.resource_uuid tag_resource_uuid,
-        resource_tags.resource_type tag_resource_type,
-        resource_tags.customer tag_customer,
-        async_job.id job_id,
-        async_job.uuid job_uuid,
-        async_job.job_status job_status,
-        async_job.account_id job_account_id,
-        affinity_group.id affinity_group_id,
-        affinity_group.uuid affinity_group_uuid,
-        affinity_group.name affinity_group_name,
-        affinity_group.description affinity_group_description,
-        vm_instance.dynamically_scalable dynamically_scalable
-
-    from
-        `cloud`.`user_vm`
-            inner join
-        `cloud`.`vm_instance` ON vm_instance.id = user_vm.id
-            and vm_instance.removed is NULL
-            inner join
-        `cloud`.`account` ON vm_instance.account_id = account.id
-            inner join
-        `cloud`.`domain` ON vm_instance.domain_id = domain.id
-            left join
-        `cloud`.`guest_os` ON vm_instance.guest_os_id = guest_os.id
-            left join
-        `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id
-            left join
-        `cloud`.`projects` ON projects.project_account_id = account.id
-            left join
-        `cloud`.`instance_group_vm_map` ON vm_instance.id = instance_group_vm_map.instance_id
-            left join
-        `cloud`.`instance_group` ON instance_group_vm_map.group_id = instance_group.id
-            left join
-        `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id
-            left join
-        `cloud`.`host` ON vm_instance.host_id = host.id
-            left join
-        `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id
-            left join
-        `cloud`.`vm_template` iso ON iso.id = user_vm.iso_id
-            left join
-        `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id
-            left join
-        `cloud`.`disk_offering` svc_disk_offering ON vm_instance.service_offering_id = svc_disk_offering.id
-            left join
-        `cloud`.`disk_offering` ON vm_instance.disk_offering_id = disk_offering.id
-            left join
-        `cloud`.`volumes` ON vm_instance.id = volumes.instance_id
-            left join
-        `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id
-            left join
-        `cloud`.`security_group_vm_map` ON vm_instance.id = security_group_vm_map.instance_id
-            left join
-        `cloud`.`security_group` ON security_group_vm_map.security_group_id = security_group.id
-            left join
-        `cloud`.`nics` ON vm_instance.id = nics.instance_id and nics.removed is null
-            left join
-        `cloud`.`networks` ON nics.network_id = networks.id
-            left join
-        `cloud`.`vpc` ON networks.vpc_id = vpc.id and vpc.removed is null
-            left join
-        `cloud`.`user_ip_address` ON user_ip_address.vm_id = vm_instance.id
-            left join
-        `cloud`.`user_vm_details` as ssh_details ON ssh_details.vm_id = vm_instance.id
-            and ssh_details.name = 'SSH.PublicKey'
-            left join
-        `cloud`.`ssh_keypairs` ON ssh_keypairs.public_key = ssh_details.value
-            left join
-        `cloud`.`resource_tags` ON resource_tags.resource_id = vm_instance.id
-            and resource_tags.resource_type = 'UserVm'
-            left join
-        `cloud`.`async_job` ON async_job.instance_id = vm_instance.id
-            and async_job.instance_type = 'VirtualMachine'
-            and async_job.job_status = 0
-            left join
-        `cloud`.`affinity_group_vm_map` ON vm_instance.id = affinity_group_vm_map.instance_id
-            left join
-        `cloud`.`affinity_group` ON affinity_group_vm_map.affinity_group_id = affinity_group.id
-            left join
-        `cloud`.`user_vm_details` `custom_cpu`  ON (((`custom_cpu`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_cpu`.`name` = 'CpuNumber')))
-            left join
-        `cloud`.`user_vm_details` `custom_speed`  ON (((`custom_speed`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_speed`.`name` = 'CpuSpeed')))
-           left join
-        `cloud`.`user_vm_details` `custom_ram_size`  ON (((`custom_ram_size`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_ram_size`.`name` = 'memory')));
-
--- ovm3 stuff
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 10(32-bit)', 79);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 10(64-bit)', 80);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 11(32-bit)', 158);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 11(64-bit)', 159);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Other Linux (32-bit)', 98);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Other Linux (64-bit)', 99);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'Other PV (32-bit)', 139);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'Other PV (64-bit)', 140);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'DOS', 102);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows 8 (32-bit)', 165);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows 8 (64-bit)', 166);
-INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows Server 2012 (64-bit)', 167);
-
-INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled) VALUES ('Ovm3', '3.2', 25, 0);
-INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled) VALUES ('Ovm3', '3.3', 50, 0);
-UPDATE  `cloud`.`volumes` v,  `cloud`.`storage_pool` s,  `cloud`.`cluster` c  set v.format='RAW' where v.pool_id=s.id and s.cluster_id=c.id and c.hypervisor_type='Ovm3';
-UPDATE configuration SET value='KVM,XenServer,VMware,BareMetal,Ovm,Ovm3,LXC' WHERE name='hypervisor.list';
-INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id,featured, cross_zones, hypervisor_type, state)
-VALUES (12, UUID(), 'routing-12', 'SystemVM Template (Ovm3)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/4.6/systemvm64template.ovm.raw.bz2', '4425688804dbcf0abc9e9e56c53070d7', 0, 'SystemVM Template (Ovm3)', 'RAW', 183, 0, 1, 'Ovm3', 'Active' );
-
-INSERT IGNORE INTO `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `default_value`, `description`) VALUES ('Advanced', 'DEFAULT', 'ManagementServer', 'ovm3.heartbeat.timeout' , '180', '120', 'Timeout value to send to the checkheartbeat script for guarding the self fencing functionality on ovm3');
-INSERT IGNORE INTO `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `default_value`, `description`) VALUES ('Advanced', 'DEFAULT', 'ManagementServer', 'ovm3.heartbeat.interval' , '10', '1', 'Interval value the checkheartbeat script uses before triggering the timeout for ovm3');
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'router.template.ovm3', 'SystemVM Template (Ovm3)', 'Name of the default router template on Ovm3.','SystemVM Template (Ovm3)', NULL, NULL, 0);
-
-UPDATE IGNORE `cloud`.`configuration` SET `value`="PLAINTEXT" WHERE `name`="user.authenticators.exclude";
-
-DROP TABLE IF EXISTS `cloud`.`external_bigswitch_vns_devices`;
-CREATE TABLE `cloud`.`external_bigswitch_bcf_devices` (
-  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
-  `uuid` varchar(255) UNIQUE,
-  `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network in to which bigswitch bcf device is added',
-  `provider_name` varchar(255) NOT NULL COMMENT 'Service Provider name corresponding to this bigswitch bcf device',
-  `device_name` varchar(255) NOT NULL COMMENT 'name of the bigswitch bcf device',
-  `host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external bigswitch bcf device',
-  `hostname` varchar(255) NOT NULL COMMENT 'host name or IP address for the bigswitch bcf device',
-  `username` varchar(255) NOT NULL COMMENT 'username for the bigswitch bcf device',
-  `password` varchar(255) NOT NULL COMMENT 'password for the bigswitch bcf device',
-  `nat` boolean NOT NULL COMMENT 'NAT support for the bigswitch bcf device',
-  `hash` varchar(255) NOT NULL COMMENT 'topology hash for the bigswitch bcf networks',
-  PRIMARY KEY  (`id`),
-  CONSTRAINT `fk_external_bigswitch_bcf_devices__host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE,
-  CONSTRAINT `fk_external_bigswitch_bcf_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE
-) ENGINE=InnoDB DEFAULT CHARSET=utf8;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/setup/db/db/schema-452to460-cleanup.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-452to460-cleanup.sql b/setup/db/db/schema-452to460-cleanup.sql
new file mode 100644
index 0000000..4bbaa95
--- /dev/null
+++ b/setup/db/db/schema-452to460-cleanup.sql
@@ -0,0 +1,20 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF 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.
+
+--
+-- Schema cleanup from 4.5.1 to 4.6.0
+--


[08/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Merge branch 'fixtravis3' of https://github.com/rsafonseca/cloudstack

This closes #531


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f72412a8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f72412a8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f72412a8

Branch: refs/heads/reporter
Commit: f72412a80d5ae1b92ed9d9f3a1f4f98dc35a9417
Parents: 02c3d14 e8c0c8f
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed Jul 1 09:12:17 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 09:12:17 2015 +0200

----------------------------------------------------------------------
 tools/travis/before_install.sh | 11 +++++++++++
 1 file changed, 11 insertions(+)
----------------------------------------------------------------------



[17/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Adding NiciraNvpCreateLogicalRouterCommandWrapper
   - Adding NiciraNvpDeleteLogicalSwitchPortCommandWrapper
   - Adding NiciraNvpFindLogicalSwitchPortCommandWrapper
   - Adding NiciraNvpUpdateLogicalSwitchPortCommandWrapper
   - Decoupling private methods from NiciraNvpResource

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b5412691
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b5412691
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b5412691

Branch: refs/heads/reporter
Commit: b54126918b4c4c620e08b0215dce9bd8da8715fd
Parents: b4ce81a
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 11:18:58 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:57 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 153 +------------------
 ...iraNvpCreateLogicalRouterCommandWrapper.java | 152 ++++++++++++++++++
 ...vpDeleteLogicalSwitchPortCommandWrapper.java |   4 -
 ...aNvpFindLogicalSwitchPortCommandWrapper.java |  59 +++++++
 ...vpUpdateLogicalSwitchPortCommandWrapper.java |  63 ++++++++
 5 files changed, 275 insertions(+), 156 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5412691/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 1fd19ea..776b512 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -19,8 +19,6 @@
 
 package com.cloud.network.resource;
 
-import java.util.ArrayList;
-import java.util.List;
 import java.util.Map;
 
 import javax.naming.ConfigurationException;
@@ -36,38 +34,24 @@ import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
 import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
 import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
 import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalRouterAnswer;
-import com.cloud.agent.api.CreateLogicalRouterCommand;
 import com.cloud.agent.api.DeleteLogicalRouterAnswer;
 import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
-import com.cloud.agent.api.FindLogicalSwitchPortCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupNiciraNvpCommand;
-import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
 import com.cloud.agent.api.to.PortForwardingRuleTO;
 import com.cloud.agent.api.to.StaticNatRuleTO;
 import com.cloud.host.Host;
 import com.cloud.host.Host.Type;
 import com.cloud.network.nicira.ControlClusterStatus;
 import com.cloud.network.nicira.DestinationNatRule;
-import com.cloud.network.nicira.L3GatewayAttachment;
-import com.cloud.network.nicira.LogicalRouter;
 import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.LogicalSwitchPort;
 import com.cloud.network.nicira.Match;
 import com.cloud.network.nicira.NatRule;
 import com.cloud.network.nicira.NiciraNvpApi;
 import com.cloud.network.nicira.NiciraNvpApiException;
 import com.cloud.network.nicira.NiciraNvpList;
-import com.cloud.network.nicira.NiciraNvpTag;
-import com.cloud.network.nicira.PatchAttachment;
-import com.cloud.network.nicira.RouterNextHop;
-import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
 import com.cloud.network.nicira.SourceNatRule;
-import com.cloud.network.nicira.VifAttachment;
 import com.cloud.network.utils.CommandRetryUtility;
 import com.cloud.resource.ServerResource;
 
@@ -205,13 +189,7 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof UpdateLogicalSwitchPortCommand) {
-            return executeRequest((UpdateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof FindLogicalSwitchPortCommand) {
-            return executeRequest((FindLogicalSwitchPortCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof CreateLogicalRouterCommand) {
-            return executeRequest((CreateLogicalRouterCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof DeleteLogicalRouterCommand) {
+        if (cmd instanceof DeleteLogicalRouterCommand) {
             return executeRequest((DeleteLogicalRouterCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof ConfigureStaticNatRulesOnLogicalRouterCommand) {
             return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand)cmd, NUM_RETRIES);
@@ -237,135 +215,6 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final UpdateLogicalSwitchPortCommand cmd, final int numRetries) {
-        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
-        final String attachmentUuid = cmd.getAttachmentUuid();
-
-        try {
-            // Tags set to scope cs_account and account name
-            final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
-            tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
-
-            niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
-            return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for  " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, UpdateLogicalSwitchPortAnswer.class, e);
-        }
-    }
-
-    private Answer executeRequest(final FindLogicalSwitchPortCommand cmd, final int numRetries) {
-        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
-
-        try {
-            final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
-            if (ports.getResultCount() == 0) {
-                return new FindLogicalSwitchPortAnswer(cmd, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
-            } else {
-                return new FindLogicalSwitchPortAnswer(cmd, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
-            }
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, FindLogicalSwitchPortAnswer.class, e);
-        }
-    }
-
-    private Answer executeRequest(final CreateLogicalRouterCommand cmd, final int numRetries) {
-        final String routerName = cmd.getName();
-        final String gatewayServiceUuid = cmd.getGatewayServiceUuid();
-        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-
-        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
-        tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
-
-        final String publicNetworkNextHopIp = cmd.getPublicNextHop();
-        final String publicNetworkIpAddress = cmd.getPublicIpCidr();
-        final String internalNetworkAddress = cmd.getInternalIpCidr();
-
-        s_logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " +
-                gatewayServiceUuid);
-
-        try {
-            // Create the Router
-            LogicalRouter lrc = new LogicalRouter();
-            lrc.setDisplayName(truncate(routerName, NAME_MAX_LEN));
-            lrc.setTags(tags);
-            lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp)));
-            lrc = niciraNvpApi.createLogicalRouter(lrc);
-
-            // store the switchport for rollback
-            LogicalSwitchPort lsp = null;
-
-            try {
-                // Create the outside port for the router
-                LogicalRouterPort lrpo = new LogicalRouterPort();
-                lrpo.setAdminStatusEnabled(true);
-                lrpo.setDisplayName(truncate(routerName + "-outside-port", NAME_MAX_LEN));
-                lrpo.setTags(tags);
-                final List<String> outsideIpAddresses = new ArrayList<String>();
-                outsideIpAddresses.add(publicNetworkIpAddress);
-                lrpo.setIpAddresses(outsideIpAddresses);
-                lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo);
-
-                // Attach the outside port to the gateway service on the correct VLAN
-                final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
-                if (cmd.getVlanId() != 0) {
-                    attachment.setVlanId(cmd.getVlanId());
-                }
-                niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment);
-
-                // Create the inside port for the router
-                LogicalRouterPort lrpi = new LogicalRouterPort();
-                lrpi.setAdminStatusEnabled(true);
-                lrpi.setDisplayName(truncate(routerName + "-inside-port", NAME_MAX_LEN));
-                lrpi.setTags(tags);
-                final List<String> insideIpAddresses = new ArrayList<String>();
-                insideIpAddresses.add(internalNetworkAddress);
-                lrpi.setIpAddresses(insideIpAddresses);
-                lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi);
-
-                // Create the inside port on the lswitch
-                lsp = new LogicalSwitchPort(truncate(routerName + "-inside-port", NAME_MAX_LEN), tags, true);
-                lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp);
-
-                // Attach the inside router port to the lswitch port with a PatchAttachment
-                niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid()));
-
-                // Attach the inside lswitch port to the router with a PatchAttachment
-                niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
-
-                // Setup the source nat rule
-                final SourceNatRule snr = new SourceNatRule();
-                snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]);
-                snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]);
-                final Match match = new Match();
-                match.setSourceIpAddresses(internalNetworkAddress);
-                snr.setMatch(match);
-                snr.setOrder(200);
-                niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr);
-            } catch (final NiciraNvpApiException e) {
-                // We need to destroy the router if we already created it
-                // this will also take care of any router ports and rules
-                try {
-                    niciraNvpApi.deleteLogicalRouter(lrc.getUuid());
-                    if (lsp != null) {
-                        niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid());
-                    }
-                } catch (final NiciraNvpApiException ex) {
-                }
-
-                throw e;
-            }
-
-            return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, CreateLogicalRouterAnswer.class, e);
-        }
-    }
-
     private Answer executeRequest(final DeleteLogicalRouterCommand cmd, final int numRetries) {
         try {
             niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5412691/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
new file mode 100644
index 0000000..1cddf4f
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalRouterCommandWrapper.java
@@ -0,0 +1,152 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NAME_MAX_LEN;
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalRouterAnswer;
+import com.cloud.agent.api.CreateLogicalRouterCommand;
+import com.cloud.network.nicira.L3GatewayAttachment;
+import com.cloud.network.nicira.LogicalRouter;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.Match;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.PatchAttachment;
+import com.cloud.network.nicira.RouterNextHop;
+import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
+import com.cloud.network.nicira.SourceNatRule;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  CreateLogicalRouterCommand.class)
+public final class NiciraNvpCreateLogicalRouterCommandWrapper extends CommandWrapper<CreateLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalRouterCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CreateLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+        final String routerName = command.getName();
+        final String gatewayServiceUuid = command.getGatewayServiceUuid();
+        final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+
+        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+        tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+        final String publicNetworkNextHopIp = command.getPublicNextHop();
+        final String publicNetworkIpAddress = command.getPublicIpCidr();
+        final String internalNetworkAddress = command.getInternalIpCidr();
+
+        s_logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " +
+                gatewayServiceUuid);
+
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            // Create the Router
+            LogicalRouter lrc = new LogicalRouter();
+            lrc.setDisplayName(niciraNvpResource.truncate(routerName, NAME_MAX_LEN));
+            lrc.setTags(tags);
+            lrc.setRoutingConfig(new SingleDefaultRouteImplicitRoutingConfig(new RouterNextHop(publicNetworkNextHopIp)));
+            lrc = niciraNvpApi.createLogicalRouter(lrc);
+
+            // store the switchport for rollback
+            LogicalSwitchPort lsp = null;
+
+            try {
+                // Create the outside port for the router
+                LogicalRouterPort lrpo = new LogicalRouterPort();
+                lrpo.setAdminStatusEnabled(true);
+                lrpo.setDisplayName(niciraNvpResource.truncate(routerName + "-outside-port", NAME_MAX_LEN));
+                lrpo.setTags(tags);
+                final List<String> outsideIpAddresses = new ArrayList<String>();
+                outsideIpAddresses.add(publicNetworkIpAddress);
+                lrpo.setIpAddresses(outsideIpAddresses);
+                lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo);
+
+                // Attach the outside port to the gateway service on the correct VLAN
+                final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
+                if (command.getVlanId() != 0) {
+                    attachment.setVlanId(command.getVlanId());
+                }
+                niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment);
+
+                // Create the inside port for the router
+                LogicalRouterPort lrpi = new LogicalRouterPort();
+                lrpi.setAdminStatusEnabled(true);
+                lrpi.setDisplayName(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN));
+                lrpi.setTags(tags);
+                final List<String> insideIpAddresses = new ArrayList<String>();
+                insideIpAddresses.add(internalNetworkAddress);
+                lrpi.setIpAddresses(insideIpAddresses);
+                lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi);
+
+                // Create the inside port on the lswitch
+                lsp = new LogicalSwitchPort(niciraNvpResource.truncate(routerName + "-inside-port", NAME_MAX_LEN), tags, true);
+                lsp = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, lsp);
+
+                // Attach the inside router port to the lswitch port with a PatchAttachment
+                niciraNvpApi.updateLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), new PatchAttachment(lsp.getUuid()));
+
+                // Attach the inside lswitch port to the router with a PatchAttachment
+                niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
+
+                // Setup the source nat rule
+                final SourceNatRule snr = new SourceNatRule();
+                snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]);
+                snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]);
+                final Match match = new Match();
+                match.setSourceIpAddresses(internalNetworkAddress);
+                snr.setMatch(match);
+                snr.setOrder(200);
+                niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr);
+            } catch (final NiciraNvpApiException e) {
+                // We need to destroy the router if we already created it
+                // this will also take care of any router ports and rules
+                try {
+                    niciraNvpApi.deleteLogicalRouter(lrc.getUuid());
+                    if (lsp != null) {
+                        niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid());
+                    }
+                } catch (final NiciraNvpApiException ex) {
+                }
+
+                throw e;
+            }
+
+            return new CreateLogicalRouterAnswer(command, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, CreateLogicalRouterAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5412691/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
index 834cccb..b8c69f2 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
@@ -21,8 +21,6 @@ package com.cloud.network.resource.wrapper;
 
 import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
 
-import org.apache.log4j.Logger;
-
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
 import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
@@ -36,8 +34,6 @@ import com.cloud.resource.ResourceWrapper;
 @ResourceWrapper(handles =  DeleteLogicalSwitchPortCommand.class)
 public final class NiciraNvpDeleteLogicalSwitchPortCommandWrapper extends CommandWrapper<DeleteLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
 
-    private static final Logger s_logger = Logger.getLogger(NiciraNvpDeleteLogicalSwitchPortCommandWrapper.class);
-
     @Override
     public Answer execute(final DeleteLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
         final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5412691/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..40d58fc
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpFindLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,59 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
+import com.cloud.agent.api.FindLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  FindLogicalSwitchPortCommand.class)
+public final class NiciraNvpFindLogicalSwitchPortCommandWrapper extends CommandWrapper<FindLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final FindLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+        final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+        final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
+
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
+            if (ports.getResultCount() == 0) {
+                return new FindLogicalSwitchPortAnswer(command, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
+            } else {
+                return new FindLogicalSwitchPortAnswer(command, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
+            }
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, FindLogicalSwitchPortAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5412691/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..9f65938
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,63 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.VifAttachment;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  UpdateLogicalSwitchPortCommand.class)
+public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends CommandWrapper<UpdateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final UpdateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+        final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+        final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
+        final String attachmentUuid = command.getAttachmentUuid();
+
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            // Tags set to scope cs_account and account name
+            final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+            tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+            niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
+            return new UpdateLogicalSwitchPortAnswer(command, true, "Attachment for  " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, UpdateLogicalSwitchPortAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file


[19/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Adding NiciraNvpCreateLogicalSwitchPortCommandWrapper
   - Removing unsued field from NiciraNvpResourceTest

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/361ab5dd
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/361ab5dd
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/361ab5dd

Branch: refs/heads/reporter
Commit: 361ab5ddbd138559423f747b1030608633f2af00
Parents: 28c1da9
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 10:22:25 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:57 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 31 +--------
 .../network/resource/NiciraNvpUtilities.java    | 17 +++++
 ...vpCreateLogicalSwitchPortCommandWrapper.java | 70 ++++++++++++++++++++
 .../network/resource/NiciraNvpResourceTest.java |  2 -
 4 files changed, 88 insertions(+), 32 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/361ab5dd/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 1ab1992..85faf9d 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -38,8 +38,6 @@ import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
 import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
 import com.cloud.agent.api.CreateLogicalRouterAnswer;
 import com.cloud.agent.api.CreateLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
 import com.cloud.agent.api.DeleteLogicalRouterAnswer;
 import com.cloud.agent.api.DeleteLogicalRouterCommand;
 import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
@@ -209,9 +207,7 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof CreateLogicalSwitchPortCommand) {
-            return executeRequest((CreateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof DeleteLogicalSwitchPortCommand) {
+        if (cmd instanceof DeleteLogicalSwitchPortCommand) {
             return executeRequest((DeleteLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof UpdateLogicalSwitchPortCommand) {
             return executeRequest((UpdateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
@@ -245,31 +241,6 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final CreateLogicalSwitchPortCommand cmd, final int numRetries) {
-        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        final String attachmentUuid = cmd.getAttachmentUuid();
-
-        try {
-            // Tags set to scope cs_account and account name
-            final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
-            tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
-
-            final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
-            final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
-            try {
-                niciraNvpApi.updateLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
-            } catch (final NiciraNvpApiException ex) {
-                s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
-                niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid());
-                throw ex; // Rethrow the original exception
-            }
-            return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, CreateLogicalSwitchPortAnswer.class, e);
-        }
-    }
-
     private Answer executeRequest(final DeleteLogicalSwitchPortCommand cmd, final int numRetries) {
         try {
             niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/361ab5dd/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
index 69cacab..f63ca98 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
@@ -18,7 +18,13 @@
 //
 package com.cloud.network.resource;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
 import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpTag;
 
 public class NiciraNvpUtilities {
 
@@ -39,4 +45,15 @@ public class NiciraNvpUtilities {
         final LogicalSwitch logicalSwitch = new LogicalSwitch();
         return logicalSwitch;
     }
+
+    public LogicalSwitchPort createLogicalSwitchPort(final CreateLogicalSwitchPortCommand command) {
+        final String attachmentUuid = command.getAttachmentUuid();
+
+        // Tags set to scope cs_account and account name
+        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+        tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+
+        final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
+        return logicalSwitchPort;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/361ab5dd/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..42a4067
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,70 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalSwitchPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.VifAttachment;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  CreateLogicalSwitchPortCommand.class)
+public final class NiciraNvpCreateLogicalSwitchPortCommandWrapper extends CommandWrapper<CreateLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpCreateLogicalSwitchPortCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CreateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
+        final String logicalSwitchUuid = command.getLogicalSwitchUuid();
+        final String attachmentUuid = command.getAttachmentUuid();
+
+        try {
+            final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+            final LogicalSwitchPort logicalSwitchPort = niciraNvpUtilities.createLogicalSwitchPort(command);
+            final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
+            try {
+                niciraNvpApi.updateLogicalSwitchPortAttachment(command.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
+            } catch (final NiciraNvpApiException ex) {
+                s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
+                niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), newPort.getUuid());
+                throw ex; // Rethrow the original exception
+            }
+            return new CreateLogicalSwitchPortAnswer(command, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, CreateLogicalSwitchPortAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/361ab5dd/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
index b8b81b2..ccee017 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -92,7 +92,6 @@ public class NiciraNvpResourceTest {
     NiciraNvpResource resource;
     Map<String, Object> parameters;
 
-    private NiciraNvpUtilities niciraNvpUtilities;
     private CommandRetryUtility retryUtility;
 
     @Before
@@ -112,7 +111,6 @@ public class NiciraNvpResourceTest {
         parameters.put("zoneId", "blublub");
         parameters.put("adminpass", "adminpass");
 
-        niciraNvpUtilities = NiciraNvpUtilities.getInstance();
         retryUtility = CommandRetryUtility.getInstance();
         retryUtility.setServerResource(resource);
     }


[04/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8457: SAML auth plugin improvements for production usage

* Move config options to SAML plugin
  This moves all configuration options from Config.java to SAML auth manager. This
  allows us to use the config framework.
* Make SAML2UserAuthenticator validate SAML token in httprequest
* Make logout API use ConfigKeys defined in saml auth manager
* Before doing SAML auth, cleanup local states and cookies
* Fix configurations in 4.5.1 to 4.5.2 upgrade path
* Fail if idp has no sso URL defined
* Add a default set of SAML SP cert for testing purposes
  Now to enable and use saml, one needs to do a deploydb-saml after doing a deploydb
* UI remembers login selections, IDP server

- CLOUDSTACK-8458:
    * On UI show dropdown list of discovered IdPs
    * Support SAML Federation, where there may be more than one IdP
        - New datastructure to hold metadata of SP or IdP
        - Recursive processing of IdP metadata
        - Fix login/logout APIs to get new interface and metadata data structure
        - Add org/contact information to metadata
        - Add new API: listIdps that returns list of all discovered IdPs
        - Refactor and cleanup code and tests

- CLOUDSTACK-8459:
    * Add HTTP-POST binding to SP metadata
    * Authn requests must use either HTTP POST/Artifact binding

- CLOUDSTACK-8461:
    * Use unspecified x509 cert as a fallback encryption/signing key
      In case a IDP's metadata does not clearly say if their certificates need to be
      used as signing or encryption and we don't find that, fallback to use the
      unspecified key itself.

- CLOUDSTACK-8462:
    * SAML Auth plugin should not do authorization
      This removes logic to create user if they don't exist. This strictly now
      assumes that users have been already created/imported/authorized by admins.
      As per SAML v2.0 spec section 4.1.2, the SP provider should create authn requests using
      either HTTP POST or HTTP Artifact binding to transfer the message through a
      user agent (browser in our case). The use of HTTP Redirect was one of the reasons
      why this plugin failed to work for some IdP servers that enforce this.
    * Add new User Source
      By reusing the source field, we can find if a user has been SAML enabled or not.
      The limitation is that, once say a user is imported by LDAP and then SAML
      enabled - they won't be able to use LDAP for authentication
    * UI should allow users to pass in domain they want to log into, though it is
      optional and needed only when a user has accounts across domains with same
      username and authorized IDP server
    * SAML users need to be authorized before they can authenticate
        - New column entity to track saml entity id for a user
        - Reusing source column to check if user is saml enabled or not
        - Add new source types, saml2 and saml2disabled
        - New table saml_token to solve the issue of multiple users across domains and
          to enforce security by tracking authn token and checking the samlresponse for
          the tokens
        - Implement API: authorizeSamlSso to enable/disable saml authentication for a
          user
        - Stubs to implement saml token flushing/expiry

- CLOUDSTACK-8463:
    * Use username attribute specified in global setting
      Use username attribute defined by admin from a global setting
      In case of encrypted assertion/attributes:
      - Decrypt them
      - Check signature if provided to check authenticity of message using IdP's
        public key and SP's private key
      - Loop through attributes to find the username

- CLOUDSTACK-8538:
    * Add new global config for SAML request sig algorithm

- CLOUDSTACK-8539:
    * Add metadata refresh timer task and token expiring
        - Fix domain path and save it to saml_tokens
        - Expire hour old saml tokens
        - Refresh metadata based on timer task
        - Fix unit tests

This closes #489

(cherry picked from commit 20ce346f3acb794b08a51841bab2188d426bf7dc)
Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

Conflicts:
	client/WEB-INF/classes/resources/messages_hu.properties
	plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixCheckHealthCommandWrapper.java
	plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java
	ui/scripts/ui-custom/login.js


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/107595a6
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/107595a6
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/107595a6

Branch: refs/heads/reporter
Commit: 107595a6a5c669c63838bb6c52a93853cbd3c855
Parents: 527d6ee
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Thu May 28 14:50:12 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon Jun 29 12:31:51 2015 +0200

----------------------------------------------------------------------
 api/src/com/cloud/user/User.java                |   7 +-
 api/src/com/cloud/user/UserAccount.java         |   4 +
 .../org/apache/cloudstack/api/ApiConstants.java |   3 +-
 .../classes/resources/messages.properties       |   5 +-
 .../classes/resources/messages_fr_FR.properties |   1 -
 .../classes/resources/messages_hu.properties    |   1 -
 client/tomcatconf/commands.properties.in        |   3 +
 developer/developer-prefill.sql                 |   5 -
 developer/developer-saml.sql                    |  63 +++
 developer/pom.xml                               |  58 +++
 .../src/com/cloud/user/UserAccountVO.java       |  11 +
 engine/schema/src/com/cloud/user/UserVO.java    |  10 +
 .../src/com/cloud/user/dao/UserAccountDao.java  |   4 +
 .../com/cloud/user/dao/UserAccountDaoImpl.java  |  19 +-
 plugins/user-authenticators/saml2/pom.xml       |   5 +
 .../cloudstack/saml2/spring-saml2-context.xml   |   3 +
 .../api/command/AuthorizeSAMLSSOCmd.java        | 105 +++++
 .../command/GetServiceProviderMetaDataCmd.java  |  82 +++-
 .../cloudstack/api/command/ListIdpsCmd.java     | 114 +++++
 .../api/command/ListSamlAuthorizationCmd.java   |  95 ++++
 .../command/SAML2LoginAPIAuthenticatorCmd.java  | 288 +++++++------
 .../command/SAML2LogoutAPIAuthenticatorCmd.java |  29 +-
 .../cloudstack/api/response/IdpResponse.java    |  62 +++
 .../api/response/SamlAuthorizationResponse.java |  68 +++
 .../cloudstack/saml/SAML2AuthManager.java       |  67 ++-
 .../cloudstack/saml/SAML2AuthManagerImpl.java   | 430 +++++++++++++++----
 .../cloudstack/saml/SAML2UserAuthenticator.java |  28 +-
 .../cloudstack/saml/SAMLPluginConstants.java    |  30 ++
 .../cloudstack/saml/SAMLProviderMetadata.java   | 122 ++++++
 .../apache/cloudstack/saml/SAMLTokenDao.java    |  23 +
 .../cloudstack/saml/SAMLTokenDaoImpl.java       |  51 +++
 .../org/apache/cloudstack/saml/SAMLTokenVO.java |  97 +++++
 .../org/apache/cloudstack/saml/SAMLUtils.java   | 354 +++++++++++++++
 .../GetServiceProviderMetaDataCmdTest.java      | 104 +++++
 .../cloudstack/SAML2UserAuthenticatorTest.java  |   8 +-
 .../org/apache/cloudstack/SAMLUtilsTest.java    |  74 ++++
 .../GetServiceProviderMetaDataCmdTest.java      | 100 -----
 .../SAML2LoginAPIAuthenticatorCmdTest.java      |  45 +-
 .../SAML2LogoutAPIAuthenticatorCmdTest.java     |  15 +-
 server/src/com/cloud/api/ApiServer.java         |   4 +-
 server/src/com/cloud/api/ApiServlet.java        |   2 +-
 server/src/com/cloud/configuration/Config.java  |  72 ----
 setup/db/db/schema-451to452-cleanup.sql         |  20 +
 setup/db/db/schema-451to452.sql                 |  35 ++
 tools/apidoc/gen_toc.py                         |   3 +
 ui/css/cloudstack3.css                          |  19 +-
 ui/dictionary.jsp                               |   5 +-
 ui/index.jsp                                    |  49 ++-
 ui/scripts/accounts.js                          | 102 +++++
 ui/scripts/accountsWizard.js                    |  63 ++-
 ui/scripts/cloudStack.js                        |  22 +-
 ui/scripts/docs.js                              |   8 +
 ui/scripts/sharedFunctions.js                   |   1 +
 ui/scripts/ui-custom/accountsWizard.js          |   5 +
 ui/scripts/ui-custom/login.js                   | 132 ++++--
 .../apache/cloudstack/utils/auth/SAMLUtils.java | 330 --------------
 .../cloudstack/utils/auth/SAMLUtilsTest.java    |  91 ----
 57 files changed, 2581 insertions(+), 975 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/api/src/com/cloud/user/User.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/user/User.java b/api/src/com/cloud/user/User.java
index 8095e23..0ecdcfa 100644
--- a/api/src/com/cloud/user/User.java
+++ b/api/src/com/cloud/user/User.java
@@ -23,7 +23,7 @@ import org.apache.cloudstack.api.InternalIdentity;
 public interface User extends OwnedBy, InternalIdentity {
 
     public enum Source {
-        LDAP, UNKNOWN
+        LDAP, SAML2, SAML2DISABLED, UNKNOWN
     }
 
     public static final long UID_SYSTEM = 1;
@@ -84,4 +84,9 @@ public interface User extends OwnedBy, InternalIdentity {
 
     public Source getSource();
 
+    void setSource(Source source);
+
+    public String getExternalEntity();
+
+    public void setExternalEntity(String entity);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/api/src/com/cloud/user/UserAccount.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/user/UserAccount.java b/api/src/com/cloud/user/UserAccount.java
index d44fcf7..0449514 100644
--- a/api/src/com/cloud/user/UserAccount.java
+++ b/api/src/com/cloud/user/UserAccount.java
@@ -63,4 +63,8 @@ public interface UserAccount extends InternalIdentity {
     int getLoginAttempts();
 
     public User.Source getSource();
+
+    public String getExternalEntity();
+
+    public void setExternalEntity(String entity);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index 2b64258..204f33b 100644
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -375,6 +375,7 @@ public class ApiConstants {
     public static final String ISOLATION_METHODS = "isolationmethods";
     public static final String PHYSICAL_NETWORK_ID = "physicalnetworkid";
     public static final String DEST_PHYSICAL_NETWORK_ID = "destinationphysicalnetworkid";
+    public static final String ENABLE = "enable";
     public static final String ENABLED = "enabled";
     public static final String SERVICE_NAME = "servicename";
     public static final String DHCP_RANGE = "dhcprange";
@@ -518,7 +519,7 @@ public class ApiConstants {
     public static final String VMPROFILE_ID = "vmprofileid";
     public static final String VMGROUP_ID = "vmgroupid";
     public static final String CS_URL = "csurl";
-    public static final String IDP_URL = "idpurl";
+    public static final String IDP_ID = "idpid";
     public static final String SCALEUP_POLICY_IDS = "scaleuppolicyids";
     public static final String SCALEDOWN_POLICY_IDS = "scaledownpolicyids";
     public static final String SCALEUP_POLICIES = "scaleuppolicies";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/client/WEB-INF/classes/resources/messages.properties
----------------------------------------------------------------------
diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties
index 20970fe..701582c 100644
--- a/client/WEB-INF/classes/resources/messages.properties
+++ b/client/WEB-INF/classes/resources/messages.properties
@@ -115,6 +115,7 @@ label.action.attach.iso=Attach ISO
 label.action.cancel.maintenance.mode.processing=Cancelling Maintenance Mode....
 label.action.cancel.maintenance.mode=Cancel Maintenance Mode
 label.action.change.password=Change Password
+label.action.configure.samlauthorization=Configure SAML SSO Authorization
 label.action.change.service.processing=Changing Service....
 label.action.change.service=Change Service
 label.action.copy.ISO.processing=Copying ISO....
@@ -763,7 +764,9 @@ label.local.storage=Local Storage
 label.local=Local
 label.login=Login
 label.logout=Logout
-label.saml.login=SAML Login
+label.saml.enable=Authorize SAML SSO
+label.saml.entity=Identity Provider
+label.add.LDAP.account=Add LDAP Account
 label.LUN.number=LUN \#
 label.lun=LUN
 label.make.project.owner=Make account project owner

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/client/WEB-INF/classes/resources/messages_fr_FR.properties
----------------------------------------------------------------------
diff --git a/client/WEB-INF/classes/resources/messages_fr_FR.properties b/client/WEB-INF/classes/resources/messages_fr_FR.properties
index 118f7f9..8a8efb7 100644
--- a/client/WEB-INF/classes/resources/messages_fr_FR.properties
+++ b/client/WEB-INF/classes/resources/messages_fr_FR.properties
@@ -1289,7 +1289,6 @@ label.s3.nfs.server=Serveur NFS S3
 label.s3.secret_key=Cl\u00e9 Priv\u00e9e
 label.s3.socket_timeout=D\u00e9lai d\\'expiration de la socket
 label.s3.use_https=Utiliser HTTPS
-label.saml.login=Identifiant SAML
 label.saturday=Samedi
 label.save.and.continue=Enregistrer et continuer
 label.save=Sauvegarder

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/client/WEB-INF/classes/resources/messages_hu.properties
----------------------------------------------------------------------
diff --git a/client/WEB-INF/classes/resources/messages_hu.properties b/client/WEB-INF/classes/resources/messages_hu.properties
index 397c43f..6482c9c 100644
--- a/client/WEB-INF/classes/resources/messages_hu.properties
+++ b/client/WEB-INF/classes/resources/messages_hu.properties
@@ -1282,7 +1282,6 @@ label.s3.nfs.server=S3 NFS kiszolg\u00e1l\u00f3
 label.s3.secret_key=Titkos kulcs
 label.s3.socket_timeout=Kapcsolat id\u0151t\u00fall\u00e9p\u00e9s
 label.s3.use_https=HTTPS haszn\u00e1lata
-label.saml.login=SAML bejelentkez\u00e9s
 label.saturday=Szombat
 label.save.and.continue=Ment\u00e9s \u00e9s folytat\u00e1s
 label.save=Ment\u00e9s

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/client/tomcatconf/commands.properties.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index f4ff1c9..29752c6 100644
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -26,6 +26,9 @@ logout=15
 samlSso=15
 samlSlo=15
 getSPMetadata=15
+listIdps=15
+authorizeSamlSso=7
+listSamlAuthorization=7
 
 ### Account commands
 createAccount=7

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/developer/developer-prefill.sql
----------------------------------------------------------------------
diff --git a/developer/developer-prefill.sql b/developer/developer-prefill.sql
index 27b36e7..3097203 100644
--- a/developer/developer-prefill.sql
+++ b/developer/developer-prefill.sql
@@ -83,9 +83,4 @@ INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
             VALUES ('Advanced', 'DEFAULT', 'management-server',
             'developer', 'true');
 
--- Enable SAML plugin for developers by default
-INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
-            VALUES ('Advanced', 'DEFAULT', 'management-server',
-            'saml2.enabled', 'true');
-
 commit;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/developer/developer-saml.sql
----------------------------------------------------------------------
diff --git a/developer/developer-saml.sql b/developer/developer-saml.sql
new file mode 100644
index 0000000..18afb288
--- /dev/null
+++ b/developer/developer-saml.sql
@@ -0,0 +1,63 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF 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.
+
+-- SAML keystore for testing, allows testing on ssocirlce and other public IdPs
+-- with pre-seeded SP metadata
+USE cloud;
+
+-- Enable SAML plugin for developers by default
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'SAML2-PLUGIN',
+            'saml2.enabled', 'true')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'SAML2-PLUGIN',
+            'saml2.default.idpid', 'https://idp.bhaisaab.org/idp/shibboleth')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'SAML2-PLUGIN',
+            'saml2.idp.metadata.url', 'http://idp.bhaisaab.org/idp/shibboleth')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+-- Enable LDAP source
+INSERT INTO `cloud`.`ldap_configuration` (hostname, port)
+            VALUES ('idp.bhaisaab.org', 389);
+
+-- Fix ldap configs
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'management-server',
+            'ldap.basedn', 'ou=people,dc=idp,dc=bhaisaab,dc=org')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'management-server',
+            'ldap.bind.principal', 'cn=admin,dc=idp,dc=bhaisaab,dc=org')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+INSERT INTO `cloud`.`configuration` (category, instance, component, name, value)
+            VALUES ('Advanced', 'DEFAULT', 'management-server',
+            'ldap.bind.password', 'password')
+            ON DUPLICATE KEY UPDATE value=VALUES(value);
+
+-- Add default set of certificates for testing
+LOCK TABLES `keystore` WRITE;
+/*!40000 ALTER TABLE `keystore` DISABLE KEYS */;
+INSERT INTO `keystore` VALUES (1,'SAMLSP_KEYPAIR','MIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQDQDirtAajTrScXCUgXrsOBgQ++y+IUcyzXwUGEYBlM9kBCmcdlbt5zuYQ8pOvoOQz6CAVqSjYNbnbg1ph37Zfv/tzGUg2V5cpB5BfEyt2KY0mBFNbwa0LKnCAYlBlarm4XZF+oZ0maH6cdboHdHiEqNRscylnXYA2zHKU3YoEfOR+9acl4z54PAyuPjr9SWUPTAyYf326i0q+h3J4nT6FwBFK+yKSC1PeVG/viYQ0otU1UUDkQ3pX81qfJfN/6Ih7W4v73LgUlZsTBMzlu/kJzMuP5Wc5IkU6Mt+8EHMZeLnN0ZErkMk0DCQE14hG8W7S8/inUJpwJlmb5E634Zq8u0I1zVUmSmAGqvvqKJBGnqY5X/j2bsA8B2qFsrcxasIlkKaWLvY+AvXD5X0OHwIZzRbuuCtguSz671C7Cwok8R3N+e9ATDHmG9gC10NJaB6dUBA9p2UdA82TR73x6nGe8pLJnGyecEQfxz1+ptPVAENj1Rl3Wrwu/dbPd/X6inlYpuwlsnWi3LYrkguT/9W3Z2uuq5PTVT04zcyev+50gVnDPzTrNCZfHpmMNQIqZGFmFKz4m+VUZmzZOdg1Vx51t9+t7iHGHqFk6/vnqqWiyEuTEFAaC9krm1VNzGvno5LyNm5Dk9JGAHFfjgNV++viGTpSPLeEeMnlvPuQJy5OJMwIDAQABAoICABME6Imn+C35izRA5fU8RaUGDlFrw+wIp1XF1d5rBoURkchE1ISCQRWlJOCCVwpwhK4qo4wW4qARtA5Tr7Zu4s/OpZH/mDxWuEmTt1SHEv9+mg6RwCBUPdPVt91nVHYEsg2zYEc9we2z7Qv0uSxkf7WjCypzmQjmP/paqQPKHnGjQDKJhCBmIlXO/WFvNDAr9tZIWGjbfP
 qndeS/DTocvm5GBuZn4xoOq99Woo0MQC6zfDEz8DOJlX56hPYXU0ZDbjxInfQsoc3MejoLG7n4xkxPn6WAvynFFsAoZFIk60Faz7UZIfuAWafoX9L0KpjkbT5Fob9CFEuQEzO7x9CIWoUr2PYn8HbThHDUOFAuVVpOLqleLPCrxkX/P01WTrLFuT6vSJKW2kxVwiHvZH6pNT01X/nlHDD6Jd9oWse2jIDBVor6fMnNDtgKl9azKgyakxoOGB7BMcb5u0Im8vFBCCRIyN3lrYjjR1F3H1tvY6Q0fEGLkilO334IyjC63he6lZ6NqslE/3QWEyyIiCL52rMzadN2SwVNawCa8YIR6+TpBjKyqY17LCP57v3UyM6J/kcUqXxDRcg1XnsjiWU+u0j9ZdlBgcbNuQeb1jD2QgICcyr/tWyJ2asyVfvARcD/xt5a9AnGjO0LnwMfw/DdBz1XCxz5uf3gOM69+nXk2gWhAoIBAQDr7NhlmVrASpOJHXXvqkpC2P4+hx7bmwKUZPbqm32pqCBypn6Qd2h4wdFzcP41wN6kpYqmmsPBoezctSgromfHeVjTyjhGku8b1HqtyRoX5sqIIPtv5pKKGS/tVWfyqQ8BspcdhZaR7+ZiRsLRwOXCscRq82+vbyq5Jd1bjsDGeLtcYyASv3II1xTBzSgNlvB+WiFXIlGWT9IPXwhv6IxZn7ME/y992d7bhgPxCcdTfKQNPBpcKerjcNxeDMto8vVijBDqujVpTf+3YvOOzWrcLn5UORFzpVho7oml5+5qnkFI/RZoiagUixFeQMv5+72qKJrxJu3VfI3mxlzZm5YjAoIBAQDhwjvzNWCQ2y7wwwnr88snVxAhd7kByvbKmnFVzHFTy2lheyWkiAqXj9juqsCtbkOK8a1ogmFAHz3i0/n+QhcJ20gudryniMt+u+wKxpmEKyqHKX3d4biPOvkKx7tdfwnlRKpSWXuynlDNVaQnJKUqBqDygLaE2s0
 LK3Fwdl+HN5ZPjRcuHkNpXA8t5lbm3tttMIs3JMneKAq77rodgRg+JcYhUNiybek3cZQcEiIGoh8UU6AhgQIOyMy5lkdG7XwZ2FEMQlqZo+T4HnkdTMU1CbTav1/ZzwDQP4/BJvKXhdRBuYHHAwhV6NIEMk5fzXcOoYmhfOMjvftrSxqUOImxAoIBAQDrhaEuJB8d0hVhD6EZ5kWGYHvHzjp2/1Ne80AwS5Pyl5309tNow1vvGYZQGaAd53Icqgo1clE0b8M3Pj5g+RtjXnfXzovJoIvFm6Pw887xx3uu1EZOmr710FkxNE62SCFsD26ekSsUe4rh10RMA6cbaz3riySW3YKoHO3Tpjo6qHJas7ZkIOzleFoHcximIGXrrWyVQPRz+zF4GOYiWeQq4KvltB8kIylAu5QZwCpV5Rsc/0BNe6c68QN9fIZgOhPQEoYc3lHN04kR+V2t1NH2BxAkYmhSq+ELt/6AOn6fv2brR4VkTPAXuhFXp5Y59B+OzESJs9RAiLxcgvBUaOdDAoIBAQCzlPJjUL5z/Cam1j76NoAP1y25saa1SmJuX9Rvz6UGZvR42qDi9GSYk5CYqbODQgbwa7bpP21kuHVeDgj6vE/fQ1NzwnfnPOXC9nGZUMmlXUEDK3o4GenZ5atda+wbP4b7nVdvEkdXmp/j9pARoxDPEV7OCJ0nqXUZwYEHWOI8iXdD6JPb168ADH72oBfYpsYdYVQclWMPGQMQ46Gg/qPuK9YjglAd/1hZBjwu6C2w4R2f6bWjcR/V6t0Pc/9W6GqjlHNEMTQoqzrkNDlbmUn2GraGm1z/wa5/+U+88eJfrdFeRtZ5HGxxCjalp+64PpTKSq1UjCeSsvlgK+oEpcTBAoIBAQCDDcS69BnjFWNa68FBrA2Uw6acQ6lnpXALohXCRL5qOTMe/FFDEBo0ADGrGpSo+cPaE2buNsYO79CafqTxPoZ38OAtTVmX3uL3z9+2ne2dc486gmAn
 KdJA8w9uawqMEkVpTA9f4WiBJJVzPwAv19AJCPKfUaB8IdNPV+HL8CdK+Dm+lZBADlB9RyvkJRLVJUAuK8/h9kbS3myKI6FIBeFFJpXRONkBSEkANknMqelvdf0GQsHliRslqIK2QVTIOmkJKecG35OhZ5WtU54oSxljlvmtvEKkEJAhEUyfFQRwQTTsDxkFFsfIVr9gv8K1RVEb4D00GUY7GSyAgPKPNsib','MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0A4q7QGo060nFwlIF67DgYEPvsviFHMs18FBhGAZTPZAQpnHZW7ec7mEPKTr6DkM+ggFako2DW524NaYd+2X7/7cxlINleXKQeQXxMrdimNJgRTW8GtCypwgGJQZWq5uF2RfqGdJmh+nHW6B3R4hKjUbHMpZ12ANsxylN2KBHzkfvWnJeM+eDwMrj46/UllD0wMmH99uotKvodyeJ0+hcARSvsikgtT3lRv74mENKLVNVFA5EN6V/NanyXzf+iIe1uL+9y4FJWbEwTM5bv5CczLj+VnOSJFOjLfvBBzGXi5zdGRK5DJNAwkBNeIRvFu0vP4p1CacCZZm+ROt+GavLtCNc1VJkpgBqr76iiQRp6mOV/49m7APAdqhbK3MWrCJZCmli72PgL1w+V9Dh8CGc0W7rgrYLks+u9QuwsKJPEdzfnvQEwx5hvYAtdDSWgenVAQPadlHQPNk0e98epxnvKSyZxsnnBEH8c9fqbT1QBDY9UZd1q8Lv3Wz3f1+op5WKbsJbJ1oty2K5ILk//Vt2drrquT01U9OM3Mnr/udIFZwz806zQmXx6ZjDUCKmRhZhSs+JvlVGZs2TnYNVcedbffre4hxh6hZOv756qloshLkxBQGgvZK5tVTcxr56OS8jZuQ5PSRgBxX44DVfvr4hk6Ujy3hHjJ5bz7kCcuTiTMCAwEAAQ==','samlsp-keypair',NULL),(2,'S
 AMLSP_X509CERT','rO0ABXNyAC1qYXZhLnNlY3VyaXR5LmNlcnQuQ2VydGlmaWNhdGUkQ2VydGlmaWNhdGVSZXCJJ2qdya48DAIAAlsABGRhdGF0AAJbQkwABHR5cGV0ABJMamF2YS9sYW5nL1N0cmluZzt4cHVyAAJbQqzzF/gGCFTgAgAAeHAAAASzMIIErzCCApcCBgFNmkdlAzANBgkqhkiG9w0BAQsFADAbMRkwFwYDVQQDExBBcGFjaGVDbG91ZFN0YWNrMB4XDTE1MDUyNzExMjc1OVoXDTE4MDUyODExMjc1OVowGzEZMBcGA1UEAxMQQXBhY2hlQ2xvdWRTdGFjazCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANAOKu0BqNOtJxcJSBeuw4GBD77L4hRzLNfBQYRgGUz2QEKZx2Vu3nO5hDyk6+g5DPoIBWpKNg1uduDWmHftl+/+3MZSDZXlykHkF8TK3YpjSYEU1vBrQsqcIBiUGVqubhdkX6hnSZofpx1ugd0eISo1GxzKWddgDbMcpTdigR85H71pyXjPng8DK4+Ov1JZQ9MDJh/fbqLSr6HcnidPoXAEUr7IpILU95Ub++JhDSi1TVRQORDelfzWp8l83/oiHtbi/vcuBSVmxMEzOW7+QnMy4/lZzkiRToy37wQcxl4uc3RkSuQyTQMJATXiEbxbtLz+KdQmnAmWZvkTrfhmry7QjXNVSZKYAaq++ookEaepjlf+PZuwDwHaoWytzFqwiWQppYu9j4C9cPlfQ4fAhnNFu64K2C5LPrvULsLCiTxHc3570BMMeYb2ALXQ0loHp1QED2nZR0DzZNHvfHqcZ7yksmcbJ5wRB/HPX6m09UAQ2PVGXdavC791s939fqKeVim7CWydaLctiuSC5P/1bdna66rk9NVPTjNzJ6/7nSBWcM/NOs0Jl8emYw1AipkYWYUrPib5VRmbNk52DVXHnW3363uI
 cYeoWTr++eqpaLIS5MQUBoL2SubVU3Ma+ejkvI2bkOT0kYAcV+OA1X76+IZOlI8t4R4yeW8+5AnLk4kzAgMBAAEwDQYJKoZIhvcNAQELBQADggIBAHZWSGpypDmQLQWr2FCVQUnulbPuMMJ0sCH0rNLGLe8qNbZ0YeAuWFsg7+0kVGZ4OuDgioIhD0h3Q3huZtF/WF81eyZqPyVfkXG8egjK58AzMDPHZECeoSVGUCZuq3wjmbnT2sLLDvr8RrzMbbCEvkrYHWivQ18Lbd3eWYYnDbXZRy9GuSWrA9cMqXVYjSTxam9Kel33BIF6CAlMQN5o11oiAv+ciNoxHqGh+8xX3kFKP+x+SRt40NOEs537lEpj/6KdLvd/bP6J4K94jAX3lsdg6zDaBiQWl7P3t50AKtP384Qsb/33uXcbTyw/TkzvPcbmsgTbEUTZIOv44CxMstFrUCyT7ptrzLvDk7Iy2cMgWghULgDvKT3esPE9pleyHG8bkjGt9ypDF/Lmp7j/kILYbF7eq1wIbHOSam4p8WyddVsW4nesu6fqLiCGXum9paChIfvL3To/VHFFKduhJd0Y7LMgWO7pXxWh7XfgRmzQaEN1eJmj5315HEYTS2wXWjptwYDrhiobKuCbpADfOQks8xNKJFLMnXp+IvAqz+ZjkNOz60MLuQ3hvKLTo6nQcTYTfZZxo3Aap30/hA2GtxxSXK/xpBDm58jcVoudgCdxML/OqERBfcADBLvIw5h9+DlXjPUg25IefU0oA336YtnzftJ6cfQfatrc0tBqNEeXdAAFWC41MDk=','','samlsp-x509cert',NULL);
+/*!40000 ALTER TABLE `keystore` ENABLE KEYS */;
+UNLOCK TABLES;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/developer/pom.xml
----------------------------------------------------------------------
diff --git a/developer/pom.xml b/developer/pom.xml
index d6dc6a1..ef38e8a 100644
--- a/developer/pom.xml
+++ b/developer/pom.xml
@@ -158,6 +158,64 @@
       </build>
     </profile>
     <profile>
+      <!-- saml deploydb property -->
+      <id>deploydb-saml</id>
+      <activation>
+        <property>
+          <name>deploydb-saml</name>
+        </property>
+      </activation>
+      <build>
+        <plugins>
+          <plugin>
+            <groupId>org.codehaus.mojo</groupId>
+            <artifactId>exec-maven-plugin</artifactId>
+            <dependencies>
+              <dependency>
+                <groupId>mysql</groupId>
+                <artifactId>mysql-connector-java</artifactId>
+                <version>${cs.mysql.version}</version>
+              </dependency>
+            </dependencies>
+            <version>1.2.1</version>
+            <executions>
+              <execution>
+                <phase>process-resources</phase>
+                <id>create-schema-simulator</id>
+                <goals>
+                  <goal>java</goal>
+                </goals>
+              </execution>
+            </executions>
+            <configuration>
+              <mainClass>com.cloud.upgrade.DatabaseCreator</mainClass>
+              <includePluginDependencies>true</includePluginDependencies>
+              <arguments>
+                <!-- db properties file -->
+                <argument>${basedir}/../utils/conf/db.properties</argument>
+                <argument>${basedir}/../utils/conf/db.properties.override</argument>
+                <!-- simulator sql files -->
+                <argument>${basedir}/developer-saml.sql</argument>
+                <!-- upgrade -->
+                <argument>com.cloud.upgrade.DatabaseUpgradeChecker</argument>
+                <argument>--rootpassword=${db.root.password}</argument>
+              </arguments>
+              <systemProperties>
+                <systemProperty>
+                  <key>catalina.home</key>
+                  <value>${basedir}/../utils</value>
+                </systemProperty>
+                <systemProperty>
+                  <key>paths.script</key>
+                  <value>${basedir}/target/db</value>
+                </systemProperty>
+              </systemProperties>
+            </configuration>
+          </plugin>
+        </plugins>
+      </build>
+    </profile>
+    <profile>
       <!-- simulator deploydb property -->
       <id>deploydb-simulator</id>
       <activation>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/engine/schema/src/com/cloud/user/UserAccountVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/UserAccountVO.java b/engine/schema/src/com/cloud/user/UserAccountVO.java
index 5f33c47..80ee873 100644
--- a/engine/schema/src/com/cloud/user/UserAccountVO.java
+++ b/engine/schema/src/com/cloud/user/UserAccountVO.java
@@ -105,6 +105,9 @@ public class UserAccountVO implements UserAccount, InternalIdentity {
     @Enumerated(value = EnumType.STRING)
     private User.Source source;
 
+    @Column(name = "external_entity", length = 65535)
+    private String externalEntity = null;
+
     public UserAccountVO() {
     }
 
@@ -296,4 +299,12 @@ public class UserAccountVO implements UserAccount, InternalIdentity {
     public void setSource(User.Source source) {
         this.source = source;
     }
+
+    public String getExternalEntity() {
+        return externalEntity;
+    }
+
+    public void setExternalEntity(String externalEntity) {
+        this.externalEntity = externalEntity;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/engine/schema/src/com/cloud/user/UserVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/UserVO.java b/engine/schema/src/com/cloud/user/UserVO.java
index eb2813b..da7811e 100644
--- a/engine/schema/src/com/cloud/user/UserVO.java
+++ b/engine/schema/src/com/cloud/user/UserVO.java
@@ -101,6 +101,9 @@ public class UserVO implements User, Identity, InternalIdentity {
     @Enumerated(value = EnumType.STRING)
     private Source source;
 
+    @Column(name = "external_entity", length = 65535)
+    private String externalEntity;
+
     public UserVO() {
         this.uuid = UUID.randomUUID().toString();
     }
@@ -283,4 +286,11 @@ public class UserVO implements User, Identity, InternalIdentity {
         this.source = source;
     }
 
+    public String getExternalEntity() {
+        return externalEntity;
+    }
+
+    public void setExternalEntity(String externalEntity) {
+        this.externalEntity = externalEntity;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserAccountDao.java b/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
index a26ff7f..1d005b2 100644
--- a/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
+++ b/engine/schema/src/com/cloud/user/dao/UserAccountDao.java
@@ -20,7 +20,11 @@ import com.cloud.user.UserAccount;
 import com.cloud.user.UserAccountVO;
 import com.cloud.utils.db.GenericDao;
 
+import java.util.List;
+
 public interface UserAccountDao extends GenericDao<UserAccountVO, Long> {
+    List<UserAccountVO> getAllUsersByNameAndEntity(String username, String entity);
+
     UserAccount getUserAccount(String username, Long domainId);
 
     boolean validateUsernameInDomain(String username, Long domainId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java b/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
index 1449e6b..a8d9e39 100644
--- a/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
+++ b/engine/schema/src/com/cloud/user/dao/UserAccountDaoImpl.java
@@ -16,15 +16,15 @@
 // under the License.
 package com.cloud.user.dao;
 
-import javax.ejb.Local;
-
-import org.springframework.stereotype.Component;
-
 import com.cloud.user.UserAccount;
 import com.cloud.user.UserAccountVO;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
+import org.springframework.stereotype.Component;
+
+import javax.ejb.Local;
+import java.util.List;
 
 @Component
 @Local(value = {UserAccountDao.class})
@@ -39,6 +39,17 @@ public class UserAccountDaoImpl extends GenericDaoBase<UserAccountVO, Long> impl
     }
 
     @Override
+    public List<UserAccountVO> getAllUsersByNameAndEntity(String username, String entity) {
+        if (username == null) {
+            return null;
+        }
+        SearchCriteria<UserAccountVO> sc = createSearchCriteria();
+        sc.addAnd("username", SearchCriteria.Op.EQ, username);
+        sc.addAnd("externalEntity", SearchCriteria.Op.EQ, entity);
+        return listBy(sc);
+    }
+
+    @Override
     public UserAccount getUserAccount(String username, Long domainId) {
         if ((username == null) || (domainId == null)) {
             return null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/pom.xml b/plugins/user-authenticators/saml2/pom.xml
index 834d5f0..6c6f5ca 100644
--- a/plugins/user-authenticators/saml2/pom.xml
+++ b/plugins/user-authenticators/saml2/pom.xml
@@ -47,5 +47,10 @@
       <artifactId>cloud-api</artifactId>
       <version>${project.version}</version>
     </dependency>
+    <dependency>
+      <groupId>org.apache.cloudstack</groupId>
+      <artifactId>cloud-framework-config</artifactId>
+      <version>${project.version}</version>
+    </dependency>
   </dependencies>
 </project>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
index 92f89b8..d3a2194 100644
--- a/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
+++ b/plugins/user-authenticators/saml2/resources/META-INF/cloudstack/saml2/spring-saml2-context.xml
@@ -33,4 +33,7 @@
         <property name="name" value="SAML2Auth"/>
     </bean>
 
+    <bean id="samlTokenDao" class="org.apache.cloudstack.saml.SAMLTokenDaoImpl">
+    </bean>
+
 </beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java
new file mode 100644
index 0000000..54ce418
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/AuthorizeSAMLSSOCmd.java
@@ -0,0 +1,105 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.command;
+
+import com.cloud.domain.Domain;
+import com.cloud.user.Account;
+import com.cloud.user.UserAccount;
+import org.apache.cloudstack.acl.SecurityChecker;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.IdpResponse;
+import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.cloudstack.api.response.UserResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.cloudstack.saml.SAML2AuthManager;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+
+@APICommand(name = "authorizeSamlSso", description = "Allow or disallow a user to use SAML SSO", responseObject = SuccessResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class AuthorizeSAMLSSOCmd extends BaseCmd {
+    public static final Logger s_logger = Logger.getLogger(AuthorizeSAMLSSOCmd.class.getName());
+
+    private static final String s_name = "authorizesamlssoresponse";
+
+    @Inject
+    SAML2AuthManager _samlAuthManager;
+
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+
+    @Parameter(name = ApiConstants.USER_ID, type = CommandType.UUID, entityType = UserResponse.class, required = true, description = "User uuid")
+    private Long id;
+
+    @Parameter(name = ApiConstants.ENABLE, type = CommandType.BOOLEAN, required = true, description = "If true, authorizes user to be able to use SAML for Single Sign. If False, disable user to user SAML SSO.")
+    private Boolean enable;
+
+    public Boolean getEnable() {
+        return enable;
+    }
+
+    public String getEntityId() {
+        return entityId;
+    }
+
+    @Parameter(name = ApiConstants.ENTITY_ID, type = CommandType.STRING, entityType = IdpResponse.class, description = "The Identity Provider ID the user is allowed to get single signed on from")
+    private String entityId;
+
+    public Long getId() {
+        return id;
+    }
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        return Account.ACCOUNT_ID_SYSTEM;
+    }
+
+    @Override
+    public void execute() {
+        // Check permissions
+        UserAccount userAccount = _accountService.getUserAccountById(getId());
+        if (userAccount == null) {
+            throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR , "Unable to find a user account with the given ID");
+        }
+        Domain domain = _domainService.getDomain(userAccount.getDomainId());
+        Account account = _accountService.getAccount(userAccount.getAccountId());
+        _accountService.checkAccess(CallContext.current().getCallingAccount(), domain);
+        _accountService.checkAccess(CallContext.current().getCallingAccount(), SecurityChecker.AccessType.OperateEntry, true, account);
+
+        CallContext.current().setEventDetails("UserId: " + getId());
+        SuccessResponse response = new SuccessResponse();
+        Boolean status = false;
+
+        if (_samlAuthManager.authorizeUser(getId(), getEntityId(), getEnable())) {
+            status = true;
+        }
+        response.setResponseName(getCommandName());
+        response.setSuccess(status);
+        setResponseObject(response);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java
index 721b18e..466a3dd 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmd.java
@@ -14,7 +14,6 @@
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License.
-
 package org.apache.cloudstack.api.command;
 
 import com.cloud.api.response.ApiResponseSerializer;
@@ -30,21 +29,36 @@ import org.apache.cloudstack.api.auth.APIAuthenticator;
 import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
 import org.apache.cloudstack.api.response.SAMLMetaDataResponse;
 import org.apache.cloudstack.saml.SAML2AuthManager;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
 import org.apache.log4j.Logger;
 import org.opensaml.Configuration;
 import org.opensaml.DefaultBootstrap;
 import org.opensaml.common.xml.SAMLConstants;
 import org.opensaml.saml2.core.NameIDType;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
+import org.opensaml.saml2.metadata.ContactPerson;
+import org.opensaml.saml2.metadata.ContactPersonTypeEnumeration;
+import org.opensaml.saml2.metadata.EmailAddress;
 import org.opensaml.saml2.metadata.EntityDescriptor;
+import org.opensaml.saml2.metadata.GivenName;
 import org.opensaml.saml2.metadata.KeyDescriptor;
+import org.opensaml.saml2.metadata.LocalizedString;
 import org.opensaml.saml2.metadata.NameIDFormat;
+import org.opensaml.saml2.metadata.Organization;
+import org.opensaml.saml2.metadata.OrganizationName;
+import org.opensaml.saml2.metadata.OrganizationURL;
 import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.SingleLogoutService;
 import org.opensaml.saml2.metadata.impl.AssertionConsumerServiceBuilder;
+import org.opensaml.saml2.metadata.impl.ContactPersonBuilder;
+import org.opensaml.saml2.metadata.impl.EmailAddressBuilder;
 import org.opensaml.saml2.metadata.impl.EntityDescriptorBuilder;
+import org.opensaml.saml2.metadata.impl.GivenNameBuilder;
 import org.opensaml.saml2.metadata.impl.KeyDescriptorBuilder;
 import org.opensaml.saml2.metadata.impl.NameIDFormatBuilder;
+import org.opensaml.saml2.metadata.impl.OrganizationBuilder;
+import org.opensaml.saml2.metadata.impl.OrganizationNameBuilder;
+import org.opensaml.saml2.metadata.impl.OrganizationURLBuilder;
 import org.opensaml.saml2.metadata.impl.SPSSODescriptorBuilder;
 import org.opensaml.saml2.metadata.impl.SingleLogoutServiceBuilder;
 import org.opensaml.xml.ConfigurationException;
@@ -73,6 +87,7 @@ import javax.xml.transform.stream.StreamResult;
 import java.io.IOException;
 import java.io.StringWriter;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.net.InetAddress;
 
@@ -119,8 +134,10 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent
                     params, responseType));
         }
 
+        final SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
+
         EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
-        spEntityDescriptor.setEntityID(_samlAuthManager.getServiceProviderId());
+        spEntityDescriptor.setEntityID(spMetadata.getEntityId());
 
         SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
         spSSODescriptor.setWantAssertionsSigned(true);
@@ -130,19 +147,23 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent
         keyInfoGeneratorFactory.setEmitEntityCertificate(true);
         KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
 
+        KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject();
+        signKeyDescriptor.setUse(UsageType.SIGNING);
+
         KeyDescriptor encKeyDescriptor = new KeyDescriptorBuilder().buildObject();
         encKeyDescriptor.setUse(UsageType.ENCRYPTION);
 
-        KeyDescriptor signKeyDescriptor = new KeyDescriptorBuilder().buildObject();
-        signKeyDescriptor.setUse(UsageType.SIGNING);
+        BasicX509Credential signingCredential = new BasicX509Credential();
+        signingCredential.setEntityCertificate(spMetadata.getSigningCertificate());
+
+        BasicX509Credential encryptionCredential = new BasicX509Credential();
+        encryptionCredential.setEntityCertificate(spMetadata.getEncryptionCertificate());
 
-        BasicX509Credential credential = new BasicX509Credential();
-        credential.setEntityCertificate(_samlAuthManager.getSpX509Certificate());
         try {
-            encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(credential));
-            signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(credential));
-            spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor);
+            signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingCredential));
+            encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(encryptionCredential));
             spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);
+            spSSODescriptor.getKeyDescriptors().add(encKeyDescriptor);
         } catch (SecurityException e) {
             s_logger.warn("Unable to add SP X509 descriptors:" + e.getMessage());
         }
@@ -160,19 +181,50 @@ public class GetServiceProviderMetaDataCmd extends BaseCmd implements APIAuthent
         spSSODescriptor.getNameIDFormats().add(transientNameIDFormat);
 
         AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
-        assertionConsumerService.setIndex(0);
-        assertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
-        assertionConsumerService.setLocation(_samlAuthManager.getSpSingleSignOnUrl());
+        assertionConsumerService.setIndex(1);
+        assertionConsumerService.setIsDefault(true);
+        assertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
+        assertionConsumerService.setLocation(spMetadata.getSsoUrl());
+        spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
+
+        AssertionConsumerService assertionConsumerService2 = new AssertionConsumerServiceBuilder().buildObject();
+        assertionConsumerService2.setIndex(2);
+        assertionConsumerService2.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
+        assertionConsumerService2.setLocation(spMetadata.getSsoUrl());
+        spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService2);
 
         SingleLogoutService ssoService = new SingleLogoutServiceBuilder().buildObject();
         ssoService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
-        ssoService.setLocation(_samlAuthManager.getSpSingleLogOutUrl());
-
+        ssoService.setLocation(spMetadata.getSloUrl());
         spSSODescriptor.getSingleLogoutServices().add(ssoService);
-        spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
+
+        SingleLogoutService ssoService2 = new SingleLogoutServiceBuilder().buildObject();
+        ssoService2.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
+        ssoService2.setLocation(spMetadata.getSloUrl());
+        spSSODescriptor.getSingleLogoutServices().add(ssoService2);
+
         spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);
         spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
 
+        ContactPerson contactPerson = new ContactPersonBuilder().buildObject();
+        GivenName givenName = new GivenNameBuilder().buildObject();
+        givenName.setName(spMetadata.getContactPersonName());
+        EmailAddress emailAddress = new EmailAddressBuilder().buildObject();
+        emailAddress.setAddress(spMetadata.getContactPersonEmail());
+        contactPerson.setType(ContactPersonTypeEnumeration.TECHNICAL);
+        contactPerson.setGivenName(givenName);
+        contactPerson.getEmailAddresses().add(emailAddress);
+        spEntityDescriptor.getContactPersons().add(contactPerson);
+
+        Organization organization = new OrganizationBuilder().buildObject();
+        OrganizationName organizationName = new OrganizationNameBuilder().buildObject();
+        organizationName.setName(new LocalizedString(spMetadata.getOrganizationName(), Locale.getDefault().getLanguage()));
+        OrganizationURL organizationURL = new OrganizationURLBuilder().buildObject();
+        organizationURL.setURL(new LocalizedString(spMetadata.getOrganizationUrl(), Locale.getDefault().getLanguage()));
+        organization.getOrganizationNames().add(organizationName);
+        organization.getURLs().add(organizationURL);
+        spEntityDescriptor.setOrganization(organization);
+
         StringWriter stringWriter = new StringWriter();
         try {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
new file mode 100644
index 0000000..7d7c95e
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListIdpsCmd.java
@@ -0,0 +1,114 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.command;
+
+import com.cloud.api.response.ApiResponseSerializer;
+import com.cloud.user.Account;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.ApiServerService;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.auth.APIAuthenticationType;
+import org.apache.cloudstack.api.auth.APIAuthenticator;
+import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
+import org.apache.cloudstack.api.response.IdpResponse;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.saml.SAML2AuthManager;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+@APICommand(name = "listIdps", description = "Returns list of discovered SAML Identity Providers", responseObject = IdpResponse.class, entityType = {})
+public class ListIdpsCmd extends BaseCmd implements APIAuthenticator {
+    public static final Logger s_logger = Logger.getLogger(ListIdpsCmd.class.getName());
+    private static final String s_name = "listidpsresponse";
+
+    @Inject
+    ApiServerService _apiServer;
+
+    SAML2AuthManager _samlAuthManager;
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        return Account.ACCOUNT_TYPE_NORMAL;
+    }
+
+    @Override
+    public void execute() throws ServerApiException {
+        // We should never reach here
+        throw new ServerApiException(ApiErrorCode.METHOD_NOT_ALLOWED, "This is an authentication api, cannot be used directly");
+    }
+
+    @Override
+    public String authenticate(String command, Map<String, Object[]> params, HttpSession session, String remoteAddress, String responseType, StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
+        auditTrailSb.append("=== SAML List IdPs ===");
+        ListResponse<IdpResponse> response = new ListResponse<IdpResponse>();
+        List<IdpResponse> idpResponseList = new ArrayList<IdpResponse>();
+        for (SAMLProviderMetadata metadata: _samlAuthManager.getAllIdPMetadata()) {
+            if (metadata == null) {
+                continue;
+            }
+            IdpResponse idpResponse = new IdpResponse();
+            idpResponse.setId(metadata.getEntityId());
+            if (metadata.getOrganizationName() == null || metadata.getOrganizationName().isEmpty()) {
+                idpResponse.setOrgName(metadata.getEntityId());
+            } else {
+                idpResponse.setOrgName(metadata.getOrganizationName());
+            }
+            idpResponse.setOrgUrl(metadata.getOrganizationUrl());
+            idpResponse.setObjectName("idp");
+            idpResponseList.add(idpResponse);
+        }
+        response.setResponses(idpResponseList, idpResponseList.size());
+        response.setResponseName(getCommandName());
+        return ApiResponseSerializer.toSerializedString(response, responseType);
+    }
+
+    @Override
+    public APIAuthenticationType getAPIType() {
+        return APIAuthenticationType.LOGIN_API;
+    }
+
+    @Override
+    public void setAuthenticators(List<PluggableAPIAuthenticator> authenticators) {
+        for (PluggableAPIAuthenticator authManager: authenticators) {
+            if (authManager != null && authManager instanceof SAML2AuthManager) {
+                _samlAuthManager = (SAML2AuthManager) authManager;
+            }
+        }
+        if (_samlAuthManager == null) {
+            s_logger.error("No suitable Pluggable Authentication Manager found for SAML2 Login Cmd");
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java
new file mode 100644
index 0000000..be958a1
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListSamlAuthorizationCmd.java
@@ -0,0 +1,95 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.command;
+
+import com.cloud.user.Account;
+import com.cloud.user.User;
+import com.cloud.user.UserVO;
+import com.cloud.user.dao.UserDao;
+import org.apache.cloudstack.acl.SecurityChecker;
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseListCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.cloudstack.api.response.SamlAuthorizationResponse;
+import org.apache.cloudstack.api.response.UserResponse;
+import org.apache.cloudstack.context.CallContext;
+import org.apache.log4j.Logger;
+
+import javax.inject.Inject;
+import java.util.ArrayList;
+import java.util.List;
+
+@APICommand(name = "listSamlAuthorization", description = "Lists authorized users who can used SAML SSO", responseObject = SamlAuthorizationResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
+public class ListSamlAuthorizationCmd extends BaseListCmd {
+    public static final Logger s_logger = Logger.getLogger(ListSamlAuthorizationCmd.class.getName());
+    private static final String s_name = "listsamlauthorizationsresponse";
+
+    @Inject
+    private UserDao _userDao;
+
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+    @Parameter(name = ApiConstants.USER_ID, type = CommandType.UUID, entityType = UserResponse.class, required = false, description = "User uuid")
+    private Long userId;
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    public Long getUserId() {
+        return userId;
+    }
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        return Account.ACCOUNT_ID_SYSTEM;
+    }
+
+    @Override
+    public void execute() {
+        List<UserVO> users = new ArrayList<UserVO>();
+        if (getUserId() != null) {
+            UserVO user = _userDao.getUser(getUserId());
+            if (user != null) {
+                Account account = _accountService.getAccount(user.getAccountId());
+                _accountService.checkAccess(CallContext.current().getCallingAccount(), SecurityChecker.AccessType.ListEntry, true, account);
+                users.add(user);
+            }
+        } else if (CallContext.current().getCallingAccount().getType() == Account.ACCOUNT_TYPE_ADMIN) {
+            users = _userDao.listAll();
+        }
+
+        ListResponse<SamlAuthorizationResponse> response = new ListResponse<SamlAuthorizationResponse>();
+        List<SamlAuthorizationResponse> authorizationResponses = new ArrayList<SamlAuthorizationResponse>();
+        for (User user: users) {
+            SamlAuthorizationResponse authorizationResponse = new SamlAuthorizationResponse(user.getUuid(), user.getSource().equals(User.Source.SAML2), user.getExternalEntity());
+            authorizationResponse.setObjectName("samlauthorization");
+            authorizationResponses.add(authorizationResponse);
+        }
+        response.setResponses(authorizationResponses);
+        response.setResponseName(getCommandName());
+        setResponseObject(response);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java
index dda5876..26a4c9b 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java
@@ -14,16 +14,14 @@
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License.
-
 package org.apache.cloudstack.api.command;
 
 import com.cloud.api.response.ApiResponseSerializer;
-import com.cloud.configuration.Config;
-import com.cloud.domain.Domain;
 import com.cloud.exception.CloudAuthenticationException;
 import com.cloud.user.Account;
 import com.cloud.user.DomainManager;
 import com.cloud.user.UserAccount;
+import com.cloud.user.UserAccountVO;
 import com.cloud.user.dao.UserAccountDao;
 import com.cloud.utils.HttpUtils;
 import com.cloud.utils.db.EntityManager;
@@ -38,24 +36,29 @@ import org.apache.cloudstack.api.auth.APIAuthenticationType;
 import org.apache.cloudstack.api.auth.APIAuthenticator;
 import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
 import org.apache.cloudstack.api.response.LoginCmdResponse;
-import org.apache.cloudstack.context.CallContext;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.saml.SAML2AuthManager;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
+import org.apache.cloudstack.saml.SAMLPluginConstants;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
+import org.apache.cloudstack.saml.SAMLTokenVO;
+import org.apache.cloudstack.saml.SAMLUtils;
 import org.apache.log4j.Logger;
 import org.opensaml.DefaultBootstrap;
 import org.opensaml.saml2.core.Assertion;
-import org.opensaml.saml2.core.Attribute;
-import org.opensaml.saml2.core.AttributeStatement;
-import org.opensaml.saml2.core.AuthnRequest;
-import org.opensaml.saml2.core.NameID;
-import org.opensaml.saml2.core.NameIDType;
+import org.opensaml.saml2.core.EncryptedAssertion;
+import org.opensaml.saml2.core.Issuer;
 import org.opensaml.saml2.core.Response;
 import org.opensaml.saml2.core.StatusCode;
+import org.opensaml.saml2.encryption.Decrypter;
 import org.opensaml.xml.ConfigurationException;
-import org.opensaml.xml.io.MarshallingException;
+import org.opensaml.xml.encryption.DecryptionException;
+import org.opensaml.xml.encryption.EncryptedKeyResolver;
+import org.opensaml.xml.encryption.InlineEncryptedKeyResolver;
 import org.opensaml.xml.io.UnmarshallingException;
+import org.opensaml.xml.security.SecurityHelper;
+import org.opensaml.xml.security.credential.Credential;
+import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver;
 import org.opensaml.xml.security.x509.BasicX509Credential;
+import org.opensaml.xml.signature.Signature;
 import org.opensaml.xml.signature.SignatureValidator;
 import org.opensaml.xml.validation.ValidationException;
 import org.xml.sax.SAXException;
@@ -68,14 +71,11 @@ import javax.servlet.http.HttpSession;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.stream.FactoryConfigurationError;
 import java.io.IOException;
-import java.net.URLEncoder;
 import java.net.InetAddress;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
+import java.net.URLEncoder;
+
 import java.util.List;
 import java.util.Map;
-import java.util.UUID;
 
 @APICommand(name = "samlSso", description = "SP initiated SAML Single Sign On", requestHasSensitiveInfo = true, responseObject = LoginCmdResponse.class, entityType = {})
 public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthenticator {
@@ -85,16 +85,14 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
     /////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////
     /////////////////////////////////////////////////////
-    @Parameter(name = ApiConstants.IDP_URL, type = CommandType.STRING, description = "Identity Provider SSO HTTP-Redirect binding URL", required = true)
-    private String idpUrl;
+    @Parameter(name = ApiConstants.IDP_ID, type = CommandType.STRING, description = "Identity Provider Entity ID", required = true)
+    private String idpId;
 
     @Inject
     ApiServerService _apiServer;
     @Inject
     EntityManager _entityMgr;
     @Inject
-    ConfigurationDao _configDao;
-    @Inject
     DomainManager _domainMgr;
     @Inject
     private UserAccountDao _userAccountDao;
@@ -105,8 +103,8 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
     /////////////////// Accessors ///////////////////////
     /////////////////////////////////////////////////////
 
-    public String getIdpUrl() {
-        return idpUrl;
+    public String getIdpId() {
+        return idpId;
     }
 
     /////////////////////////////////////////////////////
@@ -129,30 +127,6 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
         throw new ServerApiException(ApiErrorCode.METHOD_NOT_ALLOWED, "This is an authentication api, cannot be used directly");
     }
 
-    private String buildAuthnRequestUrl(String idpUrl) {
-        String spId = _samlAuthManager.getServiceProviderId();
-        String consumerUrl = _samlAuthManager.getSpSingleSignOnUrl();
-        String identityProviderUrl = _samlAuthManager.getIdpSingleSignOnUrl();
-
-        if (idpUrl != null) {
-            identityProviderUrl = idpUrl;
-        }
-
-        String redirectUrl = "";
-        try {
-            DefaultBootstrap.bootstrap();
-            AuthnRequest authnRequest = SAMLUtils.buildAuthnRequestObject(spId, identityProviderUrl, consumerUrl);
-            PrivateKey privateKey = null;
-            if (_samlAuthManager.getSpKeyPair() != null) {
-                privateKey = _samlAuthManager.getSpKeyPair().getPrivate();
-            }
-            redirectUrl = identityProviderUrl + "?" + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey);
-        } catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) {
-            s_logger.error("SAML AuthnRequest message building error: " + e.getMessage());
-        }
-        return redirectUrl;
-    }
-
     public Response processSAMLResponse(String responseMessage) {
         Response responseObject = null;
         try {
@@ -168,13 +142,44 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
     @Override
     public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, final InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
         try {
-            if (!params.containsKey("SAMLResponse") && !params.containsKey("SAMLart")) {
-                String idpUrl = null;
-                final String[] idps = (String[])params.get(ApiConstants.IDP_URL);
-                if (idps != null && idps.length > 0) {
-                    idpUrl = idps[0];
+            if (!params.containsKey(SAMLPluginConstants.SAML_RESPONSE) && !params.containsKey("SAMLart")) {
+                String idpId = null;
+                String domainPath = null;
+
+                if (params.containsKey(ApiConstants.IDP_ID)) {
+                    idpId = ((String[])params.get(ApiConstants.IDP_ID))[0];
                 }
-                String redirectUrl = this.buildAuthnRequestUrl(idpUrl);
+
+                if (params.containsKey(ApiConstants.DOMAIN)) {
+                    domainPath = ((String[])params.get(ApiConstants.DOMAIN))[0];
+                }
+
+                if (domainPath != null && !domainPath.isEmpty()) {
+                    if (!domainPath.startsWith("/")) {
+                        domainPath = "/" + domainPath;
+                    }
+                    if (!domainPath.endsWith("/")) {
+                        domainPath = domainPath + "/";
+                    }
+                }
+
+                SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
+                SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
+                if (idpMetadata == null) {
+                    throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(),
+                            "IdP ID (" + idpId + ") is not found in our list of supported IdPs, cannot proceed.",
+                            params, responseType));
+                }
+                if (idpMetadata.getSsoUrl() == null || idpMetadata.getSsoUrl().isEmpty()) {
+                    throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(),
+                            "IdP ID (" + idpId + ") has no Single Sign On URL defined please contact "
+                                    + idpMetadata.getContactPersonName() + " <" + idpMetadata.getContactPersonEmail() + ">, cannot proceed.",
+                            params, responseType));
+                }
+                String authnId = SAMLUtils.generateSecureRandomId();
+                _samlAuthManager.saveToken(authnId, domainPath, idpMetadata.getEntityId());
+                s_logger.debug("Sending SAMLRequest id=" + authnId);
+                String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value());
                 resp.sendRedirect(redirectUrl);
                 return "";
             } if (params.containsKey("SAMLart")) {
@@ -182,7 +187,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
                         "SAML2 HTTP Artifact Binding is not supported",
                         params, responseType));
             } else {
-                final String samlResponse = ((String[])params.get(SAMLUtils.SAML_RESPONSE))[0];
+                final String samlResponse = ((String[])params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
                 Response processedSAMLResponse = this.processSAMLResponse(samlResponse);
                 String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
                 if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
@@ -191,10 +196,37 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
                             params, responseType));
                 }
 
-                if (_samlAuthManager.getIdpSigningKey() != null) {
-                    org.opensaml.xml.signature.Signature sig = processedSAMLResponse.getSignature();
+                String username = null;
+                Long domainId = null;
+                Issuer issuer = processedSAMLResponse.getIssuer();
+                SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
+                SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(issuer.getValue());
+
+                String responseToId = processedSAMLResponse.getInResponseTo();
+                s_logger.debug("Received SAMLResponse in response to id=" + responseToId);
+                SAMLTokenVO token = _samlAuthManager.getToken(responseToId);
+                if (token != null) {
+                    if (token.getDomainId() != null) {
+                        domainId = token.getDomainId();
+                    }
+                    if (!(token.getEntity().equalsIgnoreCase(issuer.getValue()))) {
+                        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                                "The SAML response contains Issuer Entity ID that is different from the original SAML request",
+                                params, responseType));
+                    }
+                } else {
+                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                            "Received SAML response for a SSO request that we may not have made or has expired, please try logging in again",
+                            params, responseType));
+                }
+
+                // Set IdpId for this session
+                session.setAttribute(SAMLPluginConstants.SAML_IDPID, issuer.getValue());
+
+                Signature sig = processedSAMLResponse.getSignature();
+                if (idpMetadata.getSigningCertificate() != null && sig != null) {
                     BasicX509Credential credential = new BasicX509Credential();
-                    credential.setEntityCertificate(_samlAuthManager.getIdpSigningKey());
+                    credential.setEntityCertificate(idpMetadata.getSigningCertificate());
                     SignatureValidator validator = new SignatureValidator(credential);
                     try {
                         validator.validate(sig);
@@ -205,94 +237,106 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
                                 params, responseType));
                     }
                 }
-
-                String domainString = _configDao.getValue(Config.SAMLUserDomain.key());
-
-                Long domainId = null;
-                Domain domain = _domainMgr.getDomain(domainString);
-                if (domain != null) {
-                    domainId = domain.getId();
-                } else {
-                    try {
-                        domainId = Long.parseLong(domainString);
-                    } catch (NumberFormatException ignore) {
-                    }
-                }
-                if (domainId == null) {
-                    s_logger.error("The default domain ID for SAML users is not set correct, it should be a UUID. ROOT domain will be used.");
+                if (username == null) {
+                    username = SAMLUtils.getValueFromAssertions(processedSAMLResponse.getAssertions(), SAML2AuthManager.SAMLUserAttributeName.value());
                 }
 
-                String username = null;
-                String password = SAMLUtils.generateSecureRandomId(); // Random password
-                String firstName = "";
-                String lastName = "";
-                String timeZone = "GMT";
-                String email = "";
-                short accountType = 0; // User account
-
-                Assertion assertion = processedSAMLResponse.getAssertions().get(0);
-                NameID nameId = assertion.getSubject().getNameID();
-                String sessionIndex = assertion.getAuthnStatements().get(0).getSessionIndex();
-                session.setAttribute(SAMLUtils.SAML_NAMEID, nameId);
-                session.setAttribute(SAMLUtils.SAML_SESSION, sessionIndex);
-
-                if (nameId.getFormat().equals(NameIDType.PERSISTENT) || nameId.getFormat().equals(NameIDType.EMAIL)) {
-                    username = nameId.getValue();
-                    if (nameId.getFormat().equals(NameIDType.EMAIL)) {
-                        email = username;
+                for (Assertion assertion: processedSAMLResponse.getAssertions()) {
+                    if (assertion!= null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
+                        session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
+                        break;
                     }
                 }
 
-                List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
-                if (attributeStatements != null && attributeStatements.size() > 0) {
-                    for (AttributeStatement attributeStatement: attributeStatements) {
-                        if (attributeStatement == null) {
-                            continue;
-                        }
-                        // Try capturing standard LDAP attributes
-                        for (Attribute attribute: attributeStatement.getAttributes()) {
-                            String attributeName = attribute.getName();
-                            String attributeValue = attribute.getAttributeValues().get(0).getDOM().getTextContent();
-                            if (attributeName.equalsIgnoreCase("uid") && username == null) {
-                                username = attributeValue;
-                            } else if (attributeName.equalsIgnoreCase("givenName")) {
-                                firstName = attributeValue;
-                            } else if (attributeName.equalsIgnoreCase(("sn"))) {
-                                lastName = attributeValue;
-                            } else if (attributeName.equalsIgnoreCase("mail")) {
-                                email = attributeValue;
+                if (idpMetadata.getEncryptionCertificate() != null && spMetadata != null
+                        && spMetadata.getKeyPair() != null && spMetadata.getKeyPair().getPrivate() != null) {
+                    Credential credential = SecurityHelper.getSimpleCredential(idpMetadata.getEncryptionCertificate().getPublicKey(),
+                            spMetadata.getKeyPair().getPrivate());
+                    StaticKeyInfoCredentialResolver keyInfoResolver = new StaticKeyInfoCredentialResolver(credential);
+                    EncryptedKeyResolver keyResolver = new InlineEncryptedKeyResolver();
+                    Decrypter decrypter = new Decrypter(null, keyInfoResolver, keyResolver);
+                    decrypter.setRootInNewDocument(true);
+                    List<EncryptedAssertion> encryptedAssertions = processedSAMLResponse.getEncryptedAssertions();
+                    if (encryptedAssertions != null) {
+                        for (EncryptedAssertion encryptedAssertion : encryptedAssertions) {
+                            Assertion assertion = null;
+                            try {
+                                assertion = decrypter.decrypt(encryptedAssertion);
+                            } catch (DecryptionException e) {
+                                s_logger.warn("SAML EncryptedAssertion error: " + e.toString());
+                            }
+                            if (assertion == null) {
+                                continue;
+                            }
+                            Signature encSig = assertion.getSignature();
+                            if (idpMetadata.getSigningCertificate() != null && encSig != null) {
+                                BasicX509Credential sigCredential = new BasicX509Credential();
+                                sigCredential.setEntityCertificate(idpMetadata.getSigningCertificate());
+                                SignatureValidator validator = new SignatureValidator(sigCredential);
+                                try {
+                                    validator.validate(encSig);
+                                } catch (ValidationException e) {
+                                    s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
+                                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                                            "SAML Response's signature failed to be validated by IDP signing key",
+                                            params, responseType));
+                                }
+                            }
+                            if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
+                                session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
+                            }
+                            if (username == null) {
+                                username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());
                             }
                         }
                     }
                 }
 
-                if (username == null && email != null) {
-                    username = email;
+                if (username == null) {
+                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                            "Failed to find admin configured username attribute in the SAML Response. Please ask your administrator to check SAML user attribute name.", params, responseType));
                 }
-                final String uniqueUserId = SAMLUtils.createSAMLId(username);
 
-                UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId);
-                if (userAccount == null && uniqueUserId != null && username != null) {
-                    CallContext.current().setEventDetails("SAML Account/User with UserName: " + username + ", FirstName :" + password + ", LastName: " + lastName);
-                    userAccount = _accountService.createUserAccount(username, password, firstName, lastName, email, timeZone,
-                            username, (short) accountType, domainId, null, null, UUID.randomUUID().toString(), uniqueUserId);
+                UserAccount userAccount = null;
+                List<UserAccountVO> possibleUserAccounts = _userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue());
+                if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) {
+                    if (possibleUserAccounts.size() == 1) {
+                        userAccount = possibleUserAccounts.get(0);
+                    } else if (possibleUserAccounts.size() > 1) {
+                        if (domainId != null) {
+                            userAccount = _userAccountDao.getUserAccount(username, domainId);
+                        } else {
+                            throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                                    "You have accounts in multiple domains, please re-login by specifying the domain you want to log into.",
+                                    params, responseType));
+                        }
+                    }
+                }
+
+                if (userAccount == null || userAccount.getExternalEntity() == null || !_samlAuthManager.isUserAuthorized(userAccount.getId(), issuer.getValue())) {
+                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
+                            "Your authenticated user is not authorized, please contact your administrator",
+                            params, responseType));
                 }
 
                 if (userAccount != null) {
                     try {
                         if (_apiServer.verifyUser(userAccount.getId())) {
-                            LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, username, userAccount.getPassword(), domainId, null, remoteAddress, params);
+                            LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(),
+                                    userAccount.getDomainId(), null, remoteAddress, params);
                             resp.addCookie(new Cookie("userid", URLEncoder.encode(loginResponse.getUserId(), HttpUtils.UTF_8)));
                             resp.addCookie(new Cookie("domainid", URLEncoder.encode(loginResponse.getDomainId(), HttpUtils.UTF_8)));
                             resp.addCookie(new Cookie("role", URLEncoder.encode(loginResponse.getType(), HttpUtils.UTF_8)));
                             resp.addCookie(new Cookie("username", URLEncoder.encode(loginResponse.getUsername(), HttpUtils.UTF_8)));
-                            resp.addCookie(new Cookie("sessionkey", URLEncoder.encode(loginResponse.getSessionKey(), HttpUtils.UTF_8)));
+                            resp.addCookie(new Cookie(ApiConstants.SESSIONKEY, URLEncoder.encode(loginResponse.getSessionKey(), HttpUtils.UTF_8)));
                             resp.addCookie(new Cookie("account", URLEncoder.encode(loginResponse.getAccount(), HttpUtils.UTF_8)));
-                            resp.addCookie(new Cookie("timezone", URLEncoder.encode(loginResponse.getTimeZone(), HttpUtils.UTF_8)));
+                            String timezone = loginResponse.getTimeZone();
+                            if (timezone != null) {
+                                resp.addCookie(new Cookie("timezone", URLEncoder.encode(timezone, HttpUtils.UTF_8)));
+                            }
                             resp.addCookie(new Cookie("userfullname", URLEncoder.encode(loginResponse.getFirstName() + " " + loginResponse.getLastName(), HttpUtils.UTF_8).replace("+", "%20")));
-                            resp.sendRedirect(_configDao.getValue(Config.SAMLCloudStackRedirectionUrl.key()));
+                            resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
                             return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
-
                         }
                     } catch (final CloudAuthenticationException ignored) {
                     }
@@ -303,7 +347,7 @@ public class SAML2LoginAPIAuthenticatorCmd extends BaseCmd implements APIAuthent
             auditTrailSb.append(e.getMessage());
         }
         throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
-                "Unable to authenticate or retrieve user while performing SAML based SSO",
+                "Unable to authenticate user while performing SAML based SSO. Please make sure your user/account has been added, enable and authorized by the admin before you can authenticate. Please contact your administrator.",
                 params, responseType));
     }
 


[23/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Change the retry() method to return Answer.createUnsupportedCommandAnswer(command) instead of throwing an exception

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

This closes #546


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/96ad6f6c
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/96ad6f6c
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/96ad6f6c

Branch: refs/heads/reporter
Commit: 96ad6f6ccd0c18561172ef2e1cbcde28291a6df7
Parents: c601330
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 12:35:43 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:58 2015 +0200

----------------------------------------------------------------------
 .../src/com/cloud/network/utils/CommandRetryUtility.java       | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/96ad6f6c/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
index 4969db8..92c198a 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
@@ -27,13 +27,11 @@ import org.apache.log4j.Logger;
 
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
-import com.cloud.network.resource.NiciraNvpResource;
 import com.cloud.resource.ServerResource;
-import com.cloud.utils.exception.CloudRuntimeException;
 
 public class CommandRetryUtility {
 
-    private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
+    private static final Logger s_logger = Logger.getLogger(CommandRetryUtility.class);
 
     private static final int ZERO = 0;
     private static CommandRetryUtility instance;
@@ -85,7 +83,7 @@ public class CommandRetryUtility {
             final Constructor<? extends Answer> answerConstructor = answerClass.getConstructor(Command.class, Exception.class);
             return answerConstructor.newInstance(command, error);
         } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
-            throw new CloudRuntimeException(e);
+            return Answer.createUnsupportedCommandAnswer(command);
         }
     }
 }
\ No newline at end of file


[49/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8583 : fixing issue related to script test/integration/component/test_stopped_vm.py
This closes #567


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/616b0117
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/616b0117
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/616b0117

Branch: refs/heads/reporter
Commit: 616b0117cfd86724b5287d9de385ffce43f75789
Parents: 820a406
Author: nitt10prashant <ni...@gmail.com>
Authored: Wed Jul 8 14:42:24 2015 +0530
Committer: sanjeev <sa...@apache.org>
Committed: Wed Jul 8 16:08:14 2015 +0530

----------------------------------------------------------------------
 test/integration/component/test_stopped_vm.py | 2 --
 1 file changed, 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/616b0117/test/integration/component/test_stopped_vm.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_stopped_vm.py b/test/integration/component/test_stopped_vm.py
index bda0fe2..f83c47e 100644
--- a/test/integration/component/test_stopped_vm.py
+++ b/test/integration/component/test_stopped_vm.py
@@ -141,7 +141,6 @@ class TestDeployVM(cloudstackTestCase):
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
-            diskofferingid=self.disk_offering.id,
             mode=self.zone.networktype
         )
 
@@ -1061,7 +1060,6 @@ class TestRouterStateAfterDeploy(cloudstackTestCase):
             accountid=self.account.name,
             domainid=self.account.domainid,
             serviceofferingid=self.service_offering.id,
-            diskofferingid=self.disk_offering.id,
             startvm=False
         )
 


[28/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Adding support to update host passwd on XenServer hypervisors

   - Adding update_host_passwd to VRScripts
   - Add accessor method to host password on CitrixResourceBase
   - Add implementation to CitrixUpdateHostPasswordCommandWrapper
   - Improve testUpdateHostPasswordCommand() unit test on CitrixRequestWrapperTest
   - Add line to patch files on xenserver directory

Concerning the LibVirt change:

   - I forgot to assing the return of the getDefaultHypervisorScriptsDir() method to the hypervisorScriptsDir variable


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/0dd02ce0
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0dd02ce0
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0dd02ce0

Branch: refs/heads/reporter
Commit: 0dd02ce04341b8026f49fd84be01bfcb7f18bf3d
Parents: 47c7a10
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri Jul 3 10:24:44 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Fri Jul 3 10:24:44 2015 +0200

----------------------------------------------------------------------
 .../resource/virtualnetwork/VRScripts.java      |   1 +
 .../kvm/resource/LibvirtComputingResource.java  |   6 +-
 .../xenserver/resource/CitrixResourceBase.java  | 132 ++++++++++---------
 .../CitrixUpdateHostPasswordCommandWrapper.java |  30 ++++-
 .../xenbase/CitrixRequestWrapperTest.java       |  15 ++-
 scripts/vm/hypervisor/kvm/update_host_passwd.sh |  24 ++++
 scripts/vm/hypervisor/update_host_passwd.sh     |  25 ----
 .../hypervisor/xenserver/update_host_passwd.sh  |  24 ++++
 scripts/vm/hypervisor/xenserver/xcpserver/patch |   1 +
 .../vm/hypervisor/xenserver/xenserver56/patch   |   1 +
 .../hypervisor/xenserver/xenserver56fp1/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver60/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver62/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver65/patch   |   1 +
 14 files changed, 168 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
index b915ce6..109801c 100644
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VRScripts.java
@@ -74,6 +74,7 @@ public class VRScripts {
     public static final String VPC_STATIC_NAT = "vpc_staticnat.sh";
     public static final String VPC_STATIC_ROUTE = "vpc_staticroute.sh";
     public static final String VPN_L2TP = "vpn_l2tp.sh";
+    public static final String UPDATE_HOST_PASSWD = "update_host_passwd.sh";
 
     public static final String VR_CFG = "vr_cfg.sh";
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index bc28f82..782ea28 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -523,7 +523,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     }
 
     protected String getDefaultHypervisorScriptsDir() {
-        return "scripts/vm/hypervisor";
+        return "scripts/vm/hypervisor/kvm";
     }
 
     protected String getDefaultKvmScriptsDir() {
@@ -557,9 +557,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             domrScriptsDir = getDefaultDomrScriptsDir();
         }
 
-        final String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir");
+        String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir");
         if (hypervisorScriptsDir == null) {
-            getDefaultHypervisorScriptsDir();
+            hypervisorScriptsDir = getDefaultHypervisorScriptsDir();
         }
 
         String kvmScriptsDir = (String)params.get("kvm.scripts.dir");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
index 8ed4ffc..24970a6 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
@@ -20,9 +20,9 @@ import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
 import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -275,6 +275,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         _password.add(password);
     }
 
+    public String getPwdFromQueue() {
+        return _password.peek();
+    }
+
     protected StorageSubsystemCommandHandler buildStorageHandler() {
         final XenServerStorageProcessor processor = new XenServerStorageProcessor(this);
         return new StorageSubsystemCommandHandlerBase(processor);
@@ -3163,9 +3167,9 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
     public long getVMSnapshotChainSize(final Connection conn, final VolumeObjectTO volumeTo, final String vmName) throws BadServerResponse, XenAPIException, XmlRpcException {
         if (volumeTo.getVolumeType() == Volume.Type.DATADISK) {
-            VDI dataDisk = VDI.getByUuid(conn, volumeTo.getPath());
+            final VDI dataDisk = VDI.getByUuid(conn, volumeTo.getPath());
             if (dataDisk != null) {
-                String dataDiskName = dataDisk.getNameLabel(conn);
+                final String dataDiskName = dataDisk.getNameLabel(conn);
                 if (dataDiskName != null && !dataDiskName.isEmpty()) {
                     volumeTo.setName(dataDiskName);
                 }
@@ -4958,12 +4962,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
     }
 
-    public boolean createAndAttachConfigDriveIsoForVM(Connection conn, VM vm, List<String[]> vmDataList, String configDriveLabel) throws XenAPIException, XmlRpcException {
+    public boolean createAndAttachConfigDriveIsoForVM(final Connection conn, final VM vm, final List<String[]> vmDataList, final String configDriveLabel) throws XenAPIException, XmlRpcException {
 
-        String vmName = vm.getNameLabel(conn);
+        final String vmName = vm.getNameLabel(conn);
 
         // create SR
-        SR sr =  createLocalIsoSR(conn, _configDriveSRName+_host.getIp());
+        final SR sr =  createLocalIsoSR(conn, _configDriveSRName+_host.getIp());
         if (sr == null) {
             s_logger.debug("Failed to create local SR for the config drive");
             return false;
@@ -4989,57 +4993,57 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return true;
     }
 
-    public boolean createVmdataFiles(String vmName, List<String[]> vmDataList, String configDriveLabel) {
+    public boolean createVmdataFiles(final String vmName, final List<String[]> vmDataList, final String configDriveLabel) {
 
         // add vm iso to the isolibrary
-        String isoPath = "/tmp/"+vmName+"/configDrive/";
-        String configDriveName = "cloudstack/";
+        final String isoPath = "/tmp/"+vmName+"/configDrive/";
+        final String configDriveName = "cloudstack/";
 
         //create folder for the VM
         //Remove the folder before creating it.
 
         try {
             deleteLocalFolder("/tmp/"+isoPath);
-        } catch (IOException e) {
+        } catch (final IOException e) {
             s_logger.debug("Failed to delete the exiting config drive for vm "+vmName+ " "+ e.getMessage());
-        } catch (Exception e) {
+        } catch (final Exception e) {
             s_logger.debug("Failed to delete the exiting config drive for vm "+vmName+ " "+ e.getMessage());
         }
 
 
         if (vmDataList != null) {
-            for (String[] item : vmDataList) {
-                String dataType = item[0];
-                String fileName = item[1];
-                String content = item[2];
+            for (final String[] item : vmDataList) {
+                final String dataType = item[0];
+                final String fileName = item[1];
+                final String content = item[2];
 
                 // create file with content in folder
 
                 if (dataType != null && !dataType.isEmpty()) {
                     //create folder
-                    String  folder = isoPath+configDriveName+dataType;
+                    final String  folder = isoPath+configDriveName+dataType;
                     if (folder != null && !folder.isEmpty()) {
-                        File dir = new File(folder);
-                        boolean result = true;
+                        final File dir = new File(folder);
+                        final boolean result = true;
 
                         try {
                             if (!dir.exists()) {
                                 dir.mkdirs();
                             }
-                        }catch (SecurityException ex) {
+                        }catch (final SecurityException ex) {
                             s_logger.debug("Failed to create dir "+ ex.getMessage());
                             return false;
                         }
 
                         if (result && content != null && !content.isEmpty()) {
                             try {
-                                File file = new File(folder+"/"+fileName+".txt");
-                                OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()),"UTF-8");
-                                BufferedWriter bw = new BufferedWriter(fw);
+                                final File file = new File(folder+"/"+fileName+".txt");
+                                final OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file.getAbsoluteFile()),"UTF-8");
+                                final BufferedWriter bw = new BufferedWriter(fw);
                                 bw.write(content);
                                 bw.close();
                                 s_logger.debug("created file: "+ file + " in folder:"+folder);
-                            } catch (IOException ex) {
+                            } catch (final IOException ex) {
                                 s_logger.debug("Failed to create file "+ ex.getMessage());
                                 return false;
                             }
@@ -5053,13 +5057,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         String s = null;
         try {
 
-            String cmd =  "mkisofs -iso-level 3 -V "+ configDriveLabel +" -o "+ isoPath+vmName +".iso " + isoPath;
-            Process p = Runtime.getRuntime().exec(cmd);
+            final String cmd =  "mkisofs -iso-level 3 -V "+ configDriveLabel +" -o "+ isoPath+vmName +".iso " + isoPath;
+            final Process p = Runtime.getRuntime().exec(cmd);
 
-            BufferedReader stdInput = new BufferedReader(new
+            final BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(p.getInputStream(),Charset.defaultCharset()));
 
-            BufferedReader stdError = new BufferedReader(new
+            final BufferedReader stdError = new BufferedReader(new
                     InputStreamReader(p.getErrorStream(),Charset.defaultCharset()));
 
             // read the output from the command
@@ -5072,7 +5076,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 s_logger.debug(s);
             }
             s_logger.debug(" Created config drive ISO using the command " + cmd +" in the host "+ _host.getIp());
-        } catch (IOException e) {
+        } catch (final IOException e) {
             s_logger.debug(e.getMessage());
             return false;
         }
@@ -5080,11 +5084,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return true;
     }
 
-    public boolean copyConfigDriveIsoToHost(Connection conn, SR sr, String vmName) {
+    public boolean copyConfigDriveIsoToHost(final Connection conn, final SR sr, final String vmName) {
 
-        String vmIso = "/tmp/"+vmName+"/configDrive/"+vmName+".iso";
+        final String vmIso = "/tmp/"+vmName+"/configDrive/"+vmName+".iso";
         //scp file into the host
-        com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
+        final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
 
         try {
             sshConnection.connect(null, 60000, 60000);
@@ -5093,28 +5097,28 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             }
 
             s_logger.debug("scp config drive iso file "+vmIso +" to host " + _host.getIp() +" path "+_configDriveIsopath);
-            SCPClient scp = new SCPClient(sshConnection);
-            String p = "0755";
+            final SCPClient scp = new SCPClient(sshConnection);
+            final String p = "0755";
 
             scp.put(vmIso, _configDriveIsopath, p);
             sr.scan(conn);
             s_logger.debug("copied config drive iso to host " + _host);
-        } catch (IOException e) {
+        } catch (final IOException e) {
             s_logger.debug("failed to copy configdrive iso " + vmIso + " to host " + _host, e);
             return false;
-        } catch (XmlRpcException e) {
+        } catch (final XmlRpcException e) {
             s_logger.debug("Failed to scan config drive iso SR "+ _configDriveSRName+_host.getIp() + " in host "+ _host, e);
             return false;
         } finally {
             sshConnection.close();
             //clean up the config drive files
 
-            String configDir = "/tmp/"+vmName;
+            final String configDir = "/tmp/"+vmName;
             try {
                 deleteLocalFolder(configDir);
                 s_logger.debug("Successfully cleaned up config drive directory " + configDir
                         + " after copying it to host ");
-            } catch (Exception e) {
+            } catch (final Exception e) {
                 s_logger.debug("Failed to delete config drive folder :" + configDir + " for VM " + vmName + " "
                         + e.getMessage());
             }
@@ -5123,10 +5127,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return true;
     }
 
-    public boolean attachConfigDriveIsoToVm(Connection conn, VM vm) throws XenAPIException, XmlRpcException {
+    public boolean attachConfigDriveIsoToVm(final Connection conn, final VM vm) throws XenAPIException, XmlRpcException {
 
-        String vmName = vm.getNameLabel(conn);
-        String isoURL = _configDriveIsopath + vmName+".iso";
+        final String vmName = vm.getNameLabel(conn);
+        final String isoURL = _configDriveIsopath + vmName+".iso";
         VDI srVdi;
 
         //1. find the vdi of the iso
@@ -5134,16 +5138,16 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         //3. attach iso to vm
 
         try {
-            Set<VDI> vdis = VDI.getByNameLabel(conn, vmName+".iso");
+            final Set<VDI> vdis = VDI.getByNameLabel(conn, vmName+".iso");
             if (vdis.isEmpty()) {
                 throw new CloudRuntimeException("Could not find ISO with URL: " + isoURL);
             }
             srVdi =  vdis.iterator().next();
 
-        } catch (XenAPIException e) {
+        } catch (final XenAPIException e) {
             s_logger.debug("Unable to get config drive iso: " + isoURL + " due to " + e.toString());
             return false;
-        } catch (Exception e) {
+        } catch (final Exception e) {
             s_logger.debug("Unable to get config drive iso: " + isoURL + " due to " + e.toString());
             return false;
         }
@@ -5151,11 +5155,11 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         VBD isoVBD = null;
 
         // Find the VM's CD-ROM VBD
-        Set<VBD> vbds = vm.getVBDs(conn);
-        for (VBD vbd : vbds) {
-            Types.VbdType type = vbd.getType(conn);
+        final Set<VBD> vbds = vm.getVBDs(conn);
+        for (final VBD vbd : vbds) {
+            final Types.VbdType type = vbd.getType(conn);
 
-            VBD.Record vbdr = vbd.getRecord(conn);
+            final VBD.Record vbdr = vbd.getRecord(conn);
 
             // if the device exists then attach it
             if (!vbdr.userdevice.equals(_attachIsoDeviceNum) && type == Types.VbdType.CD) {
@@ -5166,14 +5170,14 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
         if (isoVBD == null) {
             //create vbd
-            VBD.Record cfgDriveVbdr = new VBD.Record();
+            final VBD.Record cfgDriveVbdr = new VBD.Record();
             cfgDriveVbdr.VM = vm;
             cfgDriveVbdr.empty = true;
             cfgDriveVbdr.bootable = false;
             cfgDriveVbdr.userdevice = "autodetect";
             cfgDriveVbdr.mode = Types.VbdMode.RO;
             cfgDriveVbdr.type = Types.VbdType.CD;
-            VBD cfgDriveVBD = VBD.create(conn, cfgDriveVbdr);
+            final VBD cfgDriveVBD = VBD.create(conn, cfgDriveVbdr);
             isoVBD = cfgDriveVBD;
 
             s_logger.debug("Created CD-ROM VBD for VM: " + vm);
@@ -5189,7 +5193,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
                 // Insert the new ISO
                 isoVBD.insert(conn, srVdi);
                 s_logger.debug("Attached config drive iso to vm " + vmName);
-            }catch (XmlRpcException ex) {
+            }catch (final XmlRpcException ex) {
                 s_logger.debug("Failed to attach config drive iso to vm " + vmName);
                 return false;
             }
@@ -5198,7 +5202,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return true;
     }
 
-    public SR createLocalIsoSR(Connection conn, String srName) throws XenAPIException, XmlRpcException {
+    public SR createLocalIsoSR(final Connection conn, final String srName) throws XenAPIException, XmlRpcException {
 
         // if config drive sr already exists then return
         SR sr = getSRByNameLabelandHost(conn, _configDriveSRName+_host.getIp());
@@ -5209,20 +5213,20 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
 
         try{
-            Map<String, String> deviceConfig = new HashMap<String, String>();
+            final Map<String, String> deviceConfig = new HashMap<String, String>();
 
-            com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
+            final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(_host.getIp(), 22);
             try {
                 sshConnection.connect(null, 60000, 60000);
                 if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                     throw new CloudRuntimeException("Unable to authenticate");
                 }
 
-                String cmd = "mkdir -p " + _configDriveIsopath;
+                final String cmd = "mkdir -p " + _configDriveIsopath;
                 if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) {
                     throw new CloudRuntimeException("Cannot create directory configdrive_iso on XenServer hosts");
                 }
-            } catch (IOException e) {
+            } catch (final IOException e) {
                 throw new CloudRuntimeException("Unable to create iso folder", e);
             } finally {
                 sshConnection.close();
@@ -5231,8 +5235,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
             deviceConfig.put("location",  _configDriveIsopath);
             deviceConfig.put("legacy_mode", "true");
-            Host host = Host.getByUuid(conn, _host.getUuid());
-            String type = SRType.ISO.toString();
+            final Host host = Host.getByUuid(conn, _host.getUuid());
+            final String type = SRType.ISO.toString();
             sr = SR.create(conn, host, deviceConfig, new Long(0),  _configDriveIsopath, "iso", type, "iso", false, new HashMap<String, String>());
 
             sr.setNameLabel(conn, srName);
@@ -5241,12 +5245,12 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             sr.scan(conn);
             s_logger.debug("Config drive ISO SR at the path " + _configDriveIsopath  +" got created in host " + _host);
             return sr;
-        } catch (XenAPIException e) {
-            String msg = "createLocalIsoSR failed! mountpoint " + e.toString();
+        } catch (final XenAPIException e) {
+            final String msg = "createLocalIsoSR failed! mountpoint " + e.toString();
             s_logger.warn(msg, e);
             throw new CloudRuntimeException(msg, e);
-        } catch (Exception e) {
-            String msg = "createLocalIsoSR failed! mountpoint:  due to " + e.getMessage();
+        } catch (final Exception e) {
+            final String msg = "createLocalIsoSR failed! mountpoint:  due to " + e.getMessage();
             s_logger.warn(msg, e);
             throw new CloudRuntimeException(msg, e);
         }
@@ -5254,16 +5258,16 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
     }
 
 
-    public void deleteLocalFolder(String directory) throws Exception {
+    public void deleteLocalFolder(final String directory) throws Exception {
         if (directory == null || directory.isEmpty()) {
-            String msg = "Invalid directory path (null/empty) detected. Cannot delete specified directory.";
+            final String msg = "Invalid directory path (null/empty) detected. Cannot delete specified directory.";
             s_logger.debug(msg);
             throw new Exception(msg);
         }
 
         try {
             FileUtils.deleteDirectory(new File(directory));
-        } catch (IOException e) {
+        } catch (final IOException e) {
             // IOException here means failure to delete. Not swallowing it here to
             // let the caller handle with appropriate contextual log message.
             throw e;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
index d95ba7a..7d0c99a 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
@@ -19,18 +19,46 @@
 
 package com.cloud.hypervisor.xenserver.resource.wrapper.xenbase;
 
+import org.apache.log4j.Logger;
+
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.UpdateHostPasswordCommand;
+import com.cloud.agent.resource.virtualnetwork.VRScripts;
 import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.ResourceWrapper;
+import com.cloud.utils.Pair;
+import com.cloud.utils.ssh.SshHelper;
 
 @ResourceWrapper(handles =  UpdateHostPasswordCommand.class)
 public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, CitrixResourceBase> {
 
+    private static final Logger s_logger = Logger.getLogger(CitrixUpdateHostPasswordCommandWrapper.class);
+    private static final int TIMEOUT = 10000;
+
     @Override
     public Answer execute(final UpdateHostPasswordCommand command, final CitrixResourceBase citrixResourceBase) {
+        final String hostIp = command.getHostIp();
+        final String username = command.getUsername();
+        final String newPassword = command.getNewPassword();
+
+        final StringBuffer cmdLine = new StringBuffer();
+        cmdLine.append(VRScripts.UPDATE_HOST_PASSWD);
+        cmdLine.append(' ');
+        cmdLine.append(username);
+        cmdLine.append(' ');
+        cmdLine.append(newPassword);
+
+        Pair<Boolean, String> result;
+
+        try {
+            s_logger.debug("Executing command in Host: " + cmdLine);
+            result = SshHelper.sshExecute(hostIp, 22, username, null, citrixResourceBase.getPwdFromQueue(), cmdLine.toString(), 60000, 60000, TIMEOUT);
+        } catch (final Exception e) {
+            return new Answer(command, false, e.getMessage());
+        }
+        // Add new password to the stack.
         citrixResourceBase.addToPwdQueue(command.getNewPassword());
-        return new Answer(command, true, null);
+        return new Answer(command, result.first(), result.second());
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
index 5948303..91f59be 100644
--- a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
+++ b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
@@ -118,6 +118,7 @@ import com.cloud.agent.api.to.IpAddressTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
+import com.cloud.agent.resource.virtualnetwork.VRScripts;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.host.HostEnvironment;
 import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
@@ -129,6 +130,7 @@ import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.VMTemplateStorageResourceAssoc;
 import com.cloud.storage.resource.StorageSubsystemCommandHandler;
+import com.cloud.utils.ExecutionResult;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.xensource.xenapi.Connection;
@@ -1320,14 +1322,23 @@ public class CitrixRequestWrapperTest {
 
     @Test
     public void testUpdateHostPasswordCommand() {
-        final UpdateHostPasswordCommand updatePwd = new UpdateHostPasswordCommand("test", "123");
+        final ExecutionResult executionResult = Mockito.mock(ExecutionResult.class);
+
+        final UpdateHostPasswordCommand updatePwd = new UpdateHostPasswordCommand("test", "123", "127.0.0.1");
+
+        final StringBuffer buff = new StringBuffer();
+        buff.append(updatePwd.getUsername());
+        buff.append(' ');
+        buff.append(updatePwd.getNewPassword());
+
+        when(citrixResourceBase.executeInVR(updatePwd.getHostIp(), VRScripts.UPDATE_HOST_PASSWD, buff.toString())).thenReturn(executionResult);
 
         final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(updatePwd, citrixResourceBase);
 
-        assertTrue(answer.getResult());
+        assertFalse(answer.getResult());
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/kvm/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/kvm/update_host_passwd.sh b/scripts/vm/hypervisor/kvm/update_host_passwd.sh
new file mode 100755
index 0000000..39e4a3b
--- /dev/null
+++ b/scripts/vm/hypervisor/kvm/update_host_passwd.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+username=$1
+new_passwd=$2
+
+echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username
+
+return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/update_host_passwd.sh b/scripts/vm/hypervisor/update_host_passwd.sh
deleted file mode 100755
index 7d4eec5..0000000
--- a/scripts/vm/hypervisor/update_host_passwd.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/bash
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF 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.
-
-hostIp=$1
-username=$2
-new_passwd=$3
-
-ssh -o StrictHostKeyChecking=no -p 3922 -i /root/.ssh/id_rsa.cloud root@$hostIp "echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username"
-
-return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/update_host_passwd.sh b/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
new file mode 100755
index 0000000..39e4a3b
--- /dev/null
+++ b/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+username=$1
+new_passwd=$2
+
+echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username
+
+return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xcpserver/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xcpserver/patch b/scripts/vm/hypervisor/xenserver/xcpserver/patch
index 0f9d9a0..62e15e3 100644
--- a/scripts/vm/hypervisor/xenserver/xcpserver/patch
+++ b/scripts/vm/hypervisor/xenserver/xcpserver/patch
@@ -59,3 +59,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xenserver56/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch
index e24136d..2145b31 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch
@@ -63,3 +63,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
index 5e15598..60404dc 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
@@ -62,3 +62,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xenserver60/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver60/patch b/scripts/vm/hypervisor/xenserver/xenserver60/patch
index 84472a6..c22d469 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver60/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver60/patch
@@ -68,3 +68,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xenserver62/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver62/patch b/scripts/vm/hypervisor/xenserver/xenserver62/patch
index 939e97c..0901924 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver62/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver62/patch
@@ -64,3 +64,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0dd02ce0/scripts/vm/hypervisor/xenserver/xenserver65/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver65/patch b/scripts/vm/hypervisor/xenserver/xenserver65/patch
index 939e97c..0901924 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver65/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver65/patch
@@ -64,3 +64,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file


[07/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
saml2: Use UTF-8 based charset for encoding bytes to strings

This fixes the fingbug issue DM_DEFAULT_ENCODING found in SAMLUtils

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/02c3d14f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/02c3d14f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/02c3d14f

Branch: refs/heads/reporter
Commit: 02c3d14f6ebef56c21a56297c82eda4deb0c7855
Parents: 3ff92e8
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Mon Jun 29 17:46:35 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon Jun 29 17:46:35 2015 +0200

----------------------------------------------------------------------
 .../saml2/src/org/apache/cloudstack/saml/SAMLUtils.java     | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/02c3d14f/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
index 0216ad7..77714a1 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
@@ -73,6 +73,7 @@ import java.io.StringWriter;
 import java.io.UnsupportedEncodingException;
 import java.math.BigInteger;
 import java.net.URLEncoder;
+import java.nio.charset.Charset;
 import java.security.InvalidKeyException;
 import java.security.KeyFactory;
 import java.security.KeyPair;
@@ -214,7 +215,7 @@ public class SAMLUtils {
         Deflater deflater = new Deflater(Deflater.DEFLATED, true);
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
-        deflaterOutputStream.write(requestMessage.getBytes());
+        deflaterOutputStream.write(requestMessage.getBytes(Charset.forName("UTF-8")));
         deflaterOutputStream.close();
         String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
         encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
@@ -258,7 +259,7 @@ public class SAMLUtils {
         String url = urlEncodedString + "&SigAlg=" + URLEncoder.encode(opensamlAlgoIdSignature, HttpUtils.UTF_8);
         Signature signature = Signature.getInstance(javaSignatureAlgorithmName);
         signature.initSign(signingKey);
-        signature.update(url.getBytes());
+        signature.update(url.getBytes(Charset.forName("UTF-8")));
         String signatureString = Base64.encodeBytes(signature.sign(), Base64.DONT_BREAK_LINES);
         if (signatureString != null) {
             return url + "&Signature=" + URLEncoder.encode(signatureString, HttpUtils.UTF_8);
@@ -282,7 +283,7 @@ public class SAMLUtils {
             KeyFactory keyFactory = SAMLUtils.getKeyFactory();
             if (keyFactory == null) return null;
             X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
-            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
+            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8"));
         } catch (InvalidKeySpecException e) {
             s_logger.error("Unable to create KeyFactory:" + e.getMessage());
         }
@@ -295,7 +296,7 @@ public class SAMLUtils {
             if (keyFactory == null) return null;
             PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key,
                     PKCS8EncodedKeySpec.class);
-            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
+            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()), Charset.forName("UTF-8"));
         } catch (InvalidKeySpecException e) {
             s_logger.error("Unable to create KeyFactory:" + e.getMessage());
         }


[42/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
findbugs equals(obj) implementations go against the contract these are removed from the call into separate calls

Signed-off-by: Daan Hoogland <da...@onecht.net>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/34629446
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/34629446
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/34629446

Branch: refs/heads/reporter
Commit: 34629446b6db162f6b358c2bb042b7c3844003fd
Parents: 4bba499
Author: Daan Hoogland <da...@onecht.net>
Authored: Fri Jun 26 16:06:17 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Tue Jul 7 13:48:19 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/storage/BaseType.java  | 19 ++++++++++++-------
 .../cloudstack/framework/config/ConfigKey.java   |  7 +++++++
 utils/src/com/cloud/utils/net/Ip.java            |  7 +++++++
 utils/src/com/cloud/utils/net/Ip4Address.java    | 14 +++++++++++---
 4 files changed, 37 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/34629446/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
index d92dd8d..6d27772 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
@@ -23,18 +23,23 @@ public abstract class BaseType {
     public boolean equals(Object that) {
         if (this == that) {
             return true;
-        }
-        if (that instanceof String) {
-            if (this.toString().equalsIgnoreCase((String)that)) {
-                return true;
-            }
         } else if (that instanceof BaseType) {
             BaseType th = (BaseType)that;
             if (this.toString().equalsIgnoreCase(th.toString())) {
                 return true;
             }
-        } else {
-            return false;
+        }
+        return false;
+    }
+
+    public boolean isSameTypeAs(Object that) {
+        if (this.equals(that)){
+            return true;
+        }
+        if (that instanceof String) {
+            if (this.toString().equalsIgnoreCase((String)that)) {
+                return true;
+            }
         }
         return false;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/34629446/framework/config/src/org/apache/cloudstack/framework/config/ConfigKey.java
----------------------------------------------------------------------
diff --git a/framework/config/src/org/apache/cloudstack/framework/config/ConfigKey.java b/framework/config/src/org/apache/cloudstack/framework/config/ConfigKey.java
index d39bb5d..09e143e 100644
--- a/framework/config/src/org/apache/cloudstack/framework/config/ConfigKey.java
+++ b/framework/config/src/org/apache/cloudstack/framework/config/ConfigKey.java
@@ -122,6 +122,13 @@ public class ConfigKey<T> {
         if (obj instanceof ConfigKey) {
             ConfigKey<?> that = (ConfigKey<?>)obj;
             return this._name.equals(that._name);
+        }
+        return false;
+    }
+
+    public boolean isSameKeyAs(Object obj) {
+        if(this.equals(obj)) {
+            return true;
         } else if (obj instanceof String) {
             String key = (String)obj;
             return key.equals(_name);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/34629446/utils/src/com/cloud/utils/net/Ip.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/Ip.java b/utils/src/com/cloud/utils/net/Ip.java
index e479e21..09312bc 100644
--- a/utils/src/com/cloud/utils/net/Ip.java
+++ b/utils/src/com/cloud/utils/net/Ip.java
@@ -75,6 +75,13 @@ public class Ip implements Serializable, Comparable<Ip> {
     public boolean equals(Object obj) {
         if (obj instanceof Ip) {
             return ip == ((Ip)obj).ip;
+        }
+        return false;
+    }
+
+    public boolean isSameAddressAs(Object obj) {
+        if (this.equals(obj)) {
+            return true;
         } else if (obj instanceof String) {
             return ip == NetUtils.ip2Long((String)obj);
         } else if (obj instanceof Long) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/34629446/utils/src/com/cloud/utils/net/Ip4Address.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/Ip4Address.java b/utils/src/com/cloud/utils/net/Ip4Address.java
index 67fe6da..9712a1f 100644
--- a/utils/src/com/cloud/utils/net/Ip4Address.java
+++ b/utils/src/com/cloud/utils/net/Ip4Address.java
@@ -55,15 +55,23 @@ public class Ip4Address {
 
     @Override
     public boolean equals(Object that) {
-        if (that instanceof String) { // Assume that is an ip4 address in String form
-            return _addr.equals(that);
-        } else if (that instanceof Ip4Address) {
+
+        if (that instanceof Ip4Address) {
             Ip4Address ip4 = (Ip4Address)that;
             return this._addr.equals(ip4._addr) && (this._mac == ip4._mac || this._mac.equals(ip4._mac));
         } else {
             return false;
         }
     }
+
+    public boolean isSameAddressAs(Object other) {
+        if (other instanceof String) { // Assume that is an ip4 address in String form
+            return _addr.equals(other);
+        } else {
+            return this.equals(other);
+        }
+    }
+
     @Override
     public int hashCode(){
         return (int)(_mac.hashCode()*_addr.hashCode());


[18/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Adding NiciraNvpDeleteLogicalSwitchPortCommandWrapper

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b4ce81ab
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b4ce81ab
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b4ce81ab

Branch: refs/heads/reporter
Commit: b4ce81ab6ce2a007cc787f3658934cdd9745c359
Parents: 361ab5d
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 11:07:59 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:57 2015 +0200

----------------------------------------------------------------------
 .../resource/NiciraNvpRequestWrapper.java       |  1 +
 .../network/resource/NiciraNvpResource.java     | 16 +-----
 .../network/resource/NiciraNvpUtilities.java    |  1 +
 ...vpDeleteLogicalSwitchPortCommandWrapper.java | 54 ++++++++++++++++++++
 .../network/utils/CommandRetryUtility.java      |  1 +
 5 files changed, 58 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b4ce81ab/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
index 55f0c49..9d261b2 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
@@ -16,6 +16,7 @@
 // specific language governing permissions and limitations
 // under the License.
 //
+
 package com.cloud.network.resource;
 
 import java.util.Hashtable;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b4ce81ab/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 85faf9d..1fd19ea 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -40,8 +40,6 @@ import com.cloud.agent.api.CreateLogicalRouterAnswer;
 import com.cloud.agent.api.CreateLogicalRouterCommand;
 import com.cloud.agent.api.DeleteLogicalRouterAnswer;
 import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
 import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
 import com.cloud.agent.api.FindLogicalSwitchPortCommand;
 import com.cloud.agent.api.PingCommand;
@@ -207,9 +205,7 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof DeleteLogicalSwitchPortCommand) {
-            return executeRequest((DeleteLogicalSwitchPortCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof UpdateLogicalSwitchPortCommand) {
+        if (cmd instanceof UpdateLogicalSwitchPortCommand) {
             return executeRequest((UpdateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof FindLogicalSwitchPortCommand) {
             return executeRequest((FindLogicalSwitchPortCommand)cmd, NUM_RETRIES);
@@ -241,16 +237,6 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final DeleteLogicalSwitchPortCommand cmd, final int numRetries) {
-        try {
-            niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid());
-            return new DeleteLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + cmd.getLogicalSwitchPortUuid() + " deleted");
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, DeleteLogicalSwitchPortAnswer.class, e);
-        }
-    }
-
     private Answer executeRequest(final UpdateLogicalSwitchPortCommand cmd, final int numRetries) {
         final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
         final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b4ce81ab/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
index f63ca98..2ac79c8 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
@@ -16,6 +16,7 @@
 // specific language governing permissions and limitations
 // under the License.
 //
+
 package com.cloud.network.resource;
 
 import java.util.ArrayList;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b4ce81ab/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
new file mode 100644
index 0000000..834cccb
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchPortCommandWrapper.java
@@ -0,0 +1,54 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  DeleteLogicalSwitchPortCommand.class)
+public final class NiciraNvpDeleteLogicalSwitchPortCommandWrapper extends CommandWrapper<DeleteLogicalSwitchPortCommand, Answer, NiciraNvpResource> {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpDeleteLogicalSwitchPortCommandWrapper.class);
+
+    @Override
+    public Answer execute(final DeleteLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            niciraNvpApi.deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
+            return new DeleteLogicalSwitchPortAnswer(command, true, "Logical switch port " + command.getLogicalSwitchPortUuid() + " deleted");
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, DeleteLogicalSwitchPortAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b4ce81ab/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
index 6244821..4969db8 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
@@ -16,6 +16,7 @@
 // specific language governing permissions and limitations
 // under the License.
 //
+
 package com.cloud.network.utils;
 
 import java.lang.reflect.Constructor;


[13/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Refactoring NiciraNvpResource
   - Added NiciraNvpUtilities and NiciraNvpCreateLogicalSwitchCommandWrapper
   - Removing 1 execute methods form NiciraNvpResource
   - Added 1 unit test

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/27c9651b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/27c9651b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/27c9651b

Branch: refs/heads/reporter
Commit: 27c9651b324926f11ced1ccbee29877f310b016b
Parents: 6a51294
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 23 10:47:23 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:56 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 58 ++++++----------
 .../network/resource/NiciraNvpUtilities.java    | 42 +++++++++++
 ...iraNvpCreateLogicalSwitchCommandWrapper.java | 73 ++++++++++++++++++++
 .../resource/NiciraNvpRequestWrapperTest.java   | 41 +++++++++++
 4 files changed, 176 insertions(+), 38 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/27c9651b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 9af541f..5242154 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -38,8 +38,6 @@ import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
 import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
 import com.cloud.agent.api.CreateLogicalRouterAnswer;
 import com.cloud.agent.api.CreateLogicalRouterCommand;
-import com.cloud.agent.api.CreateLogicalSwitchAnswer;
-import com.cloud.agent.api.CreateLogicalSwitchCommand;
 import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
 import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
 import com.cloud.agent.api.DeleteLogicalRouterAnswer;
@@ -64,7 +62,6 @@ import com.cloud.network.nicira.DestinationNatRule;
 import com.cloud.network.nicira.L3GatewayAttachment;
 import com.cloud.network.nicira.LogicalRouter;
 import com.cloud.network.nicira.LogicalRouterPort;
-import com.cloud.network.nicira.LogicalSwitch;
 import com.cloud.network.nicira.LogicalSwitchPort;
 import com.cloud.network.nicira.Match;
 import com.cloud.network.nicira.NatRule;
@@ -76,21 +73,22 @@ import com.cloud.network.nicira.PatchAttachment;
 import com.cloud.network.nicira.RouterNextHop;
 import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
 import com.cloud.network.nicira.SourceNatRule;
-import com.cloud.network.nicira.TransportZoneBinding;
 import com.cloud.network.nicira.VifAttachment;
 import com.cloud.resource.ServerResource;
 
 public class NiciraNvpResource implements ServerResource {
-    private static final int NAME_MAX_LEN = 40;
 
     private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
 
+    public static final int NAME_MAX_LEN = 40;
+
     private String name;
     private String guid;
     private String zoneId;
     private int numRetries;
 
     private NiciraNvpApi niciraNvpApi;
+    private NiciraNvpUtilities niciraNvpUtilities;
 
     protected NiciraNvpApi createNiciraNvpApi() {
         return new NiciraNvpApi();
@@ -131,6 +129,8 @@ public class NiciraNvpResource implements ServerResource {
             throw new ConfigurationException("Unable to find admin password");
         }
 
+        niciraNvpUtilities = NiciraNvpUtilities.getInstance();
+
         niciraNvpApi = createNiciraNvpApi();
         niciraNvpApi.setControllerAddress(ip);
         niciraNvpApi.setAdminCredentials(adminuser, adminpass);
@@ -138,6 +138,18 @@ public class NiciraNvpResource implements ServerResource {
         return true;
     }
 
+    public NiciraNvpApi getNiciraNvpApi() {
+        return niciraNvpApi;
+    }
+
+    public NiciraNvpUtilities getNiciraNvpUtilities() {
+        return niciraNvpUtilities;
+    }
+
+    public int getNumRetries() {
+        return numRetries;
+    }
+
     @Override
     public boolean start() {
         return true;
@@ -202,9 +214,7 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof CreateLogicalSwitchCommand) {
-            return executeRequest((CreateLogicalSwitchCommand)cmd, numRetries);
-        } else if (cmd instanceof DeleteLogicalSwitchCommand) {
+        if (cmd instanceof DeleteLogicalSwitchCommand) {
             return executeRequest((DeleteLogicalSwitchCommand)cmd, numRetries);
         } else if (cmd instanceof CreateLogicalSwitchPortCommand) {
             return executeRequest((CreateLogicalSwitchPortCommand)cmd, numRetries);
@@ -242,34 +252,6 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final CreateLogicalSwitchCommand cmd, int numRetries) {
-        LogicalSwitch logicalSwitch = new LogicalSwitch();
-        logicalSwitch.setDisplayName(truncate("lswitch-" + cmd.getName(), NAME_MAX_LEN));
-        logicalSwitch.setPortIsolationEnabled(false);
-
-        // Set transport binding
-        final List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
-        ltzb.add(new TransportZoneBinding(cmd.getTransportUuid(), cmd.getTransportType()));
-        logicalSwitch.setTransportZones(ltzb);
-
-        // Tags set to scope cs_account and account name
-        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
-        tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
-        logicalSwitch.setTags(tags);
-
-        try {
-            logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch);
-            return new CreateLogicalSwitchAnswer(cmd, true, "Logicalswitch " + logicalSwitch.getUuid() + " created", logicalSwitch.getUuid());
-        } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new CreateLogicalSwitchAnswer(cmd, e);
-            }
-        }
-
-    }
-
     private Answer executeRequest(final DeleteLogicalSwitchCommand cmd, int numRetries) {
         try {
             niciraNvpApi.deleteLogicalSwitch(cmd.getLogicalSwitchUuid());
@@ -646,7 +628,7 @@ public class NiciraNvpResource implements ServerResource {
 
     }
 
-    private Answer retry(final Command cmd, final int numRetries) {
+    public Answer retry(final Command cmd, final int numRetries) {
         s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
         return executeRequest(cmd, numRetries);
     }
@@ -687,7 +669,7 @@ public class NiciraNvpResource implements ServerResource {
         return natRuleStr.toString();
     }
 
-    private String truncate(final String string, final int length) {
+    public String truncate(final String string, final int length) {
         if (string.length() <= length) {
             return string;
         } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/27c9651b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
new file mode 100644
index 0000000..69cacab
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
@@ -0,0 +1,42 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource;
+
+import com.cloud.network.nicira.LogicalSwitch;
+
+public class NiciraNvpUtilities {
+
+    private static NiciraNvpUtilities instance;
+
+    static {
+        instance = new NiciraNvpUtilities();
+    }
+
+    private NiciraNvpUtilities() {
+    }
+
+    public static NiciraNvpUtilities getInstance() {
+        return instance;
+    }
+
+    public LogicalSwitch createLogicalSwitch() {
+        final LogicalSwitch logicalSwitch = new LogicalSwitch();
+        return logicalSwitch;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/27c9651b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
new file mode 100644
index 0000000..6fc6cf0
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
@@ -0,0 +1,73 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalSwitchAnswer;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.TransportZoneBinding;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  CreateLogicalSwitchCommand.class)
+public final class NiciraNvpCreateLogicalSwitchCommandWrapper extends CommandWrapper<CreateLogicalSwitchCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final CreateLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
+        LogicalSwitch logicalSwitch = niciraNvpUtilities.createLogicalSwitch();
+        logicalSwitch.setDisplayName(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN));
+        logicalSwitch.setPortIsolationEnabled(false);
+
+        // Set transport binding
+        final List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
+        ltzb.add(new TransportZoneBinding(command.getTransportUuid(), command.getTransportType()));
+        logicalSwitch.setTransportZones(ltzb);
+
+        // Tags set to scope cs_account and account name
+        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+        tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
+        logicalSwitch.setTags(tags);
+
+        try {
+            final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+            logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch);
+            final String switchUuid = logicalSwitch.getUuid();
+            return new CreateLogicalSwitchAnswer(command, true, "Logicalswitch " + switchUuid + " created", switchUuid);
+        } catch (final NiciraNvpApiException e) {
+            int numRetries = niciraNvpResource.getNumRetries();
+            if (numRetries > 0) {
+                return niciraNvpResource.retry(command, --numRetries);
+            } else {
+                return new CreateLogicalSwitchAnswer(command, e);
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/27c9651b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index ba22d18..a7349ad 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -21,14 +21,20 @@ package com.cloud.network.resource;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
 
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateLogicalSwitchCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ReadyCommand;
+import com.cloud.network.nicira.LogicalSwitch;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
 
 public class NiciraNvpRequestWrapperTest {
 
@@ -58,4 +64,39 @@ public class NiciraNvpRequestWrapperTest {
 
         assertTrue(answer.getResult());
     }
+
+    @Test
+    public void testCreateLogicalSwitchCommandWrapper() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+        final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
+        final LogicalSwitch logicalSwitch = Mockito.mock(LogicalSwitch.class);
+
+        final String transportUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String transportType = "stt";
+        final String name = "logicalswitch";
+        final String ownerName = "owner";
+
+        final CreateLogicalSwitchCommand command = new CreateLogicalSwitchCommand(transportUuid, transportType, name, ownerName);
+
+        final String truncated = "lswitch-" + command.getName();
+
+        when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
+        when(niciraNvpUtilities.createLogicalSwitch()).thenReturn(logicalSwitch);
+        when(niciraNvpResource.truncate("lswitch-" + command.getName(), NiciraNvpResource.NAME_MAX_LEN)).thenReturn(truncated);
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            when(niciraNvpApi.createLogicalSwitch(logicalSwitch)).thenReturn(logicalSwitch);
+            when(logicalSwitch.getUuid()).thenReturn(transportUuid);
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file


[41/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
rats: licenses missing

Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4bba4994
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4bba4994
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4bba4994

Branch: refs/heads/reporter
Commit: 4bba499412c697cd5d244c90c8bd11475172265f
Parents: a71c985
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jul 6 17:04:26 2015 +0200
Committer: Daan Hoogland <da...@gmail.com>
Committed: Mon Jul 6 17:04:26 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/api/ApiCmdTestUtil.java   | 16 ++++++++++++++++
 .../command/admin/vpc/CreateVPCOfferingCmdTest.java | 16 ++++++++++++++++
 2 files changed, 32 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4bba4994/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java b/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
index ca4510d..43b8b68 100644
--- a/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
+++ b/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
@@ -1,3 +1,19 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api;
 
 import java.lang.reflect.Field;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4bba4994/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java b/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
index 99433ed..18a2882 100644
--- a/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
+++ b/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
@@ -1,3 +1,19 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.command.admin.vpc;
 
 import java.util.HashMap;


[22/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Adding remaining command wrappers

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/644458f5
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/644458f5
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/644458f5

Branch: refs/heads/reporter
Commit: 644458f5aca17e44381fd7393cefe7da42a56803
Parents: b541269
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 11:34:29 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:58 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 204 +------------------
 ...figurePortForwardingRulesCommandWrapper.java | 120 +++++++++++
 ...ciraNvpConfigurePublicIpsCommandWrapper.java |  60 ++++++
 ...vpConfigureStaticNatRulesCommandWrapper.java | 113 ++++++++++
 ...iraNvpDeleteLogicalRouterCommandWrapper.java |  50 +++++
 5 files changed, 349 insertions(+), 198 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/644458f5/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 776b512..df40db4 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -28,29 +28,17 @@ import org.apache.log4j.Logger;
 import com.cloud.agent.IAgentControl;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
-import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalRouterAnswer;
-import com.cloud.agent.api.DeleteLogicalRouterCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupNiciraNvpCommand;
-import com.cloud.agent.api.to.PortForwardingRuleTO;
-import com.cloud.agent.api.to.StaticNatRuleTO;
 import com.cloud.host.Host;
 import com.cloud.host.Host.Type;
 import com.cloud.network.nicira.ControlClusterStatus;
 import com.cloud.network.nicira.DestinationNatRule;
-import com.cloud.network.nicira.LogicalRouterPort;
 import com.cloud.network.nicira.Match;
 import com.cloud.network.nicira.NatRule;
 import com.cloud.network.nicira.NiciraNvpApi;
 import com.cloud.network.nicira.NiciraNvpApiException;
-import com.cloud.network.nicira.NiciraNvpList;
 import com.cloud.network.nicira.SourceNatRule;
 import com.cloud.network.utils.CommandRetryUtility;
 import com.cloud.resource.ServerResource;
@@ -185,21 +173,9 @@ public class NiciraNvpResource implements ServerResource {
         try {
             return wrapper.execute(cmd, this);
         } catch (final Exception e) {
-            //return Answer.createUnsupportedCommandAnswer(cmd);
-            // [TODO] Remove when all the commands are refactored.
+            s_logger.debug("Received unsupported command " + cmd.toString());
+            return Answer.createUnsupportedCommandAnswer(cmd);
         }
-
-        if (cmd instanceof DeleteLogicalRouterCommand) {
-            return executeRequest((DeleteLogicalRouterCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof ConfigureStaticNatRulesOnLogicalRouterCommand) {
-            return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof ConfigurePortForwardingRulesOnLogicalRouterCommand) {
-            return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand)cmd, NUM_RETRIES);
-        } else if (cmd instanceof ConfigurePublicIpsOnLogicalRouterCommand) {
-            return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand)cmd, NUM_RETRIES);
-        }
-        s_logger.debug("Received unsupported command " + cmd.toString());
-        return Answer.createUnsupportedCommandAnswer(cmd);
     }
 
     @Override
@@ -215,175 +191,7 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final DeleteLogicalRouterCommand cmd, final int numRetries) {
-        try {
-            niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid());
-            return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")");
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, DeleteLogicalRouterAnswer.class, e);
-        }
-    }
-
-    private Answer executeRequest(final ConfigurePublicIpsOnLogicalRouterCommand cmd, final int numRetries) {
-        try {
-            final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid());
-            if (ports.getResultCount() != 1) {
-                return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, false, "No logical router ports found, unable to set ip addresses");
-            }
-            final LogicalRouterPort lrp = ports.getResults().get(0);
-            lrp.setIpAddresses(cmd.getPublicCidrs());
-            niciraNvpApi.updateLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp);
-
-            return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " +
-                    cmd.getLogicalRouterUuid());
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, ConfigurePublicIpsOnLogicalRouterAnswer.class, e);
-        }
-    }
-
-    private Answer executeRequest(final ConfigureStaticNatRulesOnLogicalRouterCommand cmd, final int numRetries) {
-        try {
-            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
-            // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
-            // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
-            // Any other SourceNat rule should have a corresponding DestinationNat rule
-
-            for (final StaticNatRuleTO rule : cmd.getRules()) {
-
-                final NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
-
-                NatRule incoming = null;
-                NatRule outgoing = null;
-
-                for (final NatRule storedRule : existingRules.getResults()) {
-                    if (storedRule.equalsIgnoreUuid(rulepair[1])) {
-                        // The outgoing rule exists
-                        outgoing = storedRule;
-                        s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
-                        if (incoming != null) {
-                            break;
-                        }
-                    } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
-                        // The incoming rule exists
-                        incoming = storedRule;
-                        s_logger.debug("Found matching incoming rule " + incoming.getUuid());
-                        if (outgoing != null) {
-                            break;
-                        }
-                    }
-                }
-                if (incoming != null && outgoing != null) {
-                    if (rule.revoked()) {
-                        s_logger.debug("Deleting incoming rule " + incoming.getUuid());
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid());
-
-                        s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid());
-                    }
-                } else {
-                    if (rule.revoked()) {
-                        s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
-                        break;
-                    }
-
-                    rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]);
-                    s_logger.debug("Created " + natRuleToString(rulepair[0]));
-
-                    try {
-                        rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]);
-                        s_logger.debug("Created " + natRuleToString(rulepair[1]));
-                    } catch (final NiciraNvpApiException ex) {
-                        s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule");
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid());
-                        throw ex; // Rethrow original exception
-                    }
-
-                }
-            }
-            return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " StaticNat rules applied");
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e);
-        }
-    }
-
-    private Answer executeRequest(final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, final int numRetries) {
-        try {
-            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
-            // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
-            // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
-            // Any other SourceNat rule should have a corresponding DestinationNat rule
-
-            for (final PortForwardingRuleTO rule : cmd.getRules()) {
-                if (rule.isAlreadyAdded() && !rule.revoked()) {
-                    // Don't need to do anything
-                    continue;
-                }
-
-                if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1]) {
-                    return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, false, "Nicira NVP doesn't support port ranges for port forwarding");
-                }
-
-                final NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
-
-                NatRule incoming = null;
-                NatRule outgoing = null;
-
-                for (final NatRule storedRule : existingRules.getResults()) {
-                    if (storedRule.equalsIgnoreUuid(rulepair[1])) {
-                        // The outgoing rule exists
-                        outgoing = storedRule;
-                        s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
-                        if (incoming != null) {
-                            break;
-                        }
-                    } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
-                        // The incoming rule exists
-                        incoming = storedRule;
-                        s_logger.debug("Found matching incoming rule " + incoming.getUuid());
-                        if (outgoing != null) {
-                            break;
-                        }
-                    }
-                }
-                if (incoming != null && outgoing != null) {
-                    if (rule.revoked()) {
-                        s_logger.debug("Deleting incoming rule " + incoming.getUuid());
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), incoming.getUuid());
-
-                        s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), outgoing.getUuid());
-                    }
-                } else {
-                    if (rule.revoked()) {
-                        s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
-                        break;
-                    }
-
-                    rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0]);
-                    s_logger.debug("Created " + natRuleToString(rulepair[0]));
-
-                    try {
-                        rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]);
-                        s_logger.debug("Created " + natRuleToString(rulepair[1]));
-                    } catch (final NiciraNvpApiException ex) {
-                        s_logger.warn("NiciraNvpApiException during create call, rolling back previous create");
-                        niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid());
-                        throw ex; // Rethrow the original exception
-                    }
-
-                }
-            }
-            return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " PortForwarding rules applied");
-        } catch (final NiciraNvpApiException e) {
-            retryUtility.addRetry(cmd, NUM_RETRIES);
-            return retryUtility.retry(cmd, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e);
-        }
-    }
-
-    private String natRuleToString(final NatRule rule) {
+    public String natRuleToString(final NatRule rule) {
 
         final StringBuilder natRuleStr = new StringBuilder();
         natRuleStr.append("Rule ");
@@ -427,7 +235,7 @@ public class NiciraNvpResource implements ServerResource {
         }
     }
 
-    protected NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) {
+    public NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) {
         final NatRule[] rulepair = new NatRule[2];
         rulepair[0] = new DestinationNatRule();
         rulepair[0].setType("DestinationNatRule");
@@ -452,7 +260,7 @@ public class NiciraNvpResource implements ServerResource {
 
     }
 
-    protected NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
+    public NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
             final String protocol) {
         // Start with a basic static nat rule, then add port and protocol details
         final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
@@ -508,4 +316,4 @@ public class NiciraNvpResource implements ServerResource {
         // TODO Auto-generated method stub
     }
 
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/644458f5/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
new file mode 100644
index 0000000..89e7a6e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePortForwardingRulesCommandWrapper.java
@@ -0,0 +1,120 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePortForwardingRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.to.PortForwardingRuleTO;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  ConfigurePortForwardingRulesOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigurePortForwardingRulesCommandWrapper extends CommandWrapper<ConfigurePortForwardingRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigurePortForwardingRulesCommandWrapper.class);
+
+    @Override
+    public Answer execute(final ConfigurePortForwardingRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+        try {
+            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+            // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
+            // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
+            // Any other SourceNat rule should have a corresponding DestinationNat rule
+
+            for (final PortForwardingRuleTO rule : command.getRules()) {
+                if (rule.isAlreadyAdded() && !rule.revoked()) {
+                    // Don't need to do anything
+                    continue;
+                }
+
+                if (rule.getDstPortRange()[0] != rule.getDstPortRange()[1] || rule.getSrcPortRange()[0] != rule.getSrcPortRange()[1]) {
+                    return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, false, "Nicira NVP doesn't support port ranges for port forwarding");
+                }
+
+                final NatRule[] rulepair = niciraNvpResource.generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
+
+                NatRule incoming = null;
+                NatRule outgoing = null;
+
+                for (final NatRule storedRule : existingRules.getResults()) {
+                    if (storedRule.equalsIgnoreUuid(rulepair[1])) {
+                        // The outgoing rule exists
+                        outgoing = storedRule;
+                        s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
+                        if (incoming != null) {
+                            break;
+                        }
+                    } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
+                        // The incoming rule exists
+                        incoming = storedRule;
+                        s_logger.debug("Found matching incoming rule " + incoming.getUuid());
+                        if (outgoing != null) {
+                            break;
+                        }
+                    }
+                }
+                if (incoming != null && outgoing != null) {
+                    if (rule.revoked()) {
+                        s_logger.debug("Deleting incoming rule " + incoming.getUuid());
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
+
+                        s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
+                    }
+                } else {
+                    if (rule.revoked()) {
+                        s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
+                        break;
+                    }
+
+                    rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
+                    s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
+
+                    try {
+                        rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
+                        s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
+                    } catch (final NiciraNvpApiException ex) {
+                        s_logger.warn("NiciraNvpApiException during create call, rolling back previous create");
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
+                        throw ex; // Rethrow the original exception
+                    }
+
+                }
+            }
+            return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " PortForwarding rules applied");
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/644458f5/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
new file mode 100644
index 0000000..e5d2dcd
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigurePublicIpsCommandWrapper.java
@@ -0,0 +1,60 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
+import com.cloud.network.nicira.LogicalRouterPort;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  ConfigurePublicIpsOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigurePublicIpsCommandWrapper extends CommandWrapper<ConfigurePublicIpsOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final ConfigurePublicIpsOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid());
+            if (ports.getResultCount() != 1) {
+                return new ConfigurePublicIpsOnLogicalRouterAnswer(command, false, "No logical router ports found, unable to set ip addresses");
+            }
+            final LogicalRouterPort lrp = ports.getResults().get(0);
+            lrp.setIpAddresses(command.getPublicCidrs());
+            niciraNvpApi.updateLogicalRouterPort(command.getLogicalRouterUuid(), lrp);
+
+            return new ConfigurePublicIpsOnLogicalRouterAnswer(command, true, "Configured " + command.getPublicCidrs().size() + " ip addresses on logical router uuid " +
+                    command.getLogicalRouterUuid());
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, ConfigurePublicIpsOnLogicalRouterAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/644458f5/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
new file mode 100644
index 0000000..1ce3ceb
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpConfigureStaticNatRulesCommandWrapper.java
@@ -0,0 +1,113 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterAnswer;
+import com.cloud.agent.api.ConfigureStaticNatRulesOnLogicalRouterCommand;
+import com.cloud.agent.api.to.StaticNatRuleTO;
+import com.cloud.network.nicira.NatRule;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  ConfigureStaticNatRulesOnLogicalRouterCommand.class)
+public final class NiciraNvpConfigureStaticNatRulesCommandWrapper extends CommandWrapper<ConfigureStaticNatRulesOnLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpConfigureStaticNatRulesCommandWrapper.class);
+
+    @Override
+    public Answer execute(final ConfigureStaticNatRulesOnLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(command.getLogicalRouterUuid());
+            // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
+            // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
+            // Any other SourceNat rule should have a corresponding DestinationNat rule
+
+            for (final StaticNatRuleTO rule : command.getRules()) {
+
+                final NatRule[] rulepair = niciraNvpResource.generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
+
+                NatRule incoming = null;
+                NatRule outgoing = null;
+
+                for (final NatRule storedRule : existingRules.getResults()) {
+                    if (storedRule.equalsIgnoreUuid(rulepair[1])) {
+                        // The outgoing rule exists
+                        outgoing = storedRule;
+                        s_logger.debug("Found matching outgoing rule " + outgoing.getUuid());
+                        if (incoming != null) {
+                            break;
+                        }
+                    } else if (storedRule.equalsIgnoreUuid(rulepair[0])) {
+                        // The incoming rule exists
+                        incoming = storedRule;
+                        s_logger.debug("Found matching incoming rule " + incoming.getUuid());
+                        if (outgoing != null) {
+                            break;
+                        }
+                    }
+                }
+                if (incoming != null && outgoing != null) {
+                    if (rule.revoked()) {
+                        s_logger.debug("Deleting incoming rule " + incoming.getUuid());
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), incoming.getUuid());
+
+                        s_logger.debug("Deleting outgoing rule " + outgoing.getUuid());
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), outgoing.getUuid());
+                    }
+                } else {
+                    if (rule.revoked()) {
+                        s_logger.warn("Tried deleting a rule that does not exist, " + rule.getSrcIp() + " -> " + rule.getDstIp());
+                        break;
+                    }
+
+                    rulepair[0] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0]);
+                    s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[0]));
+
+                    try {
+                        rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[1]);
+                        s_logger.debug("Created " + niciraNvpResource.natRuleToString(rulepair[1]));
+                    } catch (final NiciraNvpApiException ex) {
+                        s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule");
+                        niciraNvpApi.deleteLogicalRouterNatRule(command.getLogicalRouterUuid(), rulepair[0].getUuid());
+                        throw ex; // Rethrow original exception
+                    }
+
+                }
+            }
+            return new ConfigureStaticNatRulesOnLogicalRouterAnswer(command, true, command.getRules().size() + " StaticNat rules applied");
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/644458f5/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
new file mode 100644
index 0000000..43665b2
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalRouterCommandWrapper.java
@@ -0,0 +1,50 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalRouterAnswer;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  DeleteLogicalRouterCommand.class)
+public final class NiciraNvpDeleteLogicalRouterCommandWrapper extends CommandWrapper<DeleteLogicalRouterCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final DeleteLogicalRouterCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+
+        try {
+            niciraNvpApi.deleteLogicalRouter(command.getLogicalRouterUuid());
+            return new DeleteLogicalRouterAnswer(command, true, "Logical Router deleted (uuid " + command.getLogicalRouterUuid() + ")");
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, DeleteLogicalRouterAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file


[36/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Merge branch 'PR-REVIEW-335'

This closes #335


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f1a64902
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f1a64902
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f1a64902

Branch: refs/heads/reporter
Commit: f1a64902cc8bd18ace566b8f42ca24032d41dd9b
Parents: 896f6b1 510fc11
Author: Rajani Karuturi <ra...@gmail.com>
Authored: Mon Jul 6 11:48:38 2015 +0530
Committer: Rajani Karuturi <ra...@gmail.com>
Committed: Mon Jul 6 11:48:38 2015 +0530

----------------------------------------------------------------------
 .../manager/allocator/impl/RandomAllocator.java |  13 +-
 .../allocator/impl/FirstFitAllocator.java       |  28 +-
 .../component/find_hosts_for_migration.py       | 273 +++++++++++++++++++
 3 files changed, 302 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f1a64902/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
----------------------------------------------------------------------
diff --cc plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
index 5bdf4f1,390a8af..390a8af
mode 100644,100755..100644
--- a/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
+++ b/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f1a64902/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
index 44552af,990b77b..3a2b280
mode 100644,100755..100644
--- a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
+++ b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java


[32/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
BUG-ID: CLOUDSTACK-8484 - Hosts without tag are not listed while
listing the hosts for migration for instance with tag
Added marvin test for this issue.
Steps
         1. Create a Compute service offering with the tag.
         2. Create a Guest VM with the compute service offering
            created above.
         3. find hosts to migrate the vm crated above

Validations
         1. Ensure that the offering is created with the
            tag.The listServiceOffering API should list show tag
         2. findHostsForMigration cmd should list both suitable
            and not-suitable hosts


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/510fc113
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/510fc113
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/510fc113

Branch: refs/heads/reporter
Commit: 510fc11319fc90a57fd552597891842a58aa256e
Parents: b593657
Author: Sudhansu <su...@citrix.com>
Authored: Fri Jul 3 17:36:54 2015 +0530
Committer: Sudhansu <su...@citrix.com>
Committed: Fri Jul 3 17:36:54 2015 +0530

----------------------------------------------------------------------
 .../component/find_hosts_for_migration.py       | 273 +++++++++++++++++++
 1 file changed, 273 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/510fc113/test/integration/component/find_hosts_for_migration.py
----------------------------------------------------------------------
diff --git a/test/integration/component/find_hosts_for_migration.py b/test/integration/component/find_hosts_for_migration.py
new file mode 100644
index 0000000..50789b2
--- /dev/null
+++ b/test/integration/component/find_hosts_for_migration.py
@@ -0,0 +1,273 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+"""  tests for find Host for migration both suitable and not suitable
+"""
+#Import Local Modules
+from nose.plugins.attrib import attr
+from marvin.cloudstackTestCase import cloudstackTestCase, unittest
+from marvin.cloudstackAPI import (migrateVirtualMachine,
+                                  prepareHostForMaintenance,
+                                  cancelHostMaintenance,
+                                  findHostsForMigration)
+from marvin.lib.utils import cleanup_resources
+from marvin.lib.base import (Account,
+                             VirtualMachine,
+                             ServiceOffering,
+                             Cluster,
+                             Host,
+                             Configurations)
+from marvin.lib.common import (get_zone,
+                               get_domain,
+                               get_template,
+                               list_hosts,
+                               list_virtual_machines,
+                               list_service_offering,
+                               findSuitableHostForMigration)
+import time
+
+
+class Services:
+
+    def __init__(self):
+        self.services = {
+            "account": {
+                "email": "test@test.com",
+                "firstname": "HA",
+                "lastname": "HA",
+                "username": "HA",
+                # Random characters are appended for unique
+                # username
+                "password": "password",
+                },
+            "service_offering_with_tag": {
+                "name": "Tiny Instance With hosttag",
+                "displaytext": "Tiny Instance",
+                "cpunumber": 1,
+                "cpuspeed": 100, # in MHz
+                "memory": 128, # In MBs
+                "hosttags": "PREMIUM",
+            },
+            "virtual_machine": {
+                "displayname": "VM",
+                "username": "root",
+                "password": "password",
+                "ssh_port": 22,
+                "hypervisor": 'XenServer',
+                # Hypervisor type should be same as
+                # hypervisor type of cluster
+                "privateport": 22,
+                "publicport": 22,
+                "protocol": 'TCP',
+                },
+            "ostype": 'CentOS 5.3 (64-bit)',
+            "timeout": 100,
+            }
+
+
+class TestHostsForMigration(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        cls.testClient = super(TestHostsForMigration, cls).getClsTestClient()
+        cls.api_client = cls.testClient.getApiClient()
+
+        cls.services = Services().services
+        # Get Zone, Domain and templates
+        cls.domain = get_domain(cls.api_client)
+        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
+
+        cls.template = get_template(
+            cls.api_client,
+            cls.zone.id,
+            cls.services["ostype"]
+        )
+
+
+        clusterWithSufficientHosts = None
+        clusters = Cluster.list(cls.api_client, zoneid=cls.zone.id)
+        for cluster in clusters:
+            cls.hosts = Host.list(cls.api_client, clusterid=cluster.id, type="Routing")
+            if len(cls.hosts) >= 2:
+                clusterWithSufficientHosts = cluster
+                break
+
+        if clusterWithSufficientHosts is None:
+            raise unittest.SkipTest("No Cluster with 2 hosts found")
+
+
+        Host.update(cls.api_client, id=cls.hosts[1].id, hosttags="PREMIUM")
+
+        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
+        cls.services["virtual_machine"]["template"] = cls.template.id
+
+        cls.service_offering_with_tag = ServiceOffering.create(
+            cls.api_client,
+            cls.services["service_offering_with_tag"]
+        )
+
+        cls._cleanup = [
+            cls.service_offering_with_tag,
+            ]
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            # Host.update(cls.api_client, id=cls.hosts[1].id, hosttags="")
+            #Cleanup resources used
+            cleanup_resources(cls.api_client, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.dbclient = self.testClient.getDbConnection()
+        self.account = Account.create(
+            self.apiclient,
+            self.services["account"],
+            admin=True,
+            domainid=self.domain.id
+        )
+        self.cleanup = [self.account]
+        return
+
+    def tearDown(self):
+        try:
+            #Clean up, terminate the created accounts, domains etc
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    @attr(required_hardware="false")
+    @attr(tags=["advanced", "basic", "simulator"])
+    def test_01_find_hosts_for_migration(self):
+        """ Test find suitable and not-suitable list of hosts for migration """
+
+        # Steps,
+        #1. Create a Compute service offering with the tag .
+        #2. Create a Guest VM with the compute service offering created above.
+        #3. find hosts to migrate the vm crated above
+
+        # Validations,
+        #1. Ensure that the offering is created with the tag
+        #The listServiceOffering API should list show tag
+        #2. Select the newly created VM and ensure that the Compute offering field value lists the compute service offering that was selected.
+        #3. findHostsForMigration cmd should list both suitable and not-suitable hosts
+
+        list_service_response = list_service_offering(
+            self.apiclient,
+            id=self.service_offering_with_tag.id
+        )
+        self.assertEqual(
+            isinstance(list_service_response, list),
+            True,
+            "listServiceOfferings returned invalid object in response."
+        )
+        self.assertNotEqual(
+            len(list_service_response),
+            0,
+            "listServiceOfferings returned empty list."
+        )
+        self.assertEqual(
+            list_service_response[0].hosttags,
+            "PREMIUM",
+            "The service offering having tag"
+        )
+
+        #create virtual machine with the service offering with Ha enabled
+        virtual_machine = VirtualMachine.create(
+            self.apiclient,
+            self.services["virtual_machine"],
+            accountid=self.account.name,
+            domainid=self.account.domainid,
+            serviceofferingid=self.service_offering_with_tag.id
+        )
+        vms = VirtualMachine.list(
+            self.apiclient,
+            id=virtual_machine.id,
+            listall=True
+        )
+        self.assertEqual(
+            isinstance(vms, list),
+            True,
+            "listVirtualMachines returned invalid object in response."
+        )
+        self.assertNotEqual(
+            len(vms),
+            0,
+            "listVirtualMachines returned empty list."
+        )
+        self.debug("Deployed VM on host: %s" % vms[0].hostid)
+
+        #verify that the virtual machine created on the host with tag
+        list_hosts_response = list_hosts(
+            self.apiclient,
+            id=virtual_machine.hostid
+        )
+        self.assertEqual(
+            isinstance(list_hosts_response, list),
+            True,
+            "listHosts returned invalid object in response."
+        )
+
+        self.assertNotEqual(
+            len(list_hosts_response),
+            0,
+            "listHosts returned empty list."
+        )
+
+        host = list_hosts_response[0]
+
+        self.assertEqual(
+            host.hosttags,
+            "PREMIUM",
+            "VM is created on a host having appropriate tag. %s" % host.uuid
+        )
+
+        try:
+            list_hosts_response = Host.listForMigration(self.apiclient, virtualmachineid=virtual_machine.id,
+                                      )
+        except Exception as e:
+            raise Exception("Exception while getting hosts list suitable for migration: %s" % e)
+
+
+        self.assertEqual(
+            isinstance(list_hosts_response, list),
+            True,
+            "listHosts returned invalid object in response."
+        )
+
+        self.assertNotEqual(
+            len(list_hosts_response),
+            0,
+            "listHosts returned empty response."
+        )
+        suitableHost = set()
+        notSuitableHost = set()
+
+        for host in list_hosts_response:
+            if host.suitableformigration:
+                suitableHost.add(host)
+            else:
+                notSuitableHost.add(host)
+
+        self.assertTrue(notSuitableHost is not None, "notsuitablehost should not be None")
+        self.debug("Suitable Hosts: %s" % suitableHost)
+        self.debug("Not suitable Hosts: %s" % notSuitableHost)
\ No newline at end of file


[10/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Allow custom command role ACL files on classpath in Static Role API Checker.

This commit has a small refactoring of cloud-plugin-acl-static-role-based
to allow it to read files on the classpath that might have a different name
than "commands.properties". It also allows more than one file to be read from.

Rationale: Third-party plugins may want to keep their API command access level
configuration separate from the main file so as to reduce configuration
maintenance work during packaging and deployments.

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #354


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/93b201d4
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/93b201d4
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/93b201d4

Branch: refs/heads/reporter
Commit: 93b201d43a4263bc9b7e6e31c542255440a7cb39
Parents: 299c07c
Author: jeff <je...@greenqloud.com>
Authored: Wed Jun 3 17:15:57 2015 +0000
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Wed Jul 1 14:43:29 2015 +0200

----------------------------------------------------------------------
 .../spring-acl-static-role-based-context.xml           |  5 +++++
 .../acl/StaticRoleBasedAPIAccessChecker.java           | 13 ++++++++++++-
 2 files changed, 17 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b201d4/plugins/acl/static-role-based/resources/META-INF/cloudstack/acl-static-role-based/spring-acl-static-role-based-context.xml
----------------------------------------------------------------------
diff --git a/plugins/acl/static-role-based/resources/META-INF/cloudstack/acl-static-role-based/spring-acl-static-role-based-context.xml b/plugins/acl/static-role-based/resources/META-INF/cloudstack/acl-static-role-based/spring-acl-static-role-based-context.xml
index f13acc1..0b22283 100644
--- a/plugins/acl/static-role-based/resources/META-INF/cloudstack/acl-static-role-based/spring-acl-static-role-based-context.xml
+++ b/plugins/acl/static-role-based/resources/META-INF/cloudstack/acl-static-role-based/spring-acl-static-role-based-context.xml
@@ -29,6 +29,11 @@
 
     <bean id="StaticRoleBasedAPIAccessChecker" class="org.apache.cloudstack.acl.StaticRoleBasedAPIAccessChecker" >
         <property name="services" value="#{apiCommandsRegistry.registered}" />
+        <property name="commandPropertyFiles">
+            <set>
+                <value>commands.properties</value>
+            </set>
+        </property>
     </bean>
 
 </beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/93b201d4/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java
----------------------------------------------------------------------
diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java
index 1316a92..4383b45 100644
--- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java
+++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java
@@ -45,6 +45,7 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC
 
     protected static final Logger s_logger = Logger.getLogger(StaticRoleBasedAPIAccessChecker.class);
 
+    Set<String> commandPropertyFiles = new HashSet<String>();
     Set<String> commandsPropertiesOverrides = new HashSet<String>();
     Map<RoleType, Set<String>> commandsPropertiesRoleBasedApisMap = new HashMap<RoleType, Set<String>>();
     Map<RoleType, Set<String>> annotationRoleBasedApisMap = new HashMap<RoleType, Set<String>>();
@@ -84,7 +85,9 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
         super.configure(name, params);
 
-        processMapping(PropertiesUtil.processConfigFile(new String[] {"commands.properties"}));
+        for (String commandPropertyFile : commandPropertyFiles) {
+            processMapping(PropertiesUtil.processConfigFile(new String[] { commandPropertyFile }));
+        }
         return true;
     }
 
@@ -129,4 +132,12 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC
         this._services = services;
     }
 
+    public Set<String> getCommandPropertyFiles() {
+        return commandPropertyFiles;
+    }
+
+    public void setCommandPropertyFiles(Set<String> commandPropertyFiles) {
+        this.commandPropertyFiles = commandPropertyFiles;
+    }
+
 }


[05/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3ff92e88/setup/db/db/schema-452to460.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-452to460.sql b/setup/db/db/schema-452to460.sql
new file mode 100644
index 0000000..0abd4f8
--- /dev/null
+++ b/setup/db/db/schema-452to460.sql
@@ -0,0 +1,400 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF 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.
+
+--
+-- Schema upgrade from 4.5.1 to 4.6.0
+--
+
+ALTER TABLE `cloud`.`snapshots` ADD COLUMN `min_iops` bigint(20) unsigned COMMENT 'Minimum IOPS';
+ALTER TABLE `cloud`.`snapshots` ADD COLUMN `max_iops` bigint(20) unsigned COMMENT 'Maximum IOPS';
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Advanced", 'DEFAULT', 'management-server', "stats.output.uri", "", "URI to additionally send StatsCollector statistics to", "", NULL, NULL, 0);
+
+DROP VIEW IF EXISTS `cloud`.`domain_view`;
+CREATE VIEW `cloud`.`domain_view` AS
+    select
+        domain.id id,
+        domain.parent parent,
+        domain.name name,
+        domain.uuid uuid,
+        domain.owner owner,
+        domain.path path,
+        domain.level level,
+        domain.child_count child_count,
+        domain.next_child_seq next_child_seq,
+        domain.removed removed,
+        domain.state state,
+        domain.network_domain network_domain,
+        domain.type type,
+        vmlimit.max vmLimit,
+        vmcount.count vmTotal,
+        iplimit.max ipLimit,
+        ipcount.count ipTotal,
+        volumelimit.max volumeLimit,
+        volumecount.count volumeTotal,
+        snapshotlimit.max snapshotLimit,
+        snapshotcount.count snapshotTotal,
+        templatelimit.max templateLimit,
+        templatecount.count templateTotal,
+        vpclimit.max vpcLimit,
+        vpccount.count vpcTotal,
+        projectlimit.max projectLimit,
+        projectcount.count projectTotal,
+        networklimit.max networkLimit,
+        networkcount.count networkTotal,
+        cpulimit.max cpuLimit,
+        cpucount.count cpuTotal,
+        memorylimit.max memoryLimit,
+        memorycount.count memoryTotal,
+        primary_storage_limit.max primaryStorageLimit,
+        primary_storage_count.count primaryStorageTotal,
+        secondary_storage_limit.max secondaryStorageLimit,
+        secondary_storage_count.count secondaryStorageTotal
+    from
+        `cloud`.`domain`
+            left join
+        `cloud`.`resource_limit` vmlimit ON domain.id = vmlimit.domain_id
+            and vmlimit.type = 'user_vm'
+            left join
+        `cloud`.`resource_count` vmcount ON domain.id = vmcount.domain_id
+            and vmcount.type = 'user_vm'
+            left join
+        `cloud`.`resource_limit` iplimit ON domain.id = iplimit.domain_id
+            and iplimit.type = 'public_ip'
+            left join
+        `cloud`.`resource_count` ipcount ON domain.id = ipcount.domain_id
+            and ipcount.type = 'public_ip'
+            left join
+        `cloud`.`resource_limit` volumelimit ON domain.id = volumelimit.domain_id
+            and volumelimit.type = 'volume'
+            left join
+        `cloud`.`resource_count` volumecount ON domain.id = volumecount.domain_id
+            and volumecount.type = 'volume'
+            left join
+        `cloud`.`resource_limit` snapshotlimit ON domain.id = snapshotlimit.domain_id
+            and snapshotlimit.type = 'snapshot'
+            left join
+        `cloud`.`resource_count` snapshotcount ON domain.id = snapshotcount.domain_id
+            and snapshotcount.type = 'snapshot'
+            left join
+        `cloud`.`resource_limit` templatelimit ON domain.id = templatelimit.domain_id
+            and templatelimit.type = 'template'
+            left join
+        `cloud`.`resource_count` templatecount ON domain.id = templatecount.domain_id
+            and templatecount.type = 'template'
+            left join
+        `cloud`.`resource_limit` vpclimit ON domain.id = vpclimit.domain_id
+            and vpclimit.type = 'vpc'
+            left join
+        `cloud`.`resource_count` vpccount ON domain.id = vpccount.domain_id
+            and vpccount.type = 'vpc'
+            left join
+        `cloud`.`resource_limit` projectlimit ON domain.id = projectlimit.domain_id
+            and projectlimit.type = 'project'
+            left join
+        `cloud`.`resource_count` projectcount ON domain.id = projectcount.domain_id
+            and projectcount.type = 'project'
+            left join
+        `cloud`.`resource_limit` networklimit ON domain.id = networklimit.domain_id
+            and networklimit.type = 'network'
+            left join
+        `cloud`.`resource_count` networkcount ON domain.id = networkcount.domain_id
+            and networkcount.type = 'network'
+            left join
+        `cloud`.`resource_limit` cpulimit ON domain.id = cpulimit.domain_id
+            and cpulimit.type = 'cpu'
+            left join
+        `cloud`.`resource_count` cpucount ON domain.id = cpucount.domain_id
+            and cpucount.type = 'cpu'
+            left join
+        `cloud`.`resource_limit` memorylimit ON domain.id = memorylimit.domain_id
+            and memorylimit.type = 'memory'
+            left join
+        `cloud`.`resource_count` memorycount ON domain.id = memorycount.domain_id
+            and memorycount.type = 'memory'
+            left join
+        `cloud`.`resource_limit` primary_storage_limit ON domain.id = primary_storage_limit.domain_id
+            and primary_storage_limit.type = 'primary_storage'
+            left join
+        `cloud`.`resource_count` primary_storage_count ON domain.id = primary_storage_count.domain_id
+            and primary_storage_count.type = 'primary_storage'
+            left join
+        `cloud`.`resource_limit` secondary_storage_limit ON domain.id = secondary_storage_limit.domain_id
+            and secondary_storage_limit.type = 'secondary_storage'
+            left join
+        `cloud`.`resource_count` secondary_storage_count ON domain.id = secondary_storage_count.domain_id
+            and secondary_storage_count.type = 'secondary_storage';
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.user.vms','-1','The default maximum number of user VMs that can be deployed for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.public.ips','-1','The default maximum number of public IPs that can be consumed by a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.templates','-1','The default maximum number of templates that can be deployed for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.snapshots','-1','The default maximum number of snapshots that can be created for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.volumes','-1','The default maximum number of volumes that can be created for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.networks', '-1', 'The default maximum number of networks that can be created for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.vpcs', '-1', 'The default maximum number of vpcs that can be created for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.cpus', '-1', 'The default maximum number of cpu cores that can be used for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.memory', '-1', 'The default maximum memory (in MiB) that can be used for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.primary.storage', '-1', 'The default maximum primary storage space (in GiB) that can be used for a domain', '-1', NULL, NULL, 0);
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Domain Defaults', 'DEFAULT', 'management-server', 'max.domain.secondary.storage', '-1', 'The default maximum secondary storage space (in GiB) that can be used for a domain', '-1', NULL, NULL, 0);
+
+ALTER TABLE `cloud`.`vm_instance` ADD COLUMN `user_id` bigint unsigned NOT NULL DEFAULT 1 COMMENT 'user id of VM deployer';
+
+DROP VIEW IF EXISTS `cloud`.`user_vm_view`;
+CREATE VIEW `cloud`.`user_vm_view` AS
+    select
+        vm_instance.id id,
+        vm_instance.name name,
+        user_vm.display_name display_name,
+        user_vm.user_data user_data,
+        account.id account_id,
+        account.uuid account_uuid,
+        account.account_name account_name,
+        account.type account_type,
+        domain.id domain_id,
+        domain.uuid domain_uuid,
+        domain.name domain_name,
+        domain.path domain_path,
+        projects.id project_id,
+        projects.uuid project_uuid,
+        projects.name project_name,
+        instance_group.id instance_group_id,
+        instance_group.uuid instance_group_uuid,
+        instance_group.name instance_group_name,
+        vm_instance.uuid uuid,
+        vm_instance.user_id user_id,
+        vm_instance.last_host_id last_host_id,
+        vm_instance.vm_type type,
+        vm_instance.limit_cpu_use limit_cpu_use,
+        vm_instance.created created,
+        vm_instance.state state,
+        vm_instance.removed removed,
+        vm_instance.ha_enabled ha_enabled,
+        vm_instance.hypervisor_type hypervisor_type,
+        vm_instance.instance_name instance_name,
+        vm_instance.guest_os_id guest_os_id,
+        vm_instance.display_vm display_vm,
+        guest_os.uuid guest_os_uuid,
+        vm_instance.pod_id pod_id,
+        host_pod_ref.uuid pod_uuid,
+        vm_instance.private_ip_address private_ip_address,
+        vm_instance.private_mac_address private_mac_address,
+        vm_instance.vm_type vm_type,
+        data_center.id data_center_id,
+        data_center.uuid data_center_uuid,
+        data_center.name data_center_name,
+        data_center.is_security_group_enabled security_group_enabled,
+        data_center.networktype data_center_type,
+        host.id host_id,
+        host.uuid host_uuid,
+        host.name host_name,
+        vm_template.id template_id,
+        vm_template.uuid template_uuid,
+        vm_template.name template_name,
+        vm_template.display_text template_display_text,
+        vm_template.enable_password password_enabled,
+        iso.id iso_id,
+        iso.uuid iso_uuid,
+        iso.name iso_name,
+        iso.display_text iso_display_text,
+        service_offering.id service_offering_id,
+        svc_disk_offering.uuid service_offering_uuid,
+        disk_offering.uuid disk_offering_uuid,
+        disk_offering.id disk_offering_id,
+        Case
+             When (`cloud`.`service_offering`.`cpu` is null) then (`custom_cpu`.`value`)
+             Else ( `cloud`.`service_offering`.`cpu`)
+        End as `cpu`,
+        Case
+            When (`cloud`.`service_offering`.`speed` is null) then (`custom_speed`.`value`)
+            Else ( `cloud`.`service_offering`.`speed`)
+        End as `speed`,
+        Case
+            When (`cloud`.`service_offering`.`ram_size` is null) then (`custom_ram_size`.`value`)
+            Else ( `cloud`.`service_offering`.`ram_size`)
+        END as `ram_size`,
+        svc_disk_offering.name service_offering_name,
+        disk_offering.name disk_offering_name,
+        storage_pool.id pool_id,
+        storage_pool.uuid pool_uuid,
+        storage_pool.pool_type pool_type,
+        volumes.id volume_id,
+        volumes.uuid volume_uuid,
+        volumes.device_id volume_device_id,
+        volumes.volume_type volume_type,
+        security_group.id security_group_id,
+        security_group.uuid security_group_uuid,
+        security_group.name security_group_name,
+        security_group.description security_group_description,
+        nics.id nic_id,
+        nics.uuid nic_uuid,
+        nics.network_id network_id,
+        nics.ip4_address ip_address,
+        nics.ip6_address ip6_address,
+        nics.ip6_gateway ip6_gateway,
+        nics.ip6_cidr ip6_cidr,
+        nics.default_nic is_default_nic,
+        nics.gateway gateway,
+        nics.netmask netmask,
+        nics.mac_address mac_address,
+        nics.broadcast_uri broadcast_uri,
+        nics.isolation_uri isolation_uri,
+        vpc.id vpc_id,
+        vpc.uuid vpc_uuid,
+        networks.uuid network_uuid,
+        networks.name network_name,
+        networks.traffic_type traffic_type,
+        networks.guest_type guest_type,
+        user_ip_address.id public_ip_id,
+        user_ip_address.uuid public_ip_uuid,
+        user_ip_address.public_ip_address public_ip_address,
+        ssh_keypairs.keypair_name keypair_name,
+        resource_tags.id tag_id,
+        resource_tags.uuid tag_uuid,
+        resource_tags.key tag_key,
+        resource_tags.value tag_value,
+        resource_tags.domain_id tag_domain_id,
+        resource_tags.account_id tag_account_id,
+        resource_tags.resource_id tag_resource_id,
+        resource_tags.resource_uuid tag_resource_uuid,
+        resource_tags.resource_type tag_resource_type,
+        resource_tags.customer tag_customer,
+        async_job.id job_id,
+        async_job.uuid job_uuid,
+        async_job.job_status job_status,
+        async_job.account_id job_account_id,
+        affinity_group.id affinity_group_id,
+        affinity_group.uuid affinity_group_uuid,
+        affinity_group.name affinity_group_name,
+        affinity_group.description affinity_group_description,
+        vm_instance.dynamically_scalable dynamically_scalable
+
+    from
+        `cloud`.`user_vm`
+            inner join
+        `cloud`.`vm_instance` ON vm_instance.id = user_vm.id
+            and vm_instance.removed is NULL
+            inner join
+        `cloud`.`account` ON vm_instance.account_id = account.id
+            inner join
+        `cloud`.`domain` ON vm_instance.domain_id = domain.id
+            left join
+        `cloud`.`guest_os` ON vm_instance.guest_os_id = guest_os.id
+            left join
+        `cloud`.`host_pod_ref` ON vm_instance.pod_id = host_pod_ref.id
+            left join
+        `cloud`.`projects` ON projects.project_account_id = account.id
+            left join
+        `cloud`.`instance_group_vm_map` ON vm_instance.id = instance_group_vm_map.instance_id
+            left join
+        `cloud`.`instance_group` ON instance_group_vm_map.group_id = instance_group.id
+            left join
+        `cloud`.`data_center` ON vm_instance.data_center_id = data_center.id
+            left join
+        `cloud`.`host` ON vm_instance.host_id = host.id
+            left join
+        `cloud`.`vm_template` ON vm_instance.vm_template_id = vm_template.id
+            left join
+        `cloud`.`vm_template` iso ON iso.id = user_vm.iso_id
+            left join
+        `cloud`.`service_offering` ON vm_instance.service_offering_id = service_offering.id
+            left join
+        `cloud`.`disk_offering` svc_disk_offering ON vm_instance.service_offering_id = svc_disk_offering.id
+            left join
+        `cloud`.`disk_offering` ON vm_instance.disk_offering_id = disk_offering.id
+            left join
+        `cloud`.`volumes` ON vm_instance.id = volumes.instance_id
+            left join
+        `cloud`.`storage_pool` ON volumes.pool_id = storage_pool.id
+            left join
+        `cloud`.`security_group_vm_map` ON vm_instance.id = security_group_vm_map.instance_id
+            left join
+        `cloud`.`security_group` ON security_group_vm_map.security_group_id = security_group.id
+            left join
+        `cloud`.`nics` ON vm_instance.id = nics.instance_id and nics.removed is null
+            left join
+        `cloud`.`networks` ON nics.network_id = networks.id
+            left join
+        `cloud`.`vpc` ON networks.vpc_id = vpc.id and vpc.removed is null
+            left join
+        `cloud`.`user_ip_address` ON user_ip_address.vm_id = vm_instance.id
+            left join
+        `cloud`.`user_vm_details` as ssh_details ON ssh_details.vm_id = vm_instance.id
+            and ssh_details.name = 'SSH.PublicKey'
+            left join
+        `cloud`.`ssh_keypairs` ON ssh_keypairs.public_key = ssh_details.value
+            left join
+        `cloud`.`resource_tags` ON resource_tags.resource_id = vm_instance.id
+            and resource_tags.resource_type = 'UserVm'
+            left join
+        `cloud`.`async_job` ON async_job.instance_id = vm_instance.id
+            and async_job.instance_type = 'VirtualMachine'
+            and async_job.job_status = 0
+            left join
+        `cloud`.`affinity_group_vm_map` ON vm_instance.id = affinity_group_vm_map.instance_id
+            left join
+        `cloud`.`affinity_group` ON affinity_group_vm_map.affinity_group_id = affinity_group.id
+            left join
+        `cloud`.`user_vm_details` `custom_cpu`  ON (((`custom_cpu`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_cpu`.`name` = 'CpuNumber')))
+            left join
+        `cloud`.`user_vm_details` `custom_speed`  ON (((`custom_speed`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_speed`.`name` = 'CpuSpeed')))
+           left join
+        `cloud`.`user_vm_details` `custom_ram_size`  ON (((`custom_ram_size`.`vm_id` = `cloud`.`vm_instance`.`id`) and (`custom_ram_size`.`name` = 'memory')));
+
+-- ovm3 stuff
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 10(32-bit)', 79);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 10(64-bit)', 80);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 11(32-bit)', 158);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Sun Solaris 11(64-bit)', 159);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Other Linux (32-bit)', 98);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Other Linux (64-bit)', 99);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'Other PV (32-bit)', 139);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'Other PV (64-bit)', 140);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ('Ovm3', 'DOS', 102);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows 8 (32-bit)', 165);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows 8 (64-bit)', 166);
+INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES  ("Ovm3", 'Windows Server 2012 (64-bit)', 167);
+
+INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled) VALUES ('Ovm3', '3.2', 25, 0);
+INSERT IGNORE INTO `cloud`.`hypervisor_capabilities`(hypervisor_type, hypervisor_version, max_guests_limit, security_group_enabled) VALUES ('Ovm3', '3.3', 50, 0);
+UPDATE  `cloud`.`volumes` v,  `cloud`.`storage_pool` s,  `cloud`.`cluster` c  set v.format='RAW' where v.pool_id=s.id and s.cluster_id=c.id and c.hypervisor_type='Ovm3';
+UPDATE configuration SET value='KVM,XenServer,VMware,BareMetal,Ovm,Ovm3,LXC' WHERE name='hypervisor.list';
+INSERT INTO `cloud`.`vm_template` (id, uuid, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id,featured, cross_zones, hypervisor_type, state)
+VALUES (12, UUID(), 'routing-12', 'SystemVM Template (Ovm3)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://download.cloud.com/templates/4.6/systemvm64template.ovm.raw.bz2', '4425688804dbcf0abc9e9e56c53070d7', 0, 'SystemVM Template (Ovm3)', 'RAW', 183, 0, 1, 'Ovm3', 'Active' );
+
+INSERT IGNORE INTO `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `default_value`, `description`) VALUES ('Advanced', 'DEFAULT', 'ManagementServer', 'ovm3.heartbeat.timeout' , '180', '120', 'Timeout value to send to the checkheartbeat script for guarding the self fencing functionality on ovm3');
+INSERT IGNORE INTO `cloud`.`configuration` (`category`, `instance`, `component`, `name`, `value`, `default_value`, `description`) VALUES ('Advanced', 'DEFAULT', 'ManagementServer', 'ovm3.heartbeat.interval' , '10', '1', 'Interval value the checkheartbeat script uses before triggering the timeout for ovm3');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'router.template.ovm3', 'SystemVM Template (Ovm3)', 'Name of the default router template on Ovm3.','SystemVM Template (Ovm3)', NULL, NULL, 0);
+
+UPDATE IGNORE `cloud`.`configuration` SET `value`="PLAINTEXT" WHERE `name`="user.authenticators.exclude";
+
+DROP TABLE IF EXISTS `cloud`.`external_bigswitch_vns_devices`;
+CREATE TABLE `cloud`.`external_bigswitch_bcf_devices` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
+  `uuid` varchar(255) UNIQUE,
+  `physical_network_id` bigint unsigned NOT NULL COMMENT 'id of the physical network in to which bigswitch bcf device is added',
+  `provider_name` varchar(255) NOT NULL COMMENT 'Service Provider name corresponding to this bigswitch bcf device',
+  `device_name` varchar(255) NOT NULL COMMENT 'name of the bigswitch bcf device',
+  `host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external bigswitch bcf device',
+  `hostname` varchar(255) NOT NULL COMMENT 'host name or IP address for the bigswitch bcf device',
+  `username` varchar(255) NOT NULL COMMENT 'username for the bigswitch bcf device',
+  `password` varchar(255) NOT NULL COMMENT 'password for the bigswitch bcf device',
+  `nat` boolean NOT NULL COMMENT 'NAT support for the bigswitch bcf device',
+  `hash` varchar(255) NOT NULL COMMENT 'topology hash for the bigswitch bcf networks',
+  PRIMARY KEY  (`id`),
+  CONSTRAINT `fk_external_bigswitch_bcf_devices__host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE,
+  CONSTRAINT `fk_external_bigswitch_bcf_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;


[31/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8603: Random list VM failures at scale (more than 1000 VMs) when VM has resource tags There is no 'removed' field on the resource_tags table. So 'id' based search may return a record or null in case record is deleted. Added a check for null or empty in search resource tags based on 'id'.

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #551


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/5d9f851d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/5d9f851d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/5d9f851d

Branch: refs/heads/reporter
Commit: 5d9f851deb1a12e4a07297353ea715f9cf13e677
Parents: 3a19a89
Author: Koushik Das <ko...@apache.org>
Authored: Wed Jul 1 23:17:46 2015 +0530
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Fri Jul 3 15:25:11 2015 +0530

----------------------------------------------------------------------
 .../api/query/dao/ResourceTagJoinDaoImpl.java   | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5d9f851d/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java
index a496753..3ec10dd 100644
--- a/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java
@@ -149,20 +149,24 @@ public class ResourceTagJoinDaoImpl extends GenericDaoBase<ResourceTagJoinVO, Lo
     public ResourceTagJoinVO searchById(Long id) {
         SearchCriteria<ResourceTagJoinVO> sc = tagIdSearch.create();
         sc.setParameters("id", id);
-        List<ResourceTagJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
-        assert vms != null && vms.size() == 1 : "No tag found for tag id " + id;
-        return vms.get(0);
+        List<ResourceTagJoinVO> tags = searchIncludingRemoved(sc, null, null, false);
+        if (tags != null && tags.size() > 0) {
+            return tags.get(0);
+        } else {
+            return null;
+        }
     }
 
     @Override
     public ResourceTagJoinVO newResourceTagView(ResourceTag vr) {
-
         SearchCriteria<ResourceTagJoinVO> sc = tagIdSearch.create();
         sc.setParameters("id", vr.getId());
-        List<ResourceTagJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
-        assert vms != null && vms.size() == 1 : "No tag found for tag id " + vr.getId();
-        return vms.get(0);
-
+        List<ResourceTagJoinVO> tags = searchIncludingRemoved(sc, null, null, false);
+        if (tags != null && tags.size() > 0) {
+            return tags.get(0);
+        } else {
+            return null;
+        }
     }
 
 }


[45/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8615 :skip all tests in test_ps_limits.py for lxc

CLOUDSTACK-8615 :skip all tests in test_ps_limits.py for lxc
This closes #565


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/45781b95
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/45781b95
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/45781b95

Branch: refs/heads/reporter
Commit: 45781b95b993ad6f666e78e9871eeb4d5e8043ef
Parents: 4ad178e
Author: nitt10prashant <ni...@gmail.com>
Authored: Tue Jul 7 17:00:19 2015 +0530
Committer: sanjeev <sa...@apache.org>
Committed: Wed Jul 8 11:54:47 2015 +0530

----------------------------------------------------------------------
 test/integration/component/test_ps_limits.py | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/45781b95/test/integration/component/test_ps_limits.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_ps_limits.py b/test/integration/component/test_ps_limits.py
index 1c815bf..8c75cb2 100644
--- a/test/integration/component/test_ps_limits.py
+++ b/test/integration/component/test_ps_limits.py
@@ -38,7 +38,8 @@ from marvin.lib.common import (get_domain,
                                get_template,
                                matchResourceCount,
                                createSnapshotFromVirtualMachineVolume,
-                               isVmExpunged)
+                               isVmExpunged,
+                               find_storage_pool_type)
 from marvin.lib.utils import (cleanup_resources,
                               validateList)
 from marvin.codes import (PASS,
@@ -63,6 +64,12 @@ class TestVolumeLimits(cloudstackTestCase):
         cls.domain = get_domain(cls.api_client)
         cls.zone = get_zone(cls.api_client, cloudstackTestClient.getZoneForTests())
         cls.services["mode"] = cls.zone.networktype
+        cls._cleanup = []
+        cls.unsupportedStorageType = False
+        if cls.hypervisor.lower() == 'lxc':
+            if not find_storage_pool_type(cls.api_client, storagetype='rbd'):
+                cls.unsupportedStorageType = True
+                return
 
         cls.template = get_template(
                             cls.api_client,
@@ -73,7 +80,7 @@ class TestVolumeLimits(cloudstackTestCase):
         cls.services["virtual_machine"]["zoneid"] = cls.zone.id
         cls.services["virtual_machine"]["template"] = cls.template.id
         cls.services["volume"]["zoneid"] = cls.zone.id
-        cls._cleanup = []
+
         try:
             cls.service_offering = ServiceOffering.create(cls.api_client, cls.services["service_offering"])
             cls._cleanup.append(cls.service_offering)
@@ -92,6 +99,9 @@ class TestVolumeLimits(cloudstackTestCase):
         return
 
     def setUp(self):
+        if self.unsupportedStorageType:
+            self.skipTest(
+                "unsupported storage type")
         self.apiclient = self.testClient.getApiClient()
         self.dbclient = self.testClient.getDbConnection()
         self.cleanup = []


[26/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8606: DB performance impacted due to VM sync.
VM sync. generates a lot of queries on vm_instance table with 'instance_name' as filter. Since the field is not
indexed, these kind of queries will impact DB performance. Added an index for instance_name field.

This closes #553


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f138192c
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f138192c
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f138192c

Branch: refs/heads/reporter
Commit: f138192c946d45ca5982ec012f65a8b83c97422c
Parents: 96ad6f6
Author: Koushik Das <ko...@apache.org>
Authored: Thu Jul 2 12:11:53 2015 +0530
Committer: Koushik Das <ko...@apache.org>
Committed: Fri Jul 3 10:06:48 2015 +0530

----------------------------------------------------------------------
 .../com/cloud/upgrade/dao/Upgrade452to460.java   | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f138192c/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
index 9c2b1e3..0ad2603 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade452to460.java
@@ -22,6 +22,8 @@ import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
 
 import org.apache.log4j.Logger;
 
@@ -59,6 +61,7 @@ public class Upgrade452to460 implements DbUpgrade {
     @Override
     public void performDataMigration(final Connection conn) {
         updateVMInstanceUserId(conn);
+        addIndexForVMInstance(conn);
     }
 
     public void updateVMInstanceUserId(final Connection conn) {
@@ -136,6 +139,22 @@ public class Upgrade452to460 implements DbUpgrade {
         }
     }
 
+    private void addIndexForVMInstance(Connection conn) {
+        // Drop index if it exists
+        List<String> indexList = new ArrayList<String>();
+        s_logger.debug("Dropping index i_vm_instance__instance_name from vm_instance table if it exists");
+        indexList.add("i_vm_instance__instance_name");
+        DbUpgradeUtils.dropKeysIfExist(conn, "vm_instance", indexList, false);
+
+        // Now add index
+        try (PreparedStatement pstmt = conn.prepareStatement("ALTER TABLE `cloud`.`vm_instance` ADD INDEX `i_vm_instance__instance_name`(`instance_name`)");) {
+            pstmt.executeUpdate();
+            s_logger.debug("Added index i_vm_instance__instance_name to vm_instance table");
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("Unable to add index i_vm_instance__instance_name to vm_instance table for the column instance_name", e);
+        }
+    }
+
     @Override
     public File[] getCleanupScripts() {
         final String script = Script.findScript("", "db/schema-452to460-cleanup.sql");


[35/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8439:Automation for feature CPU/Memory overcommit

CLOUDSTACK-8439:Automation for feature CPU/Memory overcommit
This closes #226


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/896f6b1e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/896f6b1e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/896f6b1e

Branch: refs/heads/reporter
Commit: 896f6b1e5e2b23958886899334b09e71ffe38e6f
Parents: 5d9f851
Author: nitt10prashant <ni...@gmail.com>
Authored: Mon May 4 12:13:52 2015 +0530
Committer: sanjeev <sa...@apache.org>
Committed: Mon Jul 6 09:45:26 2015 +0530

----------------------------------------------------------------------
 test/integration/component/test_overcommit.py | 458 +++++++++++++++++++++
 1 file changed, 458 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/896f6b1e/test/integration/component/test_overcommit.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_overcommit.py b/test/integration/component/test_overcommit.py
new file mode 100644
index 0000000..db04316
--- /dev/null
+++ b/test/integration/component/test_overcommit.py
@@ -0,0 +1,458 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+""" test for feature "CPU and MEM OVERCOMMIT"
+"""
+
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.base import (Account,
+                             Capacities,
+                             Cluster,
+                             Configurations,
+                             FAILED,
+                             Host,
+                             PASS,
+                             ServiceOffering,
+                             time,
+                             VirtualMachine,)
+from marvin.lib.utils import cleanup_resources, validateList
+from marvin.lib.common import (get_zone,
+                               get_domain,
+                               get_template)
+from marvin.sshClient import SshClient
+from nose.plugins.attrib import attr
+
+
+def ssh_xen_host(password, ipaddr, instance_name):
+    """Ssh into xen host and get vm mem details"""
+    mem = []
+    sshClient = SshClient(
+        ipaddr,
+        22,
+        "root",
+        password
+    )
+    command = "xe vm-list params=all name-label=%s" % instance_name
+    vm_detail = sshClient.execute(command)
+    max_str = vm_detail[17].split(":")
+    min_str = vm_detail[20].split(":")
+    max = int(max_str[1])
+    min = int(min_str[1])
+    mem.append(max)
+    mem.append(min)
+    return mem
+
+
+def ssh_kvm_host(password, ipaddr, instance_name):
+    """Ssh into kvm host and get vm mem details"""
+    mem = []
+    sshClient = SshClient(
+        ipaddr,
+        22,
+        "root",
+        password
+    )
+
+    command = "virsh dominfo %s" % instance_name
+    vm_detail = sshClient.execute(command)
+    max = vm_detail[7].split()
+    min = vm_detail[8].split()
+    mem.append(int(max[2]))
+    mem.append(int(min[2]))
+    return mem
+
+
+def capacity_parser(capacity):
+    cpu = []
+    mem = []
+    cpu.append(capacity[0].capacitytotal)
+    cpu.append(capacity[0].capacityused)
+    cpu.append(capacity[0].percentused)
+    mem.append(capacity[1].capacitytotal)
+    mem.append(capacity[1].capacityused)
+    mem.append(capacity[1].percentused)
+    return cpu, mem
+
+
+class Overcommit (cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(Overcommit, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        # Get Zone,Domain and templates
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient)
+        cls.testdata["mode"] = cls.zone.networktype
+        cls.testdata["configurableData"]["password"] = "xenroot"
+        cls.hypervisor = testClient.getHypervisorInfo()
+
+        cls.template = get_template(
+            cls.apiclient,
+            cls.zone.id,
+            cls.testdata["ostype"])
+        cls.testdata["template"]["ostypeid"] = cls.template.ostypeid
+        list_conf = Configurations.list(cls.apiclient,
+                                        name="capacity.check.period"
+                                        )
+        cls.wait_time = 5 + int(list_conf[0].value) / 1000
+        if cls.template == FAILED:
+            cls.fail(
+                "get_template() failed to return template with description \
+                %s" %
+                cls.testdata["ostype"])
+        cls._cleanup = []
+        try:
+            cls.account = Account.create(cls.apiclient,
+                                         cls.testdata["account"],
+                                         domainid=cls.domain.id
+                                         )
+            cls._cleanup.append(cls.account)
+
+            cls.service_offering = ServiceOffering.create(
+                cls.apiclient,
+                cls.testdata["service_offerings"]["small"])
+
+            cls._cleanup.append(cls.service_offering)
+
+            cls.deployVmResponse = VirtualMachine.create(
+                cls.apiclient,
+                services=cls.testdata["virtual_machine"],
+                accountid=cls.account.name,
+                domainid=cls.account.domainid,
+                serviceofferingid=cls.service_offering.id,
+                templateid=cls.template.id,
+                zoneid=cls.zone.id,
+            )
+
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning:Exception during cleanup: %s" % e)
+
+    @attr(
+        tags=[
+            "simulator",
+            "devcloud",
+            "basic",
+            "advanced"],
+        required_hardware="false")
+    def test_01_cluster_settings(self):
+        """change cpu/mem.overprovisioning.factor at cluster level and
+         verify the change """
+        listHost = Host.list(self.apiclient,
+                             id=self.deployVmResponse.hostid
+                             )
+        self.assertEqual(
+            validateList(listHost)[0],
+            PASS,
+            "check list host response for host id %s" %
+            self.deployVmResponse.hostid)
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=2)
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="cpu.overprovisioning.factor",
+                              value=3)
+
+        list_cluster = Cluster.list(self.apiclient,
+                                    id=listHost[0].clusterid)
+        self.assertEqual(
+            validateList(list_cluster)[0],
+            PASS,
+            "check list cluster response for cluster id %s" %
+            listHost[0].clusterid)
+        self.assertEqual(int(list_cluster[0].cpuovercommitratio),
+                         3,
+                         "check the cpu overcommit value at cluster level ")
+
+        self.assertEqual(int(list_cluster[0].memoryovercommitratio),
+                         2,
+                         "check memory overcommit value at cluster level")
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=1)
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="cpu.overprovisioning.factor",
+                              value=1)
+        list_cluster1 = Cluster.list(self.apiclient,
+                                     id=listHost[0].clusterid)
+        self.assertEqual(
+            validateList(list_cluster1)[0],
+            PASS,
+            "check the list cluster response for id %s" %
+            listHost[0].clusterid)
+        self.assertEqual(int(list_cluster1[0].cpuovercommitratio),
+                         1,
+                         "check the cpu overcommit value at cluster level ")
+
+        self.assertEqual(int(list_cluster1[0].memoryovercommitratio),
+                         1,
+                         "check memory overcommit value at cluster level")
+
+    @attr(
+        tags=["simulator",
+              "devcloud",
+              "basic",
+              "advanced"],
+        required_hardware="true")
+    def test_02_Overcommit_factor(self):
+        """change mem.overprovisioning.factor and verify vm memory """
+
+        listHost = Host.list(self.apiclient,
+                             id=self.deployVmResponse.hostid
+                             )
+        self.assertEqual(
+            validateList(listHost)[0],
+            PASS,
+            "check list host for host id %s" %
+            self.deployVmResponse.hostid)
+        if listHost[0].hypervisor.lower() not in ['kvm', 'xenserver']:
+            self.skipTest(
+                "Skiping test because of not supported hypervisor type %s" %
+                listHost[0].hypervisor)
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=1)
+
+        self.deployVmResponse.stop(self.apiclient)
+        self.deployVmResponse.start(self.apiclient)
+
+        if listHost[0].hypervisor.lower() == 'xenserver':
+
+            k = ssh_xen_host(
+                self.testdata["configurableData"]["password"],
+                listHost[0].ipaddress,
+                self.deployVmResponse.instancename)
+
+        elif listHost[0].hypervisor.lower() == 'kvm':
+
+            k = ssh_kvm_host(
+                self.testdata["configurableData"]["password"],
+                listHost[0].ipaddress,
+                self.deployVmResponse.instancename)
+
+        self.assertEqual(k[0],
+                         k[1],
+                         "Check static max ,min on host for overcommit 1 ")
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=2)
+
+        self.deployVmResponse.stop(self.apiclient)
+        self.deployVmResponse.start(self.apiclient)
+
+        if listHost[0].hypervisor.lower() == 'xenserver':
+            k1 = ssh_xen_host(
+                self.testdata["configurableData"]["password"],
+                listHost[0].ipaddress,
+                self.deployVmResponse.instancename)
+
+        elif listHost[0].hypervisor.lower() == 'kvm':
+            time.sleep(200)
+            k1 = ssh_kvm_host(
+                self.testdata["configurableData"]["password"],
+                listHost[0].ipaddress,
+                self.deployVmResponse.instancename)
+        self.assertEqual(k1[0],
+                         2 * k1[1],
+                         "Check static max ,min on  host for overcommit 2")
+
+    @attr(
+        tags=[
+            "simulator",
+            "devcloud",
+            "basic",
+            "advanced"],
+        required_hardware="false")
+    def test_03_cluste_capacity_check(self):
+        """change cpu/mem.overprovisioning.factor at cluster level and
+           verify cluster capacity """
+
+        listHost = Host.list(self.apiclient,
+                             id=self.deployVmResponse.hostid
+                             )
+        self.assertEqual(
+            validateList(listHost)[0],
+            PASS,
+            "check list host for host id %s" %
+            self.deployVmResponse.hostid)
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=1)
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="cpu.overprovisioning.factor",
+                              value=1)
+
+        time.sleep(self.wait_time)
+
+        capacity = Capacities.list(self.apiclient,
+                                   clusterid=listHost[0].clusterid)
+        self.assertEqual(
+            validateList(capacity)[0],
+            PASS,
+            "check list capacity response for cluster id %s" %
+            listHost[0].clusterid)
+        cpu, mem = capacity_parser(capacity)
+
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="mem.overprovisioning.factor",
+                              value=2)
+        Configurations.update(self.apiclient,
+                              clusterid=listHost[0].clusterid,
+                              name="cpu.overprovisioning.factor",
+                              value=2)
+
+        time.sleep(self.wait_time)
+
+        capacity1 = Capacities.list(self.apiclient,
+                                    clusterid=listHost[0].clusterid)
+        self.assertEqual(
+            validateList(capacity1)[0],
+            PASS,
+            "check list capacity response for cluster id %s" %
+            listHost[0].clusterid)
+        cpu1, mem1 = capacity_parser(capacity1)
+        self.assertEqual(2 * cpu[0],
+                         cpu1[0],
+                         "check total capacity ")
+        self.assertEqual(2 * cpu[1],
+                         cpu1[1],
+                         "check capacity used")
+        self.assertEqual(cpu[2],
+                         cpu1[2],
+                         "check capacity % used")
+
+        self.assertEqual(2 * mem[0],
+                         mem1[0],
+                         "check mem total capacity ")
+        self.assertEqual(2 * mem[1],
+                         mem1[1],
+                         "check mem capacity used")
+        self.assertEqual(mem[2],
+                         mem1[2],
+                         "check mem capacity % used")
+
+    @attr(
+        tags=[
+            "simulator",
+            "devcloud",
+            "basic",
+            "advanced"],
+        required_hardware="false")
+    def test_04_zone_capacity_check(self):
+        """change cpu/mem.overprovisioning.factor at cluster level for
+           all cluster in a zone  and  verify capacity at zone level """
+        list_cluster = Cluster.list(self.apiclient,
+                                    zoneid=self.zone.id)
+        self.assertEqual(
+            validateList(list_cluster)[0],
+            PASS,
+            "check list cluster response for zone id  %s" %
+            self.zone.id)
+        k = len(list_cluster)
+        for id in xrange(k):
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="mem.overprovisioning.factor",
+                                  value=1)
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="cpu.overprovisioning.factor",
+                                  value=1)
+
+        time.sleep(self.wait_time)
+
+        capacity = Capacities.list(self.apiclient,
+                                   zoneid=self.zone.id)
+        self.assertEqual(
+            validateList(capacity)[0],
+            PASS,
+            "check list capacity response for zone id %s" %
+            self.zone.id)
+        cpu, mem = capacity_parser(capacity)
+        for id in xrange(k):
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="mem.overprovisioning.factor",
+                                  value=2)
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="cpu.overprovisioning.factor",
+                                  value=2)
+
+        time.sleep(self.wait_time)
+
+        capacity1 = Capacities.list(self.apiclient,
+                                    zoneid=self.zone.id)
+        self.assertEqual(validateList(capacity1)[0],
+                         PASS,
+                         "check list capacity for zone id %s" % self.zone.id)
+
+        cpu1, mem1 = capacity_parser(capacity1)
+        self.assertEqual(2 * cpu[0],
+                         cpu1[0],
+                         "check total capacity ")
+        self.assertEqual(2 * cpu[1],
+                         cpu1[1],
+                         "check capacity used")
+        self.assertEqual(cpu[2],
+                         cpu1[2],
+                         "check capacity % used")
+
+        self.assertEqual(2 * mem[0],
+                         mem1[0],
+                         "check mem total capacity ")
+        self.assertEqual(2 * mem[1],
+                         mem1[1],
+                         "check mem capacity used")
+        self.assertEqual(mem[2],
+                         mem1[2],
+                         "check mem capacity % used")
+        for id in xrange(k):
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="mem.overprovisioning.factor",
+                                  value=1)
+            Configurations.update(self.apiclient,
+                                  clusterid=list_cluster[id].id,
+                                  name="cpu.overprovisioning.factor",
+                                  value=1)


[33/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Changed update script to return exit code based on the result

   - Changed location of the update_host_passwd script
   - Updated the patch files for XenServer
   - Updated the script path on LibvirtComputing class
   - Removed the hostIP from the LibvirtUpdateHostPasswordCommandWrapper execute() method


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/efa34361
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/efa34361
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/efa34361

Branch: refs/heads/reporter
Commit: efa34361df72e351cdc1f719a5dba705eab771ef
Parents: 6c92ccf
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri Jul 3 14:29:57 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Fri Jul 3 14:29:57 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  2 +-
 ...LibvirtUpdateHostPasswordCommandWrapper.java |  3 +--
 .../CitrixUpdateHostPasswordCommandWrapper.java |  1 +
 scripts/vm/hypervisor/kvm/update_host_passwd.sh | 24 -----------------
 scripts/vm/hypervisor/update_host_passwd.sh     | 28 ++++++++++++++++++++
 .../hypervisor/xenserver/update_host_passwd.sh  | 24 -----------------
 scripts/vm/hypervisor/xenserver/xcposs/patch    |  1 +
 scripts/vm/hypervisor/xenserver/xcpserver/patch |  2 +-
 .../vm/hypervisor/xenserver/xenserver56/patch   |  2 +-
 .../hypervisor/xenserver/xenserver56fp1/patch   |  2 +-
 .../vm/hypervisor/xenserver/xenserver60/patch   |  2 +-
 .../vm/hypervisor/xenserver/xenserver62/patch   |  2 +-
 .../vm/hypervisor/xenserver/xenserver65/patch   |  2 +-
 .../com/cloud/resource/ResourceManagerImpl.java |  2 +-
 14 files changed, 39 insertions(+), 58 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 782ea28..5419a60 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -523,7 +523,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     }
 
     protected String getDefaultHypervisorScriptsDir() {
-        return "scripts/vm/hypervisor/kvm";
+        return "scripts/vm/hypervisor";
     }
 
     protected String getDefaultKvmScriptsDir() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
index 7ed827d..4d7d234 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
@@ -36,12 +36,11 @@ public final class LibvirtUpdateHostPasswordCommandWrapper extends CommandWrappe
 
     @Override
     public Answer execute(final UpdateHostPasswordCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final String hostIp = command.getHostIp();
         final String username = command.getUsername();
         final String newPassword = command.getNewPassword();
 
         final Script script = new Script(libvirtComputingResource.getUpdateHostPasswdPath(), TIMEOUT, s_logger);
-        script.add(hostIp, username, newPassword);
+        script.add(username, newPassword);
         final String result = script.execute();
 
         if (result != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
index 7d0c99a..d5a530b 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
@@ -43,6 +43,7 @@ public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper
         final String newPassword = command.getNewPassword();
 
         final StringBuffer cmdLine = new StringBuffer();
+        cmdLine.append("sh /opt/cloud/bin/");
         cmdLine.append(VRScripts.UPDATE_HOST_PASSWD);
         cmdLine.append(' ');
         cmdLine.append(username);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/kvm/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/kvm/update_host_passwd.sh b/scripts/vm/hypervisor/kvm/update_host_passwd.sh
deleted file mode 100755
index 39e4a3b..0000000
--- a/scripts/vm/hypervisor/kvm/update_host_passwd.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF 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.
-
-username=$1
-new_passwd=$2
-
-echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username
-
-return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/update_host_passwd.sh b/scripts/vm/hypervisor/update_host_passwd.sh
new file mode 100755
index 0000000..9dfc5a9
--- /dev/null
+++ b/scripts/vm/hypervisor/update_host_passwd.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+username=$1
+new_passwd=$2
+expected="successfully."
+result=`echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username | grep successfully | awk '{ print $6 }'`
+
+if [ $result = $expected ]; then
+   exit 0
+else
+   exit 1
+fi
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/update_host_passwd.sh b/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
deleted file mode 100755
index 39e4a3b..0000000
--- a/scripts/vm/hypervisor/xenserver/update_host_passwd.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF 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.
-
-username=$1
-new_passwd=$2
-
-echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username
-
-return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xcposs/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xcposs/patch b/scripts/vm/hypervisor/xenserver/xcposs/patch
index 561d7b6..d3c5db0 100644
--- a/scripts/vm/hypervisor/xenserver/xcposs/patch
+++ b/scripts/vm/hypervisor/xenserver/xcposs/patch
@@ -58,3 +58,4 @@ router_proxy.sh=../../../../network/domr/,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xcpserver/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xcpserver/patch b/scripts/vm/hypervisor/xenserver/xcpserver/patch
index 62e15e3..862aa2e 100644
--- a/scripts/vm/hypervisor/xenserver/xcpserver/patch
+++ b/scripts/vm/hypervisor/xenserver/xcpserver/patch
@@ -59,4 +59,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xenserver56/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/patch b/scripts/vm/hypervisor/xenserver/xenserver56/patch
index 2145b31..23da0f3 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56/patch
@@ -63,4 +63,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
index 60404dc..a67224f 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/patch
@@ -62,4 +62,4 @@ add_to_vcpus_params_live.sh=..,0755,/opt/cloud/bin
 cloudstack_plugins.conf=..,0644,/etc/xensource
 cloudstack_pluginlib.py=..,0755,/etc/xapi.d/plugins
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xenserver60/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver60/patch b/scripts/vm/hypervisor/xenserver/xenserver60/patch
index c22d469..cf2f03e 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver60/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver60/patch
@@ -68,4 +68,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xenserver62/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver62/patch b/scripts/vm/hypervisor/xenserver/xenserver62/patch
index 0901924..11d979d 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver62/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver62/patch
@@ -64,4 +64,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/scripts/vm/hypervisor/xenserver/xenserver65/patch
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/xenserver65/patch b/scripts/vm/hypervisor/xenserver/xenserver65/patch
index 0901924..11d979d 100644
--- a/scripts/vm/hypervisor/xenserver/xenserver65/patch
+++ b/scripts/vm/hypervisor/xenserver/xenserver65/patch
@@ -64,4 +64,4 @@ ovs-pvlan-cleanup.sh=../../../network,0755,/opt/cloud/bin
 ovs-get-dhcp-iface.sh=..,0755,/opt/cloud/bin
 ovs-get-bridge.sh=..,0755,/opt/cloud/bin
 cloudlog=..,0644,/etc/logrotate.d
-update_host_passwd.sh=..,0755,/opt/cloud/bin
\ No newline at end of file
+update_host_passwd.sh=../..,0755,/opt/cloud/bin
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/efa34361/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index e9825ff..b777de9 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2265,7 +2265,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
             if (shouldUpdateHostPasswd) {
                 final boolean isUpdated = doUpdateHostPassword(host.getId());
                 if (!isUpdated) {
-                    throw new CloudRuntimeException("CloudStack failed to update the password of the Host with UUID/ID ==> " + host.getUuid() + "/" + host.getId() + ". Please make sure you are still able to connect to your hosts.");
+                    throw new CloudRuntimeException("CloudStack failed to update the password of the Host with UUID / ID ==> " + host.getUuid() + " / " + host.getId() + ". Please make sure you are still able to connect to your hosts.");
                 }
             }
         }


[29/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Refactoring attribute name

   - Refactoring attribute name from shouldUpdateHost to updatePasswdOnHost
   - Fixing ApiConstants class because it had an error in the constant name


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6c92ccf8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6c92ccf8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6c92ccf8

Branch: refs/heads/reporter
Commit: 6c92ccf8d1ef5b824d6e36ea727bbebf05a95001
Parents: 0dd02ce
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri Jul 3 11:43:56 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Fri Jul 3 11:43:56 2015 +0200

----------------------------------------------------------------------
 api/src/org/apache/cloudstack/api/ApiConstants.java            | 2 +-
 .../api/command/admin/host/UpdateHostPasswordCmd.java          | 6 +++---
 server/src/com/cloud/resource/ResourceManagerImpl.java         | 4 ++--
 3 files changed, 6 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6c92ccf8/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index ee98e06..830583b 100644
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -180,7 +180,7 @@ public class ApiConstants {
     public static final String PARAMS = "params";
     public static final String PARENT_DOMAIN_ID = "parentdomainid";
     public static final String PASSWORD = "password";
-    public static final String SHOULD_UPDATE_PASSWORD = "password";
+    public static final String SHOULD_UPDATE_PASSWORD = "update_passwd_on_host";
     public static final String NEW_PASSWORD = "new_password";
     public static final String PASSWORD_ENABLED = "passwordenabled";
     public static final String SSHKEY_ENABLED = "sshkeyenabled";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6c92ccf8/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
index 3915cee..d8c4ea5 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
@@ -45,7 +45,7 @@ public class UpdateHostPasswordCmd extends BaseCmd {
     private Long clusterId;
 
     @Parameter(name = ApiConstants.SHOULD_UPDATE_PASSWORD, type = CommandType.BOOLEAN, description = "if the password should also be updated on the hosts")
-    private Boolean shouldUpdateHost;
+    private Boolean updatePasswdOnHost;
 
     @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "the username for the host/cluster")
     private String username;
@@ -66,8 +66,8 @@ public class UpdateHostPasswordCmd extends BaseCmd {
         return clusterId;
     }
 
-    public Boolean getShouldUpdateHost() {
-        return shouldUpdateHost;
+    public Boolean getUpdatePasswdOnHost() {
+        return updatePasswdOnHost;
     }
 
     public String getPassword() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6c92ccf8/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index c31d2a5..e9825ff 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2245,7 +2245,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
 
     @Override
     public boolean updateClusterPassword(final UpdateHostPasswordCmd command) {
-        final boolean shouldUpdateHostPasswd = command.getShouldUpdateHost();
+        final boolean shouldUpdateHostPasswd = command.getUpdatePasswdOnHost();
         // get agents for the cluster
         final List<HostVO> hosts = listAllHostsInCluster(command.getClusterId());
         for (final HostVO host : hosts) {
@@ -2285,7 +2285,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
             s_logger.error("Agent is not availbale!", e);
         }
 
-        final boolean shouldUpdateHostPasswd = command.getShouldUpdateHost();
+        final boolean shouldUpdateHostPasswd = command.getUpdatePasswdOnHost();
         // If shouldUpdateHostPasswd has been set to false, the method doUpdateHostPassword() won't be called.
         return shouldUpdateHostPasswd && doUpdateHostPassword(command.getHostId());
     }


[46/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Fixes to enable test to succeed. Small change to Marvin to be able to override retries

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b7b54f16
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b7b54f16
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b7b54f16

Branch: refs/heads/reporter
Commit: b7b54f1680600d9d033b6b215e0085553a8e85e6
Parents: 1a93d70
Author: Ian Southam <is...@schubergphilis.com>
Authored: Thu Jul 2 08:19:15 2015 -0400
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 8 11:19:12 2015 +0200

----------------------------------------------------------------------
 .../debian/config/opt/cloud/bin/configure.py    |  1 +
 .../debian/config/opt/cloud/bin/cs/CsAddress.py | 15 +++--
 .../config/opt/cloud/bin/cs/CsRedundant.py      | 62 ++++++++++++--------
 tools/marvin/marvin/lib/base.py                 |  4 +-
 4 files changed, 52 insertions(+), 30 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b7b54f16/systemvm/patches/debian/config/opt/cloud/bin/configure.py
----------------------------------------------------------------------
diff --git a/systemvm/patches/debian/config/opt/cloud/bin/configure.py b/systemvm/patches/debian/config/opt/cloud/bin/configure.py
index 5e6bc83..2e8be9a 100755
--- a/systemvm/patches/debian/config/opt/cloud/bin/configure.py
+++ b/systemvm/patches/debian/config/opt/cloud/bin/configure.py
@@ -39,6 +39,7 @@ from cs.CsFile import CsFile
 from cs.CsApp import CsApache, CsDnsmasq
 from cs.CsMonitor import CsMonitor
 from cs.CsLoadBalancer import CsLoadBalancer
+from cs.CsConfig import CsConfig
 
 
 class CsPassword(CsDataBag):

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b7b54f16/systemvm/patches/debian/config/opt/cloud/bin/cs/CsAddress.py
----------------------------------------------------------------------
diff --git a/systemvm/patches/debian/config/opt/cloud/bin/cs/CsAddress.py b/systemvm/patches/debian/config/opt/cloud/bin/cs/CsAddress.py
index 0c8f013..d95a2b4 100755
--- a/systemvm/patches/debian/config/opt/cloud/bin/cs/CsAddress.py
+++ b/systemvm/patches/debian/config/opt/cloud/bin/cs/CsAddress.py
@@ -48,11 +48,14 @@ class CsAddress(CsDataBag):
 
     def get_guest_if(self):
         """
-        Return CsInterface object for the first guest interface
+        Return CsInterface object for the lowest guest interface
         """
+        ipr = []
         for ip in self.get_ips():
             if ip.is_guest():
-                return ip
+                ipr.append(ip)
+        if len(ipr) > 0:
+            return sorted(ipr)[-1]
         return None
 
     def get_guest_ip(self):
@@ -407,10 +410,10 @@ class CsIP:
                             ])
 
         if self.get_type() in ["public"]:
-            self.fw.append(["nat", "front",
-                            "-A POSTROUTING -o %s -j SNAT --to-source %s" %
-                           (self.dev, self.address['public_ip'])
-                            ])
+            # self.fw.append(["nat", "front",
+                            # "-A POSTROUTING -o %s -j SNAT --to-source %s" %
+                           # (self.dev, self.address['public_ip'])
+                            # ])
             self.fw.append(["", "front",
                             "-A FORWARD -o %s -d %s -j ACL_INBOUND_%s" % (self.dev, self.address['network'], self.dev)
                             ])

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b7b54f16/systemvm/patches/debian/config/opt/cloud/bin/cs/CsRedundant.py
----------------------------------------------------------------------
diff --git a/systemvm/patches/debian/config/opt/cloud/bin/cs/CsRedundant.py b/systemvm/patches/debian/config/opt/cloud/bin/cs/CsRedundant.py
index 11173b6..8a4cd26 100755
--- a/systemvm/patches/debian/config/opt/cloud/bin/cs/CsRedundant.py
+++ b/systemvm/patches/debian/config/opt/cloud/bin/cs/CsRedundant.py
@@ -30,16 +30,13 @@
 # eth1 public ip
 # eth2+ Guest networks
 # -------------------------------------------------------------------- #
-import sys
 import os
-from pprint import pprint
-from CsDatabag import CsDataBag, CsCmdLine
 import logging
 import CsHelper
 from CsFile import CsFile
-from CsConfig import CsConfig
 from CsProcess import CsProcess
 from CsApp import CsPasswdSvc
+from CsAddress import CsDevice
 import socket
 from time import sleep
 
@@ -64,6 +61,7 @@ class CsRedundant(object):
     def __init__(self, config):
         self.cl = config.cmdline()
         self.address = config.address()
+        self.config = config
 
     def set(self):
         logging.debug("Router redundancy status is %s", self.cl.is_redundant())
@@ -83,13 +81,11 @@ class CsRedundant(object):
     def _redundant_on(self):
         guest = self.address.get_guest_if()
         # No redundancy if there is no guest network
+        if self.cl.is_master() or guest is None:
+            for obj in [o for o in self.address.get_ips() if o.is_public()]:
+                self.check_is_up(obj.get_device())
         if guest is None:
             self._redundant_off()
-            # Bring up the public Interface(s)
-            if self.cl.is_master():
-                for obj in [o for o in self.address.get_ips() if o.is_public()]:
-                    print obj.get_device()
-                    self.check_is_up(obj.get_device())
             return
         CsHelper.mkdir(self.CS_RAMDISK_DIR, 0755, False)
         CsHelper.mount_tmpfs(self.CS_RAMDISK_DIR)
@@ -159,6 +155,12 @@ class CsRedundant(object):
         if not proc.find():
             CsHelper.service("keepalived", "restart")
 
+    def release_lock(self):
+        try:
+            os.remove("/tmp/master_lock")
+        except OSError:
+            pass
+
     def set_lock(self):
         """
         Make sure that master state changes happen sequentially
@@ -169,21 +171,21 @@ class CsRedundant(object):
         for iter in range(0, iterations):
             try:
                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-                s.bind('\0master_lock')
+                s.bind('/tmp/master_lock')
                 return s
             except socket.error, e:
                 error_code = e.args[0]
                 error_string = e.args[1]
                 print "Process already running (%d:%s). Exiting" % (error_code, error_string)
                 logging.info("Master is already running, waiting")
-                sleep(1)
+                sleep(time_between)
 
     def set_fault(self):
         """ Set fault mode on this router """
         if not self.cl.is_redundant():
             logging.error("Set fault called on non-redundant router")
             return
-        s = self.set_lock()
+        self.set_lock()
         logging.info("Router switched to fault mode")
         ads = [o for o in self.address.get_ips() if o.is_public()]
         for o in ads:
@@ -195,9 +197,10 @@ class CsRedundant(object):
         CsHelper.service("dnsmasq", "stop")
         ads = [o for o in self.address.get_ips() if o.needs_vrrp()]
         for o in ads:
-            pwdsvc = CsPasswdSvc(o.get_gateway()).stop()
+            CsPasswdSvc(o.get_gateway()).stop()
         self.cl.set_fault_state()
         self.cl.save()
+        self.release_lock()
         logging.info("Router switched to fault mode")
 
     def set_backup(self):
@@ -210,22 +213,29 @@ class CsRedundant(object):
             logging.error("Set backup called on node that is already backup")
             return
         """
-        s = self.set_lock()
+        self.set_lock()
         logging.debug("Setting router to backup")
         ads = [o for o in self.address.get_ips() if o.is_public()]
+        dev = ''
         for o in ads:
-            CsHelper.execute("ifconfig %s down" % o.get_device())
+            if dev == o.get_device():
+                continue
+            logging.info("Bringing public interface %s down" % o.get_device())
+            cmd2 = "ip link set %s up" % o.get_device()
+            CsHelper.execute(cmd2)
+            dev = o.get_device()
         cmd = "%s -C %s" % (self.CONNTRACKD_BIN, self.CONNTRACKD_CONF)
         CsHelper.execute("%s -d" % cmd)
         CsHelper.service("ipsec", "stop")
         CsHelper.service("xl2tpd", "stop")
         ads = [o for o in self.address.get_ips() if o.needs_vrrp()]
         for o in ads:
-            pwdsvc = CsPasswdSvc(o.get_gateway()).stop()
+            CsPasswdSvc(o.get_gateway()).stop()
         CsHelper.service("dnsmasq", "stop")
         # self._set_priority(self.CS_PRIO_DOWN)
         self.cl.set_master_state(False)
         self.cl.save()
+        self.release_lock()
         logging.info("Router switched to backup mode")
 
     def set_master(self):
@@ -238,15 +248,20 @@ class CsRedundant(object):
             logging.error("Set master called on master node")
             return
         """
-        s = self.set_lock()
+        self.set_lock()
         logging.debug("Setting router to master")
         ads = [o for o in self.address.get_ips() if o.is_public()]
+        dev = ''
         for o in ads:
-            # cmd2 = "ip link set %s up" % self.getDevice()
-            CsHelper.execute("ifconfig %s down" % o.get_device())
-            CsHelper.execute("ifconfig %s up" % o.get_device())
-            CsHelper.execute("arping -I %s -A %s -c 1" % (o.get_device(), o.get_ip()))
-        # FIXME Need to add in the default routes but I am unsure what the gateway is
+            if dev == o.get_device():
+                continue
+            cmd2 = "ip link set %s up" % o.get_device()
+            if CsDevice(o.get_device(), self.config).waitfordevice():
+                CsHelper.execute(cmd2)
+                dev = o.get_device()
+                logging.info("Bringing public interface %s up" % o.get_device())
+            else:
+                logging.error("Device %s was not ready could not bring it up" % o.get_device())
         # ip route add default via $gw table Table_$dev proto static
         cmd = "%s -C %s" % (self.CONNTRACKD_BIN, self.CONNTRACKD_CONF)
         CsHelper.execute("%s -c" % cmd)
@@ -257,10 +272,11 @@ class CsRedundant(object):
         CsHelper.service("xl2tpd", "restart")
         ads = [o for o in self.address.get_ips() if o.needs_vrrp()]
         for o in ads:
-            pwdsvc = CsPasswdSvc(o.get_gateway()).restart()
+            CsPasswdSvc(o.get_gateway()).restart()
         CsHelper.service("dnsmasq", "restart")
         self.cl.set_master_state(True)
         self.cl.save()
+        self.release_lock()
         logging.info("Router switched to master mode")
 
     def _collect_ignore_ips(self):

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b7b54f16/tools/marvin/marvin/lib/base.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/lib/base.py b/tools/marvin/marvin/lib/base.py
index 31e6def..71aa3e6 100755
--- a/tools/marvin/marvin/lib/base.py
+++ b/tools/marvin/marvin/lib/base.py
@@ -551,7 +551,7 @@ class VirtualMachine:
 
     def get_ssh_client(
             self, ipaddress=None, reconnect=False, port=None,
-            keyPairFileLocation=None):
+            keyPairFileLocation=None, retries=20):
         """Get SSH object of VM"""
 
         # If NAT Rules are not created while VM deployment in Advanced mode
@@ -570,6 +570,7 @@ class VirtualMachine:
                 self.ssh_port,
                 self.username,
                 self.password,
+                retries=retries,
                 keyPairFileLocation=keyPairFileLocation
             )
         self.ssh_client = self.ssh_client or is_server_ssh_ready(
@@ -577,6 +578,7 @@ class VirtualMachine:
             self.ssh_port,
             self.username,
             self.password,
+            retries=retries,
             keyPairFileLocation=keyPairFileLocation
         )
         return self.ssh_client


[38/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Merge branch 'improvement/CLOUDSTACK-8607' change the host password on the host itself via the updateHostPassword API

    - Make sure the new password replaces the old one in the queue
    - Updated the patch files for XenServer
    - Updated the script path on LibvirtComputing class
    - Adding update_host_passwd to VRScripts
    - Add implementation to CitrixUpdateHostPasswordCommandWrapper
    - Improve testUpdateHostPasswordCommand() unit test on CitrixRequestWrapperTest
    - Adding update_host_passwd.sh script
    - Adding the host IP address as an instance variable on UpdateHostPasswordCommand
    - Improving the Unit Test (LibvirtComputingResourceTest) to get it covering the new code
    - Make sure doUpdateHostPassword() doesn't get called if flag is set to false
    - Do not update XenServer hosts if the cluster ID is not informed

    This closes #559


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/31c6b14d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/31c6b14d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/31c6b14d

Branch: refs/heads/reporter
Commit: 31c6b14dd474e1c82b7377f97e9c84fac4b028b6
Parents: f1a6490 e348e76
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jul 6 16:15:22 2015 +0200
Committer: Daan Hoogland <da...@gmail.com>
Committed: Mon Jul 6 16:15:22 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/api/ApiConstants.java |   3 +-
 .../admin/host/UpdateHostPasswordCmd.java       |   8 +
 .../agent/api/UpdateHostPasswordCommand.java    |  17 ++-
 .../resource/virtualnetwork/VRScripts.java      |   1 +
 .../kvm/resource/LibvirtComputingResource.java  |  20 +++
 ...LibvirtUpdateHostPasswordCommandWrapper.java |  15 +-
 .../wrapper/LibvirtUtilitiesHelper.java         |  10 +-
 .../resource/LibvirtComputingResourceTest.java  |  39 ++++-
 .../xenserver/resource/CitrixResourceBase.java  | 153 +++++++++++--------
 .../CitrixUpdateHostPasswordCommandWrapper.java |  28 +++-
 .../xenbase/XenServerUtilitiesHelper.java       |  45 ++++++
 .../xenbase/CitrixRequestWrapperTest.java       | 130 +++++++++++++++-
 scripts/vm/hypervisor/update_host_passwd.sh     |  28 ++++
 scripts/vm/hypervisor/xenserver/xcposs/patch    |   1 +
 scripts/vm/hypervisor/xenserver/xcpserver/patch |   1 +
 .../vm/hypervisor/xenserver/xenserver56/patch   |   1 +
 .../hypervisor/xenserver/xenserver56fp1/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver60/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver62/patch   |   1 +
 .../vm/hypervisor/xenserver/xenserver65/patch   |   1 +
 .../com/cloud/resource/ResourceManagerImpl.java |  27 +++-
 .../com/cloud/server/ManagementServerImpl.java  |   4 +
 22 files changed, 451 insertions(+), 84 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/31c6b14d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------


[25/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Adding update_host_passwd.sh script

   - Modifying the LibvirtUpdateHostPasswordCommandWrapper in order to execute the script on the host
   - Adding the script path to LibvirtComputingResource
   - Adding the host IP address as an instance variable on UpdateHostPasswordCommand
   - Improving the Unit Test (LibvirtComputingResourceTest) to get it covering the new code


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/47c7a108
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/47c7a108
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/47c7a108

Branch: refs/heads/reporter
Commit: 47c7a1083fc4be9e74cb3fd73fce069c5e85c1cc
Parents: a74971d
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Jul 2 14:54:51 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Thu Jul 2 14:54:51 2015 +0200

----------------------------------------------------------------------
 .../agent/api/UpdateHostPasswordCommand.java    | 17 +++++++++++--
 .../kvm/resource/LibvirtComputingResource.java  | 20 ++++++++++++++++
 ...LibvirtUpdateHostPasswordCommandWrapper.java | 19 ++++++++++++++-
 .../resource/LibvirtComputingResourceTest.java  |  7 ++++--
 scripts/vm/hypervisor/update_host_passwd.sh     | 25 ++++++++++++++++++++
 .../com/cloud/resource/ResourceManagerImpl.java |  7 +++++-
 6 files changed, 89 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java b/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java
index e8dfa13..1a75168 100644
--- a/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java
+++ b/core/src/com/cloud/agent/api/UpdateHostPasswordCommand.java
@@ -22,17 +22,26 @@ package com.cloud.agent.api;
 import com.cloud.agent.api.LogLevel.Log4jLevel;
 
 public class UpdateHostPasswordCommand extends Command {
+
     @LogLevel(Log4jLevel.Off)
     protected String username;
     @LogLevel(Log4jLevel.Off)
     protected String newPassword;
+    @LogLevel(Log4jLevel.Off)
+    protected String hostIp;
+
 
     protected UpdateHostPasswordCommand() {
     }
 
-    public UpdateHostPasswordCommand(String username, String newPassword) {
+    public UpdateHostPasswordCommand(final String username, final String newPassword) {
+        this(username, newPassword, null);
+    }
+
+    public UpdateHostPasswordCommand(final String username, final String newPassword, final String hostIp) {
         this.username = username;
         this.newPassword = newPassword;
+        this.hostIp = hostIp;
     }
 
     public String getNewPassword() {
@@ -43,8 +52,12 @@ public class UpdateHostPasswordCommand extends Command {
         return username;
     }
 
+    public String getHostIp() {
+        return hostIp;
+    }
+
     @Override
     public boolean executeInSequence() {
         return false;
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 7bd02d0..bc28f82 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -257,6 +257,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
     private String _pingTestPath;
 
+    private String _updateHostPasswdPath;
+
     private int _dom0MinMem;
 
     protected boolean _disconnected = true;
@@ -372,6 +374,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _pingTestPath;
     }
 
+    public String getUpdateHostPasswdPath() {
+        return _updateHostPasswdPath;
+    }
+
     public int getTimeout() {
         return _timeout;
     }
@@ -516,6 +522,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return "scripts/storage/qcow2";
     }
 
+    protected String getDefaultHypervisorScriptsDir() {
+        return "scripts/vm/hypervisor";
+    }
+
     protected String getDefaultKvmScriptsDir() {
         return "scripts/vm/hypervisor/kvm";
     }
@@ -547,6 +557,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             domrScriptsDir = getDefaultDomrScriptsDir();
         }
 
+        final String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir");
+        if (hypervisorScriptsDir == null) {
+            getDefaultHypervisorScriptsDir();
+        }
+
         String kvmScriptsDir = (String)params.get("kvm.scripts.dir");
         if (kvmScriptsDir == null) {
             kvmScriptsDir = getDefaultKvmScriptsDir();
@@ -595,6 +610,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
         _clusterId = (String)params.get("cluster");
 
+        _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, "update_host_passwd.sh");
+        if (_updateHostPasswdPath == null) {
+            throw new ConfigurationException("Unable to find update_host_passwd.sh");
+        }
+
         _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh");
         if (_modifyVlanPath == null) {
             throw new ConfigurationException("Unable to find modifyvlan.sh");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
index 5b7c7da..7ed827d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
@@ -19,17 +19,34 @@
 
 package com.cloud.hypervisor.kvm.resource.wrapper;
 
+import org.apache.log4j.Logger;
+
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.UpdateHostPasswordCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.ResourceWrapper;
+import com.cloud.utils.script.Script;
 
 @ResourceWrapper(handles =  UpdateHostPasswordCommand.class)
 public final class LibvirtUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, LibvirtComputingResource> {
 
+    private static final Logger s_logger = Logger.getLogger(LibvirtUpdateHostPasswordCommandWrapper.class);
+    private static final int TIMEOUT = 10000;
+
     @Override
     public Answer execute(final UpdateHostPasswordCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        return new Answer(command, true, null);
+        final String hostIp = command.getHostIp();
+        final String username = command.getUsername();
+        final String newPassword = command.getNewPassword();
+
+        final Script script = new Script(libvirtComputingResource.getUpdateHostPasswdPath(), TIMEOUT, s_logger);
+        script.add(hostIp, username, newPassword);
+        final String result = script.execute();
+
+        if (result != null) {
+            return new Answer(command, false, result);
+        }
+        return new Answer(command);
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index d5ce9bf..8ccdce5 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -5076,15 +5076,18 @@ public class LibvirtComputingResourceTest {
 
     @Test
     public void testUpdateHostPasswordCommand() {
+        final String hostIp = "127.0.0.1";
         final String username = "root";
         final String newPassword = "password";
-        final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword);
+        final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword, hostIp);
+
+        when(libvirtComputingResource.getUpdateHostPasswdPath()).thenReturn("/tmp");
 
         final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
 
-        assertTrue(answer.getResult());
+        assertFalse(answer.getResult());
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/scripts/vm/hypervisor/update_host_passwd.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/update_host_passwd.sh b/scripts/vm/hypervisor/update_host_passwd.sh
new file mode 100755
index 0000000..7d4eec5
--- /dev/null
+++ b/scripts/vm/hypervisor/update_host_passwd.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+hostIp=$1
+username=$2
+new_passwd=$3
+
+ssh -o StrictHostKeyChecking=no -p 3922 -i /root/.ssh/id_rsa.cloud root@$hostIp "echo -e "$new_passwd\n$new_passwd" | passwd --stdin $username"
+
+return $?;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/47c7a108/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index b6f7f4e..c31d2a5 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2233,7 +2233,12 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
         final String username = nv.getValue();
         nv = _hostDetailsDao.findDetail(hostId, ApiConstants.PASSWORD);
         final String password = nv.getValue();
-        final UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password);
+
+
+        final HostVO host = _hostDao.findById(hostId);
+        final String hostIpAddress = host.getPrivateIpAddress();
+
+        final UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password, hostIpAddress);
         final Answer answer = _agentMgr.easySend(hostId, cmd);
         return answer.getResult();
     }


[11/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8180 - RouterVM does no longer provide X-ForwardedFor header with Loadbalancer

   - Formatting code

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

CLOUDSTACK-8180 - RouterVM does no longer provide X-ForwardedFor header with Loadbalancer

   - Make sure the "option forwardfor" is always available by not removing it
   - If keepalived is enabled, then set "no option forceclose"

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

This closes #549


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/23c66420
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/23c66420
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/23c66420

Branch: refs/heads/reporter
Commit: 23c664209a37419e20947c8e5af114bafa377ee5
Parents: 93b201d
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed Jul 1 11:51:06 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 14:50:23 2015 +0200

----------------------------------------------------------------------
 .../com/cloud/network/HAProxyConfigurator.java  | 269 ++++++++++---------
 1 file changed, 146 insertions(+), 123 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/23c66420/core/src/com/cloud/network/HAProxyConfigurator.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/network/HAProxyConfigurator.java b/core/src/com/cloud/network/HAProxyConfigurator.java
index c3c35f3..bc428c5 100644
--- a/core/src/com/cloud/network/HAProxyConfigurator.java
+++ b/core/src/com/cloud/network/HAProxyConfigurator.java
@@ -51,13 +51,13 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
     private static String[] defaultListen = {"listen  vmops 0.0.0.0:9", "\toption transparent"};
 
     @Override
-    public String[] generateConfiguration(List<PortForwardingRuleTO> fwRules) {
+    public String[] generateConfiguration(final List<PortForwardingRuleTO> fwRules) {
         // Group the rules by publicip:publicport
-        Map<String, List<PortForwardingRuleTO>> pools = new HashMap<String, List<PortForwardingRuleTO>>();
+        final Map<String, List<PortForwardingRuleTO>> pools = new HashMap<String, List<PortForwardingRuleTO>>();
 
-        for (PortForwardingRuleTO rule : fwRules) {
-            StringBuilder sb = new StringBuilder();
-            String poolName = sb.append(rule.getSrcIp().replace(".", "_")).append('-').append(rule.getSrcPortRange()[0]).toString();
+        for (final PortForwardingRuleTO rule : fwRules) {
+            final StringBuilder sb = new StringBuilder();
+            final String poolName = sb.append(rule.getSrcIp().replace(".", "_")).append('-').append(rule.getSrcPortRange()[0]).toString();
             if (!rule.revoked()) {
                 List<PortForwardingRuleTO> fwList = pools.get(poolName);
                 if (fwList == null) {
@@ -68,7 +68,7 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
             }
         }
 
-        List<String> result = new ArrayList<String>();
+        final List<String> result = new ArrayList<String>();
 
         result.addAll(Arrays.asList(globalSection));
         result.add(blankLine);
@@ -83,21 +83,21 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
         }
         result.add(blankLine);
 
-        for (Map.Entry<String, List<PortForwardingRuleTO>> e : pools.entrySet()) {
-            List<String> poolRules = getRulesForPool(e.getKey(), e.getValue());
+        for (final Map.Entry<String, List<PortForwardingRuleTO>> e : pools.entrySet()) {
+            final List<String> poolRules = getRulesForPool(e.getKey(), e.getValue());
             result.addAll(poolRules);
         }
 
         return result.toArray(new String[result.size()]);
     }
 
-    private List<String> getRulesForPool(String poolName, List<PortForwardingRuleTO> fwRules) {
-        PortForwardingRuleTO firstRule = fwRules.get(0);
-        String publicIP = firstRule.getSrcIp();
-        String publicPort = Integer.toString(firstRule.getSrcPortRange()[0]);
+    private List<String> getRulesForPool(final String poolName, final List<PortForwardingRuleTO> fwRules) {
+        final PortForwardingRuleTO firstRule = fwRules.get(0);
+        final String publicIP = firstRule.getSrcIp();
+        final String publicPort = Integer.toString(firstRule.getSrcPortRange()[0]);
         // FIXEME: String algorithm = firstRule.getAlgorithm();
 
-        List<String> result = new ArrayList<String>();
+        final List<String> result = new ArrayList<String>();
         // add line like this: "listen  65_37_141_30-80 65.37.141.30:80"
         StringBuilder sb = new StringBuilder();
         sb.append("listen ").append(poolName).append(" ").append(publicIP).append(":").append(publicPort);
@@ -106,8 +106,8 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
         // FIXME sb.append("\t").append("balance ").append(algorithm);
         result.add(sb.toString());
         if (publicPort.equals(NetUtils.HTTP_PORT)
-        // && global option httpclose set (or maybe not in this spot???)
-        ) {
+                // && global option httpclose set (or maybe not in this spot???)
+                ) {
             sb = new StringBuilder();
             sb.append("\t").append("mode http");
             result.add(sb.toString());
@@ -116,22 +116,22 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
             result.add(sb.toString());
         }
         int i = 0;
-        for (PortForwardingRuleTO rule : fwRules) {
+        for (final PortForwardingRuleTO rule : fwRules) {
             // add line like this: "server  65_37_141_30-80_3 10.1.1.4:80 check"
             if (rule.revoked()) {
                 continue;
             }
             sb = new StringBuilder();
             sb.append("\t")
-                .append("server ")
-                .append(poolName)
-                .append("_")
-                .append(Integer.toString(i++))
-                .append(" ")
-                .append(rule.getDstIp())
-                .append(":")
-                .append(rule.getDstPortRange()[0])
-                .append(" check");
+            .append("server ")
+            .append(poolName)
+            .append("_")
+            .append(Integer.toString(i++))
+            .append(" ")
+            .append(rule.getDstIp())
+            .append(":")
+            .append(rule.getDstPortRange()[0])
+            .append(" check");
             result.add(sb.toString());
         }
         result.add(blankLine);
@@ -298,19 +298,21 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
     The definition of an application cookie is limited to one per backend.
     Example :
           appsession JSESSIONID len 52 timeout 3h
-    */
-    private String getLbSubRuleForStickiness(LoadBalancerTO lbTO) {
+     */
+    private String getLbSubRuleForStickiness(final LoadBalancerTO lbTO) {
         int i = 0;
 
-        if (lbTO.getStickinessPolicies() == null)
+        if (lbTO.getStickinessPolicies() == null) {
             return null;
+        }
 
-        StringBuilder sb = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
 
-        for (StickinessPolicyTO stickinessPolicy : lbTO.getStickinessPolicies()) {
-            if (stickinessPolicy == null)
+        for (final StickinessPolicyTO stickinessPolicy : lbTO.getStickinessPolicies()) {
+            if (stickinessPolicy == null) {
                 continue;
-            List<Pair<String, String>> paramsList = stickinessPolicy.getParams();
+            }
+            final List<Pair<String, String>> paramsList = stickinessPolicy.getParams();
             i++;
 
             /*
@@ -327,13 +329,15 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
                 Boolean postonly = false; // optional
                 StringBuilder domainSb = null; // optional
 
-                for (Pair<String, String> paramKV : paramsList) {
-                    String key = paramKV.first();
-                    String value = paramKV.second();
-                    if ("cookie-name".equalsIgnoreCase(key))
+                for (final Pair<String, String> paramKV : paramsList) {
+                    final String key = paramKV.first();
+                    final String value = paramKV.second();
+                    if ("cookie-name".equalsIgnoreCase(key)) {
                         cookieName = value;
-                    if ("mode".equalsIgnoreCase(key))
+                    }
+                    if ("mode".equalsIgnoreCase(key)) {
                         mode = value;
+                    }
                     if ("domain".equalsIgnoreCase(key)) {
                         if (domainSb == null) {
                             domainSb = new StringBuilder();
@@ -341,43 +345,53 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
                         domainSb = domainSb.append("domain ");
                         domainSb.append(value).append(" ");
                     }
-                    if ("indirect".equalsIgnoreCase(key))
+                    if ("indirect".equalsIgnoreCase(key)) {
                         indirect = true;
-                    if ("nocache".equalsIgnoreCase(key))
+                    }
+                    if ("nocache".equalsIgnoreCase(key)) {
                         nocache = true;
-                    if ("postonly".equalsIgnoreCase(key))
+                    }
+                    if ("postonly".equalsIgnoreCase(key)) {
                         postonly = true;
+                    }
                 }
                 if (cookieName == null) {// re-check all haproxy mandatory params
-                    StringBuilder tempSb = new StringBuilder();
+                    final StringBuilder tempSb = new StringBuilder();
                     String srcip = lbTO.getSrcIp();
-                    if (srcip == null)
+                    if (srcip == null) {
                         srcip = "TESTCOOKIE";
+                    }
                     tempSb.append("lbcooki_").append(srcip.hashCode()).append("_").append(lbTO.getSrcPort());
                     cookieName = tempSb.toString();
                 }
                 sb.append("\t").append("cookie ").append(cookieName).append(" ").append(mode).append(" ");
-                if (indirect)
+                if (indirect) {
                     sb.append("indirect ");
-                if (nocache)
+                }
+                if (nocache) {
                     sb.append("nocache ");
-                if (postonly)
+                }
+                if (postonly) {
                     sb.append("postonly ");
-                if (domainSb != null)
+                }
+                if (domainSb != null) {
                     sb.append(domainSb).append(" ");
+                }
             } else if (StickinessMethodType.SourceBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName())) {
                 /* Default Values */
                 String tablesize = "200k"; // optional
                 String expire = "30m"; // optional
 
                 /* overwrite default values with the stick parameters */
-                for (Pair<String, String> paramKV : paramsList) {
-                    String key = paramKV.first();
-                    String value = paramKV.second();
-                    if ("tablesize".equalsIgnoreCase(key))
+                for (final Pair<String, String> paramKV : paramsList) {
+                    final String key = paramKV.first();
+                    final String value = paramKV.second();
+                    if ("tablesize".equalsIgnoreCase(key)) {
                         tablesize = value;
-                    if ("expire".equalsIgnoreCase(key))
+                    }
+                    if ("expire".equalsIgnoreCase(key)) {
                         expire = value;
+                    }
                 }
                 sb.append("\t").append("stick-table type ip size ").append(tablesize).append(" expire ").append(expire);
                 sb.append("\n\t").append("stick on src");
@@ -395,37 +409,47 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
                 Boolean requestlearn = false; // optional
                 Boolean prefix = false; // optional
 
-                for (Pair<String, String> paramKV : paramsList) {
-                    String key = paramKV.first();
-                    String value = paramKV.second();
-                    if ("cookie-name".equalsIgnoreCase(key))
+                for (final Pair<String, String> paramKV : paramsList) {
+                    final String key = paramKV.first();
+                    final String value = paramKV.second();
+                    if ("cookie-name".equalsIgnoreCase(key)) {
                         cookieName = value;
-                    if ("length".equalsIgnoreCase(key))
+                    }
+                    if ("length".equalsIgnoreCase(key)) {
                         length = value;
-                    if ("holdtime".equalsIgnoreCase(key))
+                    }
+                    if ("holdtime".equalsIgnoreCase(key)) {
                         holdtime = value;
-                    if ("mode".equalsIgnoreCase(key))
+                    }
+                    if ("mode".equalsIgnoreCase(key)) {
                         mode = value;
-                    if ("request-learn".equalsIgnoreCase(key))
+                    }
+                    if ("request-learn".equalsIgnoreCase(key)) {
                         requestlearn = true;
-                    if ("prefix".equalsIgnoreCase(key))
+                    }
+                    if ("prefix".equalsIgnoreCase(key)) {
                         prefix = true;
+                    }
                 }
                 if (cookieName == null) {// re-check all haproxy mandatory params
-                    StringBuilder tempSb = new StringBuilder();
+                    final StringBuilder tempSb = new StringBuilder();
                     String srcip = lbTO.getSrcIp();
-                    if (srcip == null)
+                    if (srcip == null) {
                         srcip = "TESTCOOKIE";
+                    }
                     tempSb.append("appcookie_").append(srcip.hashCode()).append("_").append(lbTO.getSrcPort());
                     cookieName = tempSb.toString();
                 }
                 sb.append("\t").append("appsession ").append(cookieName).append(" len ").append(length).append(" timeout ").append(holdtime).append(" ");
-                if (prefix)
+                if (prefix) {
                     sb.append("prefix ");
-                if (requestlearn)
+                }
+                if (requestlearn) {
                     sb.append("request-learn").append(" ");
-                if (mode != null)
+                }
+                if (mode != null) {
                     sb.append("mode ").append(mode).append(" ");
+                }
             } else {
                 /*
                  * Error is silently swallowed.
@@ -436,19 +460,20 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
                 return null;
             }
         }
-        if (i == 0)
+        if (i == 0) {
             return null;
+        }
         return sb.toString();
     }
 
-    private List<String> getRulesForPool(LoadBalancerTO lbTO, boolean keepAliveEnabled) {
+    private List<String> getRulesForPool(final LoadBalancerTO lbTO, final boolean keepAliveEnabled) {
         StringBuilder sb = new StringBuilder();
-        String poolName = sb.append(lbTO.getSrcIp().replace(".", "_")).append('-').append(lbTO.getSrcPort()).toString();
-        String publicIP = lbTO.getSrcIp();
-        String publicPort = Integer.toString(lbTO.getSrcPort());
-        String algorithm = lbTO.getAlgorithm();
+        final String poolName = sb.append(lbTO.getSrcIp().replace(".", "_")).append('-').append(lbTO.getSrcPort()).toString();
+        final String publicIP = lbTO.getSrcIp();
+        final String publicPort = Integer.toString(lbTO.getSrcPort());
+        final String algorithm = lbTO.getAlgorithm();
 
-        List<String> result = new ArrayList<String>();
+        final List<String> result = new ArrayList<String>();
         // add line like this: "listen  65_37_141_30-80 65.37.141.30:80"
         sb = new StringBuilder();
         sb.append("listen ").append(poolName).append(" ").append(publicIP).append(":").append(publicPort);
@@ -459,25 +484,25 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
 
         int i = 0;
         Boolean destsAvailable = false;
-        String stickinessSubRule = getLbSubRuleForStickiness(lbTO);
-        List<String> dstSubRule = new ArrayList<String>();
-        List<String> dstWithCookieSubRule = new ArrayList<String>();
-        for (DestinationTO dest : lbTO.getDestinations()) {
+        final String stickinessSubRule = getLbSubRuleForStickiness(lbTO);
+        final List<String> dstSubRule = new ArrayList<String>();
+        final List<String> dstWithCookieSubRule = new ArrayList<String>();
+        for (final DestinationTO dest : lbTO.getDestinations()) {
             // add line like this: "server  65_37_141_30-80_3 10.1.1.4:80 check"
             if (dest.isRevoked()) {
                 continue;
             }
             sb = new StringBuilder();
             sb.append("\t")
-                .append("server ")
-                .append(poolName)
-                .append("_")
-                .append(Integer.toString(i++))
-                .append(" ")
-                .append(dest.getDestIp())
-                .append(":")
-                .append(dest.getDestPort())
-                .append(" check");
+            .append("server ")
+            .append(poolName)
+            .append("_")
+            .append(Integer.toString(i++))
+            .append(" ")
+            .append(dest.getDestIp())
+            .append(":")
+            .append(dest.getDestPort())
+            .append(" check");
             dstSubRule.add(sb.toString());
             if (stickinessSubRule != null) {
                 sb.append(" cookie ").append(dest.getDestIp().replace(".", "_")).append('-').append(dest.getDestPort()).toString();
@@ -488,12 +513,13 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
 
         Boolean httpbasedStickiness = false;
         /* attach stickiness sub rule only if the destinations are available */
-        if ((stickinessSubRule != null) && (destsAvailable == true)) {
-            for (StickinessPolicyTO stickinessPolicy : lbTO.getStickinessPolicies()) {
-                if (stickinessPolicy == null)
+        if (stickinessSubRule != null && destsAvailable == true) {
+            for (final StickinessPolicyTO stickinessPolicy : lbTO.getStickinessPolicies()) {
+                if (stickinessPolicy == null) {
                     continue;
+                }
                 if (StickinessMethodType.LBCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName()) ||
-                    StickinessMethodType.AppCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName())) {
+                        StickinessMethodType.AppCookieBased.getName().equalsIgnoreCase(stickinessPolicy.getMethodName())) {
                     httpbasedStickiness = true;
                 }
             }
@@ -506,10 +532,10 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
         } else {
             result.addAll(dstSubRule);
         }
-        if ((stickinessSubRule != null) && !destsAvailable) {
+        if (stickinessSubRule != null && !destsAvailable) {
             s_logger.warn("Haproxy stickiness policy for lb rule: " + lbTO.getSrcIp() + ":" + lbTO.getSrcPort() + ": Not Applied, cause:  backends are unavailable");
         }
-        if ((publicPort.equals(NetUtils.HTTP_PORT) && !keepAliveEnabled) || (httpbasedStickiness)) {
+        if (publicPort.equals(NetUtils.HTTP_PORT) && !keepAliveEnabled || httpbasedStickiness) {
             sb = new StringBuilder();
             sb.append("\t").append("mode http");
             result.add(sb.toString());
@@ -522,19 +548,19 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
         return result;
     }
 
-    private String generateStatsRule(LoadBalancerConfigCommand lbCmd, String ruleName, String statsIp) {
-        StringBuilder rule = new StringBuilder("\nlisten ").append(ruleName).append(" ").append(statsIp).append(":").append(lbCmd.lbStatsPort);
+    private String generateStatsRule(final LoadBalancerConfigCommand lbCmd, final String ruleName, final String statsIp) {
+        final StringBuilder rule = new StringBuilder("\nlisten ").append(ruleName).append(" ").append(statsIp).append(":").append(lbCmd.lbStatsPort);
         // TODO DH: write test for this in both cases
         if (!lbCmd.keepAliveEnabled) {
             s_logger.info("Haproxy mode http enabled");
             rule.append("\n\tmode http\n\toption httpclose");
         }
         rule.append("\n\tstats enable\n\tstats uri     ")
-            .append(lbCmd.lbStatsUri)
-            .append("\n\tstats realm   Haproxy\\ Statistics\n\tstats auth    ")
-            .append(lbCmd.lbStatsAuth);
+        .append(lbCmd.lbStatsUri)
+        .append("\n\tstats realm   Haproxy\\ Statistics\n\tstats auth    ")
+        .append(lbCmd.lbStatsAuth);
         rule.append("\n");
-        String result = rule.toString();
+        final String result = rule.toString();
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Haproxystats rule: " + result);
         }
@@ -542,35 +568,32 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
     }
 
     @Override
-    public String[] generateConfiguration(LoadBalancerConfigCommand lbCmd) {
-        List<String> result = new ArrayList<String>();
-        List<String> gSection = Arrays.asList(globalSection);
-//        note that this is overwritten on the String in the static ArrayList<String>
+    public String[] generateConfiguration(final LoadBalancerConfigCommand lbCmd) {
+        final List<String> result = new ArrayList<String>();
+        final List<String> gSection = Arrays.asList(globalSection);
+        //        note that this is overwritten on the String in the static ArrayList<String>
         gSection.set(2, "\tmaxconn " + lbCmd.maxconn);
         // TODO DH: write test for this function
-        String pipesLine = "\tmaxpipes " + Long.toString(Long.parseLong(lbCmd.maxconn) / 4);
+        final String pipesLine = "\tmaxpipes " + Long.toString(Long.parseLong(lbCmd.maxconn) / 4);
         gSection.set(3, pipesLine);
         if (s_logger.isDebugEnabled()) {
-            for (String s : gSection) {
+            for (final String s : gSection) {
                 s_logger.debug("global section: " + s);
             }
         }
         result.addAll(gSection);
         // TODO decide under what circumstances these options are needed
-//        result.add("\tnokqueue");
-//        result.add("\tnopoll");
+        //        result.add("\tnokqueue");
+        //        result.add("\tnopoll");
 
         result.add(blankLine);
-        List<String> dSection = Arrays.asList(defaultsSection);
+        final List<String> dSection = Arrays.asList(defaultsSection);
         if (lbCmd.keepAliveEnabled) {
-            dSection.set(6, "\t#no option set here :<");
             dSection.set(7, "\tno option forceclose");
-        } else {
-            dSection.set(6, "\toption forwardfor");
-            dSection.set(7, "\toption forceclose");
         }
+
         if (s_logger.isDebugEnabled()) {
-            for (String s : dSection) {
+            for (final String s : dSection) {
                 s_logger.debug("default section: " + s);
             }
         }
@@ -592,8 +615,8 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
                  * stats will be available on the default http serving port, no
                  * special stats port
                  */
-                StringBuilder subRule =
-                    new StringBuilder("\tstats enable\n\tstats uri     ").append(lbCmd.lbStatsUri)
+                final StringBuilder subRule =
+                        new StringBuilder("\tstats enable\n\tstats uri     ").append(lbCmd.lbStatsUri)
                         .append("\n\tstats realm   Haproxy\\ Statistics\n\tstats auth    ")
                         .append(lbCmd.lbStatsAuth);
                 result.add(subRule.toString());
@@ -602,11 +625,11 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
         }
         result.add(blankLine);
         boolean has_listener = false;
-        for (LoadBalancerTO lbTO : lbCmd.getLoadBalancers()) {
+        for (final LoadBalancerTO lbTO : lbCmd.getLoadBalancers()) {
             if (lbTO.isRevoked()) {
                 continue;
             }
-            List<String> poolRules = getRulesForPool(lbTO, lbCmd.keepAliveEnabled);
+            final List<String> poolRules = getRulesForPool(lbTO, lbCmd.keepAliveEnabled);
             result.addAll(poolRules);
             has_listener = true;
         }
@@ -621,18 +644,18 @@ public class HAProxyConfigurator implements LoadBalancerConfigurator {
     }
 
     @Override
-    public String[][] generateFwRules(LoadBalancerConfigCommand lbCmd) {
-        String[][] result = new String[3][];
-        Set<String> toAdd = new HashSet<String>();
-        Set<String> toRemove = new HashSet<String>();
-        Set<String> toStats = new HashSet<String>();
+    public String[][] generateFwRules(final LoadBalancerConfigCommand lbCmd) {
+        final String[][] result = new String[3][];
+        final Set<String> toAdd = new HashSet<String>();
+        final Set<String> toRemove = new HashSet<String>();
+        final Set<String> toStats = new HashSet<String>();
 
-        for (LoadBalancerTO lbTO : lbCmd.getLoadBalancers()) {
+        for (final LoadBalancerTO lbTO : lbCmd.getLoadBalancers()) {
 
-            StringBuilder sb = new StringBuilder();
+            final StringBuilder sb = new StringBuilder();
             sb.append(lbTO.getSrcIp()).append(":");
             sb.append(lbTO.getSrcPort()).append(":");
-            String lbRuleEntry = sb.toString();
+            final String lbRuleEntry = sb.toString();
             if (!lbTO.isRevoked()) {
                 toAdd.add(lbRuleEntry);
             } else {


[03/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java
index 17a0a30..817e62c 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmd.java
@@ -17,7 +17,6 @@
 package org.apache.cloudstack.api.command;
 
 import com.cloud.api.response.ApiResponseSerializer;
-import com.cloud.configuration.Config;
 import com.cloud.user.Account;
 import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.ApiErrorCode;
@@ -28,13 +27,13 @@ import org.apache.cloudstack.api.auth.APIAuthenticationType;
 import org.apache.cloudstack.api.auth.APIAuthenticator;
 import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
 import org.apache.cloudstack.api.response.LogoutCmdResponse;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.saml.SAML2AuthManager;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
+import org.apache.cloudstack.saml.SAMLPluginConstants;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
+import org.apache.cloudstack.saml.SAMLUtils;
 import org.apache.log4j.Logger;
 import org.opensaml.DefaultBootstrap;
 import org.opensaml.saml2.core.LogoutRequest;
-import org.opensaml.saml2.core.NameID;
 import org.opensaml.saml2.core.Response;
 import org.opensaml.saml2.core.StatusCode;
 import org.opensaml.xml.ConfigurationException;
@@ -60,8 +59,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen
 
     @Inject
     ApiServerService _apiServer;
-    @Inject
-    ConfigurationDao _configDao;
+
     SAML2AuthManager _samlAuthManager;
 
     /////////////////////////////////////////////////////
@@ -94,7 +92,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen
 
         if (session == null) {
             try {
-                resp.sendRedirect(_configDao.getValue(Config.SAMLCloudStackRedirectionUrl.key()));
+                resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
             } catch (IOException ignored) {
             }
             return responseString;
@@ -111,7 +109,7 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen
 
         if (params != null && params.containsKey("SAMLResponse")) {
             try {
-                final String samlResponse = ((String[])params.get(SAMLUtils.SAML_RESPONSE))[0];
+                final String samlResponse = ((String[])params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
                 Response processedSAMLResponse = SAMLUtils.decodeSAMLResponse(samlResponse);
                 String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
                 if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
@@ -123,25 +121,26 @@ public class SAML2LogoutAPIAuthenticatorCmd extends BaseCmd implements APIAuthen
                 s_logger.error("SAMLResponse processing error: " + e.getMessage());
             }
             try {
-                resp.sendRedirect(_configDao.getValue(Config.SAMLCloudStackRedirectionUrl.key()));
+                resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
             } catch (IOException ignored) {
             }
             return responseString;
         }
 
-        NameID nameId = (NameID) session.getAttribute(SAMLUtils.SAML_NAMEID);
-        String sessionIndex = (String) session.getAttribute(SAMLUtils.SAML_SESSION);
-        if (nameId == null || sessionIndex == null) {
+        String idpId = (String) session.getAttribute(SAMLPluginConstants.SAML_IDPID);
+        SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
+        String nameId = (String) session.getAttribute(SAMLPluginConstants.SAML_NAMEID);
+        if (idpMetadata == null || nameId == null || nameId.isEmpty()) {
             try {
-                resp.sendRedirect(_configDao.getValue(Config.SAMLCloudStackRedirectionUrl.key()));
+                resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
             } catch (IOException ignored) {
             }
             return responseString;
         }
-        LogoutRequest logoutRequest = SAMLUtils.buildLogoutRequest(_samlAuthManager.getIdpSingleLogOutUrl(), _samlAuthManager.getServiceProviderId(), nameId, sessionIndex);
+        LogoutRequest logoutRequest = SAMLUtils.buildLogoutRequest(idpMetadata.getSloUrl(), _samlAuthManager.getSPMetadata().getEntityId(), nameId);
 
         try {
-            String redirectUrl = _samlAuthManager.getIdpSingleLogOutUrl() + "?SAMLRequest=" + SAMLUtils.encodeSAMLRequest(logoutRequest);
+            String redirectUrl = idpMetadata.getSloUrl() + "?SAMLRequest=" + SAMLUtils.encodeSAMLRequest(logoutRequest);
             resp.sendRedirect(redirectUrl);
         } catch (MarshallingException | IOException e) {
             s_logger.error("SAML SLO error: " + e.getMessage());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/IdpResponse.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/IdpResponse.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/IdpResponse.java
new file mode 100644
index 0000000..d95cc33
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/IdpResponse.java
@@ -0,0 +1,62 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.response;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+public class IdpResponse extends AuthenticationCmdResponse {
+    @SerializedName("id")
+    @Param(description = "The IdP Entity ID")
+    private String id;
+
+    @SerializedName("orgName")
+    @Param(description = "The IdP Organization Name")
+    private String orgName;
+
+    @SerializedName("orgUrl")
+    @Param(description = "The IdP Organization URL")
+    private String orgUrl;
+
+    public IdpResponse() {
+        super();
+    }
+
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getOrgName() {
+        return orgName;
+    }
+
+    public void setOrgName(String orgName) {
+        this.orgName = orgName;
+    }
+
+    public String getOrgUrl() {
+        return orgUrl;
+    }
+
+    public void setOrgUrl(String orgUrl) {
+        this.orgUrl = orgUrl;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/SamlAuthorizationResponse.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/SamlAuthorizationResponse.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/SamlAuthorizationResponse.java
new file mode 100644
index 0000000..445ee88
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/response/SamlAuthorizationResponse.java
@@ -0,0 +1,68 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.api.response;
+
+import com.cloud.serializer.Param;
+import com.cloud.user.User;
+import com.google.gson.annotations.SerializedName;
+import org.apache.cloudstack.api.BaseResponse;
+import org.apache.cloudstack.api.EntityReference;
+
+@EntityReference(value = User.class)
+public class SamlAuthorizationResponse extends BaseResponse {
+    @SerializedName("userid")
+    @Param(description = "the user ID")
+    private String userId;
+
+    @SerializedName("status")
+    @Param(description = "the SAML authorization status")
+    private Boolean status;
+
+    @SerializedName("idpid")
+    @Param(description = "the authorized Identity Provider ID")
+    private String idpId;
+
+    public SamlAuthorizationResponse(String userId, Boolean status, String idpId) {
+        this.userId = userId;
+        this.status = status;
+        this.idpId = idpId;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
+    public Boolean getStatus() {
+        return status;
+    }
+
+    public void setStatus(Boolean status) {
+        this.status = status;
+    }
+
+    public String getIdpId() {
+        return idpId;
+    }
+
+    public void setIdpId(String idpId) {
+        this.idpId = idpId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManager.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManager.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManager.java
index 9c0d4b4..fc9a6db 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManager.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManager.java
@@ -17,23 +17,64 @@
 
 package org.apache.cloudstack.saml;
 
+import com.cloud.utils.component.PluggableService;
 import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
+import org.apache.cloudstack.framework.config.ConfigKey;
 
-import java.security.KeyPair;
-import java.security.cert.X509Certificate;
+import java.util.Collection;
 
-public interface SAML2AuthManager extends PluggableAPIAuthenticator {
-    public String getServiceProviderId();
-    public String getIdentityProviderId();
+public interface SAML2AuthManager extends PluggableAPIAuthenticator, PluggableService {
 
-    public X509Certificate getIdpSigningKey();
-    public X509Certificate getIdpEncryptionKey();
-    public X509Certificate getSpX509Certificate();
-    public KeyPair getSpKeyPair();
+    public static final ConfigKey<Boolean> SAMLIsPluginEnabled = new ConfigKey<Boolean>("Advanced", Boolean.class, "saml2.enabled", "false",
+            "Indicates whether SAML SSO plugin is enabled or not", true);
 
-    public String getSpSingleSignOnUrl();
-    public String getIdpSingleSignOnUrl();
+    public static final ConfigKey<String> SAMLServiceProviderID = new ConfigKey<String>("Advanced", String.class, "saml2.sp.id", "org.apache.cloudstack",
+            "SAML2 Service Provider Identifier String", true);
 
-    public String getSpSingleLogOutUrl();
-    public String getIdpSingleLogOutUrl();
+    public static final ConfigKey<String> SAMLServiceProviderContactPersonName = new ConfigKey<String>("Advanced", String.class, "saml2.sp.contact.person", "CloudStack Developers",
+            "SAML2 Service Provider Contact Person Name", true);
+
+    public static final ConfigKey<String> SAMLServiceProviderContactEmail = new ConfigKey<String>("Advanced", String.class, "saml2.sp.contact.email", "dev@cloudstack.apache.org",
+            "SAML2 Service Provider Contact Email Address", true);
+
+    public static final ConfigKey<String> SAMLServiceProviderOrgName = new ConfigKey<String>("Advanced", String.class, "saml2.sp.org.name", "Apache CloudStack",
+            "SAML2 Service Provider Organization Name", true);
+
+    public static final ConfigKey<String> SAMLServiceProviderOrgUrl = new ConfigKey<String>("Advanced", String.class, "saml2.sp.org.url", "http://cloudstack.apache.org",
+            "SAML2 Service Provider Organization URL", true);
+
+    public static final ConfigKey<String> SAMLServiceProviderSingleSignOnURL = new ConfigKey<String>("Advanced", String.class, "saml2.sp.sso.url", "http://localhost:8080/client/api?command=samlSso",
+            "SAML2 CloudStack Service Provider Single Sign On URL", true);
+
+    public static final ConfigKey<String> SAMLServiceProviderSingleLogOutURL = new ConfigKey<String>("Advanced", String.class, "saml2.sp.slo.url", "http://localhost:8080/client/",
+            "SAML2 CloudStack Service Provider Single Log Out URL", true);
+
+    public static final ConfigKey<String> SAMLCloudStackRedirectionUrl = new ConfigKey<String>("Advanced", String.class, "saml2.redirect.url", "http://localhost:8080/client",
+            "The CloudStack UI url the SSO should redirected to when successful", true);
+
+    public static final ConfigKey<String> SAMLUserAttributeName = new ConfigKey<String>("Advanced", String.class, "saml2.user.attribute", "uid",
+            "Attribute name to be looked for in SAML response that will contain the username", true);
+
+    public static final ConfigKey<String> SAMLIdentityProviderMetadataURL = new ConfigKey<String>("Advanced", String.class, "saml2.idp.metadata.url", "https://openidp.feide.no/simplesaml/saml2/idp/metadata.php",
+            "SAML2 Identity Provider Metadata XML Url", true);
+
+    public static final ConfigKey<String> SAMLDefaultIdentityProviderId = new ConfigKey<String>("Advanced", String.class, "saml2.default.idpid", "https://openidp.feide.no",
+            "The default IdP entity ID to use only in case of multiple IdPs", true);
+
+    public static final ConfigKey<String> SAMLSignatureAlgorithm = new ConfigKey<String>("Advanced", String.class, "saml2.sigalg", "SHA1",
+            "The algorithm to use to when signing a SAML request. Default is SHA1, allowed algorithms: SHA1, SHA256, SHA384, SHA512", true);
+
+    public static final ConfigKey<Integer> SAMLTimeout = new ConfigKey<Integer>("Advanced", Integer.class, "saml2.timeout", "1800",
+            "SAML2 IDP Metadata refresh interval in seconds, minimum value is set to 300", true);
+
+    public SAMLProviderMetadata getSPMetadata();
+    public SAMLProviderMetadata getIdPMetadata(String entityId);
+    public Collection<SAMLProviderMetadata> getAllIdPMetadata();
+
+    public boolean isUserAuthorized(Long userId, String entityId);
+    public boolean authorizeUser(Long userId, String entityId, boolean enable);
+
+    public void saveToken(String authnId, String domain, String entity);
+    public SAMLTokenVO getToken(String authnId);
+    public void expireTokens();
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java
index 36c9da5..185955c 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2AuthManagerImpl.java
@@ -16,28 +16,46 @@
 // under the License.
 package org.apache.cloudstack.saml;
 
-import com.cloud.configuration.Config;
+import com.cloud.domain.Domain;
+import com.cloud.user.DomainManager;
+import com.cloud.user.User;
+import com.cloud.user.UserVO;
+import com.cloud.user.dao.UserDao;
+import com.cloud.utils.PropertiesUtil;
 import com.cloud.utils.component.AdapterBase;
 import org.apache.cloudstack.api.auth.PluggableAPIAuthenticator;
+import org.apache.cloudstack.api.command.AuthorizeSAMLSSOCmd;
 import org.apache.cloudstack.api.command.GetServiceProviderMetaDataCmd;
+import org.apache.cloudstack.api.command.ListIdpsCmd;
+import org.apache.cloudstack.api.command.ListSamlAuthorizationCmd;
 import org.apache.cloudstack.api.command.SAML2LoginAPIAuthenticatorCmd;
 import org.apache.cloudstack.api.command.SAML2LogoutAPIAuthenticatorCmd;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
+import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.framework.security.keystore.KeystoreDao;
 import org.apache.cloudstack.framework.security.keystore.KeystoreVO;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
-import org.apache.log4j.Logger;
 import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.log4j.Logger;
 import org.opensaml.DefaultBootstrap;
 import org.opensaml.common.xml.SAMLConstants;
+import org.opensaml.saml2.metadata.ContactPerson;
+import org.opensaml.saml2.metadata.EmailAddress;
+import org.opensaml.saml2.metadata.EntitiesDescriptor;
 import org.opensaml.saml2.metadata.EntityDescriptor;
 import org.opensaml.saml2.metadata.IDPSSODescriptor;
 import org.opensaml.saml2.metadata.KeyDescriptor;
+import org.opensaml.saml2.metadata.OrganizationDisplayName;
+import org.opensaml.saml2.metadata.OrganizationName;
+import org.opensaml.saml2.metadata.OrganizationURL;
 import org.opensaml.saml2.metadata.SingleLogoutService;
 import org.opensaml.saml2.metadata.SingleSignOnService;
+import org.opensaml.saml2.metadata.provider.AbstractReloadingMetadataProvider;
+import org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider;
 import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider;
 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
 import org.opensaml.xml.ConfigurationException;
+import org.opensaml.xml.XMLObject;
 import org.opensaml.xml.parse.BasicParserPool;
 import org.opensaml.xml.security.credential.UsageType;
 import org.opensaml.xml.security.keyinfo.KeyInfoHelper;
@@ -48,6 +66,7 @@ import javax.inject.Inject;
 import javax.xml.stream.FactoryConfigurationError;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.File;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutput;
@@ -63,61 +82,87 @@ import java.security.cert.CertificateEncodingException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
 
 @Component
 @Local(value = {SAML2AuthManager.class, PluggableAPIAuthenticator.class})
-public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManager {
+public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManager, Configurable {
     private static final Logger s_logger = Logger.getLogger(SAML2AuthManagerImpl.class);
 
-    private String serviceProviderId;
-    private String identityProviderId;
+    private SAMLProviderMetadata _spMetadata = new SAMLProviderMetadata();
+    private Map<String, SAMLProviderMetadata> _idpMetadataMap = new HashMap<String, SAMLProviderMetadata>();
 
-    private X509Certificate idpSigningKey;
-    private X509Certificate idpEncryptionKey;
-    private X509Certificate spX509Key;
-    private KeyPair spKeyPair;
-
-    private String spSingleSignOnUrl;
     private String idpSingleSignOnUrl;
-
-    private String spSingleLogOutUrl;
     private String idpSingleLogOutUrl;
 
-    private HTTPMetadataProvider idpMetaDataProvider;
+    private Timer _timer;
+    private int _refreshInterval = SAMLPluginConstants.SAML_REFRESH_INTERVAL;
+    private AbstractReloadingMetadataProvider _idpMetaDataProvider;
 
     @Inject
-    ConfigurationDao _configDao;
+    private KeystoreDao _ksDao;
 
     @Inject
-    private KeystoreDao _ksDao;
+    private SAMLTokenDao _samlTokenDao;
+
+    @Inject
+    private UserDao _userDao;
+
+    @Inject
+    DomainManager _domainMgr;
 
     @Override
     public boolean start() {
         if (isSAMLPluginEnabled()) {
             setup();
+            s_logger.info("SAML auth plugin loaded");
+        } else {
+            s_logger.info("SAML auth plugin not enabled so not loading");
         }
         return super.start();
     }
 
-    private boolean setup() {
-        KeystoreVO keyStoreVO = _ksDao.findByName(SAMLUtils.SAMLSP_KEYPAIR);
+    @Override
+    public boolean stop() {
+        if (_timer != null) {
+            _timer.cancel();
+        }
+        return super.stop();
+    }
+
+    private boolean initSP() {
+        KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
         if (keyStoreVO == null) {
             try {
                 KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
-                _ksDao.save(SAMLUtils.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()), SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
-                keyStoreVO = _ksDao.findByName(SAMLUtils.SAMLSP_KEYPAIR);
+                _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()), SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
+                keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
+                s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
             } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
-                s_logger.error("Unable to create and save SAML keypair");
+                s_logger.error("Unable to create and save SAML keypair: " + e.toString());
             }
         }
 
+        String spId = SAMLServiceProviderID.value();
+        String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
+        String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
+        String spOrgName = SAMLServiceProviderOrgName.value();
+        String spOrgUrl = SAMLServiceProviderOrgUrl.value();
+        String spContactPersonName = SAMLServiceProviderContactPersonName.value();
+        String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
+        KeyPair spKeyPair = null;
+        X509Certificate spX509Key = null;
         if (keyStoreVO != null) {
             PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate());
             PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey());
             if (privateKey != null && publicKey != null) {
                 spKeyPair = new KeyPair(publicKey, privateKey);
-                KeystoreVO x509VO = _ksDao.findByName(SAMLUtils.SAMLSP_X509CERT);
+                KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
                 if (x509VO == null) {
                     try {
                         spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
@@ -125,7 +170,7 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage
                         ObjectOutput out = new ObjectOutputStream(bos);
                         out.writeObject(spX509Key);
                         out.flush();
-                        _ksDao.save(SAMLUtils.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
+                        _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
                         bos.close();
                     } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException | SignatureException | InvalidKeyException | IOException e) {
                         s_logger.error("SAML Plugin won't be able to use X509 signed authentication");
@@ -142,61 +187,194 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage
                 }
             }
         }
-
-        this.serviceProviderId = _configDao.getValue(Config.SAMLServiceProviderID.key());
-        this.identityProviderId = _configDao.getValue(Config.SAMLIdentityProviderID.key());
-
-        this.spSingleSignOnUrl = _configDao.getValue(Config.SAMLServiceProviderSingleSignOnURL.key());
-        this.spSingleLogOutUrl = _configDao.getValue(Config.SAMLServiceProviderSingleLogOutURL.key());
-
-        String idpMetaDataUrl = _configDao.getValue(Config.SAMLIdentityProviderMetadataURL.key());
-
-        int tolerance = 30000;
-        String timeout = _configDao.getValue(Config.SAMLTimeout.key());
-        if (timeout != null) {
-            tolerance = Integer.parseInt(timeout);
+        if (spKeyPair != null && spX509Key != null
+                && spId != null && spSsoUrl != null && spSloUrl != null
+                && spOrgName != null && spOrgUrl != null
+                && spContactPersonName != null && spContactPersonEmail != null) {
+            _spMetadata.setEntityId(spId);
+            _spMetadata.setOrganizationName(spOrgName);
+            _spMetadata.setOrganizationUrl(spOrgUrl);
+            _spMetadata.setContactPersonName(spContactPersonName);
+            _spMetadata.setContactPersonEmail(spContactPersonEmail);
+            _spMetadata.setSsoUrl(spSsoUrl);
+            _spMetadata.setSloUrl(spSloUrl);
+            _spMetadata.setKeyPair(spKeyPair);
+            _spMetadata.setSigningCertificate(spX509Key);
+            _spMetadata.setEncryptionCertificate(spX509Key);
+            return true;
         }
+        return false;
+    }
 
-        try {
-            DefaultBootstrap.bootstrap();
-            idpMetaDataProvider = new HTTPMetadataProvider(idpMetaDataUrl, tolerance);
-            idpMetaDataProvider.setRequireValidMetadata(true);
-            idpMetaDataProvider.setParserPool(new BasicParserPool());
-            idpMetaDataProvider.initialize();
+    private void addIdpToMap(EntityDescriptor descriptor, Map<String, SAMLProviderMetadata> idpMap) {
+        SAMLProviderMetadata idpMetadata = new SAMLProviderMetadata();
+        idpMetadata.setEntityId(descriptor.getEntityID());
+        s_logger.debug("Adding IdP to the list of discovered IdPs: " + descriptor.getEntityID());
+        if (descriptor.getOrganization() != null) {
+            if (descriptor.getOrganization().getDisplayNames() != null) {
+                for (OrganizationDisplayName orgName : descriptor.getOrganization().getDisplayNames()) {
+                    if (orgName != null && orgName.getName() != null) {
+                        idpMetadata.setOrganizationName(orgName.getName().getLocalString());
+                        break;
+                    }
+                }
+            }
+            if (idpMetadata.getOrganizationName() == null && descriptor.getOrganization().getOrganizationNames() != null) {
+                for (OrganizationName orgName : descriptor.getOrganization().getOrganizationNames()) {
+                    if (orgName != null && orgName.getName() != null) {
+                        idpMetadata.setOrganizationName(orgName.getName().getLocalString());
+                        break;
+                    }
+                }
+            }
+            if (descriptor.getOrganization().getURLs() != null) {
+                for (OrganizationURL organizationURL : descriptor.getOrganization().getURLs()) {
+                    if (organizationURL != null && organizationURL.getURL() != null) {
+                        idpMetadata.setOrganizationUrl(organizationURL.getURL().getLocalString());
+                        break;
+                    }
+                }
+            }
+        }
+        if (descriptor.getContactPersons() != null) {
+            for (ContactPerson person : descriptor.getContactPersons()) {
+                if (person == null || (person.getGivenName() == null && person.getSurName() == null)
+                        || person.getEmailAddresses() == null) {
+                    continue;
+                }
+                if (person.getGivenName() != null) {
+                    idpMetadata.setContactPersonName(person.getGivenName().getName());
 
-            EntityDescriptor idpEntityDescriptor = idpMetaDataProvider.getEntityDescriptor(this.identityProviderId);
+                } else if (person.getSurName() != null) {
+                    idpMetadata.setContactPersonName(person.getSurName().getName());
+                }
+                for (EmailAddress emailAddress : person.getEmailAddresses()) {
+                    if (emailAddress != null && emailAddress.getAddress() != null) {
+                        idpMetadata.setContactPersonEmail(emailAddress.getAddress());
+                    }
+                }
+                if (idpMetadata.getContactPersonName() != null && idpMetadata.getContactPersonEmail() != null) {
+                    break;
+                }
+            }
+        }
 
-            IDPSSODescriptor idpssoDescriptor = idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
-            if (idpssoDescriptor != null) {
-                for (SingleSignOnService ssos: idpssoDescriptor.getSingleSignOnServices()) {
+        IDPSSODescriptor idpDescriptor = descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
+        if (idpDescriptor != null) {
+            if (idpDescriptor.getSingleSignOnServices() != null) {
+                for (SingleSignOnService ssos : idpDescriptor.getSingleSignOnServices()) {
                     if (ssos.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
-                        this.idpSingleSignOnUrl = ssos.getLocation();
+                        idpMetadata.setSsoUrl(ssos.getLocation());
                     }
                 }
-
-                for (SingleLogoutService slos: idpssoDescriptor.getSingleLogoutServices()) {
+            }
+            if (idpDescriptor.getSingleLogoutServices() != null) {
+                for (SingleLogoutService slos : idpDescriptor.getSingleLogoutServices()) {
                     if (slos.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
-                        this.idpSingleLogOutUrl = slos.getLocation();
+                        idpMetadata.setSloUrl(slos.getLocation());
                     }
                 }
+            }
 
-                for (KeyDescriptor kd: idpssoDescriptor.getKeyDescriptors()) {
+            X509Certificate unspecifiedKey = null;
+            if (idpDescriptor.getKeyDescriptors() != null) {
+                for (KeyDescriptor kd : idpDescriptor.getKeyDescriptors()) {
                     if (kd.getUse() == UsageType.SIGNING) {
                         try {
-                            this.idpSigningKey = KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0);
+                            idpMetadata.setSigningCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0));
                         } catch (CertificateException ignored) {
                         }
                     }
                     if (kd.getUse() == UsageType.ENCRYPTION) {
                         try {
-                            this.idpEncryptionKey = KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0);
+                            idpMetadata.setEncryptionCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0));
+                        } catch (CertificateException ignored) {
+                        }
+                    }
+                    if (kd.getUse() == UsageType.UNSPECIFIED) {
+                        try {
+                            unspecifiedKey = KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0);
                         } catch (CertificateException ignored) {
                         }
                     }
                 }
+            }
+            if (idpMetadata.getSigningCertificate() == null && unspecifiedKey != null) {
+                idpMetadata.setSigningCertificate(unspecifiedKey);
+            }
+            if (idpMetadata.getEncryptionCertificate() == null && unspecifiedKey != null) {
+                idpMetadata.setEncryptionCertificate(unspecifiedKey);
+            }
+            if (idpMap.containsKey(idpMetadata.getEntityId())) {
+                s_logger.warn("Duplicate IdP metadata found with entity Id: " + idpMetadata.getEntityId());
+            }
+            idpMap.put(idpMetadata.getEntityId(), idpMetadata);
+        }
+    }
+
+    private void discoverAndAddIdp(XMLObject metadata, Map<String, SAMLProviderMetadata> idpMap) {
+        if (metadata instanceof EntityDescriptor) {
+            EntityDescriptor entityDescriptor = (EntityDescriptor) metadata;
+            addIdpToMap(entityDescriptor, idpMap);
+        } else if (metadata instanceof EntitiesDescriptor) {
+            EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) metadata;
+            if (entitiesDescriptor.getEntityDescriptors() != null) {
+                for (EntityDescriptor entityDescriptor: entitiesDescriptor.getEntityDescriptors()) {
+                    addIdpToMap(entityDescriptor, idpMap);
+                }
+            }
+            if (entitiesDescriptor.getEntitiesDescriptors() != null) {
+                for (EntitiesDescriptor entitiesDescriptorInner: entitiesDescriptor.getEntitiesDescriptors()) {
+                    discoverAndAddIdp(entitiesDescriptorInner, idpMap);
+                }
+            }
+        }
+    }
+
+    class MetadataRefreshTask extends TimerTask {
+        @Override
+        public void run() {
+            if (_idpMetaDataProvider == null) {
+                return;
+            }
+            s_logger.debug("Starting SAML IDP Metadata Refresh Task");
+            Map <String, SAMLProviderMetadata> metadataMap = new HashMap<String, SAMLProviderMetadata>();
+            try {
+                discoverAndAddIdp(_idpMetaDataProvider.getMetadata(), metadataMap);
+                _idpMetadataMap = metadataMap;
+                expireTokens();
+                s_logger.debug("Finished refreshing SAML Metadata and expiring old auth tokens");
+            } catch (MetadataProviderException e) {
+                s_logger.warn("SAML Metadata Refresh task failed with exception: " + e.getMessage());
+            }
+
+        }
+    }
+
+    private boolean setup() {
+        if (!initSP()) {
+            s_logger.error("SAML Plugin failed to initialize, please fix the configuration and restart management server");
+            return false;
+        }
+        _timer = new Timer();
+        final HttpClient client = new HttpClient();
+        final String idpMetaDataUrl = SAMLIdentityProviderMetadataURL.value();
+        if (SAMLTimeout.value() != null && SAMLTimeout.value() > SAMLPluginConstants.SAML_REFRESH_INTERVAL) {
+            _refreshInterval = SAMLTimeout.value();
+        }
+        try {
+            DefaultBootstrap.bootstrap();
+            if (idpMetaDataUrl.startsWith("http")) {
+                _idpMetaDataProvider = new HTTPMetadataProvider(_timer, client, idpMetaDataUrl);
             } else {
-                s_logger.warn("Provided IDP XML Metadata does not contain IDPSSODescriptor, SAML authentication may not work");
+                File metadataFile = PropertiesUtil.findConfigFile(idpMetaDataUrl);
+                s_logger.debug("Provided Metadata is not a URL, trying to read metadata file from local path: " + metadataFile.getAbsolutePath());
+                _idpMetaDataProvider = new FilesystemMetadataProvider(_timer, metadataFile);
             }
+            _idpMetaDataProvider.setRequireValidMetadata(true);
+            _idpMetaDataProvider.setParserPool(new BasicParserPool());
+            _idpMetaDataProvider.initialize();
+            _timer.scheduleAtFixedRate(new MetadataRefreshTask(), 0, _refreshInterval * 1000);
         } catch (MetadataProviderException e) {
             s_logger.error("Unable to read SAML2 IDP MetaData URL, error:" + e.getMessage());
             s_logger.error("SAML2 Authentication may be unavailable");
@@ -204,70 +382,138 @@ public class SAML2AuthManagerImpl extends AdapterBase implements SAML2AuthManage
             s_logger.error("OpenSAML bootstrapping failed: error: " + e.getMessage());
         } catch (NullPointerException e) {
             s_logger.error("Unable to setup SAML Auth Plugin due to NullPointerException" +
-                    " please check the SAML IDP metadata URL and entity ID in global settings: " + e.getMessage());
-        }
-
-        if (this.idpSingleLogOutUrl == null || this.idpSingleSignOnUrl == null) {
-            s_logger.error("SAML based authentication won't work");
+                    " please check the SAML global settings: " + e.getMessage());
         }
-
         return true;
     }
 
     @Override
-    public List<Class<?>> getAuthCommands() {
-        List<Class<?>> cmdList = new ArrayList<Class<?>>();
-        if (!isSAMLPluginEnabled()) {
-            return cmdList;
+    public SAMLProviderMetadata getSPMetadata() {
+        return _spMetadata;
+    }
+
+    @Override
+    public SAMLProviderMetadata getIdPMetadata(String entityId) {
+        if (entityId != null && _idpMetadataMap.containsKey(entityId)) {
+            return _idpMetadataMap.get(entityId);
         }
-        cmdList.add(SAML2LoginAPIAuthenticatorCmd.class);
-        cmdList.add(SAML2LogoutAPIAuthenticatorCmd.class);
-        cmdList.add(GetServiceProviderMetaDataCmd.class);
-        return cmdList;
+        String defaultIdpId = SAMLDefaultIdentityProviderId.value();
+        if (defaultIdpId != null && _idpMetadataMap.containsKey(defaultIdpId)) {
+            return _idpMetadataMap.get(defaultIdpId);
+        }
+        // In case of a single IdP, return that as default
+        if (_idpMetadataMap.size() == 1) {
+            return _idpMetadataMap.values().iterator().next();
+        }
+        return null;
     }
 
-    public String getServiceProviderId() {
-        return serviceProviderId;
+    @Override
+    public Collection<SAMLProviderMetadata> getAllIdPMetadata() {
+        return _idpMetadataMap.values();
     }
 
-    public String getIdpSingleSignOnUrl() {
-        return this.idpSingleSignOnUrl;
+    @Override
+    public boolean isUserAuthorized(Long userId, String entityId) {
+        UserVO user = _userDao.getUser(userId);
+        if (user != null) {
+            if (user.getSource().equals(User.Source.SAML2) &&
+                    user.getExternalEntity().equalsIgnoreCase(entityId)) {
+                return true;
+            }
+        }
+        return false;
     }
 
-    public String getIdpSingleLogOutUrl() {
-        return this.idpSingleLogOutUrl;
+    @Override
+    public boolean authorizeUser(Long userId, String entityId, boolean enable) {
+        UserVO user = _userDao.getUser(userId);
+        if (user != null) {
+            if (enable) {
+                user.setExternalEntity(entityId);
+                user.setSource(User.Source.SAML2);
+            } else {
+                if (user.getSource().equals(User.Source.SAML2)) {
+                    user.setSource(User.Source.SAML2DISABLED);
+                } else {
+                    return false;
+                }
+            }
+            _userDao.update(user.getId(), user);
+            return true;
+        }
+        return false;
     }
 
-    public String getSpSingleSignOnUrl() {
-        return spSingleSignOnUrl;
+    @Override
+    public void saveToken(String authnId, String domainPath, String entity) {
+        Long domainId = null;
+        if (domainPath != null) {
+            Domain domain = _domainMgr.findDomainByPath(domainPath);
+            if (domain != null) {
+                domainId = domain.getId();
+            }
+        }
+        SAMLTokenVO token = new SAMLTokenVO(authnId, domainId, entity);
+        if (_samlTokenDao.findByUuid(authnId) == null) {
+            _samlTokenDao.persist(token);
+        } else {
+            s_logger.warn("Duplicate SAML token for entity=" + entity + " token id=" + authnId + " domain=" + domainPath);
+        }
     }
 
-    public String getSpSingleLogOutUrl() {
-        return spSingleLogOutUrl;
+    @Override
+    public SAMLTokenVO getToken(String authnId) {
+        return _samlTokenDao.findByUuid(authnId);
     }
 
-    public String getIdentityProviderId() {
-        return identityProviderId;
+    @Override
+    public void expireTokens() {
+        _samlTokenDao.expireTokens();
     }
 
-    public X509Certificate getIdpSigningKey() {
-        return idpSigningKey;
+    public Boolean isSAMLPluginEnabled() {
+        return SAMLIsPluginEnabled.value();
     }
 
-    public X509Certificate getIdpEncryptionKey() {
-        return idpEncryptionKey;
+    @Override
+    public String getConfigComponentName() {
+        return "SAML2-PLUGIN";
     }
 
-    public Boolean isSAMLPluginEnabled() {
-        return Boolean.valueOf(_configDao.getValue(Config.SAMLIsPluginEnabled.key()));
+    @Override
+    public List<Class<?>> getAuthCommands() {
+        List<Class<?>> cmdList = new ArrayList<Class<?>>();
+        if (!isSAMLPluginEnabled()) {
+            return cmdList;
+        }
+        cmdList.add(SAML2LoginAPIAuthenticatorCmd.class);
+        cmdList.add(SAML2LogoutAPIAuthenticatorCmd.class);
+        cmdList.add(GetServiceProviderMetaDataCmd.class);
+        cmdList.add(ListIdpsCmd.class);
+        return cmdList;
     }
 
-    public X509Certificate getSpX509Certificate() {
-        return spX509Key;
+    @Override
+    public List<Class<?>> getCommands() {
+        List<Class<?>> cmdList = new ArrayList<Class<?>>();
+        if (!isSAMLPluginEnabled()) {
+            return cmdList;
+        }
+        cmdList.add(AuthorizeSAMLSSOCmd.class);
+        cmdList.add(ListSamlAuthorizationCmd.class);
+        return cmdList;
     }
 
     @Override
-    public KeyPair getSpKeyPair() {
-        return spKeyPair;
+    public ConfigKey<?>[] getConfigKeys() {
+        return new ConfigKey<?>[] {
+                SAMLIsPluginEnabled, SAMLServiceProviderID,
+                SAMLServiceProviderContactPersonName, SAMLServiceProviderContactEmail,
+                SAMLServiceProviderOrgName, SAMLServiceProviderOrgUrl,
+                SAMLServiceProviderSingleSignOnURL, SAMLServiceProviderSingleLogOutURL,
+                SAMLCloudStackRedirectionUrl, SAMLUserAttributeName,
+                SAMLIdentityProviderMetadataURL, SAMLDefaultIdentityProviderId,
+                SAMLSignatureAlgorithm, SAMLTimeout};
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2UserAuthenticator.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2UserAuthenticator.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2UserAuthenticator.java
index 68bd81c..5c8a390 100644
--- a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2UserAuthenticator.java
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAML2UserAuthenticator.java
@@ -21,12 +21,20 @@ import com.cloud.user.UserAccount;
 import com.cloud.user.dao.UserAccountDao;
 import com.cloud.user.dao.UserDao;
 import com.cloud.utils.Pair;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
 import org.apache.cxf.common.util.StringUtils;
 import org.apache.log4j.Logger;
+import org.opensaml.DefaultBootstrap;
+import org.opensaml.saml2.core.Response;
+import org.opensaml.saml2.core.StatusCode;
+import org.opensaml.xml.ConfigurationException;
+import org.opensaml.xml.io.UnmarshallingException;
+import org.xml.sax.SAXException;
 
 import javax.ejb.Local;
 import javax.inject.Inject;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.FactoryConfigurationError;
+import java.io.IOException;
 import java.util.Map;
 
 @Local(value = {UserAuthenticator.class})
@@ -50,13 +58,23 @@ public class SAML2UserAuthenticator extends DefaultUserAuthenticator {
         }
 
         final UserAccount userAccount = _userAccountDao.getUserAccount(username, domainId);
-        if (userAccount == null) {
-            s_logger.debug("Unable to find user with " + username + " in domain " + domainId);
+        if (userAccount == null || userAccount.getSource() != User.Source.SAML2) {
+            s_logger.debug("Unable to find user with " + username + " in domain " + domainId + ", or user source is not SAML2");
             return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
         } else {
             User user = _userDao.getUser(userAccount.getId());
-            if (user != null && SAMLUtils.checkSAMLUser(user.getUuid(), username) &&
-                    requestParameters != null && requestParameters.containsKey(SAMLUtils.SAML_RESPONSE)) {
+            if (user != null && requestParameters != null && requestParameters.containsKey(SAMLPluginConstants.SAML_RESPONSE)) {
+                final String samlResponse = ((String[])requestParameters.get(SAMLPluginConstants.SAML_RESPONSE))[0];
+                Response responseObject = null;
+                try {
+                    DefaultBootstrap.bootstrap();
+                    responseObject = SAMLUtils.decodeSAMLResponse(samlResponse);
+                } catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) {
+                    return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
+                }
+                if (!responseObject.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) {
+                    return new Pair<Boolean, ActionOnFailedAuthentication>(false, null);
+                }
                 return new Pair<Boolean, ActionOnFailedAuthentication>(true, null);
             }
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLPluginConstants.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLPluginConstants.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLPluginConstants.java
new file mode 100644
index 0000000..5f806e2
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLPluginConstants.java
@@ -0,0 +1,30 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+public class SAMLPluginConstants {
+    public static final int SAML_REFRESH_INTERVAL = 300;
+
+    public static final String SAML_RESPONSE = "SAMLResponse";
+    public static final String SAML_IDPID = "SAML_IDPID";
+    public static final String SAML_SESSIONID = "SAML_SESSIONID";
+    public static final String SAML_NAMEID = "SAML_NAMEID";
+    public static final String SAMLSP_KEYPAIR = "SAMLSP_KEYPAIR";
+    public static final String SAMLSP_X509CERT = "SAMLSP_X509CERT";
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLProviderMetadata.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLProviderMetadata.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLProviderMetadata.java
new file mode 100644
index 0000000..c7138a1
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLProviderMetadata.java
@@ -0,0 +1,122 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+import java.security.KeyPair;
+import java.security.cert.X509Certificate;
+
+public class SAMLProviderMetadata {
+    private String entityId;
+    private String organizationName;
+    private String organizationUrl;
+    private String contactPersonName;
+    private String contactPersonEmail;
+    private String ssoUrl;
+    private String sloUrl;
+    private KeyPair keyPair;
+    private X509Certificate signingCertificate;
+    private X509Certificate encryptionCertificate;
+
+    public SAMLProviderMetadata() {
+    }
+
+    public void setCommonCertificate(X509Certificate certificate) {
+        this.signingCertificate = certificate;
+        this.encryptionCertificate = certificate;
+    }
+
+    public String getEntityId() {
+        return entityId;
+    }
+
+    public void setEntityId(String entityId) {
+        this.entityId = entityId;
+    }
+
+    public String getContactPersonName() {
+        return contactPersonName;
+    }
+
+    public void setContactPersonName(String contactPersonName) {
+        this.contactPersonName = contactPersonName;
+    }
+
+    public String getContactPersonEmail() {
+        return contactPersonEmail;
+    }
+
+    public void setContactPersonEmail(String contactPersonEmail) {
+        this.contactPersonEmail = contactPersonEmail;
+    }
+
+    public String getOrganizationName() {
+        return organizationName;
+    }
+
+    public void setOrganizationName(String organizationName) {
+        this.organizationName = organizationName;
+    }
+
+    public String getOrganizationUrl() {
+        return organizationUrl;
+    }
+
+    public void setOrganizationUrl(String organizationUrl) {
+        this.organizationUrl = organizationUrl;
+    }
+
+    public KeyPair getKeyPair() {
+        return keyPair;
+    }
+
+    public void setKeyPair(KeyPair keyPair) {
+        this.keyPair = keyPair;
+    }
+
+    public X509Certificate getSigningCertificate() {
+        return signingCertificate;
+    }
+
+    public void setSigningCertificate(X509Certificate signingCertificate) {
+        this.signingCertificate = signingCertificate;
+    }
+
+    public X509Certificate getEncryptionCertificate() {
+        return encryptionCertificate;
+    }
+
+    public void setEncryptionCertificate(X509Certificate encryptionCertificate) {
+        this.encryptionCertificate = encryptionCertificate;
+    }
+
+    public String getSsoUrl() {
+        return ssoUrl;
+    }
+
+    public void setSsoUrl(String ssoUrl) {
+        this.ssoUrl = ssoUrl;
+    }
+
+    public String getSloUrl() {
+        return sloUrl;
+    }
+
+    public void setSloUrl(String sloUrl) {
+        this.sloUrl = sloUrl;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDao.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDao.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDao.java
new file mode 100644
index 0000000..b045562
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDao.java
@@ -0,0 +1,23 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+import com.cloud.utils.db.GenericDao;
+
+public interface SAMLTokenDao extends GenericDao<SAMLTokenVO, Long> {
+    public void expireTokens();
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDaoImpl.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDaoImpl.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDaoImpl.java
new file mode 100644
index 0000000..eb106d9
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenDaoImpl.java
@@ -0,0 +1,51 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.TransactionLegacy;
+import com.cloud.utils.exception.CloudRuntimeException;
+import org.springframework.stereotype.Component;
+
+import javax.ejb.Local;
+import java.sql.PreparedStatement;
+
+@DB
+@Component
+@Local(value = {SAMLTokenDao.class})
+public class SAMLTokenDaoImpl extends GenericDaoBase<SAMLTokenVO, Long> implements SAMLTokenDao {
+
+    public SAMLTokenDaoImpl() {
+        super();
+    }
+
+    @Override
+    public void expireTokens() {
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
+        try {
+            txn.start();
+            String sql = "DELETE FROM `saml_token` WHERE `created` < (NOW() - INTERVAL 1 HOUR)";
+            PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.executeUpdate();
+            txn.commit();
+        } catch (Exception e) {
+            txn.rollback();
+            throw new CloudRuntimeException("Unable to flush old SAML tokens due to exception", e);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenVO.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenVO.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenVO.java
new file mode 100644
index 0000000..c8ac2f1
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLTokenVO.java
@@ -0,0 +1,97 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+import com.cloud.utils.db.GenericDao;
+import org.apache.cloudstack.api.Identity;
+import org.apache.cloudstack.api.InternalIdentity;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.util.Date;
+
+@Entity
+@Table(name = "saml_token")
+public class SAMLTokenVO implements Identity, InternalIdentity {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    private long id;
+
+    @Column(name = "uuid")
+    private String uuid;
+
+    @Column(name = "domain_id")
+    private Long domainId = null;
+
+    @Column(name = "entity")
+    private String entity = null;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    private Date created;
+
+    public SAMLTokenVO() {
+    }
+
+    public SAMLTokenVO(String uuid, Long domainId, String entity) {
+        this.uuid = uuid;
+        this.domainId = domainId;
+        this.entity = entity;
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    @Override
+    public String getUuid() {
+        return uuid;
+    }
+
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+
+    public Long getDomainId() {
+        return domainId;
+    }
+
+    public void setDomainId(long domainId) {
+        this.domainId = domainId;
+    }
+
+    public String getEntity() {
+        return entity;
+    }
+
+    public void setEntity(String entity) {
+        this.entity = entity;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    public void setCreated(Date created) {
+        this.created = created;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
new file mode 100644
index 0000000..0216ad7
--- /dev/null
+++ b/plugins/user-authenticators/saml2/src/org/apache/cloudstack/saml/SAMLUtils.java
@@ -0,0 +1,354 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.saml;
+
+import com.cloud.utils.HttpUtils;
+import org.apache.log4j.Logger;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.x509.X509V1CertificateGenerator;
+import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
+import org.opensaml.Configuration;
+import org.opensaml.DefaultBootstrap;
+import org.opensaml.common.SAMLVersion;
+import org.opensaml.common.xml.SAMLConstants;
+import org.opensaml.saml2.core.Assertion;
+import org.opensaml.saml2.core.Attribute;
+import org.opensaml.saml2.core.AttributeStatement;
+import org.opensaml.saml2.core.AuthnContext;
+import org.opensaml.saml2.core.AuthnContextClassRef;
+import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration;
+import org.opensaml.saml2.core.AuthnRequest;
+import org.opensaml.saml2.core.Issuer;
+import org.opensaml.saml2.core.LogoutRequest;
+import org.opensaml.saml2.core.NameID;
+import org.opensaml.saml2.core.RequestedAuthnContext;
+import org.opensaml.saml2.core.Response;
+import org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder;
+import org.opensaml.saml2.core.impl.AuthnRequestBuilder;
+import org.opensaml.saml2.core.impl.IssuerBuilder;
+import org.opensaml.saml2.core.impl.LogoutRequestBuilder;
+import org.opensaml.saml2.core.impl.NameIDBuilder;
+import org.opensaml.saml2.core.impl.RequestedAuthnContextBuilder;
+import org.opensaml.xml.ConfigurationException;
+import org.opensaml.xml.XMLObject;
+import org.opensaml.xml.io.Marshaller;
+import org.opensaml.xml.io.MarshallingException;
+import org.opensaml.xml.io.Unmarshaller;
+import org.opensaml.xml.io.UnmarshallerFactory;
+import org.opensaml.xml.io.UnmarshallingException;
+import org.opensaml.xml.signature.SignatureConstants;
+import org.opensaml.xml.util.Base64;
+import org.opensaml.xml.util.XMLHelper;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+import javax.security.auth.x500.X500Principal;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.FactoryConfigurationError;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.net.URLEncoder;
+import java.security.InvalidKeyException;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.Signature;
+import java.security.SignatureException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.List;
+import java.util.zip.Deflater;
+import java.util.zip.DeflaterOutputStream;
+
+public class SAMLUtils {
+    public static final Logger s_logger = Logger.getLogger(SAMLUtils.class);
+
+    public static String generateSecureRandomId() {
+        return new BigInteger(160, new SecureRandom()).toString(32);
+    }
+
+    public static String getValueFromAttributeStatements(final List<AttributeStatement> attributeStatements, final String attributeKey) {
+        if (attributeStatements == null || attributeStatements.size() < 1 || attributeKey == null) {
+            return null;
+        }
+        for (AttributeStatement attributeStatement : attributeStatements) {
+            if (attributeStatement == null || attributeStatements.size() < 1) {
+                continue;
+            }
+            for (Attribute attribute : attributeStatement.getAttributes()) {
+                if (attribute.getAttributeValues() != null && attribute.getAttributeValues().size() > 0) {
+                    String value = attribute.getAttributeValues().get(0).getDOM().getTextContent();
+                    s_logger.debug("SAML attribute name: " + attribute.getName() + " friendly-name:" + attribute.getFriendlyName() + " value:" + value);
+                    if (attributeKey.equals(attribute.getName()) || attributeKey.equals(attribute.getFriendlyName())) {
+                        return value;
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    public static String getValueFromAssertions(final List<Assertion> assertions, final String attributeKey) {
+        if (assertions == null || attributeKey == null) {
+            return null;
+        }
+        for (Assertion assertion : assertions) {
+            String value = getValueFromAttributeStatements(assertion.getAttributeStatements(), attributeKey);
+            if (value != null) {
+                return value;
+            }
+        }
+        return null;
+    }
+
+    public static String buildAuthnRequestUrl(final String authnId, final SAMLProviderMetadata spMetadata, final SAMLProviderMetadata idpMetadata, final String signatureAlgorithm) {
+        String redirectUrl = "";
+        try {
+            DefaultBootstrap.bootstrap();
+            AuthnRequest authnRequest = SAMLUtils.buildAuthnRequestObject(authnId, spMetadata.getEntityId(), idpMetadata.getSsoUrl(), spMetadata.getSsoUrl());
+            PrivateKey privateKey = null;
+            if (spMetadata.getKeyPair() != null) {
+                privateKey = spMetadata.getKeyPair().getPrivate();
+            }
+            redirectUrl = idpMetadata.getSsoUrl() + "?" + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey, signatureAlgorithm);
+        } catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) {
+            s_logger.error("SAML AuthnRequest message building error: " + e.getMessage());
+        }
+        return redirectUrl;
+    }
+
+    public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
+        // Issuer object
+        IssuerBuilder issuerBuilder = new IssuerBuilder();
+        Issuer issuer = issuerBuilder.buildObject();
+        issuer.setValue(spId);
+
+        // AuthnContextClass
+        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
+        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
+                SAMLConstants.SAML20_NS,
+                "AuthnContextClassRef", "saml");
+        authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
+
+        // AuthnContext
+        RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
+        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
+        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
+        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
+
+        // Creation of AuthRequestObject
+        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
+        AuthnRequest authnRequest = authRequestBuilder.buildObject();
+        authnRequest.setID(authnId);
+        authnRequest.setDestination(idpUrl);
+        authnRequest.setVersion(SAMLVersion.VERSION_20);
+        authnRequest.setForceAuthn(false);
+        authnRequest.setIsPassive(false);
+        authnRequest.setIssueInstant(new DateTime());
+        authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
+        authnRequest.setAssertionConsumerServiceURL(consumerUrl);
+        authnRequest.setProviderName(spId);
+        authnRequest.setIssuer(issuer);
+        authnRequest.setRequestedAuthnContext(requestedAuthnContext);
+
+        return authnRequest;
+    }
+
+    public static LogoutRequest buildLogoutRequest(String logoutUrl, String spId, String nameIdString) {
+        Issuer issuer = new IssuerBuilder().buildObject();
+        issuer.setValue(spId);
+        NameID nameID = new NameIDBuilder().buildObject();
+        nameID.setValue(nameIdString);
+        LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
+        logoutRequest.setID(generateSecureRandomId());
+        logoutRequest.setDestination(logoutUrl);
+        logoutRequest.setVersion(SAMLVersion.VERSION_20);
+        logoutRequest.setIssueInstant(new DateTime());
+        logoutRequest.setIssuer(issuer);
+        logoutRequest.setNameID(nameID);
+        return logoutRequest;
+    }
+
+    public static String encodeSAMLRequest(XMLObject authnRequest)
+            throws MarshallingException, IOException {
+        Marshaller marshaller = Configuration.getMarshallerFactory()
+                .getMarshaller(authnRequest);
+        Element authDOM = marshaller.marshall(authnRequest);
+        StringWriter requestWriter = new StringWriter();
+        XMLHelper.writeNode(authDOM, requestWriter);
+        String requestMessage = requestWriter.toString();
+        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
+        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
+        deflaterOutputStream.write(requestMessage.getBytes());
+        deflaterOutputStream.close();
+        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
+        encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
+        return encodedRequestMessage;
+    }
+
+    public static Response decodeSAMLResponse(String responseMessage)
+            throws ConfigurationException, ParserConfigurationException,
+            SAXException, IOException, UnmarshallingException {
+        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+        documentBuilderFactory.setNamespaceAware(true);
+        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
+        byte[] base64DecodedResponse = Base64.decode(responseMessage);
+        Document document = docBuilder.parse(new ByteArrayInputStream(base64DecodedResponse));
+        Element element = document.getDocumentElement();
+        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
+        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
+        return (Response) unmarshaller.unmarshall(element);
+    }
+
+    public static String generateSAMLRequestSignature(final String urlEncodedString, final PrivateKey signingKey, final String sigAlgorithmName)
+            throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
+        if (signingKey == null) {
+            return urlEncodedString;
+        }
+
+        String opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1;
+        String javaSignatureAlgorithmName = "SHA1withRSA";
+
+        if (sigAlgorithmName.equalsIgnoreCase("SHA256")) {
+            opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256;
+            javaSignatureAlgorithmName = "SHA256withRSA";
+        } else if (sigAlgorithmName.equalsIgnoreCase("SHA384")) {
+            opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA384;
+            javaSignatureAlgorithmName = "SHA384withRSA";
+        } else if (sigAlgorithmName.equalsIgnoreCase("SHA512")) {
+            opensamlAlgoIdSignature = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA512;
+            javaSignatureAlgorithmName = "SHA512withRSA";
+        }
+
+        String url = urlEncodedString + "&SigAlg=" + URLEncoder.encode(opensamlAlgoIdSignature, HttpUtils.UTF_8);
+        Signature signature = Signature.getInstance(javaSignatureAlgorithmName);
+        signature.initSign(signingKey);
+        signature.update(url.getBytes());
+        String signatureString = Base64.encodeBytes(signature.sign(), Base64.DONT_BREAK_LINES);
+        if (signatureString != null) {
+            return url + "&Signature=" + URLEncoder.encode(signatureString, HttpUtils.UTF_8);
+        }
+        return url;
+    }
+
+    public static KeyFactory getKeyFactory() {
+        KeyFactory keyFactory = null;
+        try {
+            Security.addProvider(new BouncyCastleProvider());
+            keyFactory = KeyFactory.getInstance("RSA", "BC");
+        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
+            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
+        }
+        return keyFactory;
+    }
+
+    public static String savePublicKey(PublicKey key) {
+        try {
+            KeyFactory keyFactory = SAMLUtils.getKeyFactory();
+            if (keyFactory == null) return null;
+            X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
+            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
+        } catch (InvalidKeySpecException e) {
+            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
+        }
+        return null;
+    }
+
+    public static String savePrivateKey(PrivateKey key) {
+        try {
+            KeyFactory keyFactory = SAMLUtils.getKeyFactory();
+            if (keyFactory == null) return null;
+            PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key,
+                    PKCS8EncodedKeySpec.class);
+            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
+        } catch (InvalidKeySpecException e) {
+            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
+        }
+        return null;
+    }
+
+    public static PublicKey loadPublicKey(String publicKey) {
+        byte[] sigBytes = org.bouncycastle.util.encoders.Base64.decode(publicKey);
+        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes);
+        KeyFactory keyFact = SAMLUtils.getKeyFactory();
+        if (keyFact == null)
+            return null;
+        try {
+            return keyFact.generatePublic(x509KeySpec);
+        } catch (InvalidKeySpecException e) {
+            s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage());
+        }
+        return null;
+    }
+
+    public static PrivateKey loadPrivateKey(String privateKey) {
+        byte[] sigBytes = org.bouncycastle.util.encoders.Base64.decode(privateKey);
+        PKCS8EncodedKeySpec pkscs8KeySpec = new PKCS8EncodedKeySpec(sigBytes);
+        KeyFactory keyFact = SAMLUtils.getKeyFactory();
+        if (keyFact == null)
+            return null;
+        try {
+            return keyFact.generatePrivate(pkscs8KeySpec);
+        } catch (InvalidKeySpecException e) {
+            s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage());
+        }
+        return null;
+    }
+
+    public static KeyPair generateRandomKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
+        Security.addProvider(new BouncyCastleProvider());
+        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
+        keyPairGenerator.initialize(4096, new SecureRandom());
+        return keyPairGenerator.generateKeyPair();
+    }
+
+    public static X509Certificate generateRandomX509Certificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, SignatureException, InvalidKeyException {
+        DateTime now = DateTime.now(DateTimeZone.UTC);
+        X500Principal dnName = new X500Principal("CN=ApacheCloudStack");
+        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
+        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
+        certGen.setSubjectDN(dnName);
+        certGen.setIssuerDN(dnName);
+        certGen.setNotBefore(now.minusDays(1).toDate());
+        certGen.setNotAfter(now.plusYears(3).toDate());
+        certGen.setPublicKey(keyPair.getPublic());
+        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
+        return certGen.generate(keyPair.getPrivate(), "BC");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java
new file mode 100644
index 0000000..db1323f
--- /dev/null
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF 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.apache.cloudstack;
+
+import com.cloud.utils.HttpUtils;
+import org.apache.cloudstack.api.ApiServerService;
+import org.apache.cloudstack.api.auth.APIAuthenticationType;
+import org.apache.cloudstack.api.command.GetServiceProviderMetaDataCmd;
+import org.apache.cloudstack.saml.SAML2AuthManager;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
+import org.apache.cloudstack.saml.SAMLUtils;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.lang.reflect.Field;
+import java.security.InvalidKeyException;
+import java.security.KeyPair;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.SignatureException;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+@RunWith(MockitoJUnitRunner.class)
+public class GetServiceProviderMetaDataCmdTest {
+
+    @Mock
+    ApiServerService apiServer;
+
+    @Mock
+    SAML2AuthManager samlAuthManager;
+
+    @Mock
+    HttpSession session;
+
+    @Mock
+    HttpServletResponse resp;
+
+    @Mock
+    HttpServletRequest req;
+
+    @Test
+    public void testAuthenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, CertificateParsingException, CertificateEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, UnknownHostException {
+        GetServiceProviderMetaDataCmd cmd = new GetServiceProviderMetaDataCmd();
+
+        Field apiServerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_apiServer");
+        apiServerField.setAccessible(true);
+        apiServerField.set(cmd, apiServer);
+
+        Field managerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_samlAuthManager");
+        managerField.setAccessible(true);
+        managerField.set(cmd, samlAuthManager);
+
+        String spId = "someSPID";
+        String url = "someUrl";
+        KeyPair kp = SAMLUtils.generateRandomKeyPair();
+        X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp);
+
+        SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata();
+        providerMetadata.setEntityId("random");
+        providerMetadata.setSigningCertificate(cert);
+        providerMetadata.setEncryptionCertificate(cert);
+        providerMetadata.setKeyPair(kp);
+        providerMetadata.setSsoUrl("http://test.local");
+        providerMetadata.setSloUrl("http://test.local");
+
+        Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
+
+        String result = cmd.authenticate("command", null, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
+        Assert.assertTrue(result.contains("md:EntityDescriptor"));
+    }
+
+    @Test
+    public void testGetAPIType() {
+        Assert.assertTrue(new GetServiceProviderMetaDataCmd().getAPIType() == APIAuthenticationType.LOGIN_API);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
index 83792c6..5b37388 100644
--- a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAML2UserAuthenticatorTest.java
@@ -25,8 +25,8 @@ import com.cloud.user.UserVO;
 import com.cloud.user.dao.UserAccountDao;
 import com.cloud.user.dao.UserDao;
 import com.cloud.utils.Pair;
+import org.apache.cloudstack.saml.SAMLPluginConstants;
 import org.apache.cloudstack.saml.SAML2UserAuthenticator;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
 import org.junit.Assert;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -68,8 +68,6 @@ public class SAML2UserAuthenticatorTest {
         account.setId(1L);
 
         UserVO user = new UserVO();
-        user.setUuid(SAMLUtils.createSAMLId("someUID"));
-
         Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account);
         Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
 
@@ -81,9 +79,9 @@ public class SAML2UserAuthenticatorTest {
         Assert.assertFalse(pair.first());
 
         // When there is SAMLRequest in params and user is same as the mocked one
-        params.put(SAMLUtils.SAML_RESPONSE, new Object[]{});
+        params.put(SAMLPluginConstants.SAML_RESPONSE, new String[]{"RandomString"});
         pair = authenticator.authenticate("someUID", "random", 1l, params);
-        Assert.assertTrue(pair.first());
+        Assert.assertFalse(pair.first());
 
         // When there is SAMLRequest in params but username is null
         pair = authenticator.authenticate(null, "random", 1l, params);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAMLUtilsTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAMLUtilsTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAMLUtilsTest.java
new file mode 100644
index 0000000..bd87831
--- /dev/null
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/SAMLUtilsTest.java
@@ -0,0 +1,74 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack;
+
+import junit.framework.TestCase;
+import org.apache.cloudstack.saml.SAMLUtils;
+import org.junit.Test;
+import org.opensaml.saml2.core.AuthnRequest;
+import org.opensaml.saml2.core.LogoutRequest;
+
+import java.security.KeyPair;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+
+public class SAMLUtilsTest extends TestCase {
+
+    @Test
+    public void testGenerateSecureRandomId() throws Exception {
+        assertTrue(SAMLUtils.generateSecureRandomId().length() > 0);
+    }
+
+    @Test
+    public void testBuildAuthnRequestObject() throws Exception {
+        String consumerUrl = "http://someurl.com";
+        String idpUrl = "http://idp.domain.example";
+        String spId = "cloudstack";
+        String authnId = SAMLUtils.generateSecureRandomId();
+        AuthnRequest req = SAMLUtils.buildAuthnRequestObject(authnId, spId, idpUrl, consumerUrl);
+        assertEquals(req.getAssertionConsumerServiceURL(), consumerUrl);
+        assertEquals(req.getDestination(), idpUrl);
+        assertEquals(req.getIssuer().getValue(), spId);
+    }
+
+    @Test
+    public void testBuildLogoutRequest() throws Exception {
+        String logoutUrl = "http://logoutUrl";
+        String spId = "cloudstack";
+        String nameId = "_12345";
+        LogoutRequest req = SAMLUtils.buildLogoutRequest(logoutUrl, spId, nameId);
+        assertEquals(req.getDestination(), logoutUrl);
+        assertEquals(req.getIssuer().getValue(), spId);
+    }
+
+    @Test
+    public void testX509Helpers() throws Exception {
+        KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
+
+        String privateKeyString = SAMLUtils.savePrivateKey(keyPair.getPrivate());
+        String publicKeyString = SAMLUtils.savePublicKey(keyPair.getPublic());
+
+        PrivateKey privateKey = SAMLUtils.loadPrivateKey(privateKeyString);
+        PublicKey publicKey = SAMLUtils.loadPublicKey(publicKeyString);
+
+        assertTrue(privateKey.equals(keyPair.getPrivate()));
+        assertTrue(publicKey.equals(keyPair.getPublic()));
+    }
+}
\ No newline at end of file


[47/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
New test and fixes for vpcr code in 4.6

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/1a93d700
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/1a93d700
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/1a93d700

Branch: refs/heads/reporter
Commit: 1a93d700dd2b363ddfe6ecff5402a5e726639d55
Parents: 45781b9
Author: Ian Southam <is...@schubergphilis.com>
Authored: Thu Jul 2 08:15:20 2015 -0400
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 8 11:19:12 2015 +0200

----------------------------------------------------------------------
 .../integration/component/test_vpc_redundant.py | 508 +++++++++++++++++++
 1 file changed, 508 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/1a93d700/test/integration/component/test_vpc_redundant.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_vpc_redundant.py b/test/integration/component/test_vpc_redundant.py
new file mode 100644
index 0000000..66da462
--- /dev/null
+++ b/test/integration/component/test_vpc_redundant.py
@@ -0,0 +1,508 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+""" Test redundancy features for VPC routers
+"""
+
+from nose.plugins.attrib import attr
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.base import (stopRouter,
+                             startRouter,
+                             Account,
+                             VpcOffering,
+                             VPC,
+                             ServiceOffering,
+                             NATRule,
+                             NetworkACL,
+                             PublicIPAddress,
+                             NetworkOffering,
+                             Network,
+                             VirtualMachine,
+                             LoadBalancerRule)
+from marvin.lib.common import (get_domain,
+                               get_zone,
+                               get_template,
+                               list_routers)
+from marvin.lib.utils import cleanup_resources
+import socket
+import time
+import inspect
+
+
+class Services:
+    """Test VPC network services - Port Forwarding Rules Test Data Class.
+    """
+
+    def __init__(self):
+        self.services = {
+            "account": {
+                "email": "test@test.com",
+                "firstname": "Test",
+                "lastname": "User",
+                "username": "test",
+                # Random characters are appended for unique
+                # username
+                "password": "password",
+            },
+            "host1": None,
+            "host2": None,
+            "service_offering": {
+                "name": "Tiny Instance",
+                "displaytext": "Tiny Instance",
+                "cpunumber": 1,
+                "cpuspeed": 100,
+                "memory": 128,
+            },
+            "network_offering": {
+                "name": 'VPC Network offering',
+                "displaytext": 'VPC Network off',
+                "guestiptype": 'Isolated',
+                "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Lb,UserData,StaticNat,NetworkACL',
+                "traffictype": 'GUEST',
+                "availability": 'Optional',
+                "useVpc": 'on',
+                "serviceProviderList": {
+                    "Vpn": 'VpcVirtualRouter',
+                    "Dhcp": 'VpcVirtualRouter',
+                    "Dns": 'VpcVirtualRouter',
+                    "SourceNat": 'VpcVirtualRouter',
+                    "PortForwarding": 'VpcVirtualRouter',
+                    "Lb": 'VpcVirtualRouter',
+                    "UserData": 'VpcVirtualRouter',
+                    "StaticNat": 'VpcVirtualRouter',
+                    "NetworkACL": 'VpcVirtualRouter'
+                },
+            },
+            "network_offering_no_lb": {
+                "name": 'VPC Network offering',
+                "displaytext": 'VPC Network off',
+                "guestiptype": 'Isolated',
+                "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,UserData,StaticNat,NetworkACL',
+                "traffictype": 'GUEST',
+                "availability": 'Optional',
+                "useVpc": 'on',
+                "serviceProviderList": {
+                    "Dhcp": 'VpcVirtualRouter',
+                    "Dns": 'VpcVirtualRouter',
+                    "SourceNat": 'VpcVirtualRouter',
+                    "PortForwarding": 'VpcVirtualRouter',
+                    "UserData": 'VpcVirtualRouter',
+                    "StaticNat": 'VpcVirtualRouter',
+                    "NetworkACL": 'VpcVirtualRouter'
+                },
+            },
+            "vpc_offering": {
+                "name": 'Redundant VPC off',
+                "displaytext": 'Redundant VPC off',
+                "supportedservices": 'Dhcp,Dns,SourceNat,PortForwarding,Vpn,Lb,UserData,StaticNat',
+                "serviceProviderList": {
+                    "Vpn": 'VpcVirtualRouter',
+                    "Dhcp": 'VpcVirtualRouter',
+                    "Dns": 'VpcVirtualRouter',
+                    "SourceNat": 'VpcVirtualRouter',
+                    "PortForwarding": 'VpcVirtualRouter',
+                    "Lb": 'VpcVirtualRouter',
+                    "UserData": 'VpcVirtualRouter',
+                    "StaticNat": 'VpcVirtualRouter',
+                    "NetworkACL": 'VpcVirtualRouter'
+                },
+                "serviceCapabilityList": {
+                    "SourceNat": {
+                        "RedundantRouter": 'true'
+                    }
+                },
+            },
+            "vpc": {
+                "name": "TestVPC",
+                "displaytext": "TestVPC",
+                "cidr": '10.0.0.1/24'
+            },
+            "network": {
+                "name": "Test Network",
+                "displaytext": "Test Network",
+                "netmask": '255.255.255.0'
+            },
+            "lbrule": {
+                "name": "SSH",
+                "alg": "leastconn",
+                # Algorithm used for load balancing
+                "privateport": 22,
+                "publicport": 2222,
+                "openfirewall": False,
+                "startport": 22,
+                "endport": 2222,
+                "protocol": "TCP",
+                "cidrlist": '0.0.0.0/0',
+            },
+            "lbrule_http": {
+                "name": "HTTP",
+                "alg": "leastconn",
+                # Algorithm used for load balancing
+                "privateport": 80,
+                "publicport": 8888,
+                "openfirewall": False,
+                "startport": 80,
+                "endport": 8888,
+                "protocol": "TCP",
+                "cidrlist": '0.0.0.0/0',
+            },
+            "natrule": {
+                "privateport": 22,
+                "publicport": 22,
+                "startport": 22,
+                "endport": 22,
+                "protocol": "TCP",
+                "cidrlist": '0.0.0.0/0',
+            },
+            "http_rule": {
+                "privateport": 80,
+                "publicport": 80,
+                "startport": 80,
+                "endport": 80,
+                "cidrlist": '0.0.0.0/0',
+                "protocol": "TCP"
+            },
+            "virtual_machine": {
+                "displayname": "Test VM",
+                "username": "root",
+                "password": "password",
+                "ssh_port": 22,
+                "privateport": 22,
+                "publicport": 22,
+                "protocol": 'TCP',
+            },
+            "ostype": 'CentOS 5.3 (64-bit)',
+            "timeout": 10,
+        }
+
+
+class TestVPCRedundancy(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        # We want to fail quicker if it's failure
+        socket.setdefaulttimeout(60)
+
+        cls.testClient = super(TestVPCRedundancy, cls).getClsTestClient()
+        cls.api_client = cls.testClient.getApiClient()
+
+        cls.services = Services().services
+        # Get Zone, Domain and templates
+        cls.domain = get_domain(cls.api_client)
+        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
+        cls.template = get_template(
+            cls.api_client,
+            cls.zone.id,
+            cls.services["ostype"])
+        cls.services["virtual_machine"]["zoneid"] = cls.zone.id
+        cls.services["virtual_machine"]["template"] = cls.template.id
+
+        cls.service_offering = ServiceOffering.create(
+            cls.api_client,
+            cls.services["service_offering"])
+        cls._cleanup = [cls.service_offering]
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        return
+        try:
+            cleanup_resources(cls.api_client, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    def setUp(self):
+        self.routers = []
+        self.networks = []
+        self.ips = []
+        self.apiclient = self.testClient.getApiClient()
+        self.account = Account.create(
+            self.apiclient,
+            self.services["account"],
+            admin=True,
+            domainid=self.domain.id)
+
+        self.cleanup = [self.account]
+        self.debug("Creating a VPC offering..")
+        self.vpc_off = VpcOffering.create(
+            self.apiclient,
+            self.services["vpc_offering"])
+
+        self.debug("Enabling the VPC offering created")
+        self.vpc_off.update(self.apiclient, state='Enabled')
+
+        self.debug("Creating a VPC network in the account: %s" % self.account.name)
+        self.services["vpc"]["cidr"] = '10.1.1.1/16'
+        self.vpc = VPC.create(
+            self.apiclient,
+            self.services["vpc"],
+            vpcofferingid=self.vpc_off.id,
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid)
+        return
+
+    def tearDown(self):
+        return
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            self.debug("Warning: Exception during cleanup : %s" % e)
+        return
+
+    def query_routers(self, count=2, showall=False):
+        self.routers = list_routers(self.apiclient,
+                                    account=self.account.name,
+                                    domainid=self.account.domainid,
+                                    )
+        if not showall:
+            self.routers = [r for r in self.routers if r.state != "Stopped"]
+        self.assertEqual(
+            isinstance(self.routers, list), True,
+            "Check for list routers response return valid data")
+
+        self.assertEqual(
+            len(self.routers), count,
+            "Check that %s routers were indeed created" % count)
+
+    def check_master_status(self, count=2, showall=False):
+        vals = ["MASTER", "BACKUP", "UNKNOWN"]
+        cnts = [0, 0, 0]
+        self.query_routers(count, showall)
+        for router in self.routers:
+            cnts[vals.index(router.redundantstate)] += 1
+        if cnts[vals.index('MASTER')] != 1:
+            self.fail("No Master or too many master routers found %s" % cnts[vals.index('MASTER')])
+        # if cnts[vals.index('UNKNOWN')] > 0:
+            # self.fail("Router has unknown status")
+
+    def stop_router(self, type):
+        self.check_master_status(2)
+        self.debug('Stopping %s router' % type)
+        for router in self.routers:
+            if router.redundantstate == type:
+                cmd = stopRouter.stopRouterCmd()
+                cmd.id = router.id
+                self.apiclient.stopRouter(cmd)
+
+    def start_router(self):
+        self.check_master_status(2, showall=True)
+        self.debug('Starting stopped routers')
+        for router in self.routers:
+            self.debug('Router %s has state %s' % (router.id, router.state))
+            if router.state == "Stopped":
+                self.debug('Starting stopped router %s' % router.id)
+                cmd = startRouter.startRouterCmd()
+                cmd.id = router.id
+                self.apiclient.startRouter(cmd)
+
+    def create_network(self, net_offerring, gateway='10.1.1.1', vpc=None):
+        try:
+            self.debug('Create NetworkOffering')
+            net_offerring["name"] = "NET_OFF-" + str(gateway)
+            nw_off = NetworkOffering.create(
+                self.apiclient,
+                net_offerring,
+                conservemode=False)
+
+            nw_off.update(self.apiclient, state='Enabled')
+            self._cleanup.append(nw_off)
+            self.debug('Created and Enabled NetworkOffering')
+
+            self.services["network"]["name"] = "NETWORK-" + str(gateway)
+            self.debug('Adding Network=%s' % self.services["network"])
+            obj_network = Network.create(
+                self.apiclient,
+                self.services["network"],
+                accountid=self.account.name,
+                domainid=self.account.domainid,
+                networkofferingid=nw_off.id,
+                zoneid=self.zone.id,
+                gateway=gateway,
+                vpcid=vpc.id if vpc else self.vpc.id
+            )
+            self.debug("Created network with ID: %s" % obj_network.id)
+        except Exception, e:
+            self.fail('Unable to create a Network with offering=%s because of %s ' % (net_offerring, e))
+        o = networkO(obj_network)
+        o.add_vm(self.deployvm_in_network(obj_network))
+        o.add_vm(self.deployvm_in_network(obj_network))
+        return o
+
+    def deployvm_in_network(self, network, host_id=None):
+        try:
+            self.debug('Creating VM in network=%s' % network.name)
+            vm = VirtualMachine.create(
+                self.apiclient,
+                self.services["virtual_machine"],
+                accountid=self.account.name,
+                domainid=self.account.domainid,
+                serviceofferingid=self.service_offering.id,
+                networkids=[str(network.id)],
+                hostid=host_id
+            )
+            self.debug('Created VM=%s in network=%s' % (vm.id, network.name))
+            return vm
+        except:
+            self.fail('Unable to create VM in a Network=%s' % network.name)
+
+    def acquire_publicip(self, network):
+        self.debug("Associating public IP for network: %s" % network.name)
+        public_ip = PublicIPAddress.create(
+            self.apiclient,
+            accountid=self.account.name,
+            zoneid=self.zone.id,
+            domainid=self.account.domainid,
+            networkid=network.id,
+            vpcid=self.vpc.id
+        )
+        self.debug("Associated %s with network %s" % (
+            public_ip.ipaddress.ipaddress,
+            network.id
+        ))
+        return public_ip
+
+    def create_natrule(self, vm, public_ip, network, services=None):
+        self.debug("Creating NAT rule in network for vm with public IP")
+        if not services:
+            services = self.services["natrule"]
+        nat_rule = NATRule.create(
+            self.apiclient,
+            vm,
+            services,
+            ipaddressid=public_ip.ipaddress.id,
+            openfirewall=False,
+            networkid=network.id,
+            vpcid=self.vpc.id)
+
+        self.debug("Adding NetworkACL rules to make NAT rule accessible")
+        nwacl_nat = NetworkACL.create(
+            self.apiclient,
+            networkid=network.id,
+            services=services,
+            traffictype='Ingress'
+        )
+        self.debug('nwacl_nat=%s' % nwacl_nat.__dict__)
+        return nat_rule
+
+    def check_ssh_into_vm(self, vm, public_ip, expectFail=False, retries=20):
+        self.debug("Checking if we can SSH into VM=%s on public_ip=%s (%r)" %
+                   (vm.name, public_ip.ipaddress.ipaddress, expectFail))
+        vm.ssh_client = None
+        try:
+            if 'retries' in inspect.getargspec(vm.get_ssh_client).args:
+                vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress, retries=retries)
+            else:
+                vm.get_ssh_client(ipaddress=public_ip.ipaddress.ipaddress)
+            if expectFail:
+                self.fail("SSH into VM=%s on public_ip=%s is successful (Not Expected)" %
+                          (vm.name, public_ip.ipaddress.ipaddress))
+            else:
+                self.debug("SSH into VM=%s on public_ip=%s is successful" %
+                           (vm.name, public_ip.ipaddress.ipaddress))
+        except:
+            if expectFail:
+                self.debug("Failed to SSH into VM - %s (Expected)" % (public_ip.ipaddress.ipaddress))
+            else:
+                self.fail("Failed to SSH into VM - %s" % (public_ip.ipaddress.ipaddress))
+
+    @attr(tags=["advanced", "intervlan"], required_hardware="true")
+    def test_01a_create_redundant_VPC(self):
+        """ Create a redundant vpc with two networks with two vms in each network """
+        self.debug("Starting est 1a")
+        self.query_routers()
+        self.networks.append(self.create_network(self.services["network_offering"], "10.1.1.1"))
+        self.networks.append(self.create_network(self.services["network_offering_no_lb"], "10.1.2.1"))
+        self.check_master_status(2)
+        self.add_nat_rules()
+        self.do_vpc_test(False)
+
+        self.stop_router("MASTER")
+        time.sleep(30)
+        self.check_master_status(1)
+        self.do_vpc_test(False)
+
+        self.delete_nat_rules()
+        self.check_master_status(1)
+        self.do_vpc_test(True)
+
+        self.start_router()
+        self.add_nat_rules()
+        time.sleep(60)
+        self.check_master_status(2)
+        self.do_vpc_test(False)
+
+    def delete_nat_rules(self):
+        for o in self.networks:
+            for vm in o.get_vms():
+                if vm.get_nat() is not None:
+                    vm.get_nat().delete(self.apiclient)
+                    vm.set_nat(None)
+
+    def add_nat_rules(self):
+        for o in self.networks:
+            for vm in o.get_vms():
+                if vm.get_ip() is None:
+                    vm.set_ip(self.acquire_publicip(o.get_net()))
+                if vm.get_nat() is None:
+                    vm.set_nat(self.create_natrule(vm.get_vm(), vm.get_ip(), o.get_net()))
+
+    def do_vpc_test(self, expectFail):
+        retries = 20
+        if expectFail:
+            retries = 2
+        for o in self.networks:
+            for vm in o.get_vms():
+                self.check_ssh_into_vm(vm.get_vm(), vm.get_ip(), expectFail=expectFail, retries=retries)
+
+
+class networkO(object):
+    def __init__(self, net):
+        self.network = net
+        self.vms = []
+
+    def get_net(self):
+        return self.network
+
+    def add_vm(self, vm):
+        self.vms.append(vmsO(vm))
+
+    def get_vms(self):
+        return self.vms
+
+
+class vmsO(object):
+    def __init__(self, vm):
+        self.vm = vm
+        self.ip = None
+        self.nat = None
+
+    def get_vm(self):
+        return self.vm
+
+    def get_ip(self):
+        return self.ip
+
+    def get_nat(self):
+        return self.nat
+
+    def set_ip(self, ip):
+        self.ip = ip
+
+    def set_nat(self, nat):
+        self.nat = nat


[21/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Increasing test coverage
     - resource package: 86.7%
     - utils package: 95.1%
     - wrapper package: 97.5%

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c6013303
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c6013303
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c6013303

Branch: refs/heads/reporter
Commit: c6013303e9837c12922fbed28836d34991ec6ab3
Parents: 644458f
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 12:11:45 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:58 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpUtilities.java    |   5 +
 ...vpUpdateLogicalSwitchPortCommandWrapper.java |   7 +-
 .../resource/NiciraNvpRequestWrapperTest.java   | 127 +++++++++++++++++++
 .../network/resource/NiciraNvpResourceTest.java |  17 ++-
 4 files changed, 154 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6013303/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
index 2ac79c8..4edf5c3 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpUtilities.java
@@ -26,6 +26,7 @@ import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
 import com.cloud.network.nicira.LogicalSwitch;
 import com.cloud.network.nicira.LogicalSwitchPort;
 import com.cloud.network.nicira.NiciraNvpTag;
+import com.cloud.network.nicira.VifAttachment;
 
 public class NiciraNvpUtilities {
 
@@ -57,4 +58,8 @@ public class NiciraNvpUtilities {
         final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
         return logicalSwitchPort;
     }
+
+    public VifAttachment createVifAttachment(final String attachmentUuid) {
+        return new VifAttachment(attachmentUuid);
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6013303/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
index 9f65938..a0d7dc2 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpUpdateLogicalSwitchPortCommandWrapper.java
@@ -32,6 +32,7 @@ import com.cloud.network.nicira.NiciraNvpApiException;
 import com.cloud.network.nicira.NiciraNvpTag;
 import com.cloud.network.nicira.VifAttachment;
 import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.resource.NiciraNvpUtilities;
 import com.cloud.network.utils.CommandRetryUtility;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.ResourceWrapper;
@@ -41,6 +42,8 @@ public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends Comman
 
     @Override
     public Answer execute(final UpdateLogicalSwitchPortCommand command, final NiciraNvpResource niciraNvpResource) {
+        final NiciraNvpUtilities niciraNvpUtilities = niciraNvpResource.getNiciraNvpUtilities();
+
         final String logicalSwitchUuid = command.getLogicalSwitchUuid();
         final String logicalSwitchPortUuid = command.getLogicalSwitchPortUuid();
         final String attachmentUuid = command.getAttachmentUuid();
@@ -52,7 +55,9 @@ public final class NiciraNvpUpdateLogicalSwitchPortCommandWrapper extends Comman
             final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
             tags.add(new NiciraNvpTag("cs_account", command.getOwnerName()));
 
-            niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
+            final VifAttachment vifAttachment = niciraNvpUtilities.createVifAttachment(attachmentUuid);
+
+            niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
             return new UpdateLogicalSwitchPortAnswer(command, true, "Attachment for  " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
         } catch (final NiciraNvpApiException e) {
             final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6013303/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index 70e10e1..7fe6287 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -25,18 +25,28 @@ import static org.junit.Assert.fail;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.when;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand;
 import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalRouterCommand;
 import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ReadyCommand;
+import com.cloud.agent.api.UpdateLogicalSwitchPortCommand;
+import com.cloud.network.nicira.LogicalRouterPort;
 import com.cloud.network.nicira.LogicalSwitch;
 import com.cloud.network.nicira.NiciraNvpApi;
 import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.nicira.NiciraNvpList;
+import com.cloud.network.nicira.VifAttachment;
 
 public class NiciraNvpRequestWrapperTest {
 
@@ -125,4 +135,121 @@ public class NiciraNvpRequestWrapperTest {
 
         assertTrue(answer.getResult());
     }
+
+    @Test
+    public void testConfigurePublicIpsOnLogicalRouterCommand() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+        final LogicalRouterPort port1 = Mockito.mock(LogicalRouterPort.class);
+
+        final List<LogicalRouterPort> listPorts = new ArrayList<LogicalRouterPort>();
+        listPorts.add(port1);
+
+        final NiciraNvpList<LogicalRouterPort> ports = new NiciraNvpList<LogicalRouterPort>();
+        ports.setResults(listPorts);
+        ports.setResultCount(1);
+
+        final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String l3GatewayServiceUuid  = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final List<String> publicCidrs = new ArrayList<String>();
+        publicCidrs.add("10.1.1.0/24");
+
+        final ConfigurePublicIpsOnLogicalRouterCommand command = new ConfigurePublicIpsOnLogicalRouterCommand(logicalRouterUuid, l3GatewayServiceUuid, publicCidrs);
+
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            when(niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(command.getLogicalRouterUuid(), command.getL3GatewayServiceUuid())).thenReturn(ports);
+            doNothing().when(niciraNvpApi).updateLogicalRouterPort(command.getLogicalRouterUuid(), port1);
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testDeleteLogicalSwitchPortCommand() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+        final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String logicalSwitchPortUuid  = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+        final DeleteLogicalSwitchPortCommand command = new DeleteLogicalSwitchPortCommand(logicalSwitchUuid, logicalSwitchPortUuid);
+
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            doNothing().when(niciraNvpApi).deleteLogicalSwitchPort(command.getLogicalSwitchUuid(), command.getLogicalSwitchPortUuid());
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testDeleteLogicalRouterCommand() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+        final String logicalRouterUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+        final DeleteLogicalRouterCommand command = new DeleteLogicalRouterCommand(logicalRouterUuid);
+
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            doNothing().when(niciraNvpApi).deleteLogicalRouter(command.getLogicalRouterUuid());
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testUpdateLogicalSwitchPortCommand() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+        final NiciraNvpUtilities niciraNvpUtilities = Mockito.mock(NiciraNvpUtilities.class);
+        final VifAttachment vifAttachment = Mockito.mock(VifAttachment.class);
+
+        final String logicalSwitchPortUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String attachmentUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+        final String ownerName = "admin";
+        final String nicName = "eth0";
+
+        final UpdateLogicalSwitchPortCommand command = new UpdateLogicalSwitchPortCommand(logicalSwitchPortUuid, logicalSwitchUuid, attachmentUuid, ownerName, nicName);
+
+        when(niciraNvpResource.getNiciraNvpUtilities()).thenReturn(niciraNvpUtilities);
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            when(niciraNvpUtilities.createVifAttachment(attachmentUuid)).thenReturn(vifAttachment);
+            doNothing().when(niciraNvpApi).updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, vifAttachment);
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c6013303/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
index ccee017..ddf2993 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -432,8 +432,23 @@ public class NiciraNvpResourceTest {
 
         when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
         when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
-        doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
         when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenReturn(list);
+        doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalRouterPort((String)any(), (LogicalRouterPort)any());
+
+        final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
+        assertFalse(answer.getResult());
+
+    }
+
+    @Test
+    public void testConfigurePublicIpsOnLogicalRouterRetry() throws ConfigurationException, NiciraNvpApiException {
+        resource.configure("NiciraNvpResource", parameters);
+
+        final ConfigurePublicIpsOnLogicalRouterCommand cmd = mock(ConfigurePublicIpsOnLogicalRouterCommand.class);
+
+        when(cmd.getLogicalRouterUuid()).thenReturn("aaaaa");
+        when(cmd.getL3GatewayServiceUuid()).thenReturn("bbbbb");
+        when(nvpApi.findLogicalRouterPortByGatewayServiceUuid("aaaaa", "bbbbb")).thenThrow(new NiciraNvpApiException("retry 1")).thenThrow(new NiciraNvpApiException("retry 2"));
 
         final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer)resource.executeRequest(cmd);
         assertFalse(answer.getResult());


[34/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Make sure the new password replaces the old one in the queue

   - Added log info to show details of the operation
   - Renamed the addPwdToQueue to replaceOldPasswdInQueue


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/86297e70
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/86297e70
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/86297e70

Branch: refs/heads/reporter
Commit: 86297e70be8cd587ab07ba3109042ea782772624
Parents: efa3436
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Sat Jul 4 11:33:52 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Sat Jul 4 11:33:52 2015 +0200

----------------------------------------------------------------------
 .../xenserver/resource/CitrixResourceBase.java           | 11 ++++++++++-
 .../xenbase/CitrixUpdateHostPasswordCommandWrapper.java  |  4 ++--
 server/src/com/cloud/resource/ResourceManagerImpl.java   |  2 ++
 3 files changed, 14 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/86297e70/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
index 24970a6..b205f2d 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
@@ -271,8 +271,17 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
     public CitrixResourceBase() {
     }
 
-    public void addToPwdQueue(final String password) {
+    /**
+     * Replaces the old password with the new password used to connect to the host.
+     *
+     * @param password  - the new host password.
+     * @return the old password.
+     */
+    public String replaceOldPasswdInQueue(final String password) {
+        final String oldPasswd = _password.poll();
         _password.add(password);
+
+        return oldPasswd;
     }
 
     public String getPwdFromQueue() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/86297e70/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
index d5a530b..9e58678 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
@@ -58,8 +58,8 @@ public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper
         } catch (final Exception e) {
             return new Answer(command, false, e.getMessage());
         }
-        // Add new password to the stack.
-        citrixResourceBase.addToPwdQueue(command.getNewPassword());
+        // Add new password to the queue.
+        citrixResourceBase.replaceOldPasswdInQueue(newPassword);
         return new Answer(command, result.first(), result.second());
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/86297e70/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index b777de9..b450e31 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2240,6 +2240,8 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
 
         final UpdateHostPasswordCommand cmd = new UpdateHostPasswordCommand(username, password, hostIpAddress);
         final Answer answer = _agentMgr.easySend(hostId, cmd);
+
+        s_logger.info("Result returned from update host password ==> " + answer.getDetails());
         return answer.getResult();
     }
 


[20/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Adding command wrappers NiciraNvpCreateLogicalSwitchCommandWrapper and NiciraNvpDeleteLogicalSwitchCommandWrapper
   - Refactoring the retry mechanism
   - Applying the new retry mechanism to current wrappers and old methods in NiciraNvpResource
   - Adding 2 tests
   - Fixing the testRetries() in NiciraNvpResourceTest class

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/28c1da96
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/28c1da96
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/28c1da96

Branch: refs/heads/reporter
Commit: 28c1da969da66cb7d29c4f899ff39dde935624d4
Parents: 27c9651
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 30 09:47:57 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:57 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 144 ++++++-------------
 ...iraNvpCreateLogicalSwitchCommandWrapper.java |  12 +-
 ...iraNvpDeleteLogicalSwitchCommandWrapper.java |  49 +++++++
 .../network/utils/CommandRetryUtility.java      |  90 ++++++++++++
 .../resource/NiciraNvpRequestWrapperTest.java   |  26 ++++
 .../network/resource/NiciraNvpResourceTest.java |  10 +-
 6 files changed, 224 insertions(+), 107 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 5242154..1ab1992 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -42,8 +42,6 @@ import com.cloud.agent.api.CreateLogicalSwitchPortAnswer;
 import com.cloud.agent.api.CreateLogicalSwitchPortCommand;
 import com.cloud.agent.api.DeleteLogicalRouterAnswer;
 import com.cloud.agent.api.DeleteLogicalRouterCommand;
-import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
-import com.cloud.agent.api.DeleteLogicalSwitchCommand;
 import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
 import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
 import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
@@ -74,6 +72,7 @@ import com.cloud.network.nicira.RouterNextHop;
 import com.cloud.network.nicira.SingleDefaultRouteImplicitRoutingConfig;
 import com.cloud.network.nicira.SourceNatRule;
 import com.cloud.network.nicira.VifAttachment;
+import com.cloud.network.utils.CommandRetryUtility;
 import com.cloud.resource.ServerResource;
 
 public class NiciraNvpResource implements ServerResource {
@@ -81,14 +80,15 @@ public class NiciraNvpResource implements ServerResource {
     private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
 
     public static final int NAME_MAX_LEN = 40;
+    public static final int NUM_RETRIES = 2;
 
     private String name;
     private String guid;
     private String zoneId;
-    private int numRetries;
 
     private NiciraNvpApi niciraNvpApi;
     private NiciraNvpUtilities niciraNvpUtilities;
+    private CommandRetryUtility retryUtility;
 
     protected NiciraNvpApi createNiciraNvpApi() {
         return new NiciraNvpApi();
@@ -112,8 +112,6 @@ public class NiciraNvpResource implements ServerResource {
             throw new ConfigurationException("Unable to find zone");
         }
 
-        numRetries = 2;
-
         final String ip = (String)params.get("ip");
         if (ip == null) {
             throw new ConfigurationException("Unable to find IP");
@@ -130,6 +128,8 @@ public class NiciraNvpResource implements ServerResource {
         }
 
         niciraNvpUtilities = NiciraNvpUtilities.getInstance();
+        retryUtility = CommandRetryUtility.getInstance();
+        retryUtility.setServerResource(this);
 
         niciraNvpApi = createNiciraNvpApi();
         niciraNvpApi.setControllerAddress(ip);
@@ -146,8 +146,8 @@ public class NiciraNvpResource implements ServerResource {
         return niciraNvpUtilities;
     }
 
-    public int getNumRetries() {
-        return numRetries;
+    public CommandRetryUtility getRetryUtility() {
+        return retryUtility;
     }
 
     @Override
@@ -201,11 +201,6 @@ public class NiciraNvpResource implements ServerResource {
 
     @Override
     public Answer executeRequest(final Command cmd) {
-        return executeRequest(cmd, numRetries);
-    }
-
-    public Answer executeRequest(final Command cmd, final int numRetries) {
-
         final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
         try {
             return wrapper.execute(cmd, this);
@@ -214,26 +209,24 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof DeleteLogicalSwitchCommand) {
-            return executeRequest((DeleteLogicalSwitchCommand)cmd, numRetries);
-        } else if (cmd instanceof CreateLogicalSwitchPortCommand) {
-            return executeRequest((CreateLogicalSwitchPortCommand)cmd, numRetries);
+        if (cmd instanceof CreateLogicalSwitchPortCommand) {
+            return executeRequest((CreateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof DeleteLogicalSwitchPortCommand) {
-            return executeRequest((DeleteLogicalSwitchPortCommand)cmd, numRetries);
+            return executeRequest((DeleteLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof UpdateLogicalSwitchPortCommand) {
-            return executeRequest((UpdateLogicalSwitchPortCommand)cmd, numRetries);
+            return executeRequest((UpdateLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof FindLogicalSwitchPortCommand) {
-            return executeRequest((FindLogicalSwitchPortCommand)cmd, numRetries);
+            return executeRequest((FindLogicalSwitchPortCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof CreateLogicalRouterCommand) {
-            return executeRequest((CreateLogicalRouterCommand)cmd, numRetries);
+            return executeRequest((CreateLogicalRouterCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof DeleteLogicalRouterCommand) {
-            return executeRequest((DeleteLogicalRouterCommand)cmd, numRetries);
+            return executeRequest((DeleteLogicalRouterCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof ConfigureStaticNatRulesOnLogicalRouterCommand) {
-            return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand)cmd, numRetries);
+            return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof ConfigurePortForwardingRulesOnLogicalRouterCommand) {
-            return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand)cmd, numRetries);
+            return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand)cmd, NUM_RETRIES);
         } else if (cmd instanceof ConfigurePublicIpsOnLogicalRouterCommand) {
-            return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand)cmd, numRetries);
+            return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand)cmd, NUM_RETRIES);
         }
         s_logger.debug("Received unsupported command " + cmd.toString());
         return Answer.createUnsupportedCommandAnswer(cmd);
@@ -252,20 +245,7 @@ public class NiciraNvpResource implements ServerResource {
     public void setAgentControl(final IAgentControl agentControl) {
     }
 
-    private Answer executeRequest(final DeleteLogicalSwitchCommand cmd, int numRetries) {
-        try {
-            niciraNvpApi.deleteLogicalSwitch(cmd.getLogicalSwitchUuid());
-            return new DeleteLogicalSwitchAnswer(cmd, true, "Logicalswitch " + cmd.getLogicalSwitchUuid() + " deleted");
-        } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new DeleteLogicalSwitchAnswer(cmd, e);
-            }
-        }
-    }
-
-    private Answer executeRequest(final CreateLogicalSwitchPortCommand cmd, int numRetries) {
+    private Answer executeRequest(final CreateLogicalSwitchPortCommand cmd, final int numRetries) {
         final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
         final String attachmentUuid = cmd.getAttachmentUuid();
 
@@ -285,29 +265,22 @@ public class NiciraNvpResource implements ServerResource {
             }
             return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new CreateLogicalSwitchPortAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, CreateLogicalSwitchPortAnswer.class, e);
         }
-
     }
 
-    private Answer executeRequest(final DeleteLogicalSwitchPortCommand cmd, int numRetries) {
+    private Answer executeRequest(final DeleteLogicalSwitchPortCommand cmd, final int numRetries) {
         try {
             niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid());
             return new DeleteLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + cmd.getLogicalSwitchPortUuid() + " deleted");
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new DeleteLogicalSwitchPortAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, DeleteLogicalSwitchPortAnswer.class, e);
         }
     }
 
-    private Answer executeRequest(final UpdateLogicalSwitchPortCommand cmd, int numRetries) {
+    private Answer executeRequest(final UpdateLogicalSwitchPortCommand cmd, final int numRetries) {
         final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
         final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
         final String attachmentUuid = cmd.getAttachmentUuid();
@@ -320,16 +293,12 @@ public class NiciraNvpResource implements ServerResource {
             niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
             return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for  " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new UpdateLogicalSwitchPortAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, UpdateLogicalSwitchPortAnswer.class, e);
         }
-
     }
 
-    private Answer executeRequest(final FindLogicalSwitchPortCommand cmd, int numRetries) {
+    private Answer executeRequest(final FindLogicalSwitchPortCommand cmd, final int numRetries) {
         final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
         final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
 
@@ -341,15 +310,12 @@ public class NiciraNvpResource implements ServerResource {
                 return new FindLogicalSwitchPortAnswer(cmd, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
             }
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new FindLogicalSwitchPortAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, FindLogicalSwitchPortAnswer.class, e);
         }
     }
 
-    private Answer executeRequest(final CreateLogicalRouterCommand cmd, int numRetries) {
+    private Answer executeRequest(final CreateLogicalRouterCommand cmd, final int numRetries) {
         final String routerName = cmd.getName();
         final String gatewayServiceUuid = cmd.getGatewayServiceUuid();
         final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
@@ -438,28 +404,22 @@ public class NiciraNvpResource implements ServerResource {
 
             return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new CreateLogicalRouterAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, CreateLogicalRouterAnswer.class, e);
         }
     }
 
-    private Answer executeRequest(final DeleteLogicalRouterCommand cmd, int numRetries) {
+    private Answer executeRequest(final DeleteLogicalRouterCommand cmd, final int numRetries) {
         try {
             niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid());
             return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")");
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new DeleteLogicalRouterAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, DeleteLogicalRouterAnswer.class, e);
         }
     }
 
-    private Answer executeRequest(final ConfigurePublicIpsOnLogicalRouterCommand cmd, int numRetries) {
+    private Answer executeRequest(final ConfigurePublicIpsOnLogicalRouterCommand cmd, final int numRetries) {
         try {
             final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid());
             if (ports.getResultCount() != 1) {
@@ -472,16 +432,12 @@ public class NiciraNvpResource implements ServerResource {
             return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " +
                     cmd.getLogicalRouterUuid());
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, ConfigurePublicIpsOnLogicalRouterAnswer.class, e);
         }
-
     }
 
-    private Answer executeRequest(final ConfigureStaticNatRulesOnLogicalRouterCommand cmd, int numRetries) {
+    private Answer executeRequest(final ConfigureStaticNatRulesOnLogicalRouterCommand cmd, final int numRetries) {
         try {
             final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
             // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
@@ -542,15 +498,12 @@ public class NiciraNvpResource implements ServerResource {
             }
             return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " StaticNat rules applied");
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, ConfigureStaticNatRulesOnLogicalRouterAnswer.class, e);
         }
     }
 
-    private Answer executeRequest(final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, int numRetries) {
+    private Answer executeRequest(final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, final int numRetries) {
         try {
             final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
             // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
@@ -619,18 +572,9 @@ public class NiciraNvpResource implements ServerResource {
             }
             return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " PortForwarding rules applied");
         } catch (final NiciraNvpApiException e) {
-            if (numRetries > 0) {
-                return retry(cmd, --numRetries);
-            } else {
-                return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, e);
-            }
+            retryUtility.addRetry(cmd, NUM_RETRIES);
+            return retryUtility.retry(cmd, ConfigurePortForwardingRulesOnLogicalRouterAnswer.class, e);
         }
-
-    }
-
-    public Answer retry(final Command cmd, final int numRetries) {
-        s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
-        return executeRequest(cmd, numRetries);
     }
 
     private String natRuleToString(final NatRule rule) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
index 6fc6cf0..7d66ada 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpCreateLogicalSwitchCommandWrapper.java
@@ -19,6 +19,8 @@
 
 package com.cloud.network.resource.wrapper;
 
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
 import java.util.ArrayList;
 import java.util.List;
 
@@ -32,6 +34,7 @@ import com.cloud.network.nicira.NiciraNvpTag;
 import com.cloud.network.nicira.TransportZoneBinding;
 import com.cloud.network.resource.NiciraNvpResource;
 import com.cloud.network.resource.NiciraNvpUtilities;
+import com.cloud.network.utils.CommandRetryUtility;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.ResourceWrapper;
 
@@ -62,12 +65,9 @@ public final class NiciraNvpCreateLogicalSwitchCommandWrapper extends CommandWra
             final String switchUuid = logicalSwitch.getUuid();
             return new CreateLogicalSwitchAnswer(command, true, "Logicalswitch " + switchUuid + " created", switchUuid);
         } catch (final NiciraNvpApiException e) {
-            int numRetries = niciraNvpResource.getNumRetries();
-            if (numRetries > 0) {
-                return niciraNvpResource.retry(command, --numRetries);
-            } else {
-                return new CreateLogicalSwitchAnswer(command, e);
-            }
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, CreateLogicalSwitchAnswer.class, e);
         }
     }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
new file mode 100644
index 0000000..f7b8ab9
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpDeleteLogicalSwitchCommandWrapper.java
@@ -0,0 +1,49 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import static com.cloud.network.resource.NiciraNvpResource.NUM_RETRIES;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteLogicalSwitchAnswer;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
+import com.cloud.network.nicira.NiciraNvpApi;
+import com.cloud.network.nicira.NiciraNvpApiException;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.network.utils.CommandRetryUtility;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  DeleteLogicalSwitchCommand.class)
+public final class NiciraNvpDeleteLogicalSwitchCommandWrapper extends CommandWrapper<DeleteLogicalSwitchCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final DeleteLogicalSwitchCommand command, final NiciraNvpResource niciraNvpResource) {
+        try {
+            final NiciraNvpApi niciraNvpApi = niciraNvpResource.getNiciraNvpApi();
+            niciraNvpApi.deleteLogicalSwitch(command.getLogicalSwitchUuid());
+            return new DeleteLogicalSwitchAnswer(command, true, "Logicalswitch " + command.getLogicalSwitchUuid() + " deleted");
+        } catch (final NiciraNvpApiException e) {
+            final CommandRetryUtility retryUtility = niciraNvpResource.getRetryUtility();
+            retryUtility.addRetry(command, NUM_RETRIES);
+            return retryUtility.retry(command, DeleteLogicalSwitchAnswer.class, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
new file mode 100644
index 0000000..6244821
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/utils/CommandRetryUtility.java
@@ -0,0 +1,90 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.utils;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.resource.ServerResource;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class CommandRetryUtility {
+
+    private static final Logger s_logger = Logger.getLogger(NiciraNvpResource.class);
+
+    private static final int ZERO = 0;
+    private static CommandRetryUtility instance;
+
+    static {
+        instance = new CommandRetryUtility();
+    }
+
+    private final ConcurrentHashMap<Command, Integer> commandsToRetry;
+    private ServerResource serverResource;
+
+    private CommandRetryUtility() {
+        commandsToRetry = new ConcurrentHashMap<Command, Integer>();
+    }
+
+    public static CommandRetryUtility getInstance() {
+        return instance;
+    }
+
+    public void setServerResource(final ServerResource serverResource) {
+        this.serverResource = serverResource;
+    }
+
+    public boolean addRetry(final Command command, final int retries) {
+        if (commandsToRetry.containsKey(command)) {
+            // A retry already exists for this command, do not add it again.
+            // Once all retries are executed, the command will be removed from the map.
+            return false;
+        }
+        commandsToRetry.put(command, retries);
+        return true;
+    }
+
+    public Answer retry(final Command command, final Class<? extends Answer> answerClass, final Exception error) {
+        if (commandsToRetry.containsKey(command)) {
+            Integer numRetries = commandsToRetry.get(command);
+
+            if (numRetries > ZERO) {
+                commandsToRetry.put(command, --numRetries);
+
+                s_logger.warn("Retrying " + command.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
+
+                return serverResource.executeRequest(command);
+            } else {
+                commandsToRetry.remove(command);
+            }
+        }
+        try {
+            final Constructor<? extends Answer> answerConstructor = answerClass.getConstructor(Command.class, Exception.class);
+            return answerConstructor.newInstance(command, error);
+        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+            throw new CloudRuntimeException(e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index a7349ad..70e10e1 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -22,6 +22,7 @@ package com.cloud.network.resource;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.when;
 
 import org.junit.Test;
@@ -30,6 +31,7 @@ import org.mockito.Mockito;
 
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.CreateLogicalSwitchCommand;
+import com.cloud.agent.api.DeleteLogicalSwitchCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.network.nicira.LogicalSwitch;
@@ -99,4 +101,28 @@ public class NiciraNvpRequestWrapperTest {
 
         assertTrue(answer.getResult());
     }
+
+    @Test
+    public void testDeleteLogicalSwitchCommandWrapper() {
+        final NiciraNvpApi niciraNvpApi = Mockito.mock(NiciraNvpApi.class);
+
+        final String logicalSwitchUuid = "d2e05a9e-7120-4487-a5fc-414ab36d9345";
+
+        final DeleteLogicalSwitchCommand command = new DeleteLogicalSwitchCommand(logicalSwitchUuid);
+
+        when(niciraNvpResource.getNiciraNvpApi()).thenReturn(niciraNvpApi);
+
+        try {
+            doNothing().when(niciraNvpApi).deleteLogicalSwitch(command.getLogicalSwitchUuid());
+        } catch (final NiciraNvpApiException e) {
+            fail(e.getMessage());
+        }
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28c1da96/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
index 23fe82a..b8b81b2 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpResourceTest.java
@@ -85,12 +85,16 @@ import com.cloud.network.nicira.NiciraNvpApi;
 import com.cloud.network.nicira.NiciraNvpApiException;
 import com.cloud.network.nicira.NiciraNvpList;
 import com.cloud.network.nicira.SourceNatRule;
+import com.cloud.network.utils.CommandRetryUtility;
 
 public class NiciraNvpResourceTest {
     NiciraNvpApi nvpApi = mock(NiciraNvpApi.class);
     NiciraNvpResource resource;
     Map<String, Object> parameters;
 
+    private NiciraNvpUtilities niciraNvpUtilities;
+    private CommandRetryUtility retryUtility;
+
     @Before
     public void setUp() throws ConfigurationException {
         resource = new NiciraNvpResource() {
@@ -107,6 +111,10 @@ public class NiciraNvpResourceTest {
         parameters.put("guid", "aaaaa-bbbbb-ccccc");
         parameters.put("zoneId", "blublub");
         parameters.put("adminpass", "adminpass");
+
+        niciraNvpUtilities = NiciraNvpUtilities.getInstance();
+        retryUtility = CommandRetryUtility.getInstance();
+        retryUtility.setServerResource(resource);
     }
 
     @Test(expected = ConfigurationException.class)
@@ -295,7 +303,7 @@ public class NiciraNvpResourceTest {
 
         doThrow(new NiciraNvpApiException()).when(nvpApi).updateLogicalSwitchPortAttachment((String)any(), (String)any(), (Attachment)any());
         final UpdateLogicalSwitchPortAnswer dlspa =
-            (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
+                (UpdateLogicalSwitchPortAnswer)resource.executeRequest(new UpdateLogicalSwitchPortCommand("aaaa", "bbbb", "cccc", "owner", "nicname"));
         assertFalse(dlspa.getResult());
     }
 


[14/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Refactoring NiciraNvpResource
   - Added NiciraNvpMaintainCommandWrapper
   - Removing 1 execute methods form NiciraNvpResource
   - Added 1 unit test

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6a51294d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6a51294d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6a51294d

Branch: refs/heads/reporter
Commit: 6a51294d1972bbfd116fcd9ed36835c48423b76b
Parents: 0d943d5
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 23 09:38:56 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:56 2015 +0200

----------------------------------------------------------------------
 .../network/resource/NiciraNvpResource.java     | 10 +-----
 .../NiciraNvpMaintainCommandWrapper.java        | 36 ++++++++++++++++++++
 .../resource/NiciraNvpRequestWrapperTest.java   | 13 +++++++
 3 files changed, 50 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a51294d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index 3c1f9b5..9af541f 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -50,8 +50,6 @@ import com.cloud.agent.api.DeleteLogicalSwitchPortAnswer;
 import com.cloud.agent.api.DeleteLogicalSwitchPortCommand;
 import com.cloud.agent.api.FindLogicalSwitchPortAnswer;
 import com.cloud.agent.api.FindLogicalSwitchPortCommand;
-import com.cloud.agent.api.MaintainAnswer;
-import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupNiciraNvpCommand;
@@ -204,9 +202,7 @@ public class NiciraNvpResource implements ServerResource {
             // [TODO] Remove when all the commands are refactored.
         }
 
-        if (cmd instanceof MaintainCommand) {
-            return executeRequest((MaintainCommand)cmd);
-        } else if (cmd instanceof CreateLogicalSwitchCommand) {
+        if (cmd instanceof CreateLogicalSwitchCommand) {
             return executeRequest((CreateLogicalSwitchCommand)cmd, numRetries);
         } else if (cmd instanceof DeleteLogicalSwitchCommand) {
             return executeRequest((DeleteLogicalSwitchCommand)cmd, numRetries);
@@ -650,10 +646,6 @@ public class NiciraNvpResource implements ServerResource {
 
     }
 
-    private Answer executeRequest(final MaintainCommand cmd) {
-        return new MaintainAnswer(cmd);
-    }
-
     private Answer retry(final Command cmd, final int numRetries) {
         s_logger.warn("Retrying " + cmd.getClass().getSimpleName() + ". Number of retries remaining: " + numRetries);
         return executeRequest(cmd, numRetries);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a51294d/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
new file mode 100644
index 0000000..3015378
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpMaintainCommandWrapper.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.MaintainAnswer;
+import com.cloud.agent.api.MaintainCommand;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  MaintainCommand.class)
+public final class NiciraNvpMaintainCommandWrapper extends CommandWrapper<MaintainCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final MaintainCommand command, final NiciraNvpResource niciraNvpResource) {
+        return new MaintainAnswer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a51294d/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
index 5e5425e..ba22d18 100644
--- a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -27,6 +27,7 @@ import org.mockito.Mock;
 import org.mockito.Mockito;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ReadyCommand;
 
 public class NiciraNvpRequestWrapperTest {
@@ -45,4 +46,16 @@ public class NiciraNvpRequestWrapperTest {
 
         assertTrue(answer.getResult());
     }
+
+    @Test
+    public void testMaintainCommandWrapper() {
+        final MaintainCommand command = new MaintainCommand();
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file


[37/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Improving unit tests

   - Adding more unit tests as suggested by Daan and Rajani.
   - Mocking SshHelper and the Script classes, used by Citrix and Libvirt resources respectively.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/e348e76e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/e348e76e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/e348e76e

Branch: refs/heads/reporter
Commit: e348e76eee60d11eecf4c127cc2c9d03a72a96cb
Parents: 86297e7
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Mon Jul 6 14:58:17 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Mon Jul 6 14:58:17 2015 +0200

----------------------------------------------------------------------
 ...LibvirtUpdateHostPasswordCommandWrapper.java |   9 +-
 .../wrapper/LibvirtUtilitiesHelper.java         |  10 +-
 .../resource/LibvirtComputingResourceTest.java  |  34 +++++
 .../xenserver/resource/CitrixResourceBase.java  |  10 +-
 .../CitrixUpdateHostPasswordCommandWrapper.java |  17 +--
 .../xenbase/XenServerUtilitiesHelper.java       |  45 +++++++
 .../xenbase/CitrixRequestWrapperTest.java       | 131 ++++++++++++++++++-
 7 files changed, 228 insertions(+), 28 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
index 4d7d234..b0fd1c8 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpdateHostPasswordCommandWrapper.java
@@ -19,8 +19,6 @@
 
 package com.cloud.hypervisor.kvm.resource.wrapper;
 
-import org.apache.log4j.Logger;
-
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.UpdateHostPasswordCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
@@ -31,15 +29,14 @@ import com.cloud.utils.script.Script;
 @ResourceWrapper(handles =  UpdateHostPasswordCommand.class)
 public final class LibvirtUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, LibvirtComputingResource> {
 
-    private static final Logger s_logger = Logger.getLogger(LibvirtUpdateHostPasswordCommandWrapper.class);
-    private static final int TIMEOUT = 10000;
-
     @Override
     public Answer execute(final UpdateHostPasswordCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+
         final String username = command.getUsername();
         final String newPassword = command.getNewPassword();
 
-        final Script script = new Script(libvirtComputingResource.getUpdateHostPasswdPath(), TIMEOUT, s_logger);
+        final Script script = libvirtUtilitiesHelper.buildScript(libvirtComputingResource.getUpdateHostPasswdPath());
         script.add(username, newPassword);
         final String result = script.execute();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
index 8c8f6e6..1a1a6d3 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -31,15 +31,16 @@ import com.cloud.storage.StorageLayer;
 import com.cloud.storage.template.Processor;
 import com.cloud.storage.template.QCOW2Processor;
 import com.cloud.storage.template.TemplateLocation;
+import com.cloud.utils.script.Script;
 
 /**
  * This class is used to wrap the calls to several static methods. By doing so, we make easier to mock this class
  * and the methods wrapped here.
- *
- * Please do not instantiate this class directly, but inject it using the {@code @Inject} annotation.
  */
 public class LibvirtUtilitiesHelper {
 
+    public static final int TIMEOUT = 10000;
+
     public Connect getConnectionByVmName(final String vmName) throws LibvirtException {
         return LibvirtConnection.getConnectionByVmName(vmName);
     }
@@ -90,4 +91,9 @@ public class LibvirtUtilitiesHelper {
     public Connect retrieveQemuConnection(final String qemuURI) throws LibvirtException {
         return new Connect(qemuURI);
     }
+
+    public Script buildScript(final String scriptPath) {
+        final Script script = new Script(scriptPath, TIMEOUT);
+        return script;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 8ccdce5..42ebf86 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -168,6 +168,7 @@ import com.cloud.storage.template.TemplateLocation;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 import com.cloud.utils.Pair;
 import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
@@ -5076,12 +5077,45 @@ public class LibvirtComputingResourceTest {
 
     @Test
     public void testUpdateHostPasswordCommand() {
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Script script = Mockito.mock(Script.class);
+
+        final String hostIp = "127.0.0.1";
+        final String username = "root";
+        final String newPassword = "password";
+
+        final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword, hostIp);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getUpdateHostPasswdPath()).thenReturn("/tmp");
+        when(libvirtUtilitiesHelper.buildScript(libvirtComputingResource.getUpdateHostPasswdPath())).thenReturn(script);
+
+        when(script.execute()).thenReturn(null);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testUpdateHostPasswordCommandFail() {
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Script script = Mockito.mock(Script.class);
+
         final String hostIp = "127.0.0.1";
         final String username = "root";
         final String newPassword = "password";
+
         final UpdateHostPasswordCommand command = new UpdateHostPasswordCommand(username, newPassword, hostIp);
 
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getUpdateHostPasswdPath()).thenReturn("/tmp");
+        when(libvirtUtilitiesHelper.buildScript(libvirtComputingResource.getUpdateHostPasswdPath())).thenReturn(script);
+
+        when(script.execute()).thenReturn("#FAIL");
 
         final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
         assertNotNull(wrapper);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
index b205f2d..48e721f 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/CitrixResourceBase.java
@@ -103,6 +103,7 @@ import com.cloud.exception.InternalErrorException;
 import com.cloud.host.Host.Type;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.hypervisor.xenserver.resource.wrapper.xenbase.CitrixRequestWrapper;
+import com.cloud.hypervisor.xenserver.resource.wrapper.xenbase.XenServerUtilitiesHelper;
 import com.cloud.network.Networks;
 import com.cloud.network.Networks.BroadcastDomainType;
 import com.cloud.network.Networks.TrafficType;
@@ -259,6 +260,8 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
     protected  String _configDriveSRName = "ConfigDriveISOs";
     protected  String _attachIsoDeviceNum = "3";
 
+    protected XenServerUtilitiesHelper xenServerUtilitiesHelper = new XenServerUtilitiesHelper();
+
     protected int _wait;
     // Hypervisor specific params with generic value, may need to be overridden
     // for specific versions
@@ -288,6 +291,10 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         return _password.peek();
     }
 
+    public XenServerUtilitiesHelper getXenServerUtilitiesHelper() {
+        return xenServerUtilitiesHelper;
+    }
+
     protected StorageSubsystemCommandHandler buildStorageHandler() {
         final XenServerStorageProcessor processor = new XenServerStorageProcessor(this);
         return new StorageSubsystemCommandHandlerBase(processor);
@@ -5266,7 +5273,6 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
 
     }
 
-
     public void deleteLocalFolder(final String directory) throws Exception {
         if (directory == null || directory.isEmpty()) {
             final String msg = "Invalid directory path (null/empty) detected. Cannot delete specified directory.";
@@ -5283,4 +5289,4 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         }
     }
 
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
index 9e58678..015d9f4 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixUpdateHostPasswordCommandWrapper.java
@@ -19,6 +19,8 @@
 
 package com.cloud.hypervisor.xenserver.resource.wrapper.xenbase;
 
+import static com.cloud.hypervisor.xenserver.resource.wrapper.xenbase.XenServerUtilitiesHelper.SCRIPT_CMD_PATH;
+
 import org.apache.log4j.Logger;
 
 import com.cloud.agent.api.Answer;
@@ -28,13 +30,11 @@ import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.ResourceWrapper;
 import com.cloud.utils.Pair;
-import com.cloud.utils.ssh.SshHelper;
 
 @ResourceWrapper(handles =  UpdateHostPasswordCommand.class)
 public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper<UpdateHostPasswordCommand, Answer, CitrixResourceBase> {
 
     private static final Logger s_logger = Logger.getLogger(CitrixUpdateHostPasswordCommandWrapper.class);
-    private static final int TIMEOUT = 10000;
 
     @Override
     public Answer execute(final UpdateHostPasswordCommand command, final CitrixResourceBase citrixResourceBase) {
@@ -42,19 +42,14 @@ public final class CitrixUpdateHostPasswordCommandWrapper extends CommandWrapper
         final String username = command.getUsername();
         final String newPassword = command.getNewPassword();
 
-        final StringBuffer cmdLine = new StringBuffer();
-        cmdLine.append("sh /opt/cloud/bin/");
-        cmdLine.append(VRScripts.UPDATE_HOST_PASSWD);
-        cmdLine.append(' ');
-        cmdLine.append(username);
-        cmdLine.append(' ');
-        cmdLine.append(newPassword);
+        final XenServerUtilitiesHelper xenServerUtilitiesHelper = citrixResourceBase.getXenServerUtilitiesHelper();
+        final String cmdLine = xenServerUtilitiesHelper.buildCommandLine(SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword);
 
         Pair<Boolean, String> result;
-
         try {
             s_logger.debug("Executing command in Host: " + cmdLine);
-            result = SshHelper.sshExecute(hostIp, 22, username, null, citrixResourceBase.getPwdFromQueue(), cmdLine.toString(), 60000, 60000, TIMEOUT);
+            final String hostPassword = citrixResourceBase.getPwdFromQueue();
+            result = xenServerUtilitiesHelper.executeSshWrapper(hostIp, 22, username, null, hostPassword, cmdLine.toString());
         } catch (final Exception e) {
             return new Answer(command, false, e.getMessage());
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/XenServerUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/XenServerUtilitiesHelper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/XenServerUtilitiesHelper.java
new file mode 100644
index 0000000..9a35406
--- /dev/null
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/XenServerUtilitiesHelper.java
@@ -0,0 +1,45 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.hypervisor.xenserver.resource.wrapper.xenbase;
+
+import java.io.File;
+
+import com.cloud.utils.Pair;
+import com.cloud.utils.ssh.SshHelper;
+
+
+/**
+ * This class is used to wrap the calls to several static methods. By doing so, we make easier to mock this class
+ * and the methods wrapped here.
+ */
+public class XenServerUtilitiesHelper {
+
+    public static final int TIMEOUT = 10000;
+    public static final String SCRIPT_CMD_PATH = "sh /opt/cloud/bin/";
+
+    public Pair<Boolean, String> executeSshWrapper(final String hostIp, final int port, final String username, final File pemFile, final String hostPasswd, final String command) throws Exception {
+        final Pair<Boolean, String> result = SshHelper.sshExecute(hostIp, port, username, pemFile, hostPasswd, command, 60000, 60000, TIMEOUT);
+        return result;
+    }
+
+    public String buildCommandLine(final String scriptPath, final String script, final String username, final String newPassword) {
+        final StringBuilder cmdLine = new StringBuilder();
+        cmdLine.append(scriptPath).append(script).append(' ').append(username).append(' ').append(newPassword);
+
+        return cmdLine.toString();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e348e76e/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
index 91f59be..39dd075 100644
--- a/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
+++ b/plugins/hypervisors/xenserver/test/com/cloud/hypervisor/xenserver/resource/wrapper/xenbase/CitrixRequestWrapperTest.java
@@ -130,7 +130,7 @@ import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.VMTemplateStorageResourceAssoc;
 import com.cloud.storage.resource.StorageSubsystemCommandHandler;
-import com.cloud.utils.ExecutionResult;
+import com.cloud.utils.Pair;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.xensource.xenapi.Connection;
@@ -1320,24 +1320,141 @@ public class CitrixRequestWrapperTest {
         assertFalse(answer.getResult());
     }
 
+    @SuppressWarnings("unchecked")
     @Test
     public void testUpdateHostPasswordCommand() {
-        final ExecutionResult executionResult = Mockito.mock(ExecutionResult.class);
+        final XenServerUtilitiesHelper xenServerUtilitiesHelper = Mockito.mock(XenServerUtilitiesHelper.class);
+        final Pair<Boolean, String> result = Mockito.mock(Pair.class);
 
         final UpdateHostPasswordCommand updatePwd = new UpdateHostPasswordCommand("test", "123", "127.0.0.1");
 
-        final StringBuffer buff = new StringBuffer();
-        buff.append(updatePwd.getUsername());
-        buff.append(' ');
-        buff.append(updatePwd.getNewPassword());
+        when(citrixResourceBase.getPwdFromQueue()).thenReturn("password");
 
-        when(citrixResourceBase.executeInVR(updatePwd.getHostIp(), VRScripts.UPDATE_HOST_PASSWD, buff.toString())).thenReturn(executionResult);
+        final String hostIp = updatePwd.getHostIp();
+        final String username = updatePwd.getUsername();
+        final String hostPasswd = citrixResourceBase.getPwdFromQueue();
+        final String newPassword = updatePwd.getNewPassword();
+
+        final StringBuilder cmdLine = new StringBuilder();
+        cmdLine.append(XenServerUtilitiesHelper.SCRIPT_CMD_PATH).append(VRScripts.UPDATE_HOST_PASSWD).append(' ').append(username).append(' ').append(newPassword);
+
+        when(citrixResourceBase.getXenServerUtilitiesHelper()).thenReturn(xenServerUtilitiesHelper);
+        when(xenServerUtilitiesHelper.buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword)).thenReturn(cmdLine.toString());
+
+        try {
+            when(xenServerUtilitiesHelper.executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString())).thenReturn(result);
+            when(result.first()).thenReturn(true);
+            when(result.second()).thenReturn("");
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
+
+        final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(updatePwd, citrixResourceBase);
+
+        verify(citrixResourceBase, times(2)).getPwdFromQueue();
+        verify(citrixResourceBase, times(1)).getXenServerUtilitiesHelper();
+        verify(xenServerUtilitiesHelper, times(1)).buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword);
+        try {
+            verify(xenServerUtilitiesHelper, times(1)).executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString());
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
+        verify(result, times(1)).first();
+        verify(result, times(1)).second();
+
+        assertTrue(answer.getResult());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testUpdateHostPasswordCommandFail() {
+        final XenServerUtilitiesHelper xenServerUtilitiesHelper = Mockito.mock(XenServerUtilitiesHelper.class);
+        final Pair<Boolean, String> result = Mockito.mock(Pair.class);
+
+        final UpdateHostPasswordCommand updatePwd = new UpdateHostPasswordCommand("test", "123", "127.0.0.1");
+
+        when(citrixResourceBase.getPwdFromQueue()).thenReturn("password");
+
+        final String hostIp = updatePwd.getHostIp();
+        final String username = updatePwd.getUsername();
+        final String hostPasswd = citrixResourceBase.getPwdFromQueue();
+        final String newPassword = updatePwd.getNewPassword();
+
+        final StringBuilder cmdLine = new StringBuilder();
+        cmdLine.append(XenServerUtilitiesHelper.SCRIPT_CMD_PATH).append(VRScripts.UPDATE_HOST_PASSWD).append(' ').append(username).append(' ').append(newPassword);
+
+        when(citrixResourceBase.getXenServerUtilitiesHelper()).thenReturn(xenServerUtilitiesHelper);
+        when(xenServerUtilitiesHelper.buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword)).thenReturn(cmdLine.toString());
+
+        try {
+            when(xenServerUtilitiesHelper.executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString())).thenReturn(result);
+            when(result.first()).thenReturn(false);
+            when(result.second()).thenReturn("");
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
+
+        final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(updatePwd, citrixResourceBase);
+
+        verify(citrixResourceBase, times(2)).getPwdFromQueue();
+        verify(citrixResourceBase, times(1)).getXenServerUtilitiesHelper();
+        verify(xenServerUtilitiesHelper, times(1)).buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword);
+        try {
+            verify(xenServerUtilitiesHelper, times(1)).executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString());
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
+        verify(result, times(1)).first();
+        verify(result, times(1)).second();
+
+        assertFalse(answer.getResult());
+    }
+
+    @Test
+    public void testUpdateHostPasswordCommandException() {
+        final XenServerUtilitiesHelper xenServerUtilitiesHelper = Mockito.mock(XenServerUtilitiesHelper.class);
+
+        final UpdateHostPasswordCommand updatePwd = new UpdateHostPasswordCommand("test", "123", "127.0.0.1");
+
+        when(citrixResourceBase.getPwdFromQueue()).thenReturn("password");
+
+        final String hostIp = updatePwd.getHostIp();
+        final String username = updatePwd.getUsername();
+        final String hostPasswd = citrixResourceBase.getPwdFromQueue();
+        final String newPassword = updatePwd.getNewPassword();
+
+        final StringBuilder cmdLine = new StringBuilder();
+        cmdLine.append(XenServerUtilitiesHelper.SCRIPT_CMD_PATH).append(VRScripts.UPDATE_HOST_PASSWD).append(' ').append(username).append(' ').append(newPassword);
+
+        when(citrixResourceBase.getXenServerUtilitiesHelper()).thenReturn(xenServerUtilitiesHelper);
+        when(xenServerUtilitiesHelper.buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword)).thenReturn(cmdLine.toString());
+
+        try {
+            when(xenServerUtilitiesHelper.executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString())).thenThrow(new Exception("testing failure"));
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
 
         final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(updatePwd, citrixResourceBase);
 
+        verify(citrixResourceBase, times(2)).getPwdFromQueue();
+        verify(citrixResourceBase, times(1)).getXenServerUtilitiesHelper();
+        verify(xenServerUtilitiesHelper, times(1)).buildCommandLine(XenServerUtilitiesHelper.SCRIPT_CMD_PATH, VRScripts.UPDATE_HOST_PASSWD, username, newPassword);
+        try {
+            verify(xenServerUtilitiesHelper, times(1)).executeSshWrapper(hostIp, 22, username, null, hostPasswd, cmdLine.toString());
+        } catch (final Exception e) {
+            fail(e.getMessage());
+        }
+
         assertFalse(answer.getResult());
     }
 


[15/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

   - Refactoring NiciraNvpResource
   - Added NiciraNvpRequestWrapper
   - Removing 1 execute methods form NiciraNvpResource
   - Added 1 unit test

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/0d943d54
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0d943d54
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0d943d54

Branch: refs/heads/reporter
Commit: 0d943d5426c5c2a9c3998e7e9cc312f5b8d11838
Parents: fc47860
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue Jun 23 09:20:47 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:56 2015 +0200

----------------------------------------------------------------------
 .../resource/NiciraNvpRequestWrapper.java       |   4 +-
 .../network/resource/NiciraNvpResource.java     | 153 ++++++++++---------
 .../wrapper/NiciraNvpReadyCommandWrapper.java   |  36 +++++
 .../resource/NiciraNvpRequestWrapperTest.java   |  48 ++++++
 4 files changed, 163 insertions(+), 78 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d943d54/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
index 70eb943..55f0c49 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
@@ -48,9 +48,9 @@ public class NiciraNvpRequestWrapper extends RequestWrapper {
     @SuppressWarnings("rawtypes")
     private void init() {
         // NiciraNvpResource commands
-        final Hashtable<Class<? extends Command>, CommandWrapper> libvirtCommands = processAnnotations(baseSet);
+        final Hashtable<Class<? extends Command>, CommandWrapper> niciraCommands = processAnnotations(baseSet);
 
-        resources.put(NiciraNvpResource.class, libvirtCommands);
+        resources.put(NiciraNvpResource.class, niciraCommands);
     }
 
     public static NiciraNvpRequestWrapper getInstance() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d943d54/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
index ec95ea5..3c1f9b5 100644
--- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpResource.java
@@ -53,8 +53,6 @@ import com.cloud.agent.api.FindLogicalSwitchPortCommand;
 import com.cloud.agent.api.MaintainAnswer;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.PingCommand;
-import com.cloud.agent.api.ReadyAnswer;
-import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupNiciraNvpCommand;
 import com.cloud.agent.api.UpdateLogicalSwitchPortAnswer;
@@ -101,7 +99,7 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     @Override
-    public boolean configure(String ignoredName, final Map<String, Object> params) throws ConfigurationException {
+    public boolean configure(final String ignoredName, final Map<String, Object> params) throws ConfigurationException {
 
         name = (String)params.get("name");
         if (name == null) {
@@ -120,17 +118,17 @@ public class NiciraNvpResource implements ServerResource {
 
         numRetries = 2;
 
-        String ip = (String)params.get("ip");
+        final String ip = (String)params.get("ip");
         if (ip == null) {
             throw new ConfigurationException("Unable to find IP");
         }
 
-        String adminuser = (String)params.get("adminuser");
+        final String adminuser = (String)params.get("adminuser");
         if (adminuser == null) {
             throw new ConfigurationException("Unable to find admin username");
         }
 
-        String adminpass = (String)params.get("adminpass");
+        final String adminpass = (String)params.get("adminpass");
         if (adminpass == null) {
             throw new ConfigurationException("Unable to find admin password");
         }
@@ -165,7 +163,7 @@ public class NiciraNvpResource implements ServerResource {
 
     @Override
     public StartupCommand[] initialize() {
-        StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand();
+        final StartupNiciraNvpCommand sc = new StartupNiciraNvpCommand();
         sc.setGuid(guid);
         sc.setName(name);
         sc.setDataCenter(zoneId);
@@ -179,12 +177,12 @@ public class NiciraNvpResource implements ServerResource {
     @Override
     public PingCommand getCurrentStatus(final long id) {
         try {
-            ControlClusterStatus ccs = niciraNvpApi.getControlClusterStatus();
+            final ControlClusterStatus ccs = niciraNvpApi.getControlClusterStatus();
             if (!"stable".equals(ccs.getClusterStatus())) {
                 s_logger.error("ControlCluster state is not stable: " + ccs.getClusterStatus());
                 return null;
             }
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             s_logger.error("getControlClusterStatus failed", e);
             return null;
         }
@@ -197,9 +195,16 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     public Answer executeRequest(final Command cmd, final int numRetries) {
-        if (cmd instanceof ReadyCommand) {
-            return executeRequest((ReadyCommand)cmd);
-        } else if (cmd instanceof MaintainCommand) {
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        try {
+            return wrapper.execute(cmd, this);
+        } catch (final Exception e) {
+            //return Answer.createUnsupportedCommandAnswer(cmd);
+            // [TODO] Remove when all the commands are refactored.
+        }
+
+        if (cmd instanceof MaintainCommand) {
             return executeRequest((MaintainCommand)cmd);
         } else if (cmd instanceof CreateLogicalSwitchCommand) {
             return executeRequest((CreateLogicalSwitchCommand)cmd, numRetries);
@@ -247,19 +252,19 @@ public class NiciraNvpResource implements ServerResource {
         logicalSwitch.setPortIsolationEnabled(false);
 
         // Set transport binding
-        List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
+        final List<TransportZoneBinding> ltzb = new ArrayList<TransportZoneBinding>();
         ltzb.add(new TransportZoneBinding(cmd.getTransportUuid(), cmd.getTransportType()));
         logicalSwitch.setTransportZones(ltzb);
 
         // Tags set to scope cs_account and account name
-        List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
         tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
         logicalSwitch.setTags(tags);
 
         try {
             logicalSwitch = niciraNvpApi.createLogicalSwitch(logicalSwitch);
             return new CreateLogicalSwitchAnswer(cmd, true, "Logicalswitch " + logicalSwitch.getUuid() + " created", logicalSwitch.getUuid());
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -273,7 +278,7 @@ public class NiciraNvpResource implements ServerResource {
         try {
             niciraNvpApi.deleteLogicalSwitch(cmd.getLogicalSwitchUuid());
             return new DeleteLogicalSwitchAnswer(cmd, true, "Logicalswitch " + cmd.getLogicalSwitchUuid() + " deleted");
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -283,25 +288,25 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     private Answer executeRequest(final CreateLogicalSwitchPortCommand cmd, int numRetries) {
-        String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        String attachmentUuid = cmd.getAttachmentUuid();
+        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
+        final String attachmentUuid = cmd.getAttachmentUuid();
 
         try {
             // Tags set to scope cs_account and account name
-            List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+            final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
             tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
 
-            LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
-            LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
+            final LogicalSwitchPort logicalSwitchPort = new LogicalSwitchPort(attachmentUuid, tags, true);
+            final LogicalSwitchPort newPort = niciraNvpApi.createLogicalSwitchPort(logicalSwitchUuid, logicalSwitchPort);
             try {
                 niciraNvpApi.updateLogicalSwitchPortAttachment(cmd.getLogicalSwitchUuid(), newPort.getUuid(), new VifAttachment(attachmentUuid));
-            } catch (NiciraNvpApiException ex) {
+            } catch (final NiciraNvpApiException ex) {
                 s_logger.warn("modifyLogicalSwitchPort failed after switchport was created, removing switchport");
                 niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), newPort.getUuid());
-                throw (ex); // Rethrow the original exception
+                throw ex; // Rethrow the original exception
             }
             return new CreateLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + newPort.getUuid() + " created", newPort.getUuid());
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -315,7 +320,7 @@ public class NiciraNvpResource implements ServerResource {
         try {
             niciraNvpApi.deleteLogicalSwitchPort(cmd.getLogicalSwitchUuid(), cmd.getLogicalSwitchPortUuid());
             return new DeleteLogicalSwitchPortAnswer(cmd, true, "Logical switch port " + cmd.getLogicalSwitchPortUuid() + " deleted");
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -325,18 +330,18 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     private Answer executeRequest(final UpdateLogicalSwitchPortCommand cmd, int numRetries) {
-        String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
-        String attachmentUuid = cmd.getAttachmentUuid();
+        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
+        final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
+        final String attachmentUuid = cmd.getAttachmentUuid();
 
         try {
             // Tags set to scope cs_account and account name
-            List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+            final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
             tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
 
             niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, logicalSwitchPortUuid, new VifAttachment(attachmentUuid));
             return new UpdateLogicalSwitchPortAnswer(cmd, true, "Attachment for  " + logicalSwitchPortUuid + " updated", logicalSwitchPortUuid);
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -347,17 +352,17 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     private Answer executeRequest(final FindLogicalSwitchPortCommand cmd, int numRetries) {
-        String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
-        String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
+        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
+        final String logicalSwitchPortUuid = cmd.getLogicalSwitchPortUuid();
 
         try {
-            NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
+            final NiciraNvpList<LogicalSwitchPort> ports = niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid);
             if (ports.getResultCount() == 0) {
                 return new FindLogicalSwitchPortAnswer(cmd, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null);
             } else {
                 return new FindLogicalSwitchPortAnswer(cmd, true, "Logical switchport " + logicalSwitchPortUuid + " found", logicalSwitchPortUuid);
             }
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -367,19 +372,19 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     private Answer executeRequest(final CreateLogicalRouterCommand cmd, int numRetries) {
-        String routerName = cmd.getName();
-        String gatewayServiceUuid = cmd.getGatewayServiceUuid();
-        String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
+        final String routerName = cmd.getName();
+        final String gatewayServiceUuid = cmd.getGatewayServiceUuid();
+        final String logicalSwitchUuid = cmd.getLogicalSwitchUuid();
 
-        List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
+        final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
         tags.add(new NiciraNvpTag("cs_account", cmd.getOwnerName()));
 
-        String publicNetworkNextHopIp = cmd.getPublicNextHop();
-        String publicNetworkIpAddress = cmd.getPublicIpCidr();
-        String internalNetworkAddress = cmd.getInternalIpCidr();
+        final String publicNetworkNextHopIp = cmd.getPublicNextHop();
+        final String publicNetworkIpAddress = cmd.getPublicIpCidr();
+        final String internalNetworkAddress = cmd.getInternalIpCidr();
 
         s_logger.debug("Creating a logical router with external ip " + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + "on gateway service " +
-            gatewayServiceUuid);
+                gatewayServiceUuid);
 
         try {
             // Create the Router
@@ -398,13 +403,13 @@ public class NiciraNvpResource implements ServerResource {
                 lrpo.setAdminStatusEnabled(true);
                 lrpo.setDisplayName(truncate(routerName + "-outside-port", NAME_MAX_LEN));
                 lrpo.setTags(tags);
-                List<String> outsideIpAddresses = new ArrayList<String>();
+                final List<String> outsideIpAddresses = new ArrayList<String>();
                 outsideIpAddresses.add(publicNetworkIpAddress);
                 lrpo.setIpAddresses(outsideIpAddresses);
                 lrpo = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpo);
 
                 // Attach the outside port to the gateway service on the correct VLAN
-                L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
+                final L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid);
                 if (cmd.getVlanId() != 0) {
                     attachment.setVlanId(cmd.getVlanId());
                 }
@@ -415,7 +420,7 @@ public class NiciraNvpResource implements ServerResource {
                 lrpi.setAdminStatusEnabled(true);
                 lrpi.setDisplayName(truncate(routerName + "-inside-port", NAME_MAX_LEN));
                 lrpi.setTags(tags);
-                List<String> insideIpAddresses = new ArrayList<String>();
+                final List<String> insideIpAddresses = new ArrayList<String>();
                 insideIpAddresses.add(internalNetworkAddress);
                 lrpi.setIpAddresses(insideIpAddresses);
                 lrpi = niciraNvpApi.createLogicalRouterPort(lrc.getUuid(), lrpi);
@@ -431,15 +436,15 @@ public class NiciraNvpResource implements ServerResource {
                 niciraNvpApi.updateLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), new PatchAttachment(lrpi.getUuid()));
 
                 // Setup the source nat rule
-                SourceNatRule snr = new SourceNatRule();
+                final SourceNatRule snr = new SourceNatRule();
                 snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]);
                 snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]);
-                Match match = new Match();
+                final Match match = new Match();
                 match.setSourceIpAddresses(internalNetworkAddress);
                 snr.setMatch(match);
                 snr.setOrder(200);
                 niciraNvpApi.createLogicalRouterNatRule(lrc.getUuid(), snr);
-            } catch (NiciraNvpApiException e) {
+            } catch (final NiciraNvpApiException e) {
                 // We need to destroy the router if we already created it
                 // this will also take care of any router ports and rules
                 try {
@@ -447,14 +452,14 @@ public class NiciraNvpResource implements ServerResource {
                     if (lsp != null) {
                         niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid());
                     }
-                } catch (NiciraNvpApiException ex) {
+                } catch (final NiciraNvpApiException ex) {
                 }
 
                 throw e;
             }
 
             return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid());
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -467,7 +472,7 @@ public class NiciraNvpResource implements ServerResource {
         try {
             niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid());
             return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")");
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -478,17 +483,17 @@ public class NiciraNvpResource implements ServerResource {
 
     private Answer executeRequest(final ConfigurePublicIpsOnLogicalRouterCommand cmd, int numRetries) {
         try {
-            NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid());
+            final NiciraNvpList<LogicalRouterPort> ports = niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid());
             if (ports.getResultCount() != 1) {
                 return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, false, "No logical router ports found, unable to set ip addresses");
             }
-            LogicalRouterPort lrp = ports.getResults().get(0);
+            final LogicalRouterPort lrp = ports.getResults().get(0);
             lrp.setIpAddresses(cmd.getPublicCidrs());
             niciraNvpApi.updateLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp);
 
             return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, true, "Configured " + cmd.getPublicCidrs().size() + " ip addresses on logical router uuid " +
-                cmd.getLogicalRouterUuid());
-        } catch (NiciraNvpApiException e) {
+                    cmd.getLogicalRouterUuid());
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -500,19 +505,19 @@ public class NiciraNvpResource implements ServerResource {
 
     private Answer executeRequest(final ConfigureStaticNatRulesOnLogicalRouterCommand cmd, int numRetries) {
         try {
-            NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
+            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
             // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
             // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
             // Any other SourceNat rule should have a corresponding DestinationNat rule
 
-            for (StaticNatRuleTO rule : cmd.getRules()) {
+            for (final StaticNatRuleTO rule : cmd.getRules()) {
 
-                NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
+                final NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp());
 
                 NatRule incoming = null;
                 NatRule outgoing = null;
 
-                for (NatRule storedRule : existingRules.getResults()) {
+                for (final NatRule storedRule : existingRules.getResults()) {
                     if (storedRule.equalsIgnoreUuid(rulepair[1])) {
                         // The outgoing rule exists
                         outgoing = storedRule;
@@ -549,7 +554,7 @@ public class NiciraNvpResource implements ServerResource {
                     try {
                         rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]);
                         s_logger.debug("Created " + natRuleToString(rulepair[1]));
-                    } catch (NiciraNvpApiException ex) {
+                    } catch (final NiciraNvpApiException ex) {
                         s_logger.debug("Failed to create SourceNatRule, rolling back DestinationNatRule");
                         niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid());
                         throw ex; // Rethrow original exception
@@ -558,7 +563,7 @@ public class NiciraNvpResource implements ServerResource {
                 }
             }
             return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " StaticNat rules applied");
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -569,12 +574,12 @@ public class NiciraNvpResource implements ServerResource {
 
     private Answer executeRequest(final ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, int numRetries) {
         try {
-            NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
+            final NiciraNvpList<NatRule> existingRules = niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid());
             // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on)
             // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule
             // Any other SourceNat rule should have a corresponding DestinationNat rule
 
-            for (PortForwardingRuleTO rule : cmd.getRules()) {
+            for (final PortForwardingRuleTO rule : cmd.getRules()) {
                 if (rule.isAlreadyAdded() && !rule.revoked()) {
                     // Don't need to do anything
                     continue;
@@ -584,12 +589,12 @@ public class NiciraNvpResource implements ServerResource {
                     return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, false, "Nicira NVP doesn't support port ranges for port forwarding");
                 }
 
-                NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
+                final NatRule[] rulepair = generatePortForwardingRulePair(rule.getDstIp(), rule.getDstPortRange(), rule.getSrcIp(), rule.getSrcPortRange(), rule.getProtocol());
 
                 NatRule incoming = null;
                 NatRule outgoing = null;
 
-                for (NatRule storedRule : existingRules.getResults()) {
+                for (final NatRule storedRule : existingRules.getResults()) {
                     if (storedRule.equalsIgnoreUuid(rulepair[1])) {
                         // The outgoing rule exists
                         outgoing = storedRule;
@@ -626,7 +631,7 @@ public class NiciraNvpResource implements ServerResource {
                     try {
                         rulepair[1] = niciraNvpApi.createLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[1]);
                         s_logger.debug("Created " + natRuleToString(rulepair[1]));
-                    } catch (NiciraNvpApiException ex) {
+                    } catch (final NiciraNvpApiException ex) {
                         s_logger.warn("NiciraNvpApiException during create call, rolling back previous create");
                         niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid());
                         throw ex; // Rethrow the original exception
@@ -635,7 +640,7 @@ public class NiciraNvpResource implements ServerResource {
                 }
             }
             return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() + " PortForwarding rules applied");
-        } catch (NiciraNvpApiException e) {
+        } catch (final NiciraNvpApiException e) {
             if (numRetries > 0) {
                 return retry(cmd, --numRetries);
             } else {
@@ -645,10 +650,6 @@ public class NiciraNvpResource implements ServerResource {
 
     }
 
-    private Answer executeRequest(final ReadyCommand cmd) {
-        return new ReadyAnswer(cmd);
-    }
-
     private Answer executeRequest(final MaintainCommand cmd) {
         return new MaintainAnswer(cmd);
     }
@@ -660,13 +661,13 @@ public class NiciraNvpResource implements ServerResource {
 
     private String natRuleToString(final NatRule rule) {
 
-        StringBuilder natRuleStr = new StringBuilder();
+        final StringBuilder natRuleStr = new StringBuilder();
         natRuleStr.append("Rule ");
         natRuleStr.append(rule.getUuid());
         natRuleStr.append(" (");
         natRuleStr.append(rule.getType());
         natRuleStr.append(") :");
-        Match m = rule.getMatch();
+        final Match m = rule.getMatch();
         natRuleStr.append("match (");
         natRuleStr.append(m.getProtocol());
         natRuleStr.append(" ");
@@ -703,7 +704,7 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     protected NatRule[] generateStaticNatRulePair(final String insideIp, final String outsideIp) {
-        NatRule[] rulepair = new NatRule[2];
+        final NatRule[] rulepair = new NatRule[2];
         rulepair[0] = new DestinationNatRule();
         rulepair[0].setType("DestinationNatRule");
         rulepair[0].setOrder(100);
@@ -728,9 +729,9 @@ public class NiciraNvpResource implements ServerResource {
     }
 
     protected NatRule[] generatePortForwardingRulePair(final String insideIp, final int[] insidePorts, final String outsideIp, final int[] outsidePorts,
-        final String protocol) {
+            final String protocol) {
         // Start with a basic static nat rule, then add port and protocol details
-        NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
+        final NatRule[] rulepair = generateStaticNatRulePair(insideIp, outsideIp);
 
         ((DestinationNatRule)rulepair[0]).setToDestinationPort(insidePorts[0]);
         rulepair[0].getMatch().setDestinationPort(outsidePorts[0]);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d943d54/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
new file mode 100644
index 0000000..3d0d3f3
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/wrapper/NiciraNvpReadyCommandWrapper.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ReadyAnswer;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.network.resource.NiciraNvpResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ResourceWrapper;
+
+@ResourceWrapper(handles =  ReadyCommand.class)
+public final class NiciraNvpReadyCommandWrapper extends CommandWrapper<ReadyCommand, Answer, NiciraNvpResource> {
+
+    @Override
+    public Answer execute(final ReadyCommand command, final NiciraNvpResource niciraNvpResource) {
+        return new ReadyAnswer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d943d54/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
new file mode 100644
index 0000000..5e5425e
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/resource/NiciraNvpRequestWrapperTest.java
@@ -0,0 +1,48 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ReadyCommand;
+
+public class NiciraNvpRequestWrapperTest {
+
+    @Mock
+    private final NiciraNvpResource niciraNvpResource = Mockito.mock(NiciraNvpResource.class);
+
+    @Test
+    public void testReadyCommandWrapper() {
+        final ReadyCommand command = new ReadyCommand();
+
+        final NiciraNvpRequestWrapper wrapper = NiciraNvpRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, niciraNvpResource);
+
+        assertTrue(answer.getResult());
+    }
+}
\ No newline at end of file


[43/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
findbugs: equals unit tests

Signed-off-by: Daan Hoogland <da...@onecht.net>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/d8ab5f3a
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/d8ab5f3a
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/d8ab5f3a

Branch: refs/heads/reporter
Commit: d8ab5f3ab815579c651150ad273facd0854ea51f
Parents: 3462944
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jul 6 16:07:02 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Tue Jul 7 13:48:19 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/storage/BaseType.java | 11 +++++--
 .../apache/cloudstack/storage/BaseTypeTest.java | 32 ++++++++++++++++++
 .../framework/config/ConfigKeyTest.java         | 34 ++++++++++++++++++++
 pom.xml                                         |  1 +
 utils/pom.xml                                   |  5 +++
 utils/src/com/cloud/utils/net/Ip4Address.java   | 11 ++++---
 .../com/cloud/utils/net/Ip4AddressTest.java     | 24 ++++++++++++++
 utils/test/com/cloud/utils/net/IpTest.java      | 17 ++++++++++
 8 files changed, 127 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
index 6d27772..1df02ba 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/BaseType.java
@@ -25,19 +25,24 @@ public abstract class BaseType {
             return true;
         } else if (that instanceof BaseType) {
             BaseType th = (BaseType)that;
-            if (this.toString().equalsIgnoreCase(th.toString())) {
+            if (toString().equalsIgnoreCase(th.toString())) {
                 return true;
             }
         }
         return false;
     }
 
+    @Override
+    public int hashCode() {
+        return toString().toLowerCase().hashCode();
+    }
+
     public boolean isSameTypeAs(Object that) {
-        if (this.equals(that)){
+        if (equals(that)){
             return true;
         }
         if (that instanceof String) {
-            if (this.toString().equalsIgnoreCase((String)that)) {
+            if (toString().equalsIgnoreCase((String)that)) {
                 return true;
             }
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
----------------------------------------------------------------------
diff --git a/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java b/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
new file mode 100644
index 0000000..5cce015
--- /dev/null
+++ b/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
@@ -0,0 +1,32 @@
+package org.apache.cloudstack.storage;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.testing.EqualsTester;
+
+public class BaseTypeTest {
+    @Test
+    public void testEquals() {
+        new EqualsTester()
+                .addEqualityGroup(new TestType("a"), new TestType("A"))
+                .addEqualityGroup(new TestType("Bd"), new TestType("bD"))
+                .testEquals();
+    }
+
+    @Test
+    public void testIsSameTypeAs() {
+        Assert.assertTrue("'a' and 'A' should be considdered the same type", new TestType("a").isSameTypeAs("A"));
+        Assert.assertTrue("'B' and 'b' should be considdered the same address", new TestType("B").isSameTypeAs(new TestType("b")));
+    }
+    class TestType extends BaseType {
+        String content;
+        public TestType(String t) {
+            content = t;
+        }
+        @Override
+        public String toString() {
+            return content;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
----------------------------------------------------------------------
diff --git a/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java b/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
new file mode 100644
index 0000000..b02ac1f
--- /dev/null
+++ b/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
@@ -0,0 +1,34 @@
+package org.apache.cloudstack.framework.config;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.testing.EqualsTester;
+
+import org.apache.cloudstack.framework.config.ConfigKey.Scope;
+
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class ConfigKeyTest {
+    @Test
+    public void testEquals() {
+        new EqualsTester()
+                .addEqualityGroup(new ConfigKey("cat", String.class, "naam", "nick", "bijnaam", true, Scope.Cluster),
+                        new ConfigKey("hond", Boolean.class, "naam", "truus", "thrown name", false),
+                        new ConfigKey(Long.class, "naam", "vis", "goud", "zwemt", true, Scope.Account, 3L)
+                )
+                .testEquals();
+    }
+
+    @Test
+    public void testIsSameKeyAs() {
+        ConfigKey key = new ConfigKey("cat", String.class, "naam", "nick", "bijnaam", true, Scope.Cluster);
+        Assert.assertTrue("1 and one should be considdered the same address", key.isSameKeyAs("naam"));
+    }
+
+    @Test(expected = CloudRuntimeException.class)
+    public void testIsSameKeyAsThrowingCloudRuntimeException() {
+        ConfigKey key = new ConfigKey("hond", Boolean.class, "naam", "truus", "thrown name", false);
+        Assert.assertFalse("zero and 0L should be considdered the same address", key.isSameKeyAs(0L));
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 900f2e4..e76d747 100644
--- a/pom.xml
+++ b/pom.xml
@@ -63,6 +63,7 @@
     <cs.trilead.version>1.0.0-build217</cs.trilead.version>
     <cs.ehcache.version>2.6.9</cs.ehcache.version>
     <cs.gson.version>1.7.2</cs.gson.version>
+    <cs.guava-testlib.version>18.0</cs.guava-testlib.version>
     <cs.guava.version>18.0</cs.guava.version>
     <cs.xapi.version>6.2.0-3.1</cs.xapi.version>
     <cs.httpclient.version>4.3.6</cs.httpclient.version>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/utils/pom.xml
----------------------------------------------------------------------
diff --git a/utils/pom.xml b/utils/pom.xml
index c1a5610..937dc08 100755
--- a/utils/pom.xml
+++ b/utils/pom.xml
@@ -162,6 +162,11 @@
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
     </dependency>
+    <dependency>
+      <groupId>com.google.guava</groupId>
+      <artifactId>guava-testlib</artifactId>
+      <version>${cs.guava-testlib.version}</version>
+    </dependency>
   </dependencies>
   <build>
     <plugins>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/utils/src/com/cloud/utils/net/Ip4Address.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/net/Ip4Address.java b/utils/src/com/cloud/utils/net/Ip4Address.java
index 9712a1f..0bd814d 100644
--- a/utils/src/com/cloud/utils/net/Ip4Address.java
+++ b/utils/src/com/cloud/utils/net/Ip4Address.java
@@ -22,6 +22,7 @@ package com.cloud.utils.net;
 public class Ip4Address {
     String _addr;
     String _mac;
+    static final String s_empty_mac = "00:00:00:00:00:00";
 
     public Ip4Address(String addr, String mac) {
         _addr = addr;
@@ -34,11 +35,11 @@ public class Ip4Address {
     }
 
     public Ip4Address(String addr) {
-        this(addr, null);
+        this(addr, s_empty_mac);
     }
 
     public Ip4Address(long addr) {
-        this(NetUtils.long2Ip(addr), null);
+        this(NetUtils.long2Ip(addr), s_empty_mac);
     }
 
     public String ip4() {
@@ -58,7 +59,7 @@ public class Ip4Address {
 
         if (that instanceof Ip4Address) {
             Ip4Address ip4 = (Ip4Address)that;
-            return this._addr.equals(ip4._addr) && (this._mac == ip4._mac || this._mac.equals(ip4._mac));
+            return _addr.equals(ip4._addr) && (_mac == ip4._mac || _mac.equals(ip4._mac));
         } else {
             return false;
         }
@@ -68,12 +69,12 @@ public class Ip4Address {
         if (other instanceof String) { // Assume that is an ip4 address in String form
             return _addr.equals(other);
         } else {
-            return this.equals(other);
+            return equals(other);
         }
     }
 
     @Override
     public int hashCode(){
-        return (int)(_mac.hashCode()*_addr.hashCode());
+        return _mac.hashCode()*_addr.hashCode();
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/utils/test/com/cloud/utils/net/Ip4AddressTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/Ip4AddressTest.java b/utils/test/com/cloud/utils/net/Ip4AddressTest.java
new file mode 100644
index 0000000..d4e24d3
--- /dev/null
+++ b/utils/test/com/cloud/utils/net/Ip4AddressTest.java
@@ -0,0 +1,24 @@
+package com.cloud.utils.net;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.testing.EqualsTester;
+
+public class Ip4AddressTest {
+
+    @Test
+    public void testEquals() throws Exception {
+        new EqualsTester()
+                .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:02"), new Ip4Address(1L, 2L))
+                .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:00"), new Ip4Address(1L, 0L), new Ip4Address(1L, 0L), new Ip4Address(1L), new Ip4Address("0.0.0.1"))
+                .testEquals();
+    }
+
+    @Test
+    public void testIsSameAddressAs() {
+        Assert.assertTrue("1 and one should be considdered the same address", new Ip4Address(1L, 5L).isSameAddressAs("0.0.0.1"));
+        Assert.assertFalse("zero and 0L should be considdered the same address but a Long won't be accepted", new Ip4Address("0.0.0.0", "00:00:00:00:00:08").isSameAddressAs(0L));
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d8ab5f3a/utils/test/com/cloud/utils/net/IpTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/IpTest.java b/utils/test/com/cloud/utils/net/IpTest.java
index d11b779..89608f1 100644
--- a/utils/test/com/cloud/utils/net/IpTest.java
+++ b/utils/test/com/cloud/utils/net/IpTest.java
@@ -21,8 +21,11 @@ package com.cloud.utils.net;
 
 import static org.junit.Assert.assertEquals;
 
+import org.junit.Assert;
 import org.junit.Test;
 
+import com.google.common.testing.EqualsTester;
+
 public class IpTest {
 
     @Test
@@ -43,4 +46,18 @@ public class IpTest {
         assertEquals("Minimal address not created", "0.0.0.0", min.addr());
     }
 
+    @Test
+    public void testEquals() {
+        new EqualsTester()
+                .addEqualityGroup(new Ip("0.0.0.1"), new Ip(1L))
+                .addEqualityGroup(new Ip("0.0.0.0"), new Ip(0L))
+                .testEquals();
+    }
+
+    @Test
+    public void testIsSameAddressAs() {
+        Assert.assertTrue("1 and one should be considdered the same address", new Ip(1L).isSameAddressAs("0.0.0.1"));
+        Assert.assertTrue("zero and 0L should be considdered the same address", new Ip("0.0.0.0").isSameAddressAs(0L));
+    }
+
 }


[24/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8607 - Adding shouldUpdateHost flag

   - Make sure doUpdateHostPassword() doesn't get called if flag is set to false
   - Do not update XenServer hosts if the cluster ID is not informed


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/a74971df
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/a74971df
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/a74971df

Branch: refs/heads/reporter
Commit: a74971df06e04ee2df993a9876bb274d58c9662d
Parents: 96ad6f6
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Jul 2 11:12:08 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Thu Jul 2 11:12:08 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/api/ApiConstants.java   |  3 ++-
 .../command/admin/host/UpdateHostPasswordCmd.java |  8 ++++++++
 .../com/cloud/resource/ResourceManagerImpl.java   | 18 ++++++++++++------
 .../com/cloud/server/ManagementServerImpl.java    |  4 ++++
 4 files changed, 26 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a74971df/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index 204f33b..ee98e06 100644
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -180,6 +180,7 @@ public class ApiConstants {
     public static final String PARAMS = "params";
     public static final String PARENT_DOMAIN_ID = "parentdomainid";
     public static final String PASSWORD = "password";
+    public static final String SHOULD_UPDATE_PASSWORD = "password";
     public static final String NEW_PASSWORD = "new_password";
     public static final String PASSWORD_ENABLED = "passwordenabled";
     public static final String SSHKEY_ENABLED = "sshkeyenabled";
@@ -631,4 +632,4 @@ public class ApiConstants {
     public enum VMDetails {
         all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp;
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a74971df/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
index 74b06d7..3915cee 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java
@@ -44,12 +44,16 @@ public class UpdateHostPasswordCmd extends BaseCmd {
     @Parameter(name = ApiConstants.CLUSTER_ID, type = CommandType.UUID, entityType = ClusterResponse.class, description = "the cluster ID")
     private Long clusterId;
 
+    @Parameter(name = ApiConstants.SHOULD_UPDATE_PASSWORD, type = CommandType.BOOLEAN, description = "if the password should also be updated on the hosts")
+    private Boolean shouldUpdateHost;
+
     @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "the username for the host/cluster")
     private String username;
 
     @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "the new password for the host/cluster")
     private String password;
 
+
     // ///////////////////////////////////////////////////
     // ///////////////// Accessors ///////////////////////
     // ///////////////////////////////////////////////////
@@ -62,6 +66,10 @@ public class UpdateHostPasswordCmd extends BaseCmd {
         return clusterId;
     }
 
+    public Boolean getShouldUpdateHost() {
+        return shouldUpdateHost;
+    }
+
     public String getPassword() {
         return password;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a74971df/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java
index df6071c..b6f7f4e 100644
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@ -2240,6 +2240,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
 
     @Override
     public boolean updateClusterPassword(final UpdateHostPasswordCmd command) {
+        final boolean shouldUpdateHostPasswd = command.getShouldUpdateHost();
         // get agents for the cluster
         final List<HostVO> hosts = listAllHostsInCluster(command.getClusterId());
         for (final HostVO host : hosts) {
@@ -2255,9 +2256,12 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
             } catch (final AgentUnavailableException e) {
                 s_logger.error("Agent is not availbale!", e);
             }
-            final boolean isUpdated = doUpdateHostPassword(host.getId());
-            if (!isUpdated) {
-                throw new CloudRuntimeException("CloudStack failed to update the password of the Host with UUID/ID ==> " + host.getUuid() + "/" + host.getId() + ". Please make sure you are still able to connect to your hosts.");
+
+            if (shouldUpdateHostPasswd) {
+                final boolean isUpdated = doUpdateHostPassword(host.getId());
+                if (!isUpdated) {
+                    throw new CloudRuntimeException("CloudStack failed to update the password of the Host with UUID/ID ==> " + host.getUuid() + "/" + host.getId() + ". Please make sure you are still able to connect to your hosts.");
+                }
             }
         }
 
@@ -2265,10 +2269,10 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
     }
 
     @Override
-    public boolean updateHostPassword(final UpdateHostPasswordCmd cmd) {
+    public boolean updateHostPassword(final UpdateHostPasswordCmd command) {
         // update agent attache password
         try {
-            final Boolean result = propagateResourceEvent(cmd.getHostId(), ResourceState.Event.UpdatePassword);
+            final Boolean result = propagateResourceEvent(command.getHostId(), ResourceState.Event.UpdatePassword);
             if (result != null) {
                 return result;
             }
@@ -2276,7 +2280,9 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager,
             s_logger.error("Agent is not availbale!", e);
         }
 
-        return doUpdateHostPassword(cmd.getHostId());
+        final boolean shouldUpdateHostPasswd = command.getShouldUpdateHost();
+        // If shouldUpdateHostPasswd has been set to false, the method doUpdateHostPassword() won't be called.
+        return shouldUpdateHostPasswd && doUpdateHostPassword(command.getHostId());
     }
 
     public String getPeerName(final long agentHostId) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a74971df/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java
index acf301f..781c915 100644
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -3797,6 +3797,10 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         final HostVO host = _hostDao.findById(cmd.getHostId());
 
+        if (host.getHypervisorType() == HypervisorType.XenServer) {
+            throw new InvalidParameterValueException("Single host update is not supported by XenServer hypervisors. Please try again informing the Cluster ID.");
+        }
+
         if (!supportedHypervisors.contains(host.getHypervisorType())) {
             throw new InvalidParameterValueException("This operation is not supported for this hypervisor type");
         }


[09/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8597. Failed to migrate volume from zone-wide to cluster-wide storage. While live migrating a volume, CS chooses the endpoint to perform the migration by selecting any host that has the storage containing the volume mounted on it. Instead, if the volume is attached to a running VM, the endpoint chosen by CS should be the host that contains the VM.

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

This closes #541


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/299c07c3
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/299c07c3
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/299c07c3

Branch: refs/heads/reporter
Commit: 299c07c3e1bcafcba5ca359054c13dc655126f65
Parents: f72412a
Author: Likitha Shetty <li...@citrix.com>
Authored: Wed Apr 8 15:24:36 2015 +0530
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 12:33:26 2015 +0200

----------------------------------------------------------------------
 .../cloudstack/storage/endpoint/DefaultEndPointSelector.java     | 2 +-
 .../src/com/cloud/hypervisor/vmware/resource/VmwareResource.java | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/299c07c3/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java
index 7067b8c..0778e54 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java
@@ -332,7 +332,7 @@ public class DefaultEndPointSelector implements EndPointSelector {
             }
         } else if (action == StorageAction.MIGRATEVOLUME) {
             VolumeInfo volume = (VolumeInfo)object;
-            if (volume.getHypervisorType() == Hypervisor.HypervisorType.Hyperv) {
+            if (volume.getHypervisorType() == Hypervisor.HypervisorType.Hyperv || volume.getHypervisorType() == Hypervisor.HypervisorType.VMware) {
                 VirtualMachine vm = volume.getAttachedVM();
                 if ((vm != null) && (vm.getState() == VirtualMachine.State.Running)) {
                     Long hostId = vm.getHostId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/299c07c3/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 5701ee9..6284f86 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@ -3081,7 +3081,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
                 morDsAtTarget = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(tgtHyperHost, filerTo.getUuid());
                 morDsAtSource = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, filerTo.getUuid());
                 if (morDsAtTarget == null) {
-                    String msg = "Unable to find the mounted datastore with uuid " + morDsAtTarget + " to execute MigrateWithStorageCommand";
+                    String msg = "Unable to find the target datastore: " + filerTo.getUuid() + " on target host: " + tgtHyperHost.getHyperHostName() + " to execute MigrateWithStorageCommand";
                     s_logger.error(msg);
                     throw new Exception(msg);
                 }
@@ -3283,7 +3283,7 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
             vmName = vmMo.getName();
             morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, tgtDsName);
             if (morDs == null) {
-                String msg = "Unable to find the mounted datastore with name " + tgtDsName + " to execute MigrateVolumeCommand";
+                String msg = "Unable to find the mounted datastore with name: " + tgtDsName + " on source host: " + srcHyperHost.getHyperHostName() +" to execute MigrateVolumeCommand";
                 s_logger.error(msg);
                 throw new Exception(msg);
             }


[48/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Forgot to activate teardown

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>

This closes #558


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/820a406d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/820a406d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/820a406d

Branch: refs/heads/reporter
Commit: 820a406d0f4b7bf535f3ee49049ef462961f5575
Parents: b7b54f1
Author: Ian Southam <is...@schubergphilis.com>
Authored: Thu Jul 2 09:19:48 2015 -0400
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 8 11:19:13 2015 +0200

----------------------------------------------------------------------
 test/integration/component/test_vpc_redundant.py | 2 --
 1 file changed, 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/820a406d/test/integration/component/test_vpc_redundant.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_vpc_redundant.py b/test/integration/component/test_vpc_redundant.py
index 66da462..8fe44c2 100644
--- a/test/integration/component/test_vpc_redundant.py
+++ b/test/integration/component/test_vpc_redundant.py
@@ -219,7 +219,6 @@ class TestVPCRedundancy(cloudstackTestCase):
 
     @classmethod
     def tearDownClass(cls):
-        return
         try:
             cleanup_resources(cls.api_client, cls._cleanup)
         except Exception as e:
@@ -258,7 +257,6 @@ class TestVPCRedundancy(cloudstackTestCase):
         return
 
     def tearDown(self):
-        return
         try:
             cleanup_resources(self.apiclient, self.cleanup)
         except Exception as e:


[30/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
BUG-ID:CLOUDSTACK-7472: kvmclock fix for LXC is not required after fixing CLOUDSTACK-8177

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #557


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3a19a891
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3a19a891
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3a19a891

Branch: refs/heads/reporter
Commit: 3a19a8916eb7840302882cddd8465ac56150d32d
Parents: f138192
Author: Kishan Kavala <ki...@apache.org>
Authored: Thu Jul 2 16:52:46 2015 +0530
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Fri Jul 3 15:21:18 2015 +0530

----------------------------------------------------------------------
 .../cloud/hypervisor/kvm/resource/LibvirtComputingResource.java   | 3 ---
 1 file changed, 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3a19a891/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 7bd02d0..82b2792 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -783,9 +783,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         value = (String) params.get("kvmclock.disable");
         if (Boolean.parseBoolean(value)) {
             _noKvmClock = true;
-        } else if(HypervisorType.LXC.equals(_hypervisorType) && value == null){
-            //Disable kvmclock by default for LXC
-            _noKvmClock = true;
         }
 
         LibvirtConnection.initialize(_hypervisorURI);


[44/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
rats: licenses added

Signed-off-by: Daan Hoogland <da...@onecht.net>

This closes #535


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4ad178e4
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4ad178e4
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4ad178e4

Branch: refs/heads/reporter
Commit: 4ad178e4b17c9c0b61a0135d92557b623375f253
Parents: d8ab5f3
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jul 6 17:10:41 2015 +0200
Committer: Daan Hoogland <da...@onecht.net>
Committed: Tue Jul 7 13:48:20 2015 +0200

----------------------------------------------------------------------
 .../org/apache/cloudstack/storage/BaseTypeTest.java | 16 ++++++++++++++++
 .../cloudstack/framework/config/ConfigKeyTest.java  | 16 ++++++++++++++++
 utils/test/com/cloud/utils/net/Ip4AddressTest.java  | 16 ++++++++++++++++
 3 files changed, 48 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4ad178e4/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
----------------------------------------------------------------------
diff --git a/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java b/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
index 5cce015..48759da 100644
--- a/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
+++ b/engine/storage/test/org/apache/cloudstack/storage/BaseTypeTest.java
@@ -1,3 +1,19 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.storage;
 
 import org.junit.Assert;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4ad178e4/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
----------------------------------------------------------------------
diff --git a/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java b/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
index b02ac1f..01a3509 100644
--- a/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
+++ b/framework/config/test/org/apache/cloudstack/framework/config/ConfigKeyTest.java
@@ -1,3 +1,19 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.framework.config;
 
 import org.junit.Assert;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4ad178e4/utils/test/com/cloud/utils/net/Ip4AddressTest.java
----------------------------------------------------------------------
diff --git a/utils/test/com/cloud/utils/net/Ip4AddressTest.java b/utils/test/com/cloud/utils/net/Ip4AddressTest.java
index d4e24d3..79ff238 100644
--- a/utils/test/com/cloud/utils/net/Ip4AddressTest.java
+++ b/utils/test/com/cloud/utils/net/Ip4AddressTest.java
@@ -1,3 +1,19 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.utils.net;
 
 import org.junit.Assert;


[16/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8590 - Refactoring NiciraNVP resource

  - Adding the NiciraNvpWrapper
  - This class will keep track of all Wrappers of the Nicira NVP Plugin

Signed-off-by: wilderrodrigues <wr...@schubergphilis.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/fc478604
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/fc478604
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/fc478604

Branch: refs/heads/reporter
Commit: fc478604e8f51536847ee3cb8e955535dab2013e
Parents: 9463356
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Mon Jun 22 15:57:15 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed Jul 1 15:04:56 2015 +0200

----------------------------------------------------------------------
 .../resource/NiciraNvpRequestWrapper.java       | 76 ++++++++++++++++++++
 1 file changed, 76 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/fc478604/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
new file mode 100644
index 0000000..70eb943
--- /dev/null
+++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/resource/NiciraNvpRequestWrapper.java
@@ -0,0 +1,76 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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 com.cloud.network.resource;
+
+import java.util.Hashtable;
+import java.util.Set;
+
+import org.reflections.Reflections;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.RequestWrapper;
+import com.cloud.resource.ServerResource;
+
+public class NiciraNvpRequestWrapper extends RequestWrapper {
+
+    private static NiciraNvpRequestWrapper instance;
+
+    static {
+        instance = new NiciraNvpRequestWrapper();
+    }
+
+    Reflections baseWrappers = new Reflections("com.cloud.network.resource.wrapper");
+    @SuppressWarnings("rawtypes")
+    Set<Class<? extends CommandWrapper>> baseSet = baseWrappers.getSubTypesOf(CommandWrapper.class);
+
+    private NiciraNvpRequestWrapper() {
+        init();
+    }
+
+    @SuppressWarnings("rawtypes")
+    private void init() {
+        // NiciraNvpResource commands
+        final Hashtable<Class<? extends Command>, CommandWrapper> libvirtCommands = processAnnotations(baseSet);
+
+        resources.put(NiciraNvpResource.class, libvirtCommands);
+    }
+
+    public static NiciraNvpRequestWrapper getInstance() {
+        return instance;
+    }
+
+    @SuppressWarnings({"rawtypes" })
+    @Override
+    public Answer execute(final Command command, final ServerResource serverResource) {
+        final Class<? extends ServerResource> resourceClass = serverResource.getClass();
+
+        final Hashtable<Class<? extends Command>, CommandWrapper> resourceCommands = retrieveResource(command, resourceClass);
+
+        CommandWrapper<Command, Answer, ServerResource> commandWrapper = retrieveCommands(command.getClass(), resourceCommands);
+
+        while (commandWrapper == null) {
+            //Could not find the command in the given resource, will traverse the family tree.
+            commandWrapper = retryWhenAllFails(command, resourceClass, resourceCommands);
+        }
+
+        return commandWrapper.execute(command, serverResource);
+    }
+}
\ No newline at end of file


[27/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
BUG-ID: CLOUDSTACK-8484 - Hosts without tag are not listed while
listing the hosts for migration for instance with tag

While preparing the suitable hosts we are accidentally removing the
incompatible (host does not have host tag) hosts from otherhost list(
incorrect use of List.retainAll).


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b5936575
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b5936575
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b5936575

Branch: refs/heads/reporter
Commit: b593657503c4743c6e74c76c083df744ed0bb2ae
Parents: f8e1ff1
Author: Sudhansu <su...@citrix.com>
Authored: Thu Mar 12 17:58:31 2015 +0530
Committer: Sudhansu <su...@citrix.com>
Committed: Fri Jul 3 11:41:55 2015 +0530

----------------------------------------------------------------------
 .../manager/allocator/impl/RandomAllocator.java | 13 ++++-----
 .../allocator/impl/FirstFitAllocator.java       | 28 +++++++++++++++-----
 2 files changed, 29 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5936575/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
----------------------------------------------------------------------
diff --git a/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java b/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
index 5bdf4f1..390a8af 100755
--- a/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
+++ b/plugins/host-allocators/random/src/com/cloud/agent/manager/allocator/impl/RandomAllocator.java
@@ -61,6 +61,7 @@ public class RandomAllocator extends AdapterBase implements HostAllocator {
         Long clusterId = plan.getClusterId();
         ServiceOffering offering = vmProfile.getServiceOffering();
         List<Host> suitableHosts = new ArrayList<Host>();
+        List<Host> hostsCopy = new ArrayList<Host>(hosts);
 
         if (type == Host.Type.Storage) {
             return suitableHosts;
@@ -75,18 +76,18 @@ public class RandomAllocator extends AdapterBase implements HostAllocator {
 
         // list all computing hosts, regardless of whether they support routing...it's random after all
         if (hostTag != null) {
-            hosts.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag));
+            hostsCopy.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag));
         } else {
-            hosts.retainAll(_resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId));
+            hostsCopy.retainAll(_resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId));
         }
 
-        s_logger.debug("Random Allocator found " + hosts.size() + "  hosts");
-        if (hosts.size() == 0) {
+        s_logger.debug("Random Allocator found " + hostsCopy.size() + "  hosts");
+        if (hostsCopy.size() == 0) {
             return suitableHosts;
         }
 
-        Collections.shuffle(hosts);
-        for (Host host : hosts) {
+        Collections.shuffle(hostsCopy);
+        for (Host host : hostsCopy) {
             if (suitableHosts.size() == returnUpTo) {
                 break;
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b5936575/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
index a746eb7..990b77b 100755
--- a/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
+++ b/server/src/com/cloud/agent/manager/allocator/impl/FirstFitAllocator.java
@@ -192,6 +192,7 @@ public class FirstFitAllocator extends AdapterBase implements HostAllocator {
         VMTemplateVO template = (VMTemplateVO)vmProfile.getTemplate();
         Account account = vmProfile.getOwner();
         List<Host> suitableHosts = new ArrayList<Host>();
+        List<Host> hostsCopy = new ArrayList<Host>(hosts);
 
         if (type == Host.Type.Storage) {
             // FirstFitAllocator should be used for user VMs only since it won't care whether the host is capable of
@@ -206,23 +207,38 @@ public class FirstFitAllocator extends AdapterBase implements HostAllocator {
 
         String haVmTag = (String)vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
         if (haVmTag != null) {
-            hosts.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, haVmTag));
+            hostsCopy.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, haVmTag));
         } else {
             if (hostTagOnOffering == null && hostTagOnTemplate == null) {
-                hosts.retainAll(_resourceMgr.listAllUpAndEnabledNonHAHosts(type, clusterId, podId, dcId));
+                hostsCopy.retainAll(_resourceMgr.listAllUpAndEnabledNonHAHosts(type, clusterId, podId, dcId));
             } else {
                 if (hasSvcOfferingTag) {
-                    hosts.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTagOnOffering));
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Looking for hosts having tag specified on SvcOffering:" + hostTagOnOffering);
+                    }
+                    hostsCopy.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTagOnOffering));
+
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Hosts with tag '" + hostTagOnOffering + "' are:" + hostsCopy);
+                    }
                 }
 
                 if (hasTemplateTag) {
-                    hosts.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTagOnTemplate));
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Looking for hosts having tag specified on Template:" + hostTagOnTemplate);
+                    }
+
+                    hostsCopy.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTagOnTemplate));
+
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Hosts with tag '" + hostTagOnTemplate + "' are:" + hostsCopy);
+                    }
                 }
             }
         }
 
-        if (!hosts.isEmpty()) {
-            suitableHosts = allocateTo(plan, offering, template, avoid, hosts, returnUpTo, considerReservedCapacity, account);
+        if (!hostsCopy.isEmpty()) {
+            suitableHosts = allocateTo(plan, offering, template, avoid, hostsCopy, returnUpTo, considerReservedCapacity, account);
         }
 
         return suitableHosts;


[39/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
findbugs: added test for getServiceProvider of CreateVpcOffering api

Signed-off-by: Daan Hoogland <da...@gmail.com>

This closes #538


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/a71c9852
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/a71c9852
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/a71c9852

Branch: refs/heads/reporter
Commit: a71c9852238b01c0728fd2e1cc854dc8d48c0907
Parents: e34389a
Author: Daan Hoogland <da...@gmail.com>
Authored: Mon Jul 6 12:07:42 2015 +0200
Committer: Daan Hoogland <da...@gmail.com>
Committed: Mon Jul 6 16:22:19 2015 +0200

----------------------------------------------------------------------
 .../apache/cloudstack/api/ApiCmdTestUtil.java   | 17 +++++++
 .../CreateSecondaryStagingStoreCmdTest.java     | 25 +++-------
 .../admin/vpc/CreateVPCOfferingCmdTest.java     | 48 ++++++++++++++++++++
 3 files changed, 71 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a71c9852/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java b/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
new file mode 100644
index 0000000..ca4510d
--- /dev/null
+++ b/api/test/org/apache/cloudstack/api/ApiCmdTestUtil.java
@@ -0,0 +1,17 @@
+package org.apache.cloudstack.api;
+
+import java.lang.reflect.Field;
+
+public class ApiCmdTestUtil {
+    public static void set(BaseCmd cmd, String fieldName, Object value)
+            throws IllegalArgumentException, IllegalAccessException {
+        for (Field field : cmd.getClass().getDeclaredFields()) {
+            Parameter parameter = field.getAnnotation(Parameter.class);
+            if (parameter != null && fieldName.equals(parameter.name())) {
+                field.setAccessible(true);
+                field.set(cmd, value);
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a71c9852/api/test/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmdTest.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmdTest.java b/api/test/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmdTest.java
index 901e976..e935842 100644
--- a/api/test/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmdTest.java
+++ b/api/test/org/apache/cloudstack/api/command/admin/storage/CreateSecondaryStagingStoreCmdTest.java
@@ -16,28 +16,15 @@
 // under the License.
 package org.apache.cloudstack.api.command.admin.storage;
 
-import java.lang.reflect.Field;
 import java.util.HashMap;
 import java.util.Map;
 
-import junit.framework.Assert;
-
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.Parameter;
+import org.junit.Assert;
 import org.junit.Test;
 
-public class CreateSecondaryStagingStoreCmdTest {
+import org.apache.cloudstack.api.ApiCmdTestUtil;
 
-    static void set(BaseCmd cmd, String fieldName, Object value)
-            throws IllegalArgumentException, IllegalAccessException {
-        for (Field field : cmd.getClass().getDeclaredFields()) {
-            Parameter parameter = field.getAnnotation(Parameter.class);
-            if (parameter != null && fieldName.equals(parameter.name())) {
-                field.setAccessible(true);
-                field.set(cmd, value);
-            }
-        }
-    }
+public class CreateSecondaryStagingStoreCmdTest {
 
     @Test
     public void getDetails() throws IllegalArgumentException,
@@ -48,7 +35,7 @@ public class CreateSecondaryStagingStoreCmdTest {
         kv.put("key", "TEST-KEY");
         kv.put("value", "TEST-VALUE");
         details.put("does not matter", kv);
-        set(cmd, "details", details);
+        ApiCmdTestUtil.set(cmd, "details", details);
         Map<String, String> detailsMap = cmd.getDetails();
         Assert.assertNotNull(detailsMap);
         Assert.assertEquals(1, detailsMap.size());
@@ -60,7 +47,7 @@ public class CreateSecondaryStagingStoreCmdTest {
     public void getDetailsEmpty() throws IllegalArgumentException,
             IllegalAccessException {
         CreateSecondaryStagingStoreCmd cmd = new CreateSecondaryStagingStoreCmd();
-        set(cmd, "details", new HashMap<String, Map<String, String>>());
+        ApiCmdTestUtil.set(cmd, "details", new HashMap<String, Map<String, String>>());
         Assert.assertNull(cmd.getDetails());
     }
 
@@ -68,7 +55,7 @@ public class CreateSecondaryStagingStoreCmdTest {
     public void getDetailsNull() throws IllegalArgumentException,
             IllegalAccessException {
         CreateSecondaryStagingStoreCmd cmd = new CreateSecondaryStagingStoreCmd();
-        set(cmd, "details", null);
+        ApiCmdTestUtil.set(cmd, "details", null);
         Assert.assertNull(cmd.getDetails());
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a71c9852/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java b/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
new file mode 100644
index 0000000..99433ed
--- /dev/null
+++ b/api/test/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmdTest.java
@@ -0,0 +1,48 @@
+package org.apache.cloudstack.api.command.admin.vpc;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.cloudstack.api.ApiCmdTestUtil;
+import org.apache.cloudstack.api.ApiConstants;
+
+public class CreateVPCOfferingCmdTest {
+
+    @Test
+    public void testServiceProviders() throws IllegalArgumentException,
+            IllegalAccessException {
+        CreateVPCOfferingCmd cmd = new CreateVPCOfferingCmd();
+        HashMap<String, Map<String, String>> providers = new HashMap<String, Map<String, String>>();
+        HashMap<String, String> kv = new HashMap<String, String>();
+        kv.put("service", "TEST-SERVICE");
+        kv.put("provider", "TEST-PROVIDER");
+        providers.put("does not matter", kv);
+        ApiCmdTestUtil.set(cmd, ApiConstants.SERVICE_PROVIDER_LIST, providers);
+        Map<String, List<String>> providerMap = cmd.getServiceProviders();
+        Assert.assertNotNull(providerMap);
+        Assert.assertEquals(1, providerMap.size());
+        Assert.assertTrue(providerMap.containsKey("TEST-SERVICE"));
+        Assert.assertTrue(providerMap.get("TEST-SERVICE").contains("TEST-PROVIDER"));
+    }
+
+    @Test
+    public void testServiceProvidersEmpty() throws IllegalArgumentException,
+            IllegalAccessException {
+        CreateVPCOfferingCmd cmd = new CreateVPCOfferingCmd();
+        ApiCmdTestUtil.set(cmd, ApiConstants.SERVICE_PROVIDER_LIST, new HashMap<String, Map<String, String>>());
+        Assert.assertNull(cmd.getServiceProviders());
+    }
+
+    @Test
+    public void getDetailsNull() throws IllegalArgumentException,
+            IllegalAccessException {
+        CreateVPCOfferingCmd cmd = new CreateVPCOfferingCmd();
+        ApiCmdTestUtil.set(cmd, ApiConstants.SERVICE_PROVIDER_LIST, null);
+        Assert.assertNull(cmd.getServiceProviders());
+    }
+
+}


[02/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmdTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmdTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmdTest.java
deleted file mode 100644
index e53e701..0000000
--- a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/GetServiceProviderMetaDataCmdTest.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF 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.apache.cloudstack.api.command;
-
-import com.cloud.utils.HttpUtils;
-import org.apache.cloudstack.api.ApiServerService;
-import org.apache.cloudstack.api.auth.APIAuthenticationType;
-import org.apache.cloudstack.saml.SAML2AuthManager;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-import java.lang.reflect.Field;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.SignatureException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-@RunWith(MockitoJUnitRunner.class)
-public class GetServiceProviderMetaDataCmdTest {
-
-    @Mock
-    ApiServerService apiServer;
-
-    @Mock
-    SAML2AuthManager samlAuthManager;
-
-    @Mock
-    HttpSession session;
-
-    @Mock
-    HttpServletResponse resp;
-
-    @Mock
-    HttpServletRequest req;
-
-    @Test
-    public void testAuthenticate() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, CertificateParsingException, CertificateEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException, UnknownHostException {
-        GetServiceProviderMetaDataCmd cmd = new GetServiceProviderMetaDataCmd();
-
-        Field apiServerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_apiServer");
-        apiServerField.setAccessible(true);
-        apiServerField.set(cmd, apiServer);
-
-        Field managerField = GetServiceProviderMetaDataCmd.class.getDeclaredField("_samlAuthManager");
-        managerField.setAccessible(true);
-        managerField.set(cmd, samlAuthManager);
-
-        String spId = "someSPID";
-        String url = "someUrl";
-        X509Certificate cert = SAMLUtils.generateRandomX509Certificate(SAMLUtils.generateRandomKeyPair());
-        Mockito.when(samlAuthManager.getServiceProviderId()).thenReturn(spId);
-        Mockito.when(samlAuthManager.getIdpSigningKey()).thenReturn(cert);
-        Mockito.when(samlAuthManager.getIdpSingleLogOutUrl()).thenReturn(url);
-        Mockito.when(samlAuthManager.getSpSingleLogOutUrl()).thenReturn(url);
-
-        String result = cmd.authenticate("command", null, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
-        Assert.assertTrue(result.contains("md:EntityDescriptor"));
-
-        Mockito.verify(samlAuthManager, Mockito.atLeast(1)).getServiceProviderId();
-        Mockito.verify(samlAuthManager, Mockito.atLeast(1)).getSpSingleSignOnUrl();
-        Mockito.verify(samlAuthManager, Mockito.atLeast(1)).getSpSingleLogOutUrl();
-        Mockito.verify(samlAuthManager, Mockito.never()).getIdpSingleSignOnUrl();
-        Mockito.verify(samlAuthManager, Mockito.never()).getIdpSingleLogOutUrl();
-    }
-
-    @Test
-    public void testGetAPIType() {
-        Assert.assertTrue(new GetServiceProviderMetaDataCmd().getAPIType() == APIAuthenticationType.LOGIN_API);
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java
index 8fbed41..6960b3b 100644
--- a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java
@@ -29,9 +29,10 @@ import org.apache.cloudstack.api.ApiServerService;
 import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.auth.APIAuthenticationType;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.saml.SAML2AuthManager;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
+import org.apache.cloudstack.saml.SAMLPluginConstants;
+import org.apache.cloudstack.saml.SAMLProviderMetadata;
+import org.apache.cloudstack.saml.SAMLUtils;
 import org.joda.time.DateTime;
 import org.junit.Assert;
 import org.junit.Test;
@@ -43,6 +44,7 @@ import org.opensaml.common.SAMLVersion;
 import org.opensaml.saml2.core.Assertion;
 import org.opensaml.saml2.core.AttributeStatement;
 import org.opensaml.saml2.core.AuthnStatement;
+import org.opensaml.saml2.core.Issuer;
 import org.opensaml.saml2.core.NameID;
 import org.opensaml.saml2.core.NameIDType;
 import org.opensaml.saml2.core.Response;
@@ -52,6 +54,7 @@ import org.opensaml.saml2.core.Subject;
 import org.opensaml.saml2.core.impl.AssertionBuilder;
 import org.opensaml.saml2.core.impl.AttributeStatementBuilder;
 import org.opensaml.saml2.core.impl.AuthnStatementBuilder;
+import org.opensaml.saml2.core.impl.IssuerBuilder;
 import org.opensaml.saml2.core.impl.NameIDBuilder;
 import org.opensaml.saml2.core.impl.ResponseBuilder;
 import org.opensaml.saml2.core.impl.StatusBuilder;
@@ -62,6 +65,7 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.lang.reflect.Field;
+import java.security.KeyPair;
 import java.security.cert.X509Certificate;
 import java.util.HashMap;
 import java.util.Map;
@@ -77,9 +81,6 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
     SAML2AuthManager samlAuthManager;
 
     @Mock
-    ConfigurationDao configDao;
-
-    @Mock
     DomainManager domainMgr;
 
     @Mock
@@ -105,6 +106,9 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
         samlMessage.setID("foo");
         samlMessage.setVersion(SAMLVersion.VERSION_20);
         samlMessage.setIssueInstant(new DateTime(0));
+        Issuer issuer = new IssuerBuilder().buildObject();
+        issuer.setValue("MockedIssuer");
+        samlMessage.setIssuer(issuer);
         Status status = new StatusBuilder().buildObject();
         StatusCode statusCode = new StatusCodeBuilder().buildObject();
         statusCode.setValue(StatusCode.SUCCESS_URI);
@@ -146,32 +150,33 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
         domainMgrField.setAccessible(true);
         domainMgrField.set(cmd, domainMgr);
 
-        Field configDaoField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_configDao");
-        configDaoField.setAccessible(true);
-        configDaoField.set(cmd, configDao);
-
         Field userAccountDaoField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("_userAccountDao");
         userAccountDaoField.setAccessible(true);
         userAccountDaoField.set(cmd, userAccountDao);
 
         String spId = "someSPID";
         String url = "someUrl";
-        X509Certificate cert = SAMLUtils.generateRandomX509Certificate(SAMLUtils.generateRandomKeyPair());
-        Mockito.when(samlAuthManager.getServiceProviderId()).thenReturn(spId);
-        Mockito.when(samlAuthManager.getIdpSigningKey()).thenReturn(null);
-        Mockito.when(samlAuthManager.getIdpSingleSignOnUrl()).thenReturn(url);
-        Mockito.when(samlAuthManager.getSpSingleSignOnUrl()).thenReturn(url);
+        KeyPair kp = SAMLUtils.generateRandomKeyPair();
+        X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp);
+
+        SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata();
+        providerMetadata.setEntityId("random");
+        providerMetadata.setSigningCertificate(cert);
+        providerMetadata.setEncryptionCertificate(cert);
+        providerMetadata.setKeyPair(kp);
+        providerMetadata.setSsoUrl("http://test.local");
+        providerMetadata.setSloUrl("http://test.local");
 
         Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(null);
-        Mockito.when(configDao.getValue(Mockito.anyString())).thenReturn("someString");
 
         Mockito.when(domain.getId()).thenReturn(1L);
         Mockito.when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain);
         UserAccountVO user = new UserAccountVO();
-        user.setUsername(SAMLUtils.createSAMLId("someUID"));
         user.setId(1000L);
         Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(user);
         Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(false);
+        Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
+        Mockito.when(samlAuthManager.getIdPMetadata(Mockito.anyString())).thenReturn(providerMetadata);
 
         Map<String, Object[]> params = new HashMap<String, Object[]>();
 
@@ -180,16 +185,14 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
         Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());
 
         // SSO SAMLResponse verification test, this should throw ServerApiException for auth failure
-        params.put(SAMLUtils.SAML_RESPONSE, new String[]{"Some String"});
+        params.put(SAMLPluginConstants.SAML_RESPONSE, new String[]{"Some String"});
         Mockito.stub(cmd.processSAMLResponse(Mockito.anyString())).toReturn(buildMockResponse());
         try {
             cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
         } catch (ServerApiException ignored) {
         }
-        Mockito.verify(configDao, Mockito.atLeastOnce()).getValue(Mockito.anyString());
-        Mockito.verify(domainMgr, Mockito.times(1)).getDomain(Mockito.anyString());
-        Mockito.verify(userAccountDao, Mockito.times(1)).getUserAccount(Mockito.anyString(), Mockito.anyLong());
-        Mockito.verify(apiServer, Mockito.times(1)).verifyUser(Mockito.anyLong());
+        Mockito.verify(userAccountDao, Mockito.times(0)).getUserAccount(Mockito.anyString(), Mockito.anyLong());
+        Mockito.verify(apiServer, Mockito.times(0)).verifyUser(Mockito.anyLong());
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java
----------------------------------------------------------------------
diff --git a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java
index 4388b88..cbfcc55 100644
--- a/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java
+++ b/plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LogoutAPIAuthenticatorCmdTest.java
@@ -22,9 +22,8 @@ package org.apache.cloudstack.api.command;
 import com.cloud.utils.HttpUtils;
 import org.apache.cloudstack.api.ApiServerService;
 import org.apache.cloudstack.api.auth.APIAuthenticationType;
-import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.saml.SAML2AuthManager;
-import org.apache.cloudstack.utils.auth.SAMLUtils;
+import org.apache.cloudstack.saml.SAMLUtils;
 import org.junit.Assert;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -49,9 +48,6 @@ public class SAML2LogoutAPIAuthenticatorCmdTest {
     SAML2AuthManager samlAuthManager;
 
     @Mock
-    ConfigurationDao configDao;
-
-    @Mock
     HttpSession session;
 
     @Mock
@@ -72,19 +68,10 @@ public class SAML2LogoutAPIAuthenticatorCmdTest {
         managerField.setAccessible(true);
         managerField.set(cmd, samlAuthManager);
 
-        Field configDaoField = SAML2LogoutAPIAuthenticatorCmd.class.getDeclaredField("_configDao");
-        configDaoField.setAccessible(true);
-        configDaoField.set(cmd, configDao);
-
         String spId = "someSPID";
         String url = "someUrl";
         X509Certificate cert = SAMLUtils.generateRandomX509Certificate(SAMLUtils.generateRandomKeyPair());
-        Mockito.when(samlAuthManager.getServiceProviderId()).thenReturn(spId);
-        Mockito.when(samlAuthManager.getIdpSigningKey()).thenReturn(cert);
-        Mockito.when(samlAuthManager.getIdpSingleLogOutUrl()).thenReturn(url);
-        Mockito.when(samlAuthManager.getSpSingleLogOutUrl()).thenReturn(url);
         Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(null);
-        Mockito.when(configDao.getValue(Mockito.anyString())).thenReturn("someString");
 
         cmd.authenticate("command", null, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
         Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java
index cf719c0..4da8b1e 100644
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@ -1062,8 +1062,8 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
             final SecureRandom sesssionKeyRandom = new SecureRandom();
             final byte sessionKeyBytes[] = new byte[20];
             sesssionKeyRandom.nextBytes(sessionKeyBytes);
-            final String sessionKey = Base64.encodeBase64String(sessionKeyBytes);
-            session.setAttribute("sessionkey", sessionKey);
+            final String sessionKey = Base64.encodeBase64URLSafeString(sessionKeyBytes);
+            session.setAttribute(ApiConstants.SESSIONKEY, sessionKey);
 
             return createLoginResponse(session);
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/server/src/com/cloud/api/ApiServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java
index 3b3a0be..2a2844e 100644
--- a/server/src/com/cloud/api/ApiServlet.java
+++ b/server/src/com/cloud/api/ApiServlet.java
@@ -238,7 +238,7 @@ public class ApiServlet extends HttpServlet {
                 userId = (Long)session.getAttribute("userid");
                 final String account = (String)session.getAttribute("account");
                 final Object accountObj = session.getAttribute("accountobj");
-                final String sessionKey = (String)session.getAttribute("sessionkey");
+                final String sessionKey = (String)session.getAttribute(ApiConstants.SESSIONKEY);
                 final String[] sessionKeyParam = (String[])params.get(ApiConstants.SESSIONKEY);
                 if ((sessionKeyParam == null) || (sessionKey == null) || !sessionKey.equals(sessionKeyParam[0])) {
                     try {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index 2352313..ca89881 100644
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -1385,78 +1385,6 @@ public enum Config {
             "300000",
             "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.",
             null),
-    SAMLIsPluginEnabled(
-            "Advanced",
-            ManagementServer.class,
-            Boolean.class,
-            "saml2.enabled",
-            "false",
-            "Set it to true to enable SAML SSO plugin",
-            null),
-    SAMLUserDomain(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.default.domainid",
-            "1",
-            "The default domain UUID to use when creating users from SAML SSO",
-            null),
-    SAMLCloudStackRedirectionUrl(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.redirect.url",
-            "http://localhost:8080/client",
-            "The CloudStack UI url the SSO should redirected to when successful",
-            null),
-    SAMLServiceProviderID(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.sp.id",
-            "org.apache.cloudstack",
-            "SAML2 Service Provider Identifier String",
-            null),
-    SAMLServiceProviderSingleSignOnURL(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.sp.sso.url",
-            "http://localhost:8080/client/api?command=samlSso",
-            "SAML2 CloudStack Service Provider Single Sign On URL",
-            null),
-    SAMLServiceProviderSingleLogOutURL(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.sp.slo.url",
-            "http://localhost:8080/client/api?command=samlSlo",
-            "SAML2 CloudStack Service Provider Single Log Out URL",
-            null),
-    SAMLIdentityProviderID(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.idp.id",
-            "https://openidp.feide.no",
-            "SAML2 Identity Provider Identifier String",
-            null),
-    SAMLIdentityProviderMetadataURL(
-            "Advanced",
-            ManagementServer.class,
-            String.class,
-            "saml2.idp.metadata.url",
-            "https://openidp.feide.no/simplesaml/saml2/idp/metadata.php",
-            "SAML2 Identity Provider Metadata XML Url",
-            null),
-    SAMLTimeout(
-            "Advanced",
-            ManagementServer.class,
-            Long.class,
-            "saml2.timeout",
-            "30000",
-            "SAML2 IDP Metadata Downloading and parsing etc. activity timeout in milliseconds",
-            null),
     //NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"),
     RouterRamSize("Hidden", NetworkOrchestrationService.class, Integer.class, "router.ram.size", "256", "Default RAM for router VM (in MB).", null),
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/setup/db/db/schema-451to452-cleanup.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-451to452-cleanup.sql b/setup/db/db/schema-451to452-cleanup.sql
new file mode 100644
index 0000000..9f5e62a
--- /dev/null
+++ b/setup/db/db/schema-451to452-cleanup.sql
@@ -0,0 +1,20 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF 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.
+
+--;
+-- Schema cleanup from 4.5.1 to 4.5.2;
+--;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/setup/db/db/schema-451to452.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-451to452.sql b/setup/db/db/schema-451to452.sql
new file mode 100644
index 0000000..5c89008
--- /dev/null
+++ b/setup/db/db/schema-451to452.sql
@@ -0,0 +1,35 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF 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.
+
+--;
+-- Schema upgrade from 4.5.1 to 4.5.2;
+--;
+
+DELETE FROM `cloud`.`configuration` WHERE name like 'saml%';
+
+ALTER TABLE `cloud`.`user` ADD COLUMN `external_entity` text DEFAULT NULL COMMENT "reference to external federation entity";
+
+DROP TABLE IF EXISTS `cloud`.`saml_token`;
+CREATE TABLE `cloud`.`saml_token` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
+  `uuid` varchar(255) UNIQUE NOT NULL COMMENT 'The Authn Unique Id',
+  `domain_id` bigint unsigned DEFAULT NULL,
+  `entity` text NOT NULL COMMENT 'Identity Provider Entity Id',
+  `created` DATETIME NOT NULL,
+  PRIMARY KEY (`id`),
+  CONSTRAINT `fk_saml_token__domain_id` FOREIGN KEY(`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/tools/apidoc/gen_toc.py
----------------------------------------------------------------------
diff --git a/tools/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py
index e53d69d..cb26e2b 100644
--- a/tools/apidoc/gen_toc.py
+++ b/tools/apidoc/gen_toc.py
@@ -115,6 +115,9 @@ known_categories = {
     'logout': 'Authentication',
     'saml': 'Authentication',
     'getSPMetadata': 'Authentication',
+    'listIdps': 'Authentication',
+    'authorizeSamlSso': 'Authentication',
+    'listSamlAuthorization': 'Authentication',
     'Capacity': 'System Capacity',
     'NetworkDevice': 'Network Device',
     'ExternalLoadBalancer': 'Ext Load Balancer',

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/css/cloudstack3.css
----------------------------------------------------------------------
diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css
index a4e2a2a..2bcd5e5 100644
--- a/ui/css/cloudstack3.css
+++ b/ui/css/cloudstack3.css
@@ -369,7 +369,7 @@ body.login {
 .login .select-language select {
   width: 260px;
   border: 1px solid #808080;
-  margin-top: 30px;
+  margin-top: 20px;
   /*+border-radius:4px;*/
   -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
@@ -460,14 +460,12 @@ body.login {
   background: transparent url(../images/sprites.png) -563px -747px;
   cursor: pointer;
   border: none;
-  margin: 7px 120px 0 -1px;
   text-align: center;
   width: 60px;
   height: 15px;
   display: block;
   color: #FFFFFF;
   font-weight: bold;
-  float: left;
   text-indent: -1px;
   /*+text-shadow:0px 1px 2px #000000;*/
   -moz-text-shadow: 0px 1px 2px #000000;
@@ -12749,6 +12747,14 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it
   background-position: -196px -704px;
 }
 
+.configureSamlAuthorization .icon {
+  background-position: -165px -122px;
+}
+
+.configureSamlAuthorization:hover .icon {
+  background-position: -165px -704px;
+}
+
 .viewConsole .icon {
   background-position: -231px -2px;
 }
@@ -12972,13 +12978,6 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it
   border-radius: 4px;
   border-radius: 4px 4px 4px 4px;
   border: 1px solid #AFAFAF;
-  -moz-box-shadow: inset 0px 1px #727272;
-  -webkit-box-shadow: inset 0px 1px #727272;
-  -o-box-shadow: inset 0px 1px #727272;
-  box-shadow: inset 0px 1px #727272;
-  -moz-box-shadow: inset 0px 1px 0px #727272;
-  -webkit-box-shadow: inset 0px 1px 0px #727272;
-  -o-box-shadow: inset 0px 1px 0px #727272;
 }
 
 .manual-account-details > *:nth-child(even) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/dictionary.jsp
----------------------------------------------------------------------
diff --git a/ui/dictionary.jsp b/ui/dictionary.jsp
index 63d22bd..7d17267 100644
--- a/ui/dictionary.jsp
+++ b/ui/dictionary.jsp
@@ -143,6 +143,7 @@ dictionary = {
 'label.action.cancel.maintenance.mode': '<fmt:message key="label.action.cancel.maintenance.mode" />',
 'label.action.cancel.maintenance.mode.processing': '<fmt:message key="label.action.cancel.maintenance.mode.processing" />',
 'label.action.change.password': '<fmt:message key="label.action.change.password" />',
+'label.action.configure.samlauthorization': '<fmt:message key="label.action.configure.samlauthorization" />',
 'label.action.change.service': '<fmt:message key="label.action.change.service" />',
 'label.action.change.service.processing': '<fmt:message key="label.action.change.service.processing" />',
 'label.action.copy.ISO': '<fmt:message key="label.action.copy.ISO" />',
@@ -764,7 +765,9 @@ dictionary = {
 'label.local.storage': '<fmt:message key="label.local.storage" />',
 'label.login': '<fmt:message key="label.login" />',
 'label.logout': '<fmt:message key="label.logout" />',
-'label.saml.login': '<fmt:message key="label.saml.login" />',
+'label.saml.enable': '<fmt:message key="label.saml.enable" />',
+'label.saml.entity': '<fmt:message key="label.saml.entity" />',
+'label.add.LDAP.account': '<fmt:message key="label.add.LDAP.account" />',
 'label.lun': '<fmt:message key="label.lun" />',
 'label.LUN.number': '<fmt:message key="label.LUN.number" />',
 'label.make.project.owner': '<fmt:message key="label.make.project.owner" />',

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/index.jsp
----------------------------------------------------------------------
diff --git a/ui/index.jsp b/ui/index.jsp
index 19c2dbf..e062799 100644
--- a/ui/index.jsp
+++ b/ui/index.jsp
@@ -51,28 +51,45 @@
                 <form>
                     <div class="logo"></div>
                     <div class="fields">
-                        <!-- User name -->
-                        <div class="field username">
-                            <label for="username"><fmt:message key="label.username"/></label>
-                            <input type="text" name="username" class="required" />
+                        <div id="login-dropdown">
+                            <select id="login-options" style="width: 260px">
+                                <option value="cloudstack-login">Local <fmt:message key="label.login"/></option>
+                            </select>
                         </div>
-                        <!-- Password -->
-                        <div class="field password">
-                            <label for="password"><fmt:message key="label.password"/></label>
-                            <input type="password" name="password" class="required" autocomplete="off" />
+
+                        <div id="cloudstack-login">
+                            <!-- User name -->
+                            <div class="field username">
+                                <label for="username"><fmt:message key="label.username"/></label>
+                                <input type="text" name="username" class="required" />
+                            </div>
+                            <!-- Password -->
+                            <div class="field password">
+                                <label for="password"><fmt:message key="label.password"/></label>
+                                <input type="password" name="password" class="required" autocomplete="off" />
+                            </div>
+                            <!-- Domain -->
+                            <div class="field domain">
+                                <label for="domain"><fmt:message key="label.domain"/></label>
+                                <input type="text" name="domain" />
+                            </div>
                         </div>
-                        <!-- Domain -->
-                        <div class="field domain">
-                            <label for="domain"><fmt:message key="label.domain"/></label>
-                            <input type="text" name="domain" />
+
+                        <div id="saml-login">
+                            <div class="field domain">
+                                <label for="saml-domain"><fmt:message key="label.domain"/></label>
+                                <input id="saml-domain" type="text" name="saml-domain" />
+                            </div>
+                        </div>
+
+                        <div id="login-submit">
+                            <!-- Submit (login) -->
+                            <input id="login-submit" type="submit" value="<fmt:message key="label.login"/>" />
                         </div>
-                        <!-- Submit (login) -->
-                        <input type="submit" value="<fmt:message key="label.login"/>" />
-                        <div id="saml-login"><input type="samlsubmit" value="<fmt:message key="label.saml.login"/>"/></div>
                         <!-- Select language -->
                         <div class="select-language">
                             <select name="language">
-                                <option value=""></option> <!-- when this blank option is selected, browser's default language will be used -->
+                                <option value=""></option> <!-- when this blank option is selected, default language of the browser will be used -->
                                 <option value="en"><fmt:message key="label.lang.english"/></option>
                                 <option value="ja_JP"><fmt:message key="label.lang.japanese"/></option>
                                 <option value="zh_CN"><fmt:message key="label.lang.chinese"/></option>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/accounts.js
----------------------------------------------------------------------
diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js
index 9e47d11..b63d184 100644
--- a/ui/scripts/accounts.js
+++ b/ui/scripts/accounts.js
@@ -1223,6 +1223,102 @@
                                 }
                             },
 
+                            configureSamlAuthorization: {
+                                label: 'label.action.configure.samlauthorization',
+                                messages: {
+                                    notification: function(args) {
+                                        return 'label.action.configure.samlauthorization';
+                                    }
+                                },
+                                action: {
+                                    custom: function(args) {
+                                        var start = args.start;
+                                        var complete = args.complete;
+                                        var context = args.context;
+
+                                        if (g_idpList) {
+                                            $.ajax({
+                                                url: createURL('listSamlAuthorization'),
+                                                data: {
+                                                    userid: context.users[0].id,
+                                                },
+                                                success: function(json) {
+                                                    var authorization = json.listsamlauthorizationsresponse.samlauthorization[0];
+                                                    cloudStack.dialog.createForm({
+                                                        form: {
+                                                            title: 'label.action.configure.samlauthorization',
+                                                            fields: {
+                                                                samlEnable: {
+                                                                    label: 'label.saml.enable',
+                                                                    docID: 'helpSamlEnable',
+                                                                    isBoolean: true,
+                                                                    isChecked: authorization.status,
+                                                                    validation: {
+                                                                        required: false
+                                                                    }
+                                                                },
+                                                                samlEntity: {
+                                                                    label: 'label.saml.entity',
+                                                                    docID: 'helpSamlEntity',
+                                                                    validation: {
+                                                                        required: false
+                                                                    },
+                                                                    select: function(args) {
+                                                                        var items = [];
+                                                                        $(g_idpList).each(function() {
+                                                                            items.push({
+                                                                                id: this.id,
+                                                                                description: this.orgName
+                                                                            });
+                                                                        });
+                                                                        args.response.success({
+                                                                            data: items
+                                                                        });
+                                                                        args.$select.change(function() {
+                                                                            $('select[name="samlEntity"] option[value="' + authorization.idpid  + '"]').attr("selected", "selected");
+                                                                        });
+                                                                    }
+                                                                }
+                                                            }
+                                                        },
+                                                        after: function(args) {
+                                                            start();
+                                                            var enableSaml = false;
+                                                            var idpId = '';
+                                                            if (args.data.hasOwnProperty('samlEnable')) {
+                                                                enableSaml = (args.data.samlEnable === 'on');
+                                                            }
+                                                            if (args.data.hasOwnProperty('samlEntity')) {
+                                                                idpId = args.data.samlEntity;
+                                                            }
+                                                            $.ajax({
+                                                                url: createURL('authorizeSamlSso'),
+                                                                data: {
+                                                                    userid: context.users[0].id,
+                                                                    enable: enableSaml,
+                                                                    entityid: idpId
+                                                                },
+                                                                type: "POST",
+                                                                success: function(json) {
+                                                                    complete();
+                                                                },
+                                                                error: function(json) {
+                                                                    complete({ error: parseXMLHttpResponse(json) });
+                                                                }
+                                                            });
+                                                        }
+                                                    });
+                                                },
+                                                error: function(json) {
+                                                    complete({ error: parseXMLHttpResponse(json) });
+                                                }
+                                            });
+
+                                        }
+                                    }
+                                }
+                            },
+
                             generateKeys: {
                                 label: 'label.action.generate.keys',
                                 messages: {
@@ -1797,6 +1893,9 @@
             allowedActions.push("edit");
             allowedActions.push("changePassword");
             allowedActions.push("generateKeys");
+            if (g_idpList) {
+                allowedActions.push("configureSamlAuthorization");
+            }
             if (!(jsonObj.domain == "ROOT" && jsonObj.account == "admin" && jsonObj.accounttype == 1)) { //if not system-generated default admin account user
                 if (jsonObj.state == "enabled")
                     allowedActions.push("disable");
@@ -1818,6 +1917,9 @@
                 
                 allowedActions.push("changePassword");
                 allowedActions.push("generateKeys");
+                if (g_idpList) {
+                    allowedActions.push("configureSamlAuthorization");
+                }
         	}        	
         }
         return allowedActions;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/accountsWizard.js
----------------------------------------------------------------------
diff --git a/ui/scripts/accountsWizard.js b/ui/scripts/accountsWizard.js
index 82e7eab..7ea5eaa 100644
--- a/ui/scripts/accountsWizard.js
+++ b/ui/scripts/accountsWizard.js
@@ -162,8 +162,34 @@
                 validation: {
                     required: false
                 }
+            },
+            samlEnable: {
+                label: 'label.saml.enable',
+                docID: 'helpSamlEnable',
+                isBoolean: true,
+                validation: {
+                    required: false
+                }
+            },
+            samlEntity: {
+                label: 'label.saml.entity',
+                docID: 'helpSamlEntity',
+                validation: {
+                    required: false
+                },
+                select: function(args) {
+                    var items = [];
+                    $(g_idpList).each(function() {
+                        items.push({
+                            id: this.id,
+                            description: this.orgName
+                        });
+                    });
+                    args.response.success({
+                        data: items
+                    });
+                }
             }
-
         },
 
         action: function(args) {
@@ -218,6 +244,18 @@
                 array1.push("&group=" + args.groupname);
             }
 
+            var authorizeUsersForSamlSSO = function (users, entity) {
+                for (var i = 0; i < users.length; i++) {
+                    $.ajax({
+                        url: createURL('authorizeSamlSso&enable=true&userid=' + users[i].id + "&entityid=" + entity),
+                        error: function(XMLHttpResponse) {
+                            args.response.error(parseXMLHttpResponse(XMLHttpResponse));
+                        }
+                    });
+                }
+                return;
+            };
+
             if (ldapStatus) {
                 if (args.groupname) {
                     $.ajax({
@@ -225,6 +263,13 @@
                         dataType: "json",
                         type: "POST",
                         async: false,
+                        success: function (json) {
+                            if (json.ldapuserresponse && args.data.samlEnable && args.data.samlEnable === 'on') {
+                                cloudStack.dialog.notice({
+                                    message: "Unable to find users IDs to enable SAML Single Sign On, kindly enable it manually."
+                                });
+                            }
+                        },
                         error: function(XMLHttpResponse) {
                             args.response.error(parseXMLHttpResponse(XMLHttpResponse));
                         }
@@ -235,6 +280,14 @@
                         dataType: "json",
                         type: "POST",
                         async: false,
+                        success: function(json) {
+                            if (args.data.samlEnable && args.data.samlEnable === 'on') {
+                                var users = json.createaccountresponse.account.user;
+                                var entity = args.data.samlEntity;
+                                if (users && entity)
+                                    authorizeUsersForSamlSSO(users, entity);
+                            }
+                        },
                         error: function(XMLHttpResponse) {
                             args.response.error(parseXMLHttpResponse(XMLHttpResponse));
                         }
@@ -246,6 +299,14 @@
                     dataType: "json",
                     type: "POST",
                     async: false,
+                    success: function(json) {
+                        if (args.data.samlEnable && args.data.samlEnable === 'on') {
+                            var users = json.createaccountresponse.account.user;
+                            var entity = args.data.samlEntity;
+                            if (users && entity)
+                                authorizeUsersForSamlSSO(users, entity);
+                        }
+                    },
                     error: function(XMLHttpResponse) {
                         args.response.error(parseXMLHttpResponse(XMLHttpResponse));
                     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/cloudStack.js
----------------------------------------------------------------------
diff --git a/ui/scripts/cloudStack.js b/ui/scripts/cloudStack.js
index 55200b6..0e0a71a 100644
--- a/ui/scripts/cloudStack.js
+++ b/ui/scripts/cloudStack.js
@@ -115,7 +115,7 @@
                             cookieValue = cookieValue.slice(1, cookieValue.length-1);
                             $.cookie(cookieName, cookieValue, { expires: 1 });
                         }
-                        return cookieValue;
+                        return decodeURIComponent(cookieValue);
                     };
                     unBoxCookieValue('sessionkey');
                     // if sessionkey cookie exists use this to set g_sessionKey
@@ -353,6 +353,17 @@
             },
 
             samlLoginAction: function(args) {
+                g_sessionKey = null;
+                g_username = null;
+                g_account = null;
+                g_domainid = null;
+                g_timezoneoffset = null;
+                g_timezone = null;
+                g_supportELB = null;
+                g_kvmsnapshotenabled = null;
+                g_regionsecondaryenabled = null;
+                g_loginCmdText = null;
+
                 $.cookie('JSESSIONID', null);
                 $.cookie('sessionkey', null);
                 $.cookie('username', null);
@@ -360,7 +371,14 @@
                 $.cookie('domainid', null);
                 $.cookie('role', null);
                 $.cookie('timezone', null);
-                window.location.href = createURL('samlSso');
+                var url = 'samlSso';
+                if (args.data.idpid) {
+                    url = url + '&idpid=' + args.data.idpid;
+                }
+                if (args.data.domain) {
+                    url = url + '&domain=' + args.data.domain;
+                }
+                window.location.href = createURL(url);
             },
 
             // Show cloudStack main UI widget

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/docs.js
----------------------------------------------------------------------
diff --git a/ui/scripts/docs.js b/ui/scripts/docs.js
index 53c31c2..809c398 100755
--- a/ui/scripts/docs.js
+++ b/ui/scripts/docs.js
@@ -1261,6 +1261,14 @@ cloudStack.docs = {
         desc: 'The group name from which you want to import LDAP users',
         externalLink: ''
     },
+    helpSamlEnable: {
+        desc: 'Enable SAML Single Sign On for the user(s)',
+        externalLink: ''
+    },
+    helpSamlEntity: {
+        desc: 'Choose the SAML Identity Provider Entity ID with which you want to enable the Single Sign On for the user(s)',
+        externalLink: ''
+    },
     helpVpcOfferingName: {
         desc: 'Any desired name for the VPC offering',
         externalLink: ''

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/sharedFunctions.js
----------------------------------------------------------------------
diff --git a/ui/scripts/sharedFunctions.js b/ui/scripts/sharedFunctions.js
index e8f7cc9..c29956a 100644
--- a/ui/scripts/sharedFunctions.js
+++ b/ui/scripts/sharedFunctions.js
@@ -32,6 +32,7 @@ var g_regionsecondaryenabled = null;
 var g_userPublicTemplateEnabled = "true";
 var g_cloudstackversion = null;
 var g_queryAsyncJobResultInterval = 3000;
+var g_idpList = null;
 
 //keyboard keycode
 var keycode_Enter = 13;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/ui-custom/accountsWizard.js
----------------------------------------------------------------------
diff --git a/ui/scripts/ui-custom/accountsWizard.js b/ui/scripts/ui-custom/accountsWizard.js
index 3259227..cfbe930 100644
--- a/ui/scripts/ui-custom/accountsWizard.js
+++ b/ui/scripts/ui-custom/accountsWizard.js
@@ -271,6 +271,11 @@
                     delete args.informationNotInLdap.ldapGroupName;
                 }
 
+                if (g_idpList == null) {
+                    delete args.informationNotInLdap.samlEnable;
+                    delete args.informationNotInLdap.samlEntity;
+                }
+
                 var informationNotInLdap = cloudStack.dialog.createForm({
                     context: context,
                     noDialog: true,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/ui/scripts/ui-custom/login.js
----------------------------------------------------------------------
diff --git a/ui/scripts/ui-custom/login.js b/ui/scripts/ui-custom/login.js
index 194c881..7c7e923 100644
--- a/ui/scripts/ui-custom/login.js
+++ b/ui/scripts/ui-custom/login.js
@@ -94,54 +94,120 @@
         $inputs.filter(':first').addClass('first-input').focus();
 
         // Login action
-        $login.find('input[type=submit]').click(function() {
-            if (!$form.valid()) return false;
-
-            var data = cloudStack.serializeForm($form);
-
-            args.loginAction({
-                data: data,
-                response: {
-                    success: function(args) {
-                        $login.remove();
-                        $('html body').removeClass('login');
-                        complete({
-                            user: args.data.user
-                        });
-                    },
-                    error: function(args) {
-                        cloudStack.dialog.notice({
-                            message: args
-                        });
+        var selectedLogin = 'cloudstack';
+        $login.find('#login-submit').click(function() {
+            if (selectedLogin === 'cloudstack') {
+                // CloudStack Local Login
+                if (!$form.valid()) return false;
+
+                var data = cloudStack.serializeForm($form);
+
+                args.loginAction({
+                    data: data,
+                    response: {
+                        success: function(args) {
+                            $login.remove();
+                            $('html body').removeClass('login');
+                            complete({
+                                user: args.data.user
+                            });
+                        },
+                        error: function(args) {
+                            cloudStack.dialog.notice({
+                                message: args
+                            });
+                        }
                     }
-                }
-            });
-
+                });
+            } else if (selectedLogin === 'saml') {
+                // SAML
+                args.samlLoginAction({
+                    data: {'idpid': $login.find('#login-options').find(':selected').val(),
+                          'domain': $login.find('#saml-domain').val()}
+                });
+            }
             return false;
         });
 
-        // SAML Login action
-        $login.find('input[type=samlsubmit]').click(function() {
-            args.samlLoginAction({
-            });
+        // Show SAML button if only SP is configured
+        $login.find('#login-dropdown').hide();
+        $login.find('#saml-login').hide();
+        $login.find('#cloudstack-login').hide();
+
+        var toggleLoginView = function (selectedOption) {
+            $login.find('#login-submit').show();
+            if (selectedOption === '') {
+                    $login.find('#saml-login').hide();
+                    $login.find('#cloudstack-login').hide();
+                    $login.find('#login-submit').hide();
+                    selectedLogin = 'none';
+            } else if (selectedOption === 'cloudstack-login') {
+                    $login.find('#saml-login').hide();
+                    $login.find('#cloudstack-login').show();
+                    selectedLogin = 'cloudstack';
+            } else {
+                    $login.find('#saml-login').show();
+                    $login.find('#cloudstack-login').hide();
+                    selectedLogin = 'saml';
+            }
+        };
+
+        $login.find('#login-options').change(function() {
+            var selectedOption = $login.find('#login-options').find(':selected').val();
+            toggleLoginView(selectedOption);
+            if (selectedOption && selectedOption !== '') {
+                $.cookie('login-option', selectedOption);
+            }
         });
 
-        // Show SAML button if only SP is configured
-        $login.find("#saml-login").hide();
         $.ajax({
-            type: "GET",
-            url: createURL("getSPMetadata"),
-            dataType: "json",
+            type: 'GET',
+            url: createURL('listIdps'),
+            dataType: 'json',
             async: false,
             success: function(data, textStatus, xhr) {
                 if (xhr.status === 200) {
-                    $login.find('#saml-login').show();
+                    $login.find('#login-dropdown').show();
+                    $login.find('#login-submit').hide();
                 } else {
-                    $login.find('#saml-login').hide();
+                    $login.find('#cloudstack-login').show();
+                    $login.find('#login-submit').show();
+                    return;
+                }
+
+                $login.find('#login-options')
+                    .append($('<option>', {
+                        value: '',
+                        text: '--- Select Identity Provider -- ',
+                        selected: true
+                    }));
+
+                if (data.listidpsresponse && data.listidpsresponse.idp) {
+                    var idpList = data.listidpsresponse.idp.sort(function (a, b) {
+                        return a.orgName.localeCompare(b.orgName);
+                    });
+                    g_idpList = idpList;
+                    $.each(idpList, function(index, idp) {
+                        $login.find('#login-options')
+                            .append($('<option>', {
+                                value: idp.id,
+                                text: idp.orgName
+                            }));
+                    });
+                }
+
+                var loginOption = $.cookie('login-option');
+                if (loginOption) {
+                    var option = $login.find('#login-options option[value="' + loginOption + '"]');
+                    if (option.length > 0) {
+                        option.prop('selected', true);
+                        toggleLoginView(loginOption);
+                    }
                 }
             },
             error: function(xhr) {
                 $login.find('#saml-login').hide();
+                $login.find('#cloudstack-login').show();
             }
         });
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/utils/src/org/apache/cloudstack/utils/auth/SAMLUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/auth/SAMLUtils.java b/utils/src/org/apache/cloudstack/utils/auth/SAMLUtils.java
deleted file mode 100644
index a6d2d34..0000000
--- a/utils/src/org/apache/cloudstack/utils/auth/SAMLUtils.java
+++ /dev/null
@@ -1,330 +0,0 @@
-//
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF 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.apache.cloudstack.utils.auth;
-
-import com.cloud.utils.HttpUtils;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.log4j.Logger;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.bouncycastle.x509.X509V1CertificateGenerator;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeZone;
-import org.opensaml.Configuration;
-import org.opensaml.common.SAMLVersion;
-import org.opensaml.common.xml.SAMLConstants;
-import org.opensaml.saml2.core.AuthnContextClassRef;
-import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration;
-import org.opensaml.saml2.core.AuthnRequest;
-import org.opensaml.saml2.core.Issuer;
-import org.opensaml.saml2.core.LogoutRequest;
-import org.opensaml.saml2.core.NameID;
-import org.opensaml.saml2.core.NameIDPolicy;
-import org.opensaml.saml2.core.NameIDType;
-import org.opensaml.saml2.core.RequestedAuthnContext;
-import org.opensaml.saml2.core.Response;
-import org.opensaml.saml2.core.SessionIndex;
-import org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder;
-import org.opensaml.saml2.core.impl.AuthnRequestBuilder;
-import org.opensaml.saml2.core.impl.IssuerBuilder;
-import org.opensaml.saml2.core.impl.LogoutRequestBuilder;
-import org.opensaml.saml2.core.impl.NameIDBuilder;
-import org.opensaml.saml2.core.impl.NameIDPolicyBuilder;
-import org.opensaml.saml2.core.impl.RequestedAuthnContextBuilder;
-import org.opensaml.saml2.core.impl.SessionIndexBuilder;
-import org.opensaml.xml.ConfigurationException;
-import org.opensaml.xml.XMLObject;
-import org.opensaml.xml.io.Marshaller;
-import org.opensaml.xml.io.MarshallingException;
-import org.opensaml.xml.io.Unmarshaller;
-import org.opensaml.xml.io.UnmarshallerFactory;
-import org.opensaml.xml.io.UnmarshallingException;
-import org.opensaml.xml.signature.SignatureConstants;
-import org.opensaml.xml.util.Base64;
-import org.opensaml.xml.util.XMLHelper;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.xml.sax.SAXException;
-
-import javax.security.auth.x500.X500Principal;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.math.BigInteger;
-import java.net.URLEncoder;
-import java.security.InvalidKeyException;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.Security;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-import java.util.zip.Deflater;
-import java.util.zip.DeflaterOutputStream;
-
-public class SAMLUtils {
-    public static final Logger s_logger = Logger.getLogger(SAMLUtils.class);
-
-    public static final String SAML_RESPONSE = "SAMLResponse";
-    public static final String SAML_NS = "SAML-";
-    public static final String SAML_NAMEID = "SAML_NAMEID";
-    public static final String SAML_SESSION = "SAML_SESSION";
-    public static final String SAMLSP_KEYPAIR = "SAMLSP_KEYPAIR";
-    public static final String SAMLSP_X509CERT = "SAMLSP_X509CERT";
-
-    public static String createSAMLId(String uid) {
-        if (uid == null)  {
-            return null;
-        }
-        String hash = DigestUtils.sha256Hex(uid);
-        String samlUuid = SAML_NS + hash;
-        return samlUuid.substring(0, 40);
-    }
-
-    public static boolean checkSAMLUser(String uuid, String username) {
-        if (uuid == null || uuid.isEmpty() || username == null || username.isEmpty()) {
-            return false;
-        }
-        return uuid.startsWith(SAML_NS) && createSAMLId(username).equals(uuid);
-    }
-
-    public static String generateSecureRandomId() {
-        return new BigInteger(160, new SecureRandom()).toString(32);
-    }
-
-    public static AuthnRequest buildAuthnRequestObject(String spId, String idpUrl, String consumerUrl) {
-        String authnId = generateSecureRandomId();
-        // Issuer object
-        IssuerBuilder issuerBuilder = new IssuerBuilder();
-        Issuer issuer = issuerBuilder.buildObject();
-        issuer.setValue(spId);
-
-        // NameIDPolicy
-        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
-        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
-        nameIdPolicy.setFormat(NameIDType.PERSISTENT);
-        nameIdPolicy.setSPNameQualifier(spId);
-        nameIdPolicy.setAllowCreate(true);
-
-        // AuthnContextClass
-        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
-        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
-                SAMLConstants.SAML20_NS,
-                "AuthnContextClassRef", "saml");
-        authnContextClassRef.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
-
-        // AuthnContex
-        RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
-        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
-        requestedAuthnContext
-                .setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
-        requestedAuthnContext.getAuthnContextClassRefs().add(
-                authnContextClassRef);
-
-        // Creation of AuthRequestObject
-        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
-        AuthnRequest authnRequest = authRequestBuilder.buildObject();
-        authnRequest.setID(authnId);
-        authnRequest.setDestination(idpUrl);
-        authnRequest.setVersion(SAMLVersion.VERSION_20);
-        authnRequest.setForceAuthn(false);
-        authnRequest.setIsPassive(false);
-        authnRequest.setIssuer(issuer);
-        authnRequest.setIssueInstant(new DateTime());
-        authnRequest.setProtocolBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
-        authnRequest.setAssertionConsumerServiceURL(consumerUrl);
-        authnRequest.setProviderName(spId);
-        authnRequest.setNameIDPolicy(nameIdPolicy);
-        authnRequest.setRequestedAuthnContext(requestedAuthnContext);
-
-        return authnRequest;
-    }
-
-    public static LogoutRequest buildLogoutRequest(String logoutUrl, String spId, NameID sessionNameId, String sessionIndex) {
-        IssuerBuilder issuerBuilder = new IssuerBuilder();
-        Issuer issuer = issuerBuilder.buildObject();
-        issuer.setValue(spId);
-
-        SessionIndex sessionIndexElement = new SessionIndexBuilder().buildObject();
-        sessionIndexElement.setSessionIndex(sessionIndex);
-
-        NameID nameID = new NameIDBuilder().buildObject();
-        nameID.setValue(sessionNameId.getValue());
-        nameID.setFormat(sessionNameId.getFormat());
-
-        LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
-        logoutRequest.setID(generateSecureRandomId());
-        logoutRequest.setDestination(logoutUrl);
-        logoutRequest.setVersion(SAMLVersion.VERSION_20);
-        logoutRequest.setIssueInstant(new DateTime());
-        logoutRequest.setIssuer(issuer);
-        logoutRequest.getSessionIndexes().add(sessionIndexElement);
-        logoutRequest.setNameID(nameID);
-        return logoutRequest;
-    }
-
-    public static String encodeSAMLRequest(XMLObject authnRequest)
-            throws MarshallingException, IOException {
-        Marshaller marshaller = Configuration.getMarshallerFactory()
-                .getMarshaller(authnRequest);
-        Element authDOM = marshaller.marshall(authnRequest);
-        StringWriter requestWriter = new StringWriter();
-        XMLHelper.writeNode(authDOM, requestWriter);
-        String requestMessage = requestWriter.toString();
-        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
-        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
-        deflaterOutputStream.write(requestMessage.getBytes());
-        deflaterOutputStream.close();
-        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
-        encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
-        return encodedRequestMessage;
-    }
-
-    public static Response decodeSAMLResponse(String responseMessage)
-            throws ConfigurationException, ParserConfigurationException,
-            SAXException, IOException, UnmarshallingException {
-        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
-        documentBuilderFactory.setNamespaceAware(true);
-        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
-        byte[] base64DecodedResponse = Base64.decode(responseMessage);
-        Document document = docBuilder.parse(new ByteArrayInputStream(base64DecodedResponse));
-        Element element = document.getDocumentElement();
-        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
-        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
-        return (Response) unmarshaller.unmarshall(element);
-    }
-
-    public static String generateSAMLRequestSignature(String urlEncodedString, PrivateKey signingKey)
-            throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, UnsupportedEncodingException {
-        if (signingKey == null) {
-            return urlEncodedString;
-        }
-        String url = urlEncodedString + "&SigAlg=" + URLEncoder.encode(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1, HttpUtils.UTF_8);
-        Signature signature = Signature.getInstance("SHA1withRSA");
-        signature.initSign(signingKey);
-        signature.update(url.getBytes());
-        String signatureString = Base64.encodeBytes(signature.sign(), Base64.DONT_BREAK_LINES);
-        if (signatureString != null) {
-            return url + "&Signature=" + URLEncoder.encode(signatureString, HttpUtils.UTF_8);
-        }
-        return url;
-    }
-
-    public static KeyFactory getKeyFactory() {
-        KeyFactory keyFactory = null;
-        try {
-            Security.addProvider(new BouncyCastleProvider());
-            keyFactory = KeyFactory.getInstance("RSA", "BC");
-        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
-            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
-        }
-        return keyFactory;
-    }
-
-    public static String savePublicKey(PublicKey key) {
-        try {
-            KeyFactory keyFactory = SAMLUtils.getKeyFactory();
-            if (keyFactory == null) return null;
-            X509EncodedKeySpec spec = keyFactory.getKeySpec(key, X509EncodedKeySpec.class);
-            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
-        } catch (InvalidKeySpecException e) {
-            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
-        }
-        return null;
-    }
-
-    public static String savePrivateKey(PrivateKey key) {
-        try {
-            KeyFactory keyFactory = SAMLUtils.getKeyFactory();
-            if (keyFactory == null) return null;
-            PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key,
-                    PKCS8EncodedKeySpec.class);
-            return new String(org.bouncycastle.util.encoders.Base64.encode(spec.getEncoded()));
-        } catch (InvalidKeySpecException e) {
-            s_logger.error("Unable to create KeyFactory:" + e.getMessage());
-        }
-        return null;
-    }
-
-    public static PublicKey loadPublicKey(String publicKey) {
-        byte[] sigBytes = org.bouncycastle.util.encoders.Base64.decode(publicKey);
-        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(sigBytes);
-        KeyFactory keyFact = SAMLUtils.getKeyFactory();
-        if (keyFact == null)
-            return null;
-        try {
-            return keyFact.generatePublic(x509KeySpec);
-        } catch (InvalidKeySpecException e) {
-            s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage());
-        }
-        return null;
-    }
-
-    public static PrivateKey loadPrivateKey(String privateKey) {
-        byte[] sigBytes = org.bouncycastle.util.encoders.Base64.decode(privateKey);
-        PKCS8EncodedKeySpec pkscs8KeySpec = new PKCS8EncodedKeySpec(sigBytes);
-        KeyFactory keyFact = SAMLUtils.getKeyFactory();
-        if (keyFact == null)
-            return null;
-        try {
-            return keyFact.generatePrivate(pkscs8KeySpec);
-        } catch (InvalidKeySpecException e) {
-            s_logger.error("Unable to create PrivateKey from privateKey string:" + e.getMessage());
-        }
-        return null;
-    }
-
-    public static KeyPair generateRandomKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
-        Security.addProvider(new BouncyCastleProvider());
-        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
-        keyPairGenerator.initialize(4096, new SecureRandom());
-        return keyPairGenerator.generateKeyPair();
-    }
-
-    public static X509Certificate generateRandomX509Certificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException, SignatureException, InvalidKeyException {
-        DateTime now = DateTime.now(DateTimeZone.UTC);
-        X500Principal dnName = new X500Principal("CN=ApacheCloudStack");
-        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
-        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
-        certGen.setSubjectDN(dnName);
-        certGen.setIssuerDN(dnName);
-        certGen.setNotBefore(now.minusDays(1).toDate());
-        certGen.setNotAfter(now.plusYears(3).toDate());
-        certGen.setPublicKey(keyPair.getPublic());
-        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
-        return certGen.generate(keyPair.getPrivate(), "BC");
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/107595a6/utils/test/org/apache/cloudstack/utils/auth/SAMLUtilsTest.java
----------------------------------------------------------------------
diff --git a/utils/test/org/apache/cloudstack/utils/auth/SAMLUtilsTest.java b/utils/test/org/apache/cloudstack/utils/auth/SAMLUtilsTest.java
deleted file mode 100644
index bebfd13..0000000
--- a/utils/test/org/apache/cloudstack/utils/auth/SAMLUtilsTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-//
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF 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.apache.cloudstack.utils.auth;
-
-import junit.framework.TestCase;
-import org.junit.Test;
-import org.opensaml.saml2.core.AuthnRequest;
-import org.opensaml.saml2.core.LogoutRequest;
-import org.opensaml.saml2.core.NameID;
-import org.opensaml.saml2.core.impl.NameIDBuilder;
-
-import java.security.KeyPair;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-
-public class SAMLUtilsTest extends TestCase {
-
-    @Test
-    public void testSAMLId() throws Exception {
-        assertEquals(SAMLUtils.createSAMLId(null), null);
-        assertEquals(SAMLUtils.createSAMLId("someUserName"), "SAML-305e19dd2581f33fd90b3949298ec8b17de");
-
-        assertTrue(SAMLUtils.checkSAMLUser(SAMLUtils.createSAMLId("someUserName"), "someUserName"));
-        assertFalse(SAMLUtils.checkSAMLUser(SAMLUtils.createSAMLId("someUserName"), "someOtherUserName"));
-        assertFalse(SAMLUtils.checkSAMLUser(SAMLUtils.createSAMLId(null), "someOtherUserName"));
-        assertFalse(SAMLUtils.checkSAMLUser("randomUID", "randomUID"));
-        assertFalse(SAMLUtils.checkSAMLUser(null, null));
-    }
-
-    @Test
-    public void testGenerateSecureRandomId() throws Exception {
-        assertTrue(SAMLUtils.generateSecureRandomId().length() > 0);
-    }
-
-    @Test
-    public void testBuildAuthnRequestObject() throws Exception {
-        String consumerUrl = "http://someurl.com";
-        String idpUrl = "http://idp.domain.example";
-        String spId = "cloudstack";
-        AuthnRequest req = SAMLUtils.buildAuthnRequestObject(spId, idpUrl, consumerUrl);
-        assertEquals(req.getAssertionConsumerServiceURL(), consumerUrl);
-        assertEquals(req.getDestination(), idpUrl);
-        assertEquals(req.getIssuer().getValue(), spId);
-    }
-
-    @Test
-    public void testBuildLogoutRequest() throws Exception {
-        String logoutUrl = "http://logoutUrl";
-        String spId = "cloudstack";
-        String sessionIndex = "12345";
-        String nameIdString = "someNameID";
-        NameID sessionNameId = new NameIDBuilder().buildObject();
-        sessionNameId.setValue(nameIdString);
-        LogoutRequest req = SAMLUtils.buildLogoutRequest(logoutUrl, spId, sessionNameId,  sessionIndex);
-        assertEquals(req.getDestination(), logoutUrl);
-        assertEquals(req.getIssuer().getValue(), spId);
-        assertEquals(req.getNameID().getValue(), nameIdString);
-        assertEquals(req.getSessionIndexes().get(0).getSessionIndex(), sessionIndex);
-    }
-
-    @Test
-    public void testX509Helpers() throws Exception {
-        KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
-
-        String privateKeyString = SAMLUtils.savePrivateKey(keyPair.getPrivate());
-        String publicKeyString = SAMLUtils.savePublicKey(keyPair.getPublic());
-
-        PrivateKey privateKey = SAMLUtils.loadPrivateKey(privateKeyString);
-        PublicKey publicKey = SAMLUtils.loadPublicKey(publicKeyString);
-
-        assertTrue(privateKey.equals(keyPair.getPrivate()));
-        assertTrue(publicKey.equals(keyPair.getPublic()));
-    }
-}
\ No newline at end of file


[50/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
Proposal of a Usage Reporter / call-home functionality for CloudStack

With this commit the Management Server will be default generate a anonymous Usage
report every 7 (seven) days and submit this information back to the Apache CloudStack project.

These anonymous reports do NOT contain any information about Instance names, subnets, etc. It only
contains numbers about how CloudStack is being used.

This information is vital for the project to gain more insight in how CloudStack is being used.

Users can turn the reporting off by setting usage.report.interval to 0 (zero)


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/28300b5d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/28300b5d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/28300b5d

Branch: refs/heads/reporter
Commit: 28300b5d08c4512743453b67a96af2277f3ee7a2
Parents: 616b011
Author: Wido den Hollander <wi...@widodh.nl>
Authored: Wed Jul 8 21:17:30 2015 +0200
Committer: Wido den Hollander <wi...@widodh.nl>
Committed: Wed Jul 8 21:17:47 2015 +0200

----------------------------------------------------------------------
 .../src/com/cloud/upgrade/dao/VersionDao.java   |   4 +
 .../com/cloud/upgrade/dao/VersionDaoImpl.java   |   9 +
 pom.xml                                         |   1 +
 reporter/README.md                              |  18 +
 reporter/usage-report-collector.py              |  64 +++
 server/pom.xml                                  |  10 +
 .../spring-server-core-managers-context.xml     |   2 +
 server/src/com/cloud/configuration/Config.java  |   5 +-
 .../cloudstack/report/AtomicGsonAdapter.java    |  48 ++
 .../apache/cloudstack/report/UsageReporter.java | 470 +++++++++++++++++++
 setup/db/db/schema-452to460.sql                 |   2 +
 11 files changed, 632 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/engine/schema/src/com/cloud/upgrade/dao/VersionDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/VersionDao.java b/engine/schema/src/com/cloud/upgrade/dao/VersionDao.java
index e280e0b..1a60f36 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/VersionDao.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/VersionDao.java
@@ -16,6 +16,8 @@
 // under the License.
 package com.cloud.upgrade.dao;
 
+import java.util.List;
+
 import com.cloud.upgrade.dao.VersionVO.Step;
 import com.cloud.utils.db.GenericDao;
 
@@ -23,4 +25,6 @@ public interface VersionDao extends GenericDao<VersionVO, Long> {
     VersionVO findByVersion(String version, Step step);
 
     String getCurrentVersion();
+
+    List<VersionVO> getAllVersions();
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java b/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
index bc9c2f0..a3e5eb0 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/VersionDaoImpl.java
@@ -170,4 +170,13 @@ public class VersionDaoImpl extends GenericDaoBase<VersionVO, Long> implements V
         }
 
     }
+
+    @Override
+    @DB
+    public List<VersionVO> getAllVersions() {
+        SearchCriteria<VersionVO> sc = AllFieldsSearch.create();
+        sc.setParameters("step", "Complete");
+
+        return listBy(sc);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index e76d747..0511e91 100644
--- a/pom.xml
+++ b/pom.xml
@@ -64,6 +64,7 @@
     <cs.ehcache.version>2.6.9</cs.ehcache.version>
     <cs.gson.version>1.7.2</cs.gson.version>
     <cs.guava-testlib.version>18.0</cs.guava-testlib.version>
+    <cs.gson.version>2.3.1</cs.gson.version>
     <cs.guava.version>18.0</cs.guava.version>
     <cs.xapi.version>6.2.0-3.1</cs.xapi.version>
     <cs.httpclient.version>4.3.6</cs.httpclient.version>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/reporter/README.md
----------------------------------------------------------------------
diff --git a/reporter/README.md b/reporter/README.md
new file mode 100644
index 0000000..6453fa4
--- /dev/null
+++ b/reporter/README.md
@@ -0,0 +1,18 @@
+# CloudStack Usage Report
+
+This directory contains the CloudStack reporter webservice used by the Apache CloudStack project
+to gather anonymous statistical information about CloudStack deployments.
+
+Since version <FIX ME!!> the management server sends out a anonymized Usage Report out to the
+project every 7 days.
+
+This information is used to gain information about how CloudStack is being used.
+
+Turning this Usage Reporting functionality off can be done in the Global Settings by setting
+'usage.report.interval' to 0.
+
+# The webservice
+The Python Flask application in this directory is the webservice running on https://reports.cloudstack.apache.org/ (FIX ME?)
+and stores all the incoming information in a ElasticSearch database.
+
+Since Apache CloudStack is Open Source we show not only how we generate the report, but also how we process it.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/reporter/usage-report-collector.py
----------------------------------------------------------------------
diff --git a/reporter/usage-report-collector.py b/reporter/usage-report-collector.py
new file mode 100755
index 0000000..500a4d2
--- /dev/null
+++ b/reporter/usage-report-collector.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF 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.
+
+from flask import abort, Flask, request, Response
+from elasticsearch import Elasticsearch
+import json
+import time
+
+def json_response(response):
+    return json.dumps(response, indent=2) + "\n", 200, {'Content-Type': 'application/json; charset=utf-8'}
+
+def generate_app(config=None):
+    app = Flask(__name__)
+
+    @app.route('/report/<unique_id>', methods=['POST'])
+    def report(unique_id):
+        # We expect JSON data, so if the Content-Type doesn't match JSON data we throw an error
+        if 'Content-Type' in request.headers:
+            if request.headers['Content-Type'] != 'application/json':
+                abort(417, "No or incorrect Content-Type header was supplied")
+
+        index = "cloudstack-%s" % time.strftime("%Y.%m.%d", time.gmtime())
+        timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+        es = Elasticsearch()
+        es.indices.create(index=index, ignore=400)
+
+        report = json.loads(request.data)
+        report["unique_id"] = unique_id
+        report["timestamp"] = timestamp
+
+        es.index(index=index, doc_type="usage-report", body=json.dumps(report), timestamp=timestamp, refresh=True)
+
+        response = {}
+        return json_response(response)
+
+    return app
+
+
+app = generate_app()
+
+# Only run the App if this script is invoked from a Shell
+if __name__ == '__main__':
+    app.debug = True
+    app.run(host='0.0.0.0', port=8088)
+
+# Otherwise provide a variable called 'application' for mod_wsgi
+else:
+    application = app

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/server/pom.xml
----------------------------------------------------------------------
diff --git a/server/pom.xml b/server/pom.xml
index e68e678..0b279f4 100644
--- a/server/pom.xml
+++ b/server/pom.xml
@@ -140,6 +140,16 @@
       <artifactId>opensaml</artifactId>
       <version>${cs.opensaml.version}</version>
     </dependency>
+    <dependency>
+      <groupId>com.google.code.gson</groupId>
+      <artifactId>gson</artifactId>
+      <version>${cs.gson.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>com.google.guava</groupId>
+      <artifactId>guava</artifactId>
+      <version>${cs.guava.version}</version>
+    </dependency>
   </dependencies>
   <build>
     <testResources>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
----------------------------------------------------------------------
diff --git a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
index e39d918..594c2b8 100644
--- a/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
+++ b/server/resources/META-INF/cloudstack/core/spring-server-core-managers-context.xml
@@ -224,6 +224,8 @@
 
     <bean id="statsCollector" class="com.cloud.server.StatsCollector" />
 
+    <bean id="usageReporter" class="org.apache.cloudstack.report.UsageReporter" />
+
     <bean id="storagePoolAutomationImpl" class="com.cloud.storage.StoragePoolAutomationImpl" />
 
     <bean id="domainManagerImpl" class="com.cloud.user.DomainManagerImpl" />

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index ca89881..bc2d93c 100644
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -1999,7 +1999,10 @@ public enum Config {
     // StatsCollector
     StatsOutPutGraphiteHost("Advanced", ManagementServer.class, String.class, "stats.output.uri", "", "URI to additionally send StatsCollector statistics to", null),
 
-    SSVMPSK("Hidden", ManagementServer.class, String.class, "upload.post.secret.key", "", "PSK with SSVM", null);
+    SSVMPSK("Hidden", ManagementServer.class, String.class, "upload.post.secret.key", "", "PSK with SSVM", null),
+
+    // Usage Reporting service
+    UsageReportInterval("Advanced", ManagementServer.class, Integer.class, "usage.report.interval", "7", "Interval (days) between sending anonymous Usage Reports back to the CloudStack project", null);
 
     private final String _category;
     private final Class<?> _componentClass;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/server/src/org/apache/cloudstack/report/AtomicGsonAdapter.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/report/AtomicGsonAdapter.java b/server/src/org/apache/cloudstack/report/AtomicGsonAdapter.java
new file mode 100644
index 0000000..23d83f1
--- /dev/null
+++ b/server/src/org/apache/cloudstack/report/AtomicGsonAdapter.java
@@ -0,0 +1,48 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.report;
+
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import com.google.common.util.concurrent.AtomicLongMap;
+import java.util.Map;
+import java.io.IOException;
+
+public class AtomicGsonAdapter extends TypeAdapter<AtomicLongMap> {
+
+    public AtomicLongMap<Object> read(JsonReader reader) throws IOException {
+        reader.nextNull();
+        return null;
+    }
+
+    public void write(JsonWriter writer, AtomicLongMap value) throws IOException {
+        if (value == null) {
+            writer.nullValue();
+            return;
+        }
+
+        @SuppressWarnings("unchecked")
+        Map <String, Long> map = value.asMap();
+
+        writer.beginObject();
+        for (Map.Entry<String, Long> entry : map.entrySet()) {
+            writer.name(entry.getKey()).value(entry.getValue());
+        }
+        writer.endObject();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/server/src/org/apache/cloudstack/report/UsageReporter.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/report/UsageReporter.java b/server/src/org/apache/cloudstack/report/UsageReporter.java
new file mode 100644
index 0000000..4656cc4
--- /dev/null
+++ b/server/src/org/apache/cloudstack/report/UsageReporter.java
@@ -0,0 +1,470 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF 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.apache.cloudstack.report;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.net.URL;
+import java.net.HttpURLConnection;
+import java.net.SocketTimeoutException;
+import java.net.MalformedURLException;
+import java.net.ProtocolException;
+import java.io.OutputStreamWriter;
+import java.io.IOException;
+
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
+import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+
+import org.apache.commons.codec.digest.DigestUtils;
+
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.dao.ClusterDao;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.dao.UserVmDao;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.dao.VMInstanceDao;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.component.ComponentMethodInterceptable;
+import com.cloud.utils.concurrency.NamedThreadFactory;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.TransactionLegacy;
+import com.cloud.upgrade.dao.VersionDao;
+import com.cloud.upgrade.dao.VersionVO;
+import com.cloud.storage.dao.DiskOfferingDao;
+import com.cloud.storage.DiskOfferingVO;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.common.util.concurrent.AtomicLongMap;
+
+@Component
+public class UsageReporter extends ManagerBase implements ComponentMethodInterceptable {
+    public static final Logger s_logger = Logger.getLogger(UsageReporter.class.getName());
+
+    /* !FIX ME! This should point to a Apache Infra host with SSL! */
+    private String reportHost = "http://cs-report.widodh.nl:8088/report";
+
+    private String uniqueID = null;
+
+    private static UsageReporter s_instance = null;
+
+    private ScheduledExecutorService _executor = null;
+
+    @Inject
+    private ConfigurationDao _configDao;
+    @Inject
+    private HostDao _hostDao;
+    @Inject
+    private ClusterDao _clusterDao;
+    @Inject
+    private PrimaryDataStoreDao _storagePoolDao;
+    @Inject
+    private DataCenterDao _dataCenterDao;
+    @Inject
+    private UserVmDao _userVmDao;
+    @Inject
+    private VMInstanceDao _vmInstance;
+    @Inject
+    private VersionDao _versionDao;
+    @Inject
+    private DiskOfferingDao _diskOfferingDao;
+
+    int usageReportInterval = -1;
+
+    public static UsageReporter getInstance() {
+        return s_instance;
+    }
+
+    public static UsageReporter getInstance(Map<String, String> configs) {
+        s_instance.init(configs);
+        return s_instance;
+    }
+
+    public UsageReporter() {
+        s_instance = this;
+    }
+
+    @Override
+    public boolean start() {
+        init(_configDao.getConfiguration());
+        return true;
+    }
+
+    private void init(Map<String, String> configs) {
+        _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("UsageReporter"));
+
+        usageReportInterval = NumbersUtil.parseInt(configs.get("usage.report.interval"), 7);
+
+        if (usageReportInterval > 0) {
+            _executor.scheduleWithFixedDelay(new UsageCollector(), 7, usageReportInterval, TimeUnit.DAYS);
+        }
+
+        uniqueID = getUniqueId();
+    }
+
+    private void sendReport(String reportUri, String uniqueID, Map<String, Object> reportMap) {
+
+        GsonBuilder builder = new GsonBuilder();
+
+        AtomicGsonAdapter adapter = new AtomicGsonAdapter();
+        builder.registerTypeAdapter(AtomicLongMap.class, adapter);
+
+        Gson gson = builder.create();
+        String report = gson.toJson(reportMap);
+
+        int http_timeout = 15000;
+
+        try {
+            s_logger.info("Usage Report will be send to: " + reportUri);
+            s_logger.debug("REPORT: " + report);
+
+            URL url = new URL(reportUri + "/" + uniqueID);
+
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            conn.setConnectTimeout(http_timeout);
+            conn.setReadTimeout(http_timeout);
+            conn.setRequestMethod("POST");
+            conn.setDoOutput(true);
+            conn.setRequestProperty("Content-Type", "application/json");
+            conn.setRequestProperty("Accept", "application/json");
+
+            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
+            osw.write(report);
+            osw.flush();
+            osw.close();
+
+            int resp_code = conn.getResponseCode();
+
+            if (resp_code == HttpURLConnection.HTTP_OK){
+                s_logger.info("Usage Report succesfully send to: " + reportUri);
+            } else {
+                s_logger.warn("Failed to send Usage Report: " + conn.getResponseMessage());
+            }
+
+        } catch (SocketTimeoutException e) {
+            s_logger.warn("Sending Usage Report to " + reportUri + " timed out: " + e.getMessage());
+        } catch (MalformedURLException e) {
+            s_logger.warn(reportUri + " is a invalid URL for sending Usage Report to: "+ e.getMessage());
+        } catch (ProtocolException e) {
+            s_logger.warn("Sending Usage Report failed due to a invalid protocol: " + e.getMessage());
+        } catch (IOException e) {
+            s_logger.warn("Failed to write Usage Report due to a IOException: " + e.getMessage());
+        }
+    }
+
+    @DB
+    private String getUniqueId() {
+        String unique = null;
+        Connection conn = null;
+
+        try {
+            conn = TransactionLegacy.getStandaloneConnection();
+
+            PreparedStatement pstmt = conn.prepareStatement("SELECT version,updated FROM version ORDER BY id ASC LIMIT 1");
+            ResultSet rs = pstmt.executeQuery();
+            if (rs.next()) {
+                unique = DigestUtils.sha256Hex(rs.getString(1) + rs.getString(2));
+            } else {
+                s_logger.debug("No rows found in the version table. Unable to obtain unique ID for this environment");
+            }
+
+            rs.close();
+        } catch (SQLException e) {
+            s_logger.debug("Unable to get the unique ID of this environment: " + e.getMessage());
+        } finally {
+            try {
+                conn.close();
+            } catch (SQLException e) {
+            }
+        }
+
+        s_logger.debug("Usage Report Unique ID is: " + unique);
+
+        return unique;
+    }
+
+    private Map<String, AtomicLongMap> getHostReport() {
+        Map<String, AtomicLongMap> hostMap = new HashMap<String, AtomicLongMap>();
+        AtomicLongMap<Object> host_types = AtomicLongMap.create();
+        AtomicLongMap<Object> host_hypervisor_type = AtomicLongMap.create();
+        AtomicLongMap<Object> host_version = AtomicLongMap.create();
+
+        SearchCriteria<HostVO> host_sc = _hostDao.createSearchCriteria();
+        List<HostVO> hosts = _hostDao.search(host_sc, null);
+        for (HostVO host : hosts) {
+            host_types.getAndIncrement(host.getType());
+            if (host.getHypervisorType() != null) {
+                host_hypervisor_type.getAndIncrement(host.getHypervisorType());
+            }
+
+            host_version.getAndIncrement(host.getVersion());
+        }
+
+        hostMap.put("version", host_version);
+        hostMap.put("hypervisor_type", host_hypervisor_type);
+        hostMap.put("type", host_types);
+
+        return hostMap;
+    }
+
+    private Map<String, AtomicLongMap> getClusterReport() {
+        Map<String, AtomicLongMap> clusterMap = new HashMap<String, AtomicLongMap>();
+        AtomicLongMap<Object> cluster_hypervisor_type = AtomicLongMap.create();
+        AtomicLongMap<Object> cluster_types = AtomicLongMap.create();
+
+        SearchCriteria<ClusterVO> cluster_sc = _clusterDao.createSearchCriteria();
+        List<ClusterVO> clusters = _clusterDao.search(cluster_sc, null);
+        for (ClusterVO cluster : clusters) {
+            if (cluster.getClusterType() != null) {
+                cluster_types.getAndIncrement(cluster.getClusterType());
+            }
+
+            if (cluster.getHypervisorType() != null) {
+                cluster_hypervisor_type.getAndIncrement(cluster.getHypervisorType());
+            }
+        }
+
+        clusterMap.put("hypervisor_type", cluster_hypervisor_type);
+        clusterMap.put("type", cluster_types);
+
+        return clusterMap;
+    }
+
+    private Map<String, AtomicLongMap> getStoragePoolReport() {
+        Map<String, AtomicLongMap> storagePoolMap = new HashMap<String, AtomicLongMap>();
+        AtomicLongMap<Object> storage_pool_types = AtomicLongMap.create();
+        AtomicLongMap<Object> storage_pool_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> storage_pool_scope = AtomicLongMap.create();
+
+        List<StoragePoolVO> storagePools = _storagePoolDao.listAll();
+        for (StoragePoolVO pool : storagePools) {
+            if (pool.getPoolType() != null) {
+                storage_pool_types.getAndIncrement(pool.getPoolType());
+            }
+
+            if (pool.getStorageProviderName() != null) {
+                storage_pool_provider.getAndIncrement(pool.getStorageProviderName());
+            }
+
+            if (pool.getScope() != null) {
+                storage_pool_scope.getAndIncrement(pool.getScope());
+            }
+        }
+
+        storagePoolMap.put("type", storage_pool_types);
+        storagePoolMap.put("provider", storage_pool_provider);
+        storagePoolMap.put("scope", storage_pool_scope);
+
+        return storagePoolMap;
+    }
+
+    private Map<String, AtomicLongMap> getDataCenterReport() {
+        Map<String, AtomicLongMap> datacenterMap = new HashMap<String, AtomicLongMap>();
+        AtomicLongMap<Object> network_type = AtomicLongMap.create();
+        AtomicLongMap<Object> dns_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> dhcp_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> lb_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> firewall_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> gateway_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> userdata_provider = AtomicLongMap.create();
+        AtomicLongMap<Object> vpn_provider = AtomicLongMap.create();
+
+        List<DataCenterVO> datacenters = _dataCenterDao.listAllZones();
+        for (DataCenterVO datacenter : datacenters) {
+            if (datacenter.getNetworkType() != null) {
+                network_type.getAndIncrement(datacenter.getNetworkType());
+            }
+
+            if (datacenter.getDnsProvider() != null) {
+                dns_provider.getAndIncrement(datacenter.getDnsProvider());
+            }
+
+            if (datacenter.getDhcpProvider() != null) {
+                dhcp_provider.getAndIncrement(datacenter.getDhcpProvider());
+            }
+
+            if (datacenter.getLoadBalancerProvider() != null) {
+                lb_provider.getAndIncrement(datacenter.getLoadBalancerProvider());
+            }
+
+            if (datacenter.getFirewallProvider() != null) {
+                firewall_provider.getAndIncrement(datacenter.getFirewallProvider());
+            }
+
+            if (datacenter.getGatewayProvider() != null) {
+                gateway_provider.getAndIncrement(datacenter.getGatewayProvider());
+            }
+
+            if (datacenter.getUserDataProvider() != null) {
+                userdata_provider.getAndIncrement(datacenter.getUserDataProvider());
+            }
+
+            if (datacenter.getVpnProvider() != null) {
+                vpn_provider.getAndIncrement(datacenter.getVpnProvider());
+            }
+        }
+
+        datacenterMap.put("network_type", network_type);
+        datacenterMap.put("dns_provider", dns_provider);
+        datacenterMap.put("dhcp_provider", dhcp_provider);
+        datacenterMap.put("lb_provider", lb_provider);
+        datacenterMap.put("firewall_provider", firewall_provider);
+        datacenterMap.put("gateway_provider", gateway_provider);
+        datacenterMap.put("userdata_provider", userdata_provider);
+        datacenterMap.put("vpn_provider", vpn_provider);
+
+        return datacenterMap;
+    }
+
+    private Map<String, AtomicLongMap> getInstanceReport() {
+
+        Map<String, AtomicLongMap> instanceMap = new HashMap<String, AtomicLongMap>();
+        AtomicLongMap<Object> hypervisor_type = AtomicLongMap.create();
+        AtomicLongMap<Object> instance_state = AtomicLongMap.create();
+        AtomicLongMap<Object> instance_type = AtomicLongMap.create();
+        AtomicLongMap<Object> ha_enabled = AtomicLongMap.create();
+        AtomicLongMap<Object> dynamically_scalable = AtomicLongMap.create();
+
+        SearchCriteria<HostVO> host_sc = _hostDao.createSearchCriteria();
+        List<HostVO> hosts = _hostDao.search(host_sc, null);
+        for (HostVO host : hosts) {
+            List<UserVmVO> vms = _userVmDao.listByLastHostId(host.getId());
+            for (UserVmVO vm : vms) {
+                VMInstanceVO vmVO = _vmInstance.findById(vm.getId());
+
+                if (vmVO.getHypervisorType() != null) {
+                    hypervisor_type.getAndIncrement(vmVO.getHypervisorType());
+                }
+
+                if (vmVO.getState() != null) {
+                    instance_state.getAndIncrement(vmVO.getState());
+                }
+
+                if (vmVO.getType() != null) {
+                    instance_type.getAndIncrement(vmVO.getType());
+                }
+
+                ha_enabled.getAndIncrement(vmVO.isHaEnabled());
+                dynamically_scalable.getAndIncrement(vmVO.isDynamicallyScalable());
+            }
+        }
+
+        instanceMap.put("hypervisor_type", hypervisor_type);
+        instanceMap.put("state", instance_state);
+        instanceMap.put("type", instance_type);
+        instanceMap.put("ha_enabled", ha_enabled);
+        instanceMap.put("dynamically_scalable", dynamically_scalable);
+
+        return instanceMap;
+    }
+
+    private Map<String, Object> getDiskOfferingReport() {
+        Map<String, Object> diskOfferingReport = new HashMap<String, Object>();
+
+        AtomicLongMap<Object> system_use = AtomicLongMap.create();
+        AtomicLongMap<Object> provisioning_type = AtomicLongMap.create();
+        AtomicLongMap<Object> use_local_storage = AtomicLongMap.create();
+
+        List<DiskOfferingVO> private_offerings = _diskOfferingDao.findPrivateDiskOffering();
+        List<DiskOfferingVO> public_offerings = _diskOfferingDao.findPublicDiskOfferings();
+
+        List<DiskOfferingVO> offerings = new ArrayList<DiskOfferingVO>();
+        offerings.addAll(private_offerings);
+        offerings.addAll(public_offerings);
+
+        long disk_size = 0;
+        for (DiskOfferingVO offering : offerings) {
+            provisioning_type.getAndIncrement(offering.getProvisioningType());
+            system_use.getAndIncrement(offering.getSystemUse());
+            use_local_storage.getAndIncrement(offering.getUseLocalStorage());
+            disk_size += offering.getDiskSize();
+        }
+
+        diskOfferingReport.put("system_use", system_use);
+        diskOfferingReport.put("provisioning_type", provisioning_type);
+        diskOfferingReport.put("use_local_storage", use_local_storage);
+        diskOfferingReport.put("avg_disk_size", disk_size / offerings.size());
+
+        return diskOfferingReport;
+    }
+
+    private Map<String, String> getVersionReport() {
+        Map<String, String> versionMap = new HashMap<String, String>();
+
+        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+
+        List<VersionVO> versions = _versionDao.getAllVersions();
+        for (VersionVO version : versions) {
+            versionMap.put(version.getVersion(), dateFormat.format(version.getUpdated()));
+        }
+
+        return versionMap;
+    }
+
+    private String getCurrentVersion() {
+        return _versionDao.getCurrentVersion();
+    }
+
+    class UsageCollector extends ManagedContextRunnable {
+        @Override
+        protected void runInContext() {
+            try {
+                s_logger.warn("UsageReporter is running...");
+
+                Map<String, Object> reportMap = new HashMap<String, Object>();
+
+                reportMap.put("hosts", getHostReport());
+                reportMap.put("clusters", getClusterReport());
+                reportMap.put("primaryStorage", getStoragePoolReport());
+                reportMap.put("zones", getDataCenterReport());
+                reportMap.put("instances", getInstanceReport());
+                reportMap.put("diskOffering", getDiskOfferingReport());
+                reportMap.put("versions", getVersionReport());
+                reportMap.put("current_version", getCurrentVersion());
+
+                sendReport(reportHost, uniqueID, reportMap);
+
+            } catch (Exception e) {
+                s_logger.warn("Failed to compile Usage Report: " + e.getMessage());
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/28300b5d/setup/db/db/schema-452to460.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-452to460.sql b/setup/db/db/schema-452to460.sql
index 0abd4f8..00204f0 100644
--- a/setup/db/db/schema-452to460.sql
+++ b/setup/db/db/schema-452to460.sql
@@ -398,3 +398,5 @@ CREATE TABLE `cloud`.`external_bigswitch_bcf_devices` (
   CONSTRAINT `fk_external_bigswitch_bcf_devices__host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE,
   CONSTRAINT `fk_external_bigswitch_bcf_devices__physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ("Advanced", 'DEFAULT', 'management-server', "usage.report.interval", 7, "Interval (days) between sending anonymous Usage Reports back to the CloudStack project", "", NULL, NULL, 0);


[12/50] [abbrv] git commit: updated refs/heads/reporter to 28300b5

Posted by wi...@apache.org.
CLOUDSTACK-8600. Upon detaching a disk, delete VM folder if empty.

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #545


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/9463356c
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/9463356c
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/9463356c

Branch: refs/heads/reporter
Commit: 9463356ca61dc77faf539b8018db1f834d8fe815
Parents: 23c6642
Author: Likitha Shetty <li...@citrix.com>
Authored: Thu Apr 16 14:22:13 2015 +0530
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Wed Jul 1 14:53:23 2015 +0200

----------------------------------------------------------------------
 .../storage/resource/VmwareStorageLayoutHelper.java | 16 ++++++++++++++--
 .../storage/resource/VmwareStorageProcessor.java    |  2 +-
 2 files changed, 15 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9463356c/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageLayoutHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageLayoutHelper.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageLayoutHelper.java
index 96197ff..4096333 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageLayoutHelper.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageLayoutHelper.java
@@ -109,7 +109,7 @@ public class VmwareStorageLayoutHelper {
             // be left over in its previous owner VM. We will do a fixup synchronization here by moving it to root
             // again.
             //
-            syncVolumeToRootFolder(dcMo, ds, vmdkName);
+            syncVolumeToRootFolder(dcMo, ds, vmdkName, vmName);
         }
 
         if (ds.fileExists(vmdkFullCloneModeLegacyPair[1])) {
@@ -133,11 +133,16 @@ public class VmwareStorageLayoutHelper {
         return vmdkLinkedCloneModePair[0];
     }
 
-    public static void syncVolumeToRootFolder(DatacenterMO dcMo, DatastoreMO ds, String vmdkName) throws Exception {
+    public static void syncVolumeToRootFolder(DatacenterMO dcMo, DatastoreMO ds, String vmdkName, String vmName) throws Exception {
         String fileDsFullPath = ds.searchFileInSubFolders(vmdkName + ".vmdk", false);
         if (fileDsFullPath == null)
             return;
 
+        String folderName = null;
+        if (ds.folderExists(String.format("[%s]", ds.getName()), vmName)) {
+            folderName = String.format("[%s] %s", ds.getName(), vmName);
+        }
+
         DatastoreFile srcDsFile = new DatastoreFile(fileDsFullPath);
         String companionFilePath = srcDsFile.getCompanionPath(vmdkName + "-flat.vmdk");
         if (ds.fileExists(companionFilePath)) {
@@ -159,6 +164,13 @@ public class VmwareStorageLayoutHelper {
         String targetPath = getLegacyDatastorePathFromVmdkFileName(ds, vmdkName + ".vmdk");
         s_logger.info("Fixup folder-synchronization. move " + fileDsFullPath + " -> " + targetPath);
         ds.moveDatastoreFile(fileDsFullPath, dcMo.getMor(), ds.getMor(), targetPath, dcMo.getMor(), true);
+
+        if (folderName != null) {
+            String[] files = ds.listDirContent(folderName);
+            if (files == null || files.length == 0) {
+                ds.deleteFolder(folderName, dcMo.getMor());
+            }
+        }
     }
 
     public static void moveVolumeToRootFolder(DatacenterMO dcMo, List<String> detachedDisks) throws Exception {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9463356c/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
index 7295685..ab07ec5 100644
--- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
@@ -1368,7 +1368,7 @@ public class VmwareStorageProcessor implements StorageProcessor {
                 if (isManaged) {
                     handleDatastoreAndVmdkDetachManaged(diskUuid, iScsiName, storageHost, storagePort);
                 } else {
-                    VmwareStorageLayoutHelper.syncVolumeToRootFolder(dsMo.getOwnerDatacenter().first(), dsMo, volumeTO.getPath());
+                    VmwareStorageLayoutHelper.syncVolumeToRootFolder(dsMo.getOwnerDatacenter().first(), dsMo, volumeTO.getPath(), vmName);
                 }
             }