You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ts...@apache.org on 2013/03/29 13:46:03 UTC

[01/25] git commit: updated refs/heads/bvt to 5727bd0

Updated Branches:
  refs/heads/bvt 1ae4d7f37 -> 5727bd0ea


Inject GslbServiceProvider using @Inject fails in oss build, as it requires an
implemenation by default to autowire but only implementation avaialable
is in nonoss plugin. So using autowired required=false for injecting
GslbServiceProvider that will work with both oss and non-oss builds.


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

Branch: refs/heads/bvt
Commit: f8b8f60977dcb37dcabaa395c4e1a0c7adb114de
Parents: d437cb6
Author: Murali Reddy <mu...@citrix.com>
Authored: Thu Mar 28 16:10:54 2013 +0530
Committer: Murali Reddy <mu...@citrix.com>
Committed: Thu Mar 28 16:20:13 2013 +0530

----------------------------------------------------------------------
 .../gslb/GlobalLoadBalancingRulesServiceImpl.java  |    5 +++--
 1 files changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f8b8f609/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
index 86c9c50..9cc10aa 100644
--- a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
+++ b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
@@ -44,6 +44,7 @@ import org.apache.cloudstack.api.command.user.region.ha.gslb.*;
 import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.region.dao.RegionDao;
 import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import javax.ejb.Local;
@@ -79,8 +80,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
     IPAddressDao _ipAddressDao;
     @Inject
     AgentManager _agentMgr;
-
-    protected GslbServiceProvider _gslbProvider = null;
+    @Autowired(required=false)
+    protected GslbServiceProvider _gslbProvider;
 
 
     @Override


[08/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
Fixed createNetworkOfferingUnittest


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

Branch: refs/heads/bvt
Commit: 34a59fc3a7cbd8d1d261dc3fca10cbc6a02f0ec9
Parents: 0f3b7ef
Author: Alena Prokharchyk <al...@citrix.com>
Authored: Thu Mar 28 12:16:05 2013 -0700
Committer: Alena Prokharchyk <al...@citrix.com>
Committed: Thu Mar 28 12:16:05 2013 -0700

----------------------------------------------------------------------
 .../networkoffering/CreateNetworkOfferingTest.java |    6 ------
 1 files changed, 0 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/34a59fc3/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java b/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
index bb82991..1353959 100644
--- a/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
+++ b/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
@@ -46,7 +46,6 @@ import com.cloud.offerings.NetworkOfferingServiceMapVO;
 import com.cloud.offerings.NetworkOfferingVO;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
-import com.cloud.user.UserContext;
 import com.cloud.user.UserContextInitializer;
 
 @RunWith(SpringJUnit4ClassRunner.class)
@@ -64,9 +63,6 @@ public class CreateNetworkOfferingTest extends TestCase{
     NetworkOfferingDao offDao;
     
     @Inject
-    UserContext usrCtx;
-    
-    @Inject
     UserContextInitializer usrCtxInit;
     
     @Inject
@@ -79,7 +75,6 @@ public class CreateNetworkOfferingTest extends TestCase{
         
         Mockito.when(offDao.persist(Mockito.any(NetworkOfferingVO.class))).thenReturn(new NetworkOfferingVO());
         Mockito.when(mapDao.persist(Mockito.any(NetworkOfferingServiceMapVO.class))).thenReturn(new NetworkOfferingServiceMapVO());
-        Mockito.when(usrCtx.current()).thenReturn(new UserContext());
     }
 
     //Test Shared network offerings
@@ -88,7 +83,6 @@ public class CreateNetworkOfferingTest extends TestCase{
         NetworkOfferingVO off = configMgr.createNetworkOffering("shared", "shared", TrafficType.Guest, null, true,
                 Availability.Optional, 200, null, false, Network.GuestType.Shared, false,
                 null, false, null, true, false);
-        
         assertNotNull("Shared network offering with specifyVlan=true failed to create ", off);
     }
     


[15/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1156: Limit Primary and Secondary storage for domain/accounts

    Addition of two new resource types i.e. Primary and Secondary storage space in the existing pool of
    resource types.
    Added methods to set the limits on these resources using updateResourceLimit
    API command and to get a count using updateResourceCount. Also added calls in the
    Templates, Volumes, Snapshots life cycle to check these limits and to increment/decrement the new
    resource types

    Resource Name          :: Resource type number
        Primary Storage               10
        Secondary Storage             11

    Also added jUnit Tests for the same.
Reviewed by : nitin mehta<ni...@citrix.com>


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

Branch: refs/heads/bvt
Commit: 18695276f79a4cf90279f6ff25ebc7c66b6a9c49
Parents: d6e11f2
Author: Sanjay Tripathi <sa...@citrix.com>
Authored: Fri Mar 29 11:21:10 2013 +0530
Committer: Nitin Mehta <ni...@citrix.com>
Committed: Fri Mar 29 11:26:38 2013 +0530

----------------------------------------------------------------------
 api/src/com/cloud/configuration/Resource.java      |    7 +-
 api/src/com/cloud/storage/VolumeApiService.java    |    5 +-
 .../user/resource/UpdateResourceCountCmd.java      |    6 +-
 .../user/resource/UpdateResourceLimitCmd.java      |    6 +-
 .../api/command/user/volume/ResizeVolumeCmd.java   |    3 +-
 .../cloudstack/api/response/AccountResponse.java   |   54 +++++-
 .../api/response/ResourceCountResponse.java        |    2 +-
 .../api/response/ResourceLimitResponse.java        |    2 +-
 .../manager/BareMetalTemplateAdapter.java          |   15 ++-
 server/src/com/cloud/alert/AlertManagerImpl.java   |    3 +-
 server/src/com/cloud/api/ApiResponseHelper.java    |  149 ++++++++++----
 .../cloud/api/query/dao/AccountJoinDaoImpl.java    |   18 ++
 .../src/com/cloud/api/query/vo/AccountJoinVO.java  |   54 +++++
 server/src/com/cloud/configuration/Config.java     |    5 +-
 .../resourcelimit/ResourceLimitManagerImpl.java    |   54 +++++
 server/src/com/cloud/storage/VolumeManager.java    |    3 +-
 .../src/com/cloud/storage/VolumeManagerImpl.java   |   95 +++++++--
 server/src/com/cloud/storage/dao/SnapshotDao.java  |   12 +-
 .../src/com/cloud/storage/dao/SnapshotDaoImpl.java |   65 ++++--
 server/src/com/cloud/storage/dao/VolumeDao.java    |   66 ++++---
 .../src/com/cloud/storage/dao/VolumeDaoImpl.java   |   48 ++++-
 .../cloud/storage/download/DownloadListener.java   |   62 +++++-
 .../storage/download/DownloadMonitorImpl.java      |   56 +++++-
 .../storage/snapshot/SnapshotManagerImpl.java      |   70 ++++---
 .../cloud/template/HypervisorTemplateAdapter.java  |   29 ++--
 .../com/cloud/template/TemplateManagerImpl.java    |   47 +++--
 server/src/com/cloud/vm/UserVmManagerImpl.java     |   15 ++-
 .../ResourceLimitManagerImplTest.java              |   18 ++-
 .../cloud/vpc/MockResourceLimitManagerImpl.java    |    8 +
 setup/db/db/schema-40to410.sql                     |   24 ---
 setup/db/db/schema-410to420.sql                    |  153 ++++++++++++++-
 utils/src/com/cloud/utils/UriUtils.java            |   33 +++
 32 files changed, 936 insertions(+), 251 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/com/cloud/configuration/Resource.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/configuration/Resource.java b/api/src/com/cloud/configuration/Resource.java
index 7614c8a..5550e29 100644
--- a/api/src/com/cloud/configuration/Resource.java
+++ b/api/src/com/cloud/configuration/Resource.java
@@ -20,7 +20,7 @@ public interface Resource {
 
     public static final short RESOURCE_UNLIMITED = -1;
 
-    public enum ResourceType {
+    public enum ResourceType { // Primary and Secondary storage are allocated_storage and not the physical storage.
         user_vm("user_vm", 0, ResourceOwnerType.Account, ResourceOwnerType.Domain),
         public_ip("public_ip", 1, ResourceOwnerType.Account, ResourceOwnerType.Domain),
         volume("volume", 2, ResourceOwnerType.Account, ResourceOwnerType.Domain),
@@ -30,11 +30,14 @@ public interface Resource {
         network("network", 6, ResourceOwnerType.Account, ResourceOwnerType.Domain),
         vpc("vpc", 7, ResourceOwnerType.Account, ResourceOwnerType.Domain),
         cpu("cpu", 8, ResourceOwnerType.Account, ResourceOwnerType.Domain),
-        memory("memory", 9, ResourceOwnerType.Account, ResourceOwnerType.Domain);
+        memory("memory", 9, ResourceOwnerType.Account, ResourceOwnerType.Domain),
+        primary_storage("primary_storage", 10, ResourceOwnerType.Account, ResourceOwnerType.Domain),
+        secondary_storage("secondary_storage", 11, ResourceOwnerType.Account, ResourceOwnerType.Domain);
 
         private String name;
         private ResourceOwnerType[] supportedOwners;
         private int ordinal;
+        public static final long bytesToGiB = 1024 * 1024 * 1024;
 
         ResourceType(String name, int ordinal, ResourceOwnerType... supportedOwners) {
             this.name = name;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/com/cloud/storage/VolumeApiService.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/storage/VolumeApiService.java b/api/src/com/cloud/storage/VolumeApiService.java
index 8517988..09a07d4 100644
--- a/api/src/com/cloud/storage/VolumeApiService.java
+++ b/api/src/com/cloud/storage/VolumeApiService.java
@@ -59,9 +59,10 @@ public interface VolumeApiService {
      * @param cmd
      *            the API command wrapping the criteria
      * @return the volume object
+     * @throws ResourceAllocationException
      */
-    Volume resizeVolume(ResizeVolumeCmd cmd);
-    
+    Volume resizeVolume(ResizeVolumeCmd cmd) throws ResourceAllocationException;
+
     Volume migrateVolume(MigrateVolumeCmd cmd) throws ConcurrentOperationException;
 
     /**

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java
index f6d3a98..0f4c932 100644
--- a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java
@@ -53,7 +53,7 @@ public class UpdateResourceCountCmd extends BaseCmd {
             required=true, description="If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.")
     private Long domainId;
 
-    @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description=  "Type of resource to update. If specifies valid values are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. If not specified will update all resource counts" +
+    @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description=  "Type of resource to update. If specifies valid values are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 11. If not specified will update all resource counts" +
                                                                                         "0 - Instance. Number of instances a user can create. " +
                                                                                         "1 - IP. Number of public IP addresses a user can own. " +
                                                                                         "2 - Volume. Number of disk volumes a user can create." +
@@ -63,7 +63,9 @@ public class UpdateResourceCountCmd extends BaseCmd {
                                                                                         "6 - Network. Number of guest network a user can create." +
                                                                                         "7 - VPC. Number of VPC a user can create." +
                                                                                         "8 - CPU. Total number of CPU cores a user can use." +
-                                                                                        "9 - Memory. Total Memory (in MB) a user can use." )
+                                                                                        "9 - Memory. Total Memory (in MB) a user can use." +
+                                                                                        "10 - PrimaryStorage. Total primary storage space (in GiB) a user can use." +
+                                                                                        "11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use." )
     private Integer resourceType;
 
     @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java
index 0039f62..826596c 100644
--- a/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java
@@ -54,7 +54,7 @@ public class UpdateResourceLimitCmd extends BaseCmd {
     @Parameter(name=ApiConstants.MAX, type=CommandType.LONG, description="  Maximum resource limit.")
     private Long max;
 
-    @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, required=true, description="Type of resource to update. Values are 0, 1, 2, 3, 4, 6, 7, 8 and 9. 0 - Instance. Number of instances a user can create. " +
+    @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, required=true, description="Type of resource to update. Values are 0, 1, 2, 3, 4, 6, 7, 8, 9, 10 and 11. 0 - Instance. Number of instances a user can create. " +
                                                                                         "1 - IP. Number of public IP addresses a user can own. " +
                                                                                         "2 - Volume. Number of disk volumes a user can create." +
                                                                                         "3 - Snapshot. Number of snapshots a user can create." +
@@ -62,7 +62,9 @@ public class UpdateResourceLimitCmd extends BaseCmd {
                                                                                         "6 - Network. Number of guest network a user can create." +
                                                                                         "7 - VPC. Number of VPC a user can create." +
                                                                                         "8 - CPU. Total number of CPU cores a user can use." +
-                                                                                        "9 - Memory. Total Memory (in MB) a user can use." )
+                                                                                        "9 - Memory. Total Memory (in MB) a user can use." +
+                                                                                        "10 - PrimaryStorage. Total primary storage space (in GiB) a user can use." +
+                                                                                        "11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use." )
     private Integer resourceType;
 
     /////////////////////////////////////////////////////

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
index 955727a..871bf45 100644
--- a/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/volume/ResizeVolumeCmd.java
@@ -30,6 +30,7 @@ import com.cloud.async.AsyncJob;
 import com.cloud.event.EventTypes;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.exception.PermissionDeniedException;
+import com.cloud.exception.ResourceAllocationException;
 import com.cloud.projects.Project;
 import com.cloud.storage.Volume;
 import com.cloud.user.Account;
@@ -131,7 +132,7 @@ public class ResizeVolumeCmd extends BaseAsyncCmd {
     }
 
     @Override
-    public void execute(){
+    public void execute() throws ResourceAllocationException{
         UserContext.current().setEventDetails("Volume Id: " + getEntityId() + " to size " + getSize() + "G");
     	Volume volume = _volumeService.resizeVolume(this);
     	if (volume != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/response/AccountResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/AccountResponse.java b/api/src/org/apache/cloudstack/api/response/AccountResponse.java
index 9a98a35..c109a63 100644
--- a/api/src/org/apache/cloudstack/api/response/AccountResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/AccountResponse.java
@@ -132,24 +132,42 @@ public class AccountResponse extends BaseResponse {
     @SerializedName("vpcavailable") @Param(description="the total number of vpcs available to be created for this account", since="4.0.0")
     private String vpcAvailable;
 
-    @SerializedName("cpulimit") @Param(description="the total number of cpu cores the account can own", since="4.1.0")
+    @SerializedName("cpulimit") @Param(description="the total number of cpu cores the account can own", since="4.2.0")
     private String cpuLimit;
 
-    @SerializedName("cputotal") @Param(description="the total number of cpu cores owned by account", since="4.1.0")
+    @SerializedName("cputotal") @Param(description="the total number of cpu cores owned by account", since="4.2.0")
     private Long cpuTotal;
 
-    @SerializedName("cpuavailable") @Param(description="the total number of cpu cores available to be created for this account", since="4.1.0")
+    @SerializedName("cpuavailable") @Param(description="the total number of cpu cores available to be created for this account", since="4.2.0")
     private String cpuAvailable;
 
-    @SerializedName("memorylimit") @Param(description="the total memory (in MB) the account can own", since="4.1.0")
+    @SerializedName("memorylimit") @Param(description="the total memory (in MB) the account can own", since="4.2.0")
     private String memoryLimit;
 
-    @SerializedName("memorytotal") @Param(description="the total memory (in MB) owned by account", since="4.1.0")
+    @SerializedName("memorytotal") @Param(description="the total memory (in MB) owned by account", since="4.2.0")
     private Long memoryTotal;
 
-    @SerializedName("memoryavailable") @Param(description="the total memory (in MB) available to be created for this account", since="4.1.0")
+    @SerializedName("memoryavailable") @Param(description="the total memory (in MB) available to be created for this account", since="4.2.0")
     private String memoryAvailable;
 
+    @SerializedName("primarystoragelimit") @Param(description="the total primary storage space (in GiB) the account can own", since="4.2.0")
+    private String primaryStorageLimit;
+
+    @SerializedName("primarystoragetotal") @Param(description="the total primary storage space (in GiB) owned by account", since="4.2.0")
+    private Long primaryStorageTotal;
+
+    @SerializedName("primarystorageavailable") @Param(description="the total primary storage space (in GiB) available to be used for this account", since="4.2.0")
+    private String primaryStorageAvailable;
+
+    @SerializedName("secondarystoragelimit") @Param(description="the total secondary storage space (in GiB) the account can own", since="4.2.0")
+    private String secondaryStorageLimit;
+
+    @SerializedName("secondarystoragetotal") @Param(description="the total secondary storage space (in GiB) owned by account", since="4.2.0")
+    private Long secondaryStorageTotal;
+
+    @SerializedName("secondarystorageavailable") @Param(description="the total secondary storage space (in GiB) available to be used for this account", since="4.2.0")
+    private String secondaryStorageAvailable;
+
 
     @SerializedName(ApiConstants.STATE) @Param(description="the state of the account")
     private String state;
@@ -336,6 +354,30 @@ public class AccountResponse extends BaseResponse {
         this.memoryAvailable = memoryAvailable;
     }
 
+    public void setPrimaryStorageLimit(String primaryStorageLimit) {
+        this.primaryStorageLimit = primaryStorageLimit;
+    }
+
+    public void setPrimaryStorageTotal(Long primaryStorageTotal) {
+        this.primaryStorageTotal = primaryStorageTotal;
+    }
+
+    public void setPrimaryStorageAvailable(String primaryStorageAvailable) {
+        this.primaryStorageAvailable = primaryStorageAvailable;
+    }
+
+    public void setSecondaryStorageLimit(String secondaryStorageLimit) {
+        this.secondaryStorageLimit = secondaryStorageLimit;
+    }
+
+    public void setSecondaryStorageTotal(Long secondaryStorageTotal) {
+        this.secondaryStorageTotal = secondaryStorageTotal;
+    }
+
+    public void setSecondaryStorageAvailable(String secondaryStorageAvailable) {
+        this.secondaryStorageAvailable = secondaryStorageAvailable;
+    }
+
     public void setDefaultZone(String defaultZoneId) {
         this.defaultZoneId = defaultZoneId;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java
index a7fbbf2..842eaa6 100644
--- a/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java
@@ -40,7 +40,7 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt
     @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name for which resource count's are updated")
     private String domainName;
 
-    @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type. Values include 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. See the resourceType parameter for more information on these values.")
+    @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type. Values include 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. See the resourceType parameter for more information on these values.")
     private String resourceType;
 
     @SerializedName("resourcecount") @Param(description="resource count")

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java
index b444e7a..e7735f5 100644
--- a/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java
@@ -36,7 +36,7 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt
     @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the resource limit")
     private String domainName;
 
-    @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type. Values include 0, 1, 2, 3, 4, 6, 7, 8, 9. See the resourceType parameter for more information on these values.")
+    @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type. Values include 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11. See the resourceType parameter for more information on these values.")
     private String resourceType;
 
     @SerializedName("max") @Param(description="the maximum number of the resource. A -1 means the resource currently has no limit.")

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
index 33725f6..928183b 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/manager/BareMetalTemplateAdapter.java
@@ -50,6 +50,7 @@ import com.cloud.storage.VMTemplateZoneVO;
 import com.cloud.template.TemplateAdapter;
 import com.cloud.template.TemplateAdapterBase;
 import com.cloud.user.Account;
+import com.cloud.utils.UriUtils;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.exception.CloudRuntimeException;
 
@@ -82,7 +83,11 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
 				throw new CloudRuntimeException("Please add PXE server before adding baremetal template in zone " + profile.getZoneId());
 			}
 		}
-		
+
+        // Check that the resource limit for secondary storage won't be exceeded
+        _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
+                ResourceType.secondary_storage, UriUtils.getRemoteSize(profile.getUrl()));
+
 		return profile;
 	}
 	
@@ -133,6 +138,8 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
 		}
 		
 		_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
+        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.secondary_storage,
+                UriUtils.getRemoteSize(profile.getUrl()));
 		return template;
 	}
 
@@ -205,8 +212,10 @@ public class BareMetalTemplateAdapter extends TemplateAdapterBase implements Tem
 					s_logger.debug("Failed to acquire lock when deleting template with ID: " + templateId);
 					success = false;
 				} else if (_tmpltDao.remove(templateId)) {
-					// Decrement the number of templates
-				    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
+                    // Decrement the number of templates and total secondary storage space used by the account.
+                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
+                    _resourceLimitMgr.recalculateResourceCount(accountId, template.getDomainId(),
+                            ResourceType.secondary_storage.getOrdinal());
 				}
 
 			} finally {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/alert/AlertManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java
index a45482f..655ed98 100755
--- a/server/src/com/cloud/alert/AlertManagerImpl.java
+++ b/server/src/com/cloud/alert/AlertManagerImpl.java
@@ -802,7 +802,8 @@ public class AlertManagerImpl extends ManagerBase implements AlertManager {
                     (alertType != AlertManager.ALERT_TYPE_CONSOLE_PROXY) &&
                     (alertType != AlertManager.ALERT_TYPE_SSVM) &&
                     (alertType != AlertManager.ALERT_TYPE_STORAGE_MISC) &&
-                    (alertType != AlertManager.ALERT_TYPE_MANAGMENT_NODE)) {
+                    (alertType != AlertManager.ALERT_TYPE_MANAGMENT_NODE) &&
+                    (alertType != AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED)) {
                 alert = _alertDao.getLastAlert(alertType, dataCenterId, podId, clusterId);
             }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index f33601f..ec80909 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -16,10 +16,32 @@
 // under the License.
 package com.cloud.api;
 
-import com.cloud.api.query.ViewResponseHelper;
-import com.cloud.api.query.vo.*;
-import com.cloud.api.response.ApiResponseSerializer;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.singletonList;
 
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TimeZone;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.acl.ControlledEntity;
+import org.apache.cloudstack.acl.ControlledEntity.ACLType;
+import org.apache.cloudstack.api.ApiConstants.HostDetails;
+import org.apache.cloudstack.api.ApiConstants.VMDetails;
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.api.ResponseGenerator;
+import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
+import org.apache.cloudstack.api.response.AccountResponse;
 import org.apache.cloudstack.api.response.AsyncJobResponse;
 import org.apache.cloudstack.api.response.AutoScalePolicyResponse;
 import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse;
@@ -30,6 +52,7 @@ import org.apache.cloudstack.api.response.ClusterResponse;
 import org.apache.cloudstack.api.response.ConditionResponse;
 import org.apache.cloudstack.api.response.ConfigurationResponse;
 import org.apache.cloudstack.api.response.ControlledEntityResponse;
+import org.apache.cloudstack.api.response.ControlledViewEntityResponse;
 import org.apache.cloudstack.api.response.CounterResponse;
 import org.apache.cloudstack.api.response.CreateCmdResponse;
 import org.apache.cloudstack.api.response.DiskOfferingResponse;
@@ -39,10 +62,10 @@ import org.apache.cloudstack.api.response.EventResponse;
 import org.apache.cloudstack.api.response.ExtractResponse;
 import org.apache.cloudstack.api.response.FirewallResponse;
 import org.apache.cloudstack.api.response.FirewallRuleResponse;
+import org.apache.cloudstack.api.response.GlobalLoadBalancerResponse;
 import org.apache.cloudstack.api.response.GuestOSResponse;
 import org.apache.cloudstack.api.response.HostResponse;
 import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse;
-import org.apache.cloudstack.api.response.ControlledViewEntityResponse;
 import org.apache.cloudstack.api.response.IPAddressResponse;
 import org.apache.cloudstack.api.response.InstanceGroupResponse;
 import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
@@ -56,6 +79,7 @@ import org.apache.cloudstack.api.response.NetworkACLResponse;
 import org.apache.cloudstack.api.response.NetworkOfferingResponse;
 import org.apache.cloudstack.api.response.NetworkResponse;
 import org.apache.cloudstack.api.response.NicResponse;
+import org.apache.cloudstack.api.response.NicSecondaryIpResponse;
 import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
 import org.apache.cloudstack.api.response.PodResponse;
 import org.apache.cloudstack.api.response.PrivateGatewayResponse;
@@ -63,10 +87,12 @@ import org.apache.cloudstack.api.response.ProjectAccountResponse;
 import org.apache.cloudstack.api.response.ProjectInvitationResponse;
 import org.apache.cloudstack.api.response.ProjectResponse;
 import org.apache.cloudstack.api.response.ProviderResponse;
+import org.apache.cloudstack.api.response.RegionResponse;
 import org.apache.cloudstack.api.response.RemoteAccessVpnResponse;
 import org.apache.cloudstack.api.response.ResourceCountResponse;
 import org.apache.cloudstack.api.response.ResourceLimitResponse;
 import org.apache.cloudstack.api.response.ResourceTagResponse;
+import org.apache.cloudstack.api.response.S3Response;
 import org.apache.cloudstack.api.response.SecurityGroupResponse;
 import org.apache.cloudstack.api.response.SecurityGroupRuleResponse;
 import org.apache.cloudstack.api.response.ServiceOfferingResponse;
@@ -90,6 +116,7 @@ import org.apache.cloudstack.api.response.TrafficTypeResponse;
 import org.apache.cloudstack.api.response.UsageRecordResponse;
 import org.apache.cloudstack.api.response.UserResponse;
 import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.cloudstack.api.response.VMSnapshotResponse;
 import org.apache.cloudstack.api.response.VirtualRouterProviderResponse;
 import org.apache.cloudstack.api.response.VlanIpRangeResponse;
 import org.apache.cloudstack.api.response.VolumeResponse;
@@ -97,37 +124,86 @@ import org.apache.cloudstack.api.response.VpcOfferingResponse;
 import org.apache.cloudstack.api.response.VpcResponse;
 import org.apache.cloudstack.api.response.VpnUsersResponse;
 import org.apache.cloudstack.api.response.ZoneResponse;
-import org.apache.cloudstack.api.response.S3Response;
+import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+import org.apache.cloudstack.usage.Usage;
+import org.apache.cloudstack.usage.UsageService;
+import org.apache.cloudstack.usage.UsageTypes;
+import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
+import com.cloud.api.query.ViewResponseHelper;
+import com.cloud.api.query.vo.AccountJoinVO;
+import com.cloud.api.query.vo.AsyncJobJoinVO;
+import com.cloud.api.query.vo.ControlledViewEntity;
+import com.cloud.api.query.vo.DataCenterJoinVO;
+import com.cloud.api.query.vo.DiskOfferingJoinVO;
+import com.cloud.api.query.vo.DomainRouterJoinVO;
+import com.cloud.api.query.vo.EventJoinVO;
+import com.cloud.api.query.vo.HostJoinVO;
+import com.cloud.api.query.vo.InstanceGroupJoinVO;
+import com.cloud.api.query.vo.ProjectAccountJoinVO;
+import com.cloud.api.query.vo.ProjectInvitationJoinVO;
+import com.cloud.api.query.vo.ProjectJoinVO;
+import com.cloud.api.query.vo.ResourceTagJoinVO;
+import com.cloud.api.query.vo.SecurityGroupJoinVO;
+import com.cloud.api.query.vo.ServiceOfferingJoinVO;
+import com.cloud.api.query.vo.StoragePoolJoinVO;
+import com.cloud.api.query.vo.UserAccountJoinVO;
+import com.cloud.api.query.vo.UserVmJoinVO;
+import com.cloud.api.query.vo.VolumeJoinVO;
+import com.cloud.api.response.ApiResponseSerializer;
 import com.cloud.async.AsyncJob;
 import com.cloud.capacity.Capacity;
 import com.cloud.capacity.CapacityVO;
 import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity;
 import com.cloud.configuration.Configuration;
 import com.cloud.configuration.Resource.ResourceOwnerType;
+import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.configuration.ResourceCount;
 import com.cloud.configuration.ResourceLimit;
 import com.cloud.dao.EntityManager;
-import com.cloud.dc.*;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.HostPodVO;
+import com.cloud.dc.Pod;
+import com.cloud.dc.StorageNetworkIpRange;
+import com.cloud.dc.Vlan;
 import com.cloud.dc.Vlan.VlanType;
+import com.cloud.dc.VlanVO;
 import com.cloud.domain.Domain;
 import com.cloud.event.Event;
 import com.cloud.host.Host;
 import com.cloud.host.HostVO;
 import com.cloud.hypervisor.HypervisorCapabilities;
-import com.cloud.network.*;
+import com.cloud.network.IpAddress;
+import com.cloud.network.Network;
 import com.cloud.network.Network.Capability;
 import com.cloud.network.Network.Provider;
 import com.cloud.network.Network.Service;
+import com.cloud.network.NetworkProfile;
 import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.as.*;
+import com.cloud.network.PhysicalNetwork;
+import com.cloud.network.PhysicalNetworkServiceProvider;
+import com.cloud.network.PhysicalNetworkTrafficType;
+import com.cloud.network.RemoteAccessVpn;
+import com.cloud.network.Site2SiteCustomerGateway;
+import com.cloud.network.Site2SiteVpnConnection;
+import com.cloud.network.Site2SiteVpnGateway;
+import com.cloud.network.VirtualRouterProvider;
+import com.cloud.network.VpnUser;
+import com.cloud.network.as.AutoScalePolicy;
+import com.cloud.network.as.AutoScaleVmGroup;
+import com.cloud.network.as.AutoScaleVmProfile;
+import com.cloud.network.as.AutoScaleVmProfileVO;
+import com.cloud.network.as.Condition;
+import com.cloud.network.as.ConditionVO;
+import com.cloud.network.as.Counter;
 import com.cloud.network.dao.IPAddressVO;
 import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.router.VirtualRouter;
-import com.cloud.network.rules.*;
 import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.FirewallRuleVO;
 import com.cloud.network.rules.HealthCheckPolicy;
@@ -156,12 +232,25 @@ import com.cloud.server.Criteria;
 import com.cloud.server.ResourceTag;
 import com.cloud.server.ResourceTag.TaggedResourceType;
 import com.cloud.service.ServiceOfferingVO;
-import com.cloud.storage.*;
+import com.cloud.storage.DiskOfferingVO;
+import com.cloud.storage.GuestOS;
+import com.cloud.storage.GuestOSCategoryVO;
+import com.cloud.storage.S3;
+import com.cloud.storage.Snapshot;
+import com.cloud.storage.SnapshotVO;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.Storage.TemplateType;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.Swift;
+import com.cloud.storage.UploadVO;
+import com.cloud.storage.VMTemplateHostVO;
+import com.cloud.storage.VMTemplateS3VO;
 import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
-
+import com.cloud.storage.VMTemplateSwiftVO;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.Volume;
+import com.cloud.storage.VolumeVO;
 import com.cloud.storage.snapshot.SnapshotPolicy;
 import com.cloud.storage.snapshot.SnapshotSchedule;
 import com.cloud.template.VirtualMachineTemplate;
@@ -179,40 +268,10 @@ import com.cloud.vm.Nic;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
 import com.cloud.vm.VMInstanceVO;
-import com.cloud.vm.NicSecondaryIp;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.Type;
 import com.cloud.vm.dao.NicSecondaryIpVO;
-
-import org.apache.cloudstack.acl.ControlledEntity;
-import org.apache.cloudstack.acl.ControlledEntity.ACLType;
-import org.apache.cloudstack.api.ApiConstants.HostDetails;
-import org.apache.cloudstack.api.ApiConstants.VMDetails;
-import org.apache.cloudstack.api.BaseCmd;
-import org.apache.cloudstack.api.ResponseGenerator;
-import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
-import org.apache.cloudstack.api.response.*;
-import org.apache.cloudstack.region.Region;
-import org.apache.cloudstack.usage.Usage;
-import org.apache.cloudstack.usage.UsageService;
-import org.apache.cloudstack.usage.UsageTypes;
-import com.cloud.vm.VmStats;                                                                                                        
-import com.cloud.vm.dao.UserVmData;                                                                                                 
-import com.cloud.vm.dao.UserVmData.NicData;                                                                                         
-import com.cloud.vm.dao.UserVmData.SecurityGroupData;                                                                               
-import com.cloud.vm.snapshot.VMSnapshot;                                                                                            
-import org.apache.cloudstack.api.ResponseGenerator;                                                                                 
-import org.apache.cloudstack.api.response.VMSnapshotResponse;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
-import java.text.DecimalFormat;
-import java.util.*;
-
-import javax.inject.Inject;
-
-import static java.util.Collections.emptyList;
-import static java.util.Collections.singletonList;
+import com.cloud.vm.snapshot.VMSnapshot;
 
 @Component
 public class ApiResponseHelper implements ResponseGenerator {
@@ -290,7 +349,11 @@ public class ApiResponseHelper implements ResponseGenerator {
             populateDomain(resourceLimitResponse, accountTemp.getDomainId());
         }
         resourceLimitResponse.setResourceType(Integer.valueOf(limit.getType().getOrdinal()).toString());
-        resourceLimitResponse.setMax(limit.getMax());
+        if(limit.getType() == ResourceType.primary_storage || limit.getType() == ResourceType.secondary_storage) {
+            resourceLimitResponse.setMax((long) Math.ceil(limit.getMax()/ResourceType.bytesToGiB));
+        } else {
+            resourceLimitResponse.setMax(limit.getMax());
+        }
         resourceLimitResponse.setObjectName("resourcelimit");
 
         return resourceLimitResponse;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java
index 898bafc..51ac5e6 100644
--- a/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java
@@ -175,6 +175,24 @@ public class AccountJoinDaoImpl extends GenericDaoBase<AccountJoinVO, Long> impl
         accountResponse.setMemoryTotal(memoryTotal);
         accountResponse.setMemoryAvailable(memoryAvail);
 
+      //get resource limits for primary storage space and convert it from Bytes to GiB
+        long primaryStorageLimit = ApiDBUtils.findCorrectResourceLimit(account.getPrimaryStorageLimit(), account.getType(), ResourceType.primary_storage);
+        String primaryStorageLimitDisplay = (accountIsAdmin || primaryStorageLimit == -1) ? "Unlimited" : String.valueOf(primaryStorageLimit / ResourceType.bytesToGiB);
+        long primaryStorageTotal = (account.getPrimaryStorageTotal() == null) ? 0 : (account.getPrimaryStorageTotal() / ResourceType.bytesToGiB);
+        String primaryStorageAvail = (accountIsAdmin || primaryStorageLimit == -1) ? "Unlimited" : String.valueOf((primaryStorageLimit / ResourceType.bytesToGiB) - primaryStorageTotal);
+        accountResponse.setPrimaryStorageLimit(primaryStorageLimitDisplay);
+        accountResponse.setPrimaryStorageTotal(primaryStorageTotal);
+        accountResponse.setPrimaryStorageAvailable(primaryStorageAvail);
+
+        //get resource limits for secondary storage space and convert it from Bytes to GiB
+        long secondaryStorageLimit = ApiDBUtils.findCorrectResourceLimit(account.getSecondaryStorageLimit(), account.getType(), ResourceType.secondary_storage);
+        String secondaryStorageLimitDisplay = (accountIsAdmin || secondaryStorageLimit == -1) ? "Unlimited" : String.valueOf(secondaryStorageLimit / ResourceType.bytesToGiB);
+        long secondaryStorageTotal = (account.getSecondaryStorageTotal() == null) ? 0 : (account.getSecondaryStorageTotal() / ResourceType.bytesToGiB);
+        String secondaryStorageAvail = (accountIsAdmin || secondaryStorageLimit == -1) ? "Unlimited" : String.valueOf((secondaryStorageLimit / ResourceType.bytesToGiB) - secondaryStorageTotal);
+        accountResponse.setSecondaryStorageLimit(secondaryStorageLimitDisplay);
+        accountResponse.setSecondaryStorageTotal(secondaryStorageTotal);
+        accountResponse.setSecondaryStorageAvailable(secondaryStorageAvail);
+
         // adding all the users for an account as part of the response obj
         List<UserAccountJoinVO> usersForAccount = ApiDBUtils.findUserViewByAccountId(account.getId());
         List<UserResponse> userResponses = ViewResponseHelper.createUserResponse(usersForAccount.toArray(new UserAccountJoinVO[usersForAccount.size()]));

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/api/query/vo/AccountJoinVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/query/vo/AccountJoinVO.java b/server/src/com/cloud/api/query/vo/AccountJoinVO.java
index cd7231c..1cb17ef 100644
--- a/server/src/com/cloud/api/query/vo/AccountJoinVO.java
+++ b/server/src/com/cloud/api/query/vo/AccountJoinVO.java
@@ -162,6 +162,20 @@ public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Ident
     @Column(name="memoryTotal")
     private Long memoryTotal;
 
+
+    @Column(name="primaryStorageLimit")
+    private Long primaryStorageLimit;
+
+    @Column(name="primaryStorageTotal")
+    private Long primaryStorageTotal;
+
+
+    @Column(name="secondaryStorageLimit")
+    private Long secondaryStorageLimit;
+
+    @Column(name="secondaryStorageTotal")
+    private Long secondaryStorageTotal;
+
     @Column(name="job_id")
     private long jobId;
 
@@ -478,6 +492,7 @@ public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Ident
         this.cpuTotal = cpuTotal;
     }
 
+
     public Long getMemoryTotal() {
         return memoryTotal;
     }
@@ -488,6 +503,25 @@ public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Ident
     }
 
 
+    public Long getPrimaryStorageTotal() {
+        return primaryStorageTotal;
+    }
+
+
+    public void setPrimaryStorageTotal(Long primaryStorageTotal) {
+        this.primaryStorageTotal = primaryStorageTotal;
+    }
+
+    public Long getSecondaryStorageTotal() {
+        return secondaryStorageTotal;
+    }
+
+
+    public void setSecondaryStorageTotal(Long secondaryStorageTotal) {
+        this.secondaryStorageTotal = secondaryStorageTotal;
+    }
+
+
     public Long getVmLimit() {
         return vmLimit;
     }
@@ -588,6 +622,26 @@ public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Ident
     }
 
 
+    public Long getPrimaryStorageLimit() {
+        return primaryStorageLimit;
+    }
+
+
+    public void setPrimaryStorageLimit(Long primaryStorageLimit) {
+        this.primaryStorageLimit = primaryStorageLimit;
+    }
+
+
+    public Long getSecondaryStorageLimit() {
+        return secondaryStorageLimit;
+    }
+
+
+    public void setSecondaryStorageLimit(Long secondaryStorageLimit) {
+        this.secondaryStorageLimit = secondaryStorageLimit;
+    }
+
+
     public long getJobId() {
         return jobId;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/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 ba4ae62..5b2616f 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -323,7 +323,8 @@ public enum Config {
 	DefaultMaxAccountVpcs("Account Defaults", ManagementServer.class, Long.class, "max.account.vpcs", "20", "The default maximum number of vpcs that can be created for an account", null),
 	DefaultMaxAccountCpus("Account Defaults", ManagementServer.class, Long.class, "max.account.cpus", "40", "The default maximum number of cpu cores that can be used for an account", null),
 	DefaultMaxAccountMemory("Account Defaults", ManagementServer.class, Long.class, "max.account.memory", "40960", "The default maximum memory (in MB) that can be used for an account", null),
-
+	DefaultMaxAccountPrimayStorage("Account Defaults", ManagementServer.class, Long.class, "max.account.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an account", null),
+	DefaultMaxAccountSecondaryStorage("Account Defaults", ManagementServer.class, Long.class, "max.account.secondary.storage", "400", "The default maximum secondary storage space (in GiB) that can be used for an account", null),
 
 	ResourceCountCheckInterval("Advanced", ManagementServer.class, Long.class, "resourcecount.check.interval", "0", "Time (in seconds) to wait before retrying resource count check task. Default is 0 which is to never run the task", "Seconds"),
 	DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null),
@@ -349,6 +350,8 @@ public enum Config {
     DefaultMaxProjectVpcs("Project Defaults", ManagementServer.class, Long.class, "max.project.vpcs", "20", "The default maximum number of vpcs that can be created for a project", null),
     DefaultMaxProjectCpus("Project Defaults", ManagementServer.class, Long.class, "max.project.cpus", "40", "The default maximum number of cpu cores that can be used for a project", null),
     DefaultMaxProjectMemory("Project Defaults", ManagementServer.class, Long.class, "max.project.memory", "40960", "The default maximum memory (in MB) that can be used for a project", null),
+    DefaultMaxProjectPrimayStorage("Project Defaults", ManagementServer.class, Long.class, "max.project.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an project", null),
+    DefaultMaxProjectSecondaryStorage("Project Defaults", ManagementServer.class, Long.class, "max.project.secondary.storage", "400", "The default maximum secondary storage space (in GiB) that can be used for an project", null),
 
     ProjectInviteRequired("Project Defaults", ManagementServer.class, Boolean.class, "project.invite.required", "false", "If invitation confirmation is required when add account to project. Default value is false", null),
     ProjectInvitationExpirationTime("Project Defaults", ManagementServer.class, Long.class, "project.invite.timeout", "86400", "Invitation expiration time (in seconds). Default is 1 day - 86400 seconds", null),

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
index 23c0796..bbe0190 100755
--- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
+++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
@@ -61,8 +61,12 @@ import com.cloud.projects.dao.ProjectAccountDao;
 import com.cloud.projects.dao.ProjectDao;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.storage.VMTemplateHostVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
+import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.dao.SnapshotDao;
 import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.storage.dao.VMTemplateHostDao;
 import com.cloud.storage.dao.VolumeDao;
 import com.cloud.storage.dao.VolumeDaoImpl.SumCount;
 import com.cloud.user.Account;
@@ -135,6 +139,10 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
     private VpcDao _vpcDao;
     @Inject
     private ServiceOfferingDao _serviceOfferingDao;
+    @Inject
+    private VMTemplateHostDao _vmTemplateHostDao;
+
+    protected GenericSearchBuilder<VMTemplateHostVO, SumCount> templateSizeSearch;
 
     protected SearchBuilder<ResourceCountVO> ResourceCountSearch;
     ScheduledExecutorService _rcExecutor;
@@ -164,6 +172,15 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
         ResourceCountSearch.and("domainId", ResourceCountSearch.entity().getDomainId(), SearchCriteria.Op.EQ);
         ResourceCountSearch.done();
 
+        templateSizeSearch = _vmTemplateHostDao.createSearchBuilder(SumCount.class);
+        templateSizeSearch.select("sum", Func.SUM, templateSizeSearch.entity().getSize());
+        templateSizeSearch.and("downloadState", templateSizeSearch.entity().getDownloadState(), Op.EQ);
+        templateSizeSearch.and("destroyed", templateSizeSearch.entity().getDestroyed(), Op.EQ);
+        SearchBuilder<VMTemplateVO> join1 = _vmTemplateDao.createSearchBuilder();
+        join1.and("accountId", join1.entity().getAccountId(), Op.EQ);
+        templateSizeSearch.join("templates", join1, templateSizeSearch.entity().getTemplateId(), join1.entity().getId(), JoinBuilder.JoinType.INNER);
+        templateSizeSearch.done();
+
         _resourceCountCheckInterval = NumbersUtil.parseInt(_configDao.getValue(Config.ResourceCountCheckInterval.key()), 0);
         if (_resourceCountCheckInterval > 0) {
             _rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker"));
@@ -178,6 +195,8 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
         projectResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVpcs.key())));
         projectResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectCpus.key())));
         projectResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectMemory.key())));
+        projectResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPrimayStorage.key())));
+        projectResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSecondaryStorage.key())));
 
         accountResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPublicIPs.key())));
         accountResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.key())));
@@ -188,6 +207,8 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
         accountResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVpcs.key())));
         accountResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountCpus.key())));
         accountResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountMemory.key())));
+        accountResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPrimayStorage.key())));
+        accountResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key())));
 
         return true;
     }
@@ -246,6 +267,10 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
                 value = accountResourceLimitMap.get(type);
             }
             if (value != null) {
+                // convert the value from GiB to bytes in case of primary or secondary storage.
+                if (type == ResourceType.primary_storage || type == ResourceType.secondary_storage) {
+                    value = value * ResourceType.bytesToGiB;
+                }
                 return value;
             }
         }
@@ -276,6 +301,9 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
                 value = accountResourceLimitMap.get(type);
             }
             if (value != null) {
+                if (type == ResourceType.primary_storage || type == ResourceType.secondary_storage) {
+                    value = value * ResourceType.bytesToGiB;
+                }
                 return value;
             }
         }
@@ -548,6 +576,11 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
             }
         }
 
+        //Convert max storage size from GiB to bytes
+        if (resourceType == ResourceType.primary_storage || resourceType == ResourceType.secondary_storage) {
+            max = max * ResourceType.bytesToGiB;
+        }
+
         ResourceOwnerType ownerType = null;
         Long ownerId = null;
 
@@ -789,6 +822,10 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
             newCount = countCpusForAccount(accountId);
         } else if (type == Resource.ResourceType.memory) {
             newCount = calculateMemoryForAccount(accountId);
+        } else if (type == Resource.ResourceType.primary_storage) {
+            newCount = _volumeDao.primaryStorageUsedForAccount(accountId);
+        } else if (type == Resource.ResourceType.secondary_storage) {
+            newCount = calculateSecondaryStorageForAccount(accountId);
         } else {
             throw new InvalidParameterValueException("Unsupported resource type " + type);
         }
@@ -847,6 +884,23 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
         }
     }
 
+    public long calculateSecondaryStorageForAccount(long accountId) {
+        long totalVolumesSize = _volumeDao.secondaryStorageUsedForAccount(accountId);
+        long totalSnapshotsSize = _snapshotDao.secondaryStorageUsedForAccount(accountId);
+        long totalTemplatesSize = 0;
+
+        SearchCriteria<SumCount> sc = templateSizeSearch.create();
+        sc.setParameters("downloadState", Status.DOWNLOADED);
+        sc.setParameters("destroyed", false);
+        sc.setJoinParameters("templates", "accountId", accountId);
+        List<SumCount> templates = _vmTemplateHostDao.customSearch(sc, null);
+        if (templates != null) {
+            totalTemplatesSize = templates.get(0).sum;
+        }
+
+        return totalVolumesSize + totalSnapshotsSize + totalTemplatesSize;
+    }
+
     @Override
     public long getResourceCount(Account account, ResourceType type) {
         return _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/VolumeManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/VolumeManager.java b/server/src/com/cloud/storage/VolumeManager.java
index af3cbbf..2101038 100644
--- a/server/src/com/cloud/storage/VolumeManager.java
+++ b/server/src/com/cloud/storage/VolumeManager.java
@@ -61,7 +61,8 @@ public interface VolumeManager extends VolumeApiService {
 
     VolumeVO createVolume(CreateVolumeCmd cmd);
 
-    VolumeVO resizeVolume(ResizeVolumeCmd cmd);
+    VolumeVO resizeVolume(ResizeVolumeCmd cmd)
+            throws ResourceAllocationException;
 
     boolean deleteVolume(long volumeId, Account caller)
             throws ConcurrentOperationException;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/VolumeManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/VolumeManagerImpl.java b/server/src/com/cloud/storage/VolumeManagerImpl.java
index 737ed0a..ff0235f 100644
--- a/server/src/com/cloud/storage/VolumeManagerImpl.java
+++ b/server/src/com/cloud/storage/VolumeManagerImpl.java
@@ -146,6 +146,7 @@ import com.cloud.uservm.UserVm;
 import com.cloud.utils.EnumUtils;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
+import com.cloud.utils.UriUtils;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.JoinBuilder;
@@ -469,6 +470,10 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
         }
         validateUrl(url);
 
+        // Check that the resource limit for secondary storage won't be exceeded
+        _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.secondary_storage,
+                UriUtils.getRemoteSize(url));
+
         return false;
     }
     
@@ -736,6 +741,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
         // decrement it
         _resourceLimitMgr.incrementResourceCount(volume.getAccountId(),
                 ResourceType.volume);
+        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage,
+                UriUtils.getRemoteSize(url));
 
         txn.commit();
         return volume;
@@ -906,6 +913,10 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
             _accountMgr.checkAccess(caller, null, true, snapshotCheck);
         }
 
+        // Check that the resource limit for primary storage won't be exceeded
+        _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(ownerId), ResourceType.primary_storage,
+                new Long(size));
+
         // Verify that zone exists
         DataCenterVO zone = _dcDao.findById(zoneId);
         if (zone == null) {
@@ -974,6 +985,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
         // decrement it
         _resourceLimitMgr.incrementResourceCount(volume.getAccountId(),
                 ResourceType.volume);
+        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                new Long(volume.getSize()));
 
         txn.commit();
 
@@ -1006,6 +1019,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
                         + " as volume failed to create on the backend");
                 _resourceLimitMgr.decrementResourceCount(volume.getAccountId(),
                         ResourceType.volume);
+                _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                        new Long(volume.getSize()));
             }
         }
     }
@@ -1013,7 +1028,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_VOLUME_RESIZE, eventDescription = "resizing volume", async = true)
-    public VolumeVO resizeVolume(ResizeVolumeCmd cmd) {
+    public VolumeVO resizeVolume(ResizeVolumeCmd cmd)
+            throws ResourceAllocationException {
         Long newSize = null;
         boolean shrinkOk = cmd.getShrinkOk();
         
@@ -1149,6 +1165,12 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
                             + " would shrink the volume, need to sign off by supplying the shrinkok parameter with value of true");
         }
 
+        if (!shrinkOk) {
+            /* Check resource limit for this account on primary storage resource */
+            _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()),
+                    ResourceType.primary_storage, new Long(newSize - currentSize));
+        }
+
         /*
          * get a list of hosts to send the commands to, try the system the
          * associated vm is running on first, then the last known place it ran.
@@ -1176,27 +1198,35 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
         ResizeVolumePayload payload = new ResizeVolumePayload(newSize, shrinkOk, instanceName, hosts);
         
         try {
-        	VolumeInfo vol = this.volFactory.getVolume(volume.getId());
+            VolumeInfo vol = this.volFactory.getVolume(volume.getId());
             vol.addPayload(payload);
-            
-        	AsyncCallFuture<VolumeApiResult> future = this.volService.resize(vol);
-        	future.get();
-        	volume = _volsDao.findById(volume.getId());
-
-        	if (newDiskOffering != null) {
-        		volume.setDiskOfferingId(cmd.getNewDiskOfferingId());
-        	}
-        	_volsDao.update(volume.getId(), volume);
-
-        	return volume;
-		} catch (InterruptedException e) {
-			s_logger.debug("failed get resize volume result", e);
-		} catch (ExecutionException e) {
-			s_logger.debug("failed get resize volume result", e);
-		} catch (Exception e) {
-			s_logger.debug("failed get resize volume result", e);
-		}
-       
+
+            AsyncCallFuture<VolumeApiResult> future = this.volService.resize(vol);
+            future.get();
+            volume = _volsDao.findById(volume.getId());
+
+            if (newDiskOffering != null) {
+                volume.setDiskOfferingId(cmd.getNewDiskOfferingId());
+            }
+            _volsDao.update(volume.getId(), volume);
+
+            /* Update resource count for the account on primary storage resource */
+            if (!shrinkOk) {
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                        new Long(newSize - currentSize));
+            } else {
+                _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                        new Long(currentSize - newSize));
+            }
+            return volume;
+        } catch (InterruptedException e) {
+            s_logger.debug("failed get resize volume result", e);
+        } catch (ExecutionException e) {
+            s_logger.debug("failed get resize volume result", e);
+        } catch (Exception e) {
+            s_logger.debug("failed get resize volume result", e);
+        }
+
         return null;
     }
     
@@ -1243,9 +1273,19 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
                 VMInstanceVO vmInstance = this._vmInstanceDao.findById(instanceId);
                 if (instanceId == null
                         || (vmInstance.getType().equals(VirtualMachine.Type.User))) {
-                    // Decrement the resource count for volumes belonging user VM's only
+                    // Decrement the resource count for volumes and primary storage belonging user VM's only
                     _resourceLimitMgr.decrementResourceCount(volume.getAccountId(),
                             ResourceType.volume);
+                    /* If volume is in primary storage, decrement primary storage count else decrement secondary
+                     storage count (in case of upload volume). */
+                    if (volume.getFolder() != null) {
+                        _resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                                new Long(volume.getSize()));
+                    } else {
+                        _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(),
+                                ResourceType.secondary_storage.getOrdinal());
+                    }
+
                     // Log usage event for volumes belonging user VM's only
                     UsageEventVO usageEvent = new UsageEventVO(
                             EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(),
@@ -1317,6 +1357,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
 
             _resourceLimitMgr.incrementResourceCount(vm.getAccountId(),
                     ResourceType.volume);
+            _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage,
+                    new Long(vol.getSize()));
         }
         return toDiskProfile(vol, offering);
     }
@@ -1364,6 +1406,8 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
 
             _resourceLimitMgr.incrementResourceCount(vm.getAccountId(),
                     ResourceType.volume);
+            _resourceLimitMgr.incrementResourceCount(vm.getAccountId(), ResourceType.primary_storage,
+                    new Long(vol.getSize()));
         }
         return toDiskProfile(vol, offering);
     }
@@ -1435,6 +1479,13 @@ public class VolumeManagerImpl extends ManagerBase implements VolumeManager {
             vol = copyVolume(rootDiskPool
                     , volume, vm, rootDiskTmplt,  dcVO,
                     pod,  diskVO,  svo,  rootDiskHyperType);
+            if (vol != null) {
+                // Moving of Volume is successful, decrement the volume resource count from secondary for an account and increment it into primary storage under same account.
+                _resourceLimitMgr.decrementResourceCount(volume.getAccountId(),
+                        ResourceType.secondary_storage, new Long(volume.getSize()));
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(),
+                        ResourceType.primary_storage, new Long(volume.getSize()));
+            }
         }
         return vol;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/dao/SnapshotDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/SnapshotDao.java b/server/src/com/cloud/storage/dao/SnapshotDao.java
index 0e378a7..3ac9e77 100644
--- a/server/src/com/cloud/storage/dao/SnapshotDao.java
+++ b/server/src/com/cloud/storage/dao/SnapshotDao.java
@@ -40,7 +40,15 @@ public interface SnapshotDao extends GenericDao<SnapshotVO, Long>, StateDao<Snap
     List<SnapshotVO> listByHostId(Filter filter, long hostId);
     List<SnapshotVO> listByHostId(long hostId);
     public Long countSnapshotsForAccount(long accountId);
-	List<SnapshotVO> listByInstanceId(long instanceId, Snapshot.State... status);
-	List<SnapshotVO> listByStatus(long volumeId, Snapshot.State... status);
+    List<SnapshotVO> listByInstanceId(long instanceId, Snapshot.State... status);
+    List<SnapshotVO> listByStatus(long volumeId, Snapshot.State... status);
     List<SnapshotVO> listAllByStatus(Snapshot.State... status);
+    /**
+     * Gets the Total Secondary Storage space (in bytes) used by snapshots allocated for an account
+     *
+     * @param account
+     * @return total Secondary Storage space allocated
+     */
+    long secondaryStorageUsedForAccount(long accountId);
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java b/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java
index 825b6d5..f55663f 100644
--- a/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/SnapshotDaoImpl.java
@@ -35,15 +35,20 @@ import com.cloud.storage.Snapshot.Type;
 import com.cloud.storage.SnapshotVO;
 import com.cloud.storage.Volume;
 import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.VolumeDaoImpl.SumCount;
 import com.cloud.tags.dao.ResourceTagDao;
-import com.cloud.tags.dao.ResourceTagsDaoImpl;
-
-import com.cloud.utils.db.*;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.GenericSearchBuilder;
 import com.cloud.utils.db.JoinBuilder.JoinType;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.SearchCriteria.Func;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.Transaction;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.dao.VMInstanceDao;
-import com.cloud.vm.dao.VMInstanceDaoImpl;
 
 @Component
 @Local (value={SnapshotDao.class})
@@ -53,19 +58,19 @@ public class SnapshotDaoImpl extends GenericDaoBase<SnapshotVO, Long> implements
     private static final String UPDATE_SNAPSHOT_VERSION = "UPDATE snapshots SET version = ? WHERE volume_id = ? AND version = ?";
     private static final String GET_SECHOST_ID = "SELECT sechost_id FROM snapshots where volume_id = ? AND backup_snap_id IS NOT NULL AND sechost_id IS NOT NULL LIMIT 1";
     private static final String UPDATE_SECHOST_ID = "UPDATE snapshots SET sechost_id = ? WHERE data_center_id = ?";
-    
+
     private SearchBuilder<SnapshotVO> VolumeIdSearch;
     private SearchBuilder<SnapshotVO> VolumeIdTypeSearch;
     private SearchBuilder<SnapshotVO> ParentIdSearch;
-    private SearchBuilder<SnapshotVO> backupUuidSearch;   
+    private SearchBuilder<SnapshotVO> backupUuidSearch;
     private SearchBuilder<SnapshotVO> VolumeIdVersionSearch;
     private SearchBuilder<SnapshotVO> HostIdSearch;
     private SearchBuilder<SnapshotVO> AccountIdSearch;
     private SearchBuilder<SnapshotVO> InstanceIdSearch;
     private SearchBuilder<SnapshotVO> StatusSearch;
     private GenericSearchBuilder<SnapshotVO, Long> CountSnapshotsByAccount;
+    private GenericSearchBuilder<SnapshotVO, SumCount> secondaryStorageSearch;
     @Inject ResourceTagDao _tagsDao;
-    
     @Inject protected VMInstanceDao _instanceDao;
     @Inject protected VolumeDao _volumeDao;
 
@@ -187,23 +192,29 @@ public class SnapshotDaoImpl extends GenericDaoBase<SnapshotVO, Long> implements
         CountSnapshotsByAccount.and("removed", CountSnapshotsByAccount.entity().getRemoved(), SearchCriteria.Op.NULL);
         CountSnapshotsByAccount.done();
         
-    	InstanceIdSearch = createSearchBuilder();
+        InstanceIdSearch = createSearchBuilder();
         InstanceIdSearch.and("status", InstanceIdSearch.entity().getState(), SearchCriteria.Op.IN);
-    	
-    	SearchBuilder<VMInstanceVO> instanceSearch = _instanceDao.createSearchBuilder();
-    	instanceSearch.and("instanceId", instanceSearch.entity().getId(), SearchCriteria.Op.EQ);
-    	
-    	SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
-    	volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ);
-    	volumeSearch.join("instanceVolumes", instanceSearch, instanceSearch.entity().getId(), volumeSearch.entity().getInstanceId(), JoinType.INNER);
-    	
-    	InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch.entity().getVolumeId(), JoinType.INNER);
-    	InstanceIdSearch.done();
+
+        SearchBuilder<VMInstanceVO> instanceSearch = _instanceDao.createSearchBuilder();
+        instanceSearch.and("instanceId", instanceSearch.entity().getId(), SearchCriteria.Op.EQ);
+
+        SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
+        volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ);
+        volumeSearch.join("instanceVolumes", instanceSearch, instanceSearch.entity().getId(), volumeSearch.entity().getInstanceId(), JoinType.INNER);
+
+        InstanceIdSearch.join("instanceSnapshots", volumeSearch, volumeSearch.entity().getId(), InstanceIdSearch.entity().getVolumeId(), JoinType.INNER);
+        InstanceIdSearch.done();
+
+        secondaryStorageSearch = createSearchBuilder(SumCount.class);
+        secondaryStorageSearch.select("sum", Func.SUM, secondaryStorageSearch.entity().getSize());
+        secondaryStorageSearch.and("accountId", secondaryStorageSearch.entity().getAccountId(), Op.EQ);
+        secondaryStorageSearch.and("isRemoved", secondaryStorageSearch.entity().getRemoved(), Op.NULL);
+        secondaryStorageSearch.done();
     }
-    
-    @Override 
+
+    @Override
     public Long getSecHostId(long volumeId) {
-        
+
         Transaction txn = Transaction.currentTxn();
         PreparedStatement pstmt = null;
         String sql = GET_SECHOST_ID;
@@ -331,4 +342,16 @@ public class SnapshotDaoImpl extends GenericDaoBase<SnapshotVO, Long> implements
         txn.commit();
         return true;
     }
+
+    @Override
+    public long secondaryStorageUsedForAccount(long accountId) {
+        SearchCriteria<SumCount> sc = secondaryStorageSearch.create();
+        sc.setParameters("accountId", accountId);
+        List<SumCount> storageSpace = customSearch(sc, null);
+        if (storageSpace != null) {
+            return storageSpace.get(0).sum;
+        } else {
+            return 0;
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/dao/VolumeDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VolumeDao.java b/server/src/com/cloud/storage/dao/VolumeDao.java
index d7a2667..2513181 100755
--- a/server/src/com/cloud/storage/dao/VolumeDao.java
+++ b/server/src/com/cloud/storage/dao/VolumeDao.java
@@ -27,50 +27,66 @@ import com.cloud.utils.db.GenericDao;
 import com.cloud.utils.fsm.StateDao;
 
 public interface VolumeDao extends GenericDao<VolumeVO, Long>, StateDao<Volume.State, Volume.Event, Volume> {
-    
-	List<VolumeVO> findDetachedByAccount(long accountId);
-	
+
+    List<VolumeVO> findDetachedByAccount(long accountId);
+
     List<VolumeVO> findByAccount(long accountId);
-    
+
     Pair<Long, Long> getCountAndTotalByPool(long poolId);
-    
+
     Pair<Long, Long> getNonDestroyedCountAndTotalByPool(long poolId);
-    
+
     List<VolumeVO> findByInstance(long id);
-    
+
     List<VolumeVO> findByInstanceAndType(long id, Volume.Type vType);
-    
+
     List<VolumeVO> findByInstanceIdDestroyed(long vmId);
-    
+
     List<VolumeVO> findByAccountAndPod(long accountId, long podId);
-    
+
     List<VolumeVO> findByTemplateAndZone(long templateId, long zoneId);
-    
+
     void deleteVolumesByInstance(long instanceId);
-    
+
     void attachVolume(long volumeId, long vmId, long deviceId);
-    
+
     void detachVolume(long volumeId);
-    
+
     boolean isAnyVolumeActivelyUsingTemplateOnPool(long templateId, long poolId);
-    
+
     List<VolumeVO> findCreatedByInstance(long id);
-    
+
     List<VolumeVO> findByPoolId(long poolId);
-    
-	List<VolumeVO> findByInstanceAndDeviceId(long instanceId, long deviceId);
-	
+
+    List<VolumeVO> findByInstanceAndDeviceId(long instanceId, long deviceId);
+
     List<VolumeVO> findUsableVolumesForInstance(long instanceId);
-    
+
     Long countAllocatedVolumesForAccount(long accountId); 
-   
+
     HypervisorType getHypervisorType(long volumeId);
-    
+
     List<VolumeVO> listVolumesToBeDestroyed();
-    
+
     ImageFormat getImageFormat(Long volumeId);
-    
+
     List<VolumeVO> findReadyRootVolumesByInstance(long instanceId);
-    
+
     List<Long> listPoolIdsByVolumeCount(long dcId, Long podId, Long clusterId, long accountId);
+
+    /**
+     * Gets the Total Primary Storage space allocated for an account
+     *
+     * @param account
+     * @return total Primary Storage space (in bytes) used
+     */
+    long primaryStorageUsedForAccount(long accountId);
+
+    /**
+     * Gets the Total Secondary Storage space used by volumes allocated for an account
+     *
+     * @param account
+     * @return total Secondary Storage space (in bytes) used
+     */
+    long secondaryStorageUsedForAccount(long accountId);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
index 40ed875..12ca3c7 100755
--- a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
@@ -38,7 +38,6 @@ import com.cloud.storage.Volume.State;
 import com.cloud.storage.Volume.Type;
 import com.cloud.storage.VolumeVO;
 import com.cloud.tags.dao.ResourceTagDao;
-import com.cloud.tags.dao.ResourceTagsDaoImpl;
 import com.cloud.utils.Pair;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;
@@ -62,8 +61,10 @@ public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements Vol
     protected final SearchBuilder<VolumeVO> InstanceStatesSearch;
     protected final SearchBuilder<VolumeVO> AllFieldsSearch;
     protected GenericSearchBuilder<VolumeVO, Long> CountByAccount;
+    protected GenericSearchBuilder<VolumeVO, SumCount> primaryStorageSearch;
+    protected GenericSearchBuilder<VolumeVO, SumCount> secondaryStorageSearch;
     @Inject ResourceTagDao _tagsDao;
-    
+
     protected static final String SELECT_VM_SQL = "SELECT DISTINCT instance_id from volumes v where v.host_id = ? and v.mirror_state = ?";
     protected static final String SELECT_HYPERTYPE_FROM_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?";
 
@@ -298,8 +299,22 @@ public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements Vol
         CountByAccount = createSearchBuilder(Long.class);
         CountByAccount.select(null, Func.COUNT, null);
         CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
-        CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN);        
+        CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN);
         CountByAccount.done();
+
+        primaryStorageSearch = createSearchBuilder(SumCount.class);
+        primaryStorageSearch.select("sum", Func.SUM, primaryStorageSearch.entity().getSize());
+        primaryStorageSearch.and("accountId", primaryStorageSearch.entity().getAccountId(), Op.EQ);
+        primaryStorageSearch.and("path", primaryStorageSearch.entity().getPath(), Op.NNULL);
+        primaryStorageSearch.and("isRemoved", primaryStorageSearch.entity().getRemoved(), Op.NULL);
+        primaryStorageSearch.done();
+
+        secondaryStorageSearch = createSearchBuilder(SumCount.class);
+        secondaryStorageSearch.select("sum", Func.SUM, secondaryStorageSearch.entity().getSize());
+        secondaryStorageSearch.and("accountId", secondaryStorageSearch.entity().getAccountId(), Op.EQ);
+        secondaryStorageSearch.and("path", secondaryStorageSearch.entity().getPath(), Op.NULL);
+        secondaryStorageSearch.and("isRemoved", secondaryStorageSearch.entity().getRemoved(), Op.NULL);
+        secondaryStorageSearch.done();
 	}
 
 	@Override @DB(txn=false)
@@ -316,9 +331,34 @@ public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements Vol
 	  	SearchCriteria<Long> sc = CountByAccount.create();
         sc.setParameters("account", accountId);
 		sc.setParameters("state", Volume.State.Destroy);
-        return customSearch(sc, null).get(0);		
+        return customSearch(sc, null).get(0);
 	}
 
+    @Override
+    public long primaryStorageUsedForAccount(long accountId) {
+        SearchCriteria<SumCount> sc = primaryStorageSearch.create();
+        sc.setParameters("accountId", accountId);
+        List<SumCount> storageSpace = customSearch(sc, null);
+        if (storageSpace != null) {
+            return storageSpace.get(0).sum;
+        } else {
+            return 0;
+        }
+    }
+
+    @Override
+    public long secondaryStorageUsedForAccount(long accountId) {
+        SearchCriteria<SumCount> sc = secondaryStorageSearch.create();
+        sc.setParameters("accountId", accountId);
+        List<SumCount> storageSpace = customSearch(sc, null);
+        if (storageSpace != null) {
+            return storageSpace.get(0).sum;
+        } else {
+            return 0;
+        }
+    }
+
+
 	public static class SumCount {
 	    public long sum;
 	    public long count;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/download/DownloadListener.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/download/DownloadListener.java b/server/src/com/cloud/storage/download/DownloadListener.java
index d4c20cf..1d48803 100755
--- a/server/src/com/cloud/storage/download/DownloadListener.java
+++ b/server/src/com/cloud/storage/download/DownloadListener.java
@@ -22,6 +22,8 @@ import java.util.Map;
 import java.util.Timer;
 import java.util.TimerTask;
 
+import javax.inject.Inject;
+
 import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 
@@ -36,28 +38,31 @@ import com.cloud.agent.api.StartupSecondaryStorageCommand;
 import com.cloud.agent.api.StartupStorageCommand;
 import com.cloud.agent.api.storage.DownloadAnswer;
 import com.cloud.agent.api.storage.DownloadCommand;
-import com.cloud.agent.api.storage.DownloadProgressCommand;
 import com.cloud.agent.api.storage.DownloadCommand.ResourceType;
+import com.cloud.agent.api.storage.DownloadProgressCommand;
 import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType;
+import com.cloud.alert.AlertManager;
 import com.cloud.exception.AgentUnavailableException;
 import com.cloud.exception.ConnectionException;
+import com.cloud.exception.ResourceAllocationException;
 import com.cloud.host.HostVO;
-
+import com.cloud.host.dao.HostDao;
 import com.cloud.storage.Storage;
 import com.cloud.storage.StorageManager;
 import com.cloud.storage.VMTemplateHostVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.VolumeHostVO;
 import com.cloud.storage.VolumeVO;
-import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
-import com.cloud.storage.Volume.Event;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VMTemplateHostDao;
 import com.cloud.storage.dao.VolumeDao;
 import com.cloud.storage.dao.VolumeHostDao;
 import com.cloud.storage.download.DownloadState.DownloadEvent;
+import com.cloud.user.AccountManager;
+import com.cloud.user.ResourceLimitService;
+import com.cloud.utils.UriUtils;
 import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.fsm.NoTransitionException;
 
 /**
  * Monitor progress of template download to a single storage server
@@ -119,6 +124,9 @@ public class DownloadListener implements Listener {
 	private StorageManager _storageMgr;
 	private VMTemplateHostDao vmTemplateHostDao;
 	private VMTemplateDao _vmTemplateDao;
+	private ResourceLimitService _resourceLimitMgr;
+	private AccountManager _accountMgr;
+	private AlertManager _alertMgr;
 
 	private final DownloadMonitorImpl downloadMonitor;
 	
@@ -137,7 +145,7 @@ public class DownloadListener implements Listener {
 	private Long templateHostId;
 	private Long volumeHostId;
 	
-	public DownloadListener(HostVO ssAgent, HostVO host, VMTemplateVO template, Timer _timer, VMTemplateHostDao dao, Long templHostId, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, VMTemplateDao templateDao) {
+	public DownloadListener(HostVO ssAgent, HostVO host, VMTemplateVO template, Timer _timer, VMTemplateHostDao dao, Long templHostId, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, VMTemplateDao templateDao, ResourceLimitService _resourceLimitMgr, AlertManager _alertMgr, AccountManager _accountMgr) {
 	    this.ssAgent = ssAgent;
         this.sserver = host;
 		this.template = template;
@@ -151,10 +159,13 @@ public class DownloadListener implements Listener {
 		this.timeoutTask = new TimeoutTask(this);
 		this.timer.schedule(timeoutTask, 3*STATUS_POLL_INTERVAL);
 		this._vmTemplateDao = templateDao;
+		this._resourceLimitMgr = _resourceLimitMgr;
+		this._accountMgr = _accountMgr;
+		this._alertMgr = _alertMgr;
 		updateDatabase(Status.NOT_DOWNLOADED, "");
 	}
 	
-	public DownloadListener(HostVO ssAgent, HostVO host, VolumeVO volume, Timer _timer, VolumeHostDao dao, Long volHostId, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, VolumeDao volumeDao, StorageManager storageMgr) {
+	public DownloadListener(HostVO ssAgent, HostVO host, VolumeVO volume, Timer _timer, VolumeHostDao dao, Long volHostId, DownloadMonitorImpl downloadMonitor, DownloadCommand cmd, VolumeDao volumeDao, StorageManager storageMgr, ResourceLimitService _resourceLimitMgr, AlertManager _alertMgr, AccountManager _accountMgr) {
 	    this.ssAgent = ssAgent;
         this.sserver = host;
 		this.volume = volume;
@@ -169,6 +180,9 @@ public class DownloadListener implements Listener {
 		this.timer.schedule(timeoutTask, 3*STATUS_POLL_INTERVAL);
 		this._volumeDao = volumeDao;
 		this._storageMgr = storageMgr;
+		this._resourceLimitMgr = _resourceLimitMgr;
+		this._accountMgr = _accountMgr;
+		this._alertMgr = _alertMgr;
 		updateDatabase(Status.NOT_DOWNLOADED, "");
 	}
 	
@@ -332,6 +346,24 @@ public class DownloadListener implements Listener {
 				templateDaoBuilder.setChecksum(answer.getCheckSum());
 				_vmTemplateDao.update(template.getId(), templateDaoBuilder);
 			}
+
+            if (answer.getTemplateSize() > 0) {
+                //long hostId = vmTemplateHostDao.findByTemplateId(template.getId()).getHostId();
+                long accountId = template.getAccountId();
+                try {
+                    _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(accountId),
+                            com.cloud.configuration.Resource.ResourceType.secondary_storage,
+                            answer.getTemplateSize() - UriUtils.getRemoteSize(template.getUrl()));
+                } catch (ResourceAllocationException e) {
+                    s_logger.warn(e.getMessage());
+                    _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, sserver.getDataCenterId(),
+                            null, e.getMessage(), e.getMessage());
+                } finally {
+                    _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(),
+                            com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                }
+            }
+
 		} else {
 	        VolumeHostVO updateBuilder = volumeHostDao.createForUpdate();
 			updateBuilder.setDownloadPercent(answer.getDownloadPct());
@@ -351,6 +383,22 @@ public class DownloadListener implements Listener {
 			updateVolume.setSize(answer.getTemplateSize());
 			_volumeDao.update(volume.getId(), updateVolume);
 
+            if (answer.getTemplateSize() > 0) {
+                try {
+                    String url = volumeHostDao.findByVolumeId(volume.getId()).getDownloadUrl();
+                    _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()),
+                            com.cloud.configuration.Resource.ResourceType.secondary_storage,
+                            answer.getTemplateSize() - UriUtils.getRemoteSize(url));
+                } catch (ResourceAllocationException e) {
+                    s_logger.warn(e.getMessage());
+                    _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(),
+                            volume.getPodId(), e.getMessage(), e.getMessage());
+                } finally {
+                    _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(),
+                            com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                }
+            }
+
 			/*if (answer.getCheckSum() != null) {
 				VMTemplateVO templateDaoBuilder = _vmTemplateDao.createForUpdate();
 				templateDaoBuilder.setChecksum(answer.getCheckSum());


[02/25] CLOUDSTACK-658 - Scaleup vm support for Xenserver Added the framweork so that it can be extended for vmware and kvm as well. Added unitests and marvin tests.

Posted by ts...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/test/integration/smoke/test_ScaleVm.py
----------------------------------------------------------------------
diff --git a/test/integration/smoke/test_ScaleVm.py b/test/integration/smoke/test_ScaleVm.py
new file mode 100644
index 0000000..710d2ad
--- /dev/null
+++ b/test/integration/smoke/test_ScaleVm.py
@@ -0,0 +1,221 @@
+# 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.
+""" P1 tests for Scaling up Vm
+"""
+#Import Local Modules
+import marvin
+from marvin.cloudstackTestCase import *
+from marvin.cloudstackAPI import *
+from marvin.remoteSSHClient import remoteSSHClient
+from marvin.integration.lib.utils import *
+from marvin.integration.lib.base import *
+from marvin.integration.lib.common import *
+from nose.plugins.attrib import attr
+#Import System modules
+import time
+
+_multiprocess_shared_ = True
+class Services:
+    """Test VM Life Cycle Services
+    """
+
+    def __init__(self):
+        self.services = {
+
+                "account": {
+                    "email": "test@test.com",
+                    "firstname": "Test",
+                    "lastname": "User",
+                    "username": "test",
+                    # Random characters are appended in create account to 
+                    # ensure unique username generated each time
+                    "password": "password",
+                },
+                "small":
+                # Create a small virtual machine instance with disk offering 
+                {
+                    "displayname": "testserver",
+                    "username": "root", # VM creds for SSH
+                    "password": "password",
+                    "ssh_port": 22,
+                    "hypervisor": 'XenServer',
+                    "privateport": 22,
+                    "publicport": 22,
+                    "protocol": 'TCP',
+                },
+                "service_offerings":
+                {
+                 "small":
+                    {
+                     # Small service offering ID to for change VM 
+                     # service offering from medium to small
+                        "name": "SmallInstance",
+                        "displaytext": "SmallInstance",
+                        "cpunumber": 1,
+                        "cpuspeed": 100,
+                        "memory": 256,
+                    },
+                "big":
+                    {
+                     # Big service offering ID to for change VM 
+                        "name": "BigInstance",
+                        "displaytext": "BigInstance",
+                        "cpunumber": 1,
+                        "cpuspeed": 100,
+                        "memory": 512,
+                    }
+                },
+                #Change this
+                "template": {
+                    "displaytext": "xs",
+                    "name": "xs",
+                    "passwordenabled": False,
+                },
+            "diskdevice": '/dev/xvdd',
+            # Disk device where ISO is attached to instance
+            "mount_dir": "/mnt/tmp",
+            "sleep": 60,
+            "timeout": 10,
+            #Migrate VM to hostid
+            "ostype": 'CentOS 5.6 (64-bit)',
+            # CentOS 5.3 (64-bit)
+        }
+
+class TestScaleVm(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        cls.api_client = super(TestScaleVm, cls).getClsTestClient().getApiClient()
+        cls.services = Services().services
+
+        # Get Zone, Domain and templates
+        domain = get_domain(cls.api_client, cls.services)
+        zone = get_zone(cls.api_client, cls.services)
+        cls.services['mode'] = zone.networktype
+
+        template = get_template(
+                            cls.api_client,
+                            zone.id,
+                            cls.services["ostype"]
+                            )
+        # Set Zones and disk offerings ??
+        cls.services["small"]["zoneid"] = zone.id
+        cls.services["small"]["template"] = template.id
+
+        # Create account, service offerings, vm.
+        cls.account = Account.create(
+                            cls.api_client,
+                            cls.services["account"],
+                            domainid=domain.id
+                            )
+
+        cls.small_offering = ServiceOffering.create(
+                                    cls.api_client,
+                                    cls.services["service_offerings"]["small"]
+                                    )
+        
+        cls.big_offering = ServiceOffering.create(
+                                    cls.api_client,
+                                    cls.services["service_offerings"]["big"]
+                                    )
+
+        #create a virtual machine
+        cls.virtual_machine = VirtualMachine.create(
+                                        cls.api_client,
+                                        cls.services["small"],
+                                        accountid=cls.account.account.name,
+                                        domainid=cls.account.account.domainid,
+                                        serviceofferingid=cls.small_offering.id,
+                                        mode=cls.services["mode"]
+                                        )
+        #how does it work ??
+        cls._cleanup = [
+                        cls.small_offering,
+                        cls.account
+                        ]
+
+    @classmethod
+    def tearDownClass(cls):
+        cls.api_client = super(TestScaleVm, cls).getClsTestClient().getApiClient()
+        cleanup_resources(cls.api_client, cls._cleanup)
+        return
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.dbclient = self.testClient.getDbConnection()
+        self.cleanup = []
+
+    def tearDown(self):
+        #Clean up, terminate the created ISOs
+        cleanup_resources(self.apiclient, self.cleanup)
+        return
+
+    @attr(tags = ["advanced", "basic", "multicluster", "storagemotion", "xenserver"])
+    def test_01_scale_vm(self):
+        """Test scale virtual machine 
+        """
+        # Validate the following
+        # Scale up the vm and see if it scales to the new svc offering and is finally in running state
+        
+      
+      
+        self.debug("Scaling VM-ID: %s to service offering: %s" % (
+                                        self.virtual_machine.id,
+                                        self.big_offering.id
+                                        ))
+        
+        cmd = scaleVirtualMachine.scaleVirtualMachineCmd()
+        cmd.serviceofferingid = self.big_offering.id
+        cmd.id = self.virtual_machine.id
+        self.apiclient.scaleVirtualMachine(cmd)  
+
+        list_vm_response = list_virtual_machines(
+                                            self.apiclient,
+                                            id=self.virtual_machine.id
+                                            )
+        self.assertEqual(
+                        isinstance(list_vm_response, list),
+                        True,
+                        "Check list response returns a valid list"
+                        )
+
+        self.assertNotEqual(
+                            list_vm_response,
+                            None,
+                            "Check virtual machine is listVirtualMachines"
+                            )
+
+        vm_response = list_vm_response[0]
+
+        self.assertEqual(
+                        vm_response.id,
+                        self.virtual_machine.id,
+                        "Check virtual machine ID of scaled VM"
+                        )
+
+        self.assertEqual(
+                        vm_response.serviceofferingid,
+                        self.big_offering.id,
+                        "Check service offering of the VM"
+                        )
+
+        self.assertEqual(
+                        vm_response.state,
+                        'Running',
+                        "Check the state of VM"
+                        )
+        return


[21/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1156 Fix small typo

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

Branch: refs/heads/bvt
Commit: 95fce112157526b0727821e145ec53d0e8f3e824
Parents: 4831136
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Fri Mar 29 11:53:49 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Fri Mar 29 12:05:58 2013 +0100

----------------------------------------------------------------------
 server/src/com/cloud/configuration/Config.java     |    4 +-
 .../resourcelimit/ResourceLimitManagerImpl.java    |   51 ++++++++-------
 2 files changed, 30 insertions(+), 25 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fce112/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 5b2616f..8ec5a41 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -323,7 +323,7 @@ public enum Config {
 	DefaultMaxAccountVpcs("Account Defaults", ManagementServer.class, Long.class, "max.account.vpcs", "20", "The default maximum number of vpcs that can be created for an account", null),
 	DefaultMaxAccountCpus("Account Defaults", ManagementServer.class, Long.class, "max.account.cpus", "40", "The default maximum number of cpu cores that can be used for an account", null),
 	DefaultMaxAccountMemory("Account Defaults", ManagementServer.class, Long.class, "max.account.memory", "40960", "The default maximum memory (in MB) that can be used for an account", null),
-	DefaultMaxAccountPrimayStorage("Account Defaults", ManagementServer.class, Long.class, "max.account.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an account", null),
+	DefaultMaxAccountPrimaryStorage("Account Defaults", ManagementServer.class, Long.class, "max.account.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an account", null),
 	DefaultMaxAccountSecondaryStorage("Account Defaults", ManagementServer.class, Long.class, "max.account.secondary.storage", "400", "The default maximum secondary storage space (in GiB) that can be used for an account", null),
 
 	ResourceCountCheckInterval("Advanced", ManagementServer.class, Long.class, "resourcecount.check.interval", "0", "Time (in seconds) to wait before retrying resource count check task. Default is 0 which is to never run the task", "Seconds"),
@@ -350,7 +350,7 @@ public enum Config {
     DefaultMaxProjectVpcs("Project Defaults", ManagementServer.class, Long.class, "max.project.vpcs", "20", "The default maximum number of vpcs that can be created for a project", null),
     DefaultMaxProjectCpus("Project Defaults", ManagementServer.class, Long.class, "max.project.cpus", "40", "The default maximum number of cpu cores that can be used for a project", null),
     DefaultMaxProjectMemory("Project Defaults", ManagementServer.class, Long.class, "max.project.memory", "40960", "The default maximum memory (in MB) that can be used for a project", null),
-    DefaultMaxProjectPrimayStorage("Project Defaults", ManagementServer.class, Long.class, "max.project.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an project", null),
+    DefaultMaxProjectPrimaryStorage("Project Defaults", ManagementServer.class, Long.class, "max.project.primary.storage", "200", "The default maximum primary storage space (in GiB) that can be used for an project", null),
     DefaultMaxProjectSecondaryStorage("Project Defaults", ManagementServer.class, Long.class, "max.project.secondary.storage", "400", "The default maximum secondary storage space (in GiB) that can be used for an project", null),
 
     ProjectInviteRequired("Project Defaults", ManagementServer.class, Boolean.class, "project.invite.required", "false", "If invitation confirmation is required when add account to project. Default value is false", null),

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fce112/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
index bbe0190..e8805ae 100755
--- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
+++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
@@ -186,29 +186,34 @@ public class ResourceLimitManagerImpl extends ManagerBase implements ResourceLim
             _rcExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ResourceCountChecker"));
         }
 
-        projectResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPublicIPs.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSnapshots.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectTemplates.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectUserVms.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVolumes.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.network, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectNetworks.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVpcs.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectCpus.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectMemory.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPrimayStorage.key())));
-        projectResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSecondaryStorage.key())));
-
-        accountResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPublicIPs.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountTemplates.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountUserVms.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.network, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountNetworks.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVpcs.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountCpus.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountMemory.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPrimayStorage.key())));
-        accountResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key())));
+        try {
+            projectResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPublicIPs.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSnapshots.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectTemplates.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectUserVms.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVolumes.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.network, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectNetworks.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectVpcs.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectCpus.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectMemory.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectPrimaryStorage.key())));
+            projectResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxProjectSecondaryStorage.key())));
+    
+            accountResourceLimitMap.put(Resource.ResourceType.public_ip, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPublicIPs.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.snapshot, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSnapshots.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.template, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountTemplates.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.user_vm, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountUserVms.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.volume, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVolumes.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.network, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountNetworks.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.vpc, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountVpcs.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.cpu, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountCpus.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.memory, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountMemory.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.primary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountPrimaryStorage.key())));
+            accountResourceLimitMap.put(Resource.ResourceType.secondary_storage, Long.parseLong(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key())));
+        } catch (NumberFormatException e) {
+            s_logger.error("NumberFormatException during configuration", e);
+            throw new ConfigurationException("Configuration failed due to NumberFormatException, see log for the stacktrace");
+        }
 
         return true;
     }


[22/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
Better error handling for some corner cases

Make the exceptions more descriptive so admins can pinpoint the issue
easier.

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

Branch: refs/heads/bvt
Commit: 9a5bf78c3ee156daf5527a4faf70375fc3a5fa47
Parents: 95fce11
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Fri Mar 29 11:55:00 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Fri Mar 29 12:06:03 2013 +0100

----------------------------------------------------------------------
 .../cloud/agent/manager/ClusteredAgentAttache.java |   13 +++++++++++--
 1 files changed, 11 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9a5bf78c/server/src/com/cloud/agent/manager/ClusteredAgentAttache.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/agent/manager/ClusteredAgentAttache.java b/server/src/com/cloud/agent/manager/ClusteredAgentAttache.java
index a648740..058a904 100755
--- a/server/src/com/cloud/agent/manager/ClusteredAgentAttache.java
+++ b/server/src/com/cloud/agent/manager/ClusteredAgentAttache.java
@@ -95,8 +95,13 @@ public class ClusteredAgentAttache extends ConnectedAgentAttache implements Rout
                 SynchronousListener synchronous = (SynchronousListener)listener;
                 String peerName = synchronous.getPeer();
                 if (peerName != null) {
-                    s_logger.debug(log(seq, "Forwarding to peer to cancel due to timeout"));
-                    s_clusteredAgentMgr.cancel(peerName, _id, seq, "Timed Out");
+                    if (s_clusteredAgentMgr != null) {
+                        s_logger.debug(log(seq, "Forwarding to peer to cancel due to timeout"));
+                        s_clusteredAgentMgr.cancel(peerName, _id, seq, "Timed Out");
+                    } else {
+                        s_logger.error("Unable to forward cancel, ClusteredAgentAttache is not properly initialized");
+                    }
+
                 }
             }
         }
@@ -159,6 +164,10 @@ public class ClusteredAgentAttache extends ConnectedAgentAttache implements Rout
             }
         } 
 
+        if (s_clusteredAgentMgr == null) {
+            throw new AgentUnavailableException("ClusteredAgentAttache not properly initialized", _id);
+        }
+        
         int i = 0;
         SocketChannel ch = null;
         boolean error = true;


[23/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1689: KVM agent install.sh should install ipset command

Added ipset in cloud.spec as part of agent install.

Signed-off-by: Pradeep <pr...@citrix.com>
Signed-off-by: Prasanna Santhanam <ts...@apache.org>


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

Branch: refs/heads/bvt
Commit: 5a66ec35ad08ff3313e72b54eba7e1754868eee4
Parents: 9a5bf78
Author: Pradeep <pr...@citrix.com>
Authored: Fri Mar 29 15:54:09 2013 +0530
Committer: Prasanna Santhanam <ts...@apache.org>
Committed: Fri Mar 29 16:39:35 2013 +0530

----------------------------------------------------------------------
 packaging/centos63/cloud.spec |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5a66ec35/packaging/centos63/cloud.spec
----------------------------------------------------------------------
diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec
index f8e3133..7d6e638 100644
--- a/packaging/centos63/cloud.spec
+++ b/packaging/centos63/cloud.spec
@@ -114,6 +114,7 @@ Requires: %{name}-common = %{_ver}
 Requires: libvirt
 Requires: bridge-utils
 Requires: ebtables
+Requires: ipset
 Requires: jsvc
 Requires: jakarta-commons-daemon
 Requires: jakarta-commons-daemon-jsvc


[13/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-712: Feature Syslog Enhancements

Signed-off-by: Anshul Gangwar <an...@citrix.com>
Signed-off-by: Sateesh Chodapuneedi <sa...@apache.org>


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

Branch: refs/heads/bvt
Commit: 6a7156ad9af6ca173c0b685d69d5724d91d0a401
Parents: 2c176ab
Author: Anshul Gangwar <an...@citrix.com>
Authored: Wed Mar 6 14:11:47 2013 +0530
Committer: Sateesh Chodapuneedi <sa...@apache.org>
Committed: Fri Mar 29 09:53:05 2013 +0530

----------------------------------------------------------------------
 client/pom.xml                                     |    5 +
 client/tomcatconf/log4j-cloud.xml.in               |   15 +
 plugins/alert-handlers/syslog-alerts/pom.xml       |   40 ++
 .../cloudstack/syslog/AlertsSyslogAppender.java    |  336 +++++++++++++++
 .../syslog/AlertsSyslogAppenderTest.java           |   61 +++
 plugins/pom.xml                                    |    1 +
 6 files changed, 458 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/client/pom.xml
----------------------------------------------------------------------
diff --git a/client/pom.xml b/client/pom.xml
index 23892e1..61cda76 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -67,6 +67,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.cloudstack</groupId>
+      <artifactId>cloud-plugin-syslog-alerts</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.cloudstack</groupId>
       <artifactId>cloud-plugin-snmp-alerts</artifactId>
       <version>${project.version}</version>
     </dependency>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/client/tomcatconf/log4j-cloud.xml.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/log4j-cloud.xml.in b/client/tomcatconf/log4j-cloud.xml.in
index ce4079f..0e7f004 100755
--- a/client/tomcatconf/log4j-cloud.xml.in
+++ b/client/tomcatconf/log4j-cloud.xml.in
@@ -74,6 +74,20 @@ under the License.
          <param name="ConversionPattern" value="%-5p [%c{3}] (%t:%x) %m%n"/>
       </layout>
    </appender>
+
+   <!-- ============================== -->
+   <!-- Append alerts to the syslog if it is configured -->
+   <!-- ============================== -->
+
+   <appender name="ALERTSYSLOG" class="org.apache.cloudstack.syslog.AlertsSyslogAppender">
+      <param name="Threshold" value="WARN"/>
+      <param name="SyslogHosts" value=""/>
+      <param name="Facility" value="LOCAL6"/>
+      <layout class="org.apache.log4j.PatternLayout">
+         <param name="ConversionPattern" value="%-5p [%c{3}] (%t:%x) %m%n"/>
+      </layout>
+   </appender>
+
    <!-- ============================== -->
    <!-- send alert warnings+ as the SNMP trap if it is configured! -->
    <!-- ============================== -->
@@ -166,6 +180,7 @@ under the License.
       <appender-ref ref="CONSOLE"/>
       <appender-ref ref="FILE"/>
       <appender-ref ref="SNMP"/>
+      <appender-ref ref="ALERTSYSLOG"/>
    </logger>
 
    <!-- ======================= -->

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/plugins/alert-handlers/syslog-alerts/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/alert-handlers/syslog-alerts/pom.xml b/plugins/alert-handlers/syslog-alerts/pom.xml
new file mode 100644
index 0000000..21aa54a
--- /dev/null
+++ b/plugins/alert-handlers/syslog-alerts/pom.xml
@@ -0,0 +1,40 @@
+<!--
+  ~ 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
+  -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <parent>
+    <artifactId>cloudstack-plugins</artifactId>
+    <groupId>org.apache.cloudstack</groupId>
+    <version>4.2.0-SNAPSHOT</version>
+    <relativePath>../../pom.xml</relativePath>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <name>Apache CloudStack Plugin - Syslog Alerts</name>
+  <artifactId>cloud-plugin-syslog-alerts</artifactId>
+
+  <dependencies>
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+      <version>${cs.log4j.version}</version>
+    </dependency>
+  </dependencies>
+
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java
----------------------------------------------------------------------
diff --git a/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java b/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java
new file mode 100644
index 0000000..d2f2565
--- /dev/null
+++ b/plugins/alert-handlers/syslog-alerts/src/org/apache/cloudstack/syslog/AlertsSyslogAppender.java
@@ -0,0 +1,336 @@
+// 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.syslog;
+
+import com.cloud.utils.net.NetUtils;
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.net.SyslogAppender;
+import org.apache.log4j.spi.LoggingEvent;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+public class AlertsSyslogAppender extends AppenderSkeleton {
+    String _syslogHosts = null;
+    String _delimiter = ",";
+    List<String> _syslogHostsList = null;
+    List<SyslogAppender> _syslogAppenders = null;
+    private String _facility;
+    private String _pairDelimiter = "//";
+    private String _keyValueDelimiter = "::";
+    private int alertType = -1;
+    private long dataCenterId = 0;
+    private long podId = 0;
+    private long clusterId = 0;
+    private String sysMessage = null;
+    public static final int LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER = 9;
+    public static final int LENGTH_OF_STRING_MESSAGE = 8;
+    public static final String MESSAGE_DELIMITER_STRING = "   ";
+    //add the alertType in this array it its level needs to be set to critical
+    private static final int[] criticalAlerts = {7, 8, 9, 10, 11, 12, 13, 15, 16, 19, 20};
+    private static final Map<Integer, String> alertsMap;
+
+    static {
+        Map<Integer, String> aMap = new HashMap<Integer, String>(27);
+        aMap.put(0, "availableMemory");
+        aMap.put(1, "availableCpu");
+        aMap.put(2, "availableStorage");
+        aMap.put(3, "remainingStorageAllocated");
+        aMap.put(4, "unallocatedVirtualNetworkpublicIp");
+        aMap.put(5, "unallocatedPrivateIp");
+        aMap.put(6, "availableSecondaryStorage");
+        aMap.put(7, "host");
+        aMap.put(8, "userVmState");
+        aMap.put(9, "domainRouterVmState ");
+        aMap.put(10, "consoleProxyVmState");
+        aMap.put(11, "routingConnection");
+        aMap.put(12, "storageIssueSystemVms");
+        aMap.put(13, "usageServerStatus");
+        aMap.put(14, "managementNode");
+        aMap.put(15, "domainRouterMigrate");
+        aMap.put(16, "consoleProxyMigrate");
+        aMap.put(17, "userVmMigrate");
+        aMap.put(18, "unallocatedVlan");
+        aMap.put(19, "ssvmStopped");
+        aMap.put(20, "usageServerResult");
+        aMap.put(21, "storageDelete");
+        aMap.put(22, "updateResourceCount");
+        aMap.put(23, "usageSanityResult");
+        aMap.put(24, "unallocatedDirectAttachedPublicIp");
+        aMap.put(25, "unallocatedLocalStorage");
+        aMap.put(26, "resourceLimitExceeded");
+
+        alertsMap = Collections.unmodifiableMap(aMap);
+    }
+
+    @Override
+    protected void append(LoggingEvent event) {
+        if (!isAsSevereAsThreshold(event.getLevel())) {
+            return;
+        }
+
+        if (_syslogAppenders != null && !_syslogAppenders.isEmpty()) {
+            try {
+                String logMessage = event.getRenderedMessage();
+                if (logMessage.contains("alertType") && logMessage.contains("message")) {
+                    parseMessage(logMessage);
+                    String syslogMessage = createSyslogMessage();
+
+                    LoggingEvent syslogEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
+                        event.getLevel(), syslogMessage, null);
+
+                    for (SyslogAppender syslogAppender : _syslogAppenders) {
+                        syslogAppender.append(syslogEvent);
+                    }
+                }
+            } catch (Exception e) {
+                errorHandler.error(e.getMessage());
+            }
+        }
+    }
+
+    @Override
+    synchronized public void close() {
+        for (SyslogAppender syslogAppender : _syslogAppenders) {
+            syslogAppender.close();
+        }
+    }
+
+    @Override
+    public boolean requiresLayout() {
+        return true;
+    }
+
+    void setSyslogAppenders() {
+        if (_syslogAppenders == null) {
+            _syslogAppenders = new ArrayList<SyslogAppender>();
+        }
+
+        if (_syslogHosts == null || _syslogHosts.trim().isEmpty()) {
+            reset();
+            return;
+        }
+
+        _syslogHostsList = parseSyslogHosts(_syslogHosts);
+
+        if (!validateIpAddresses()) {
+            reset();
+            errorHandler.error(" Invalid format for the IP Addresses parameter ");
+            return;
+        }
+
+        for (String syslogHost : _syslogHostsList) {
+            _syslogAppenders.add(new SyslogAppender(getLayout(), syslogHost, SyslogAppender.getFacility(_facility)));
+        }
+    }
+
+    private List<String> parseSyslogHosts(String syslogHosts) {
+        List<String> result = new ArrayList<String>();
+
+        final StringTokenizer tokenizer = new StringTokenizer(syslogHosts, _delimiter);
+        while (tokenizer.hasMoreTokens()) {
+            result.add(tokenizer.nextToken().trim());
+        }
+        return result;
+    }
+
+    private boolean validateIpAddresses() {
+        for (String ipAddress : _syslogHostsList) {
+            if (ipAddress.trim().equalsIgnoreCase("localhost")) {
+                continue;
+            }
+            if (!NetUtils.isValidIp(ipAddress)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    void parseMessage(String logMessage) {
+            final StringTokenizer messageSplitter = new StringTokenizer(logMessage, _pairDelimiter);
+            while (messageSplitter.hasMoreTokens()) {
+                final String pairToken = messageSplitter.nextToken();
+                final StringTokenizer pairSplitter = new StringTokenizer(pairToken, _keyValueDelimiter);
+                String keyToken;
+                String valueToken;
+
+                if (pairSplitter.hasMoreTokens()) {
+                    keyToken = pairSplitter.nextToken().trim();
+                } else {
+                    break;
+                }
+
+                if (pairSplitter.hasMoreTokens()) {
+                    valueToken = pairSplitter.nextToken().trim();
+                } else {
+                    break;
+                }
+
+                if (keyToken.equalsIgnoreCase("alertType") && !valueToken.equalsIgnoreCase("null")) {
+                    alertType = Short.parseShort(valueToken);
+                } else if (keyToken.equalsIgnoreCase("dataCenterId") && !valueToken.equalsIgnoreCase("null")) {
+                    dataCenterId = Long.parseLong(valueToken);
+                } else if (keyToken.equalsIgnoreCase("podId") && !valueToken.equalsIgnoreCase("null")) {
+                    podId = Long.parseLong(valueToken);
+                } else if (keyToken.equalsIgnoreCase("clusterId") && !valueToken.equalsIgnoreCase("null")) {
+                    clusterId = Long.parseLong(valueToken);
+                } else if (keyToken.equalsIgnoreCase("message") && !valueToken.equalsIgnoreCase("null")) {
+                    sysMessage = getSyslogMessage(logMessage);
+                }
+            }
+    }
+
+    String createSyslogMessage() {
+        StringBuilder message = new StringBuilder();
+        message.append(severityOfAlert(alertType)).append(MESSAGE_DELIMITER_STRING);
+        InetAddress ip;
+        try {
+            ip = InetAddress.getLocalHost();
+        } catch (UnknownHostException e) {
+            ip = null;
+        }
+
+        if (ip != null) {
+            message.append(ip.getHostName()).append(MESSAGE_DELIMITER_STRING);
+        } else {
+            message.append("unknown" + MESSAGE_DELIMITER_STRING);
+        }
+
+        if (alertType > 0) {
+            message.append("alertType").append(_keyValueDelimiter).append(" ").append(alertsMap.get(alertType))
+                .append(MESSAGE_DELIMITER_STRING);
+            if (dataCenterId != 0) {
+                message.append("dataCenterId").append(_keyValueDelimiter).append(" ").append(dataCenterId)
+                    .append(MESSAGE_DELIMITER_STRING);
+            }
+
+            if (podId != 0) {
+                message.append("podId").append(_keyValueDelimiter).append(" ").append(podId)
+                    .append(MESSAGE_DELIMITER_STRING);
+            }
+
+            if (clusterId != 0) {
+                message.append("clusterId").append(_keyValueDelimiter).append(" ").append(clusterId)
+                    .append(MESSAGE_DELIMITER_STRING);
+            }
+
+            if (sysMessage != null) {
+                message.append("message").append(_keyValueDelimiter).append(" ").append(sysMessage);
+            } else {
+                errorHandler.error(" What is the use of alert without message ");
+            }
+        } else {
+            errorHandler.error(" Invalid alert Type ");
+        }
+
+        return message.toString();
+    }
+
+    private String getSyslogMessage(String message) {
+        int lastIndexOfKeyValueDelimiter = message.lastIndexOf(_keyValueDelimiter);
+        int lastIndexOfMessageInString = message.lastIndexOf("message");
+
+        if (lastIndexOfKeyValueDelimiter - lastIndexOfMessageInString <=
+            LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER) {
+            return message.substring(lastIndexOfKeyValueDelimiter + _keyValueDelimiter.length()).trim();
+        } else if (lastIndexOfMessageInString < lastIndexOfKeyValueDelimiter) {
+            return message.substring(
+                lastIndexOfMessageInString + _keyValueDelimiter.length() + LENGTH_OF_STRING_MESSAGE).trim();
+        }
+
+        return message.substring(message.lastIndexOf("message" + _keyValueDelimiter) +
+            LENGTH_OF_STRING_MESSAGE_AND_KEY_VALUE_DELIMITER).trim();
+    }
+
+    private void reset() {
+        _syslogAppenders.clear();
+    }
+
+    public void setFacility(String facility) {
+        if (facility == null) {
+            return;
+        }
+
+        this._facility = facility;
+        if (_syslogAppenders != null && !_syslogAppenders.isEmpty()) {
+            for (SyslogAppender syslogAppender : _syslogAppenders) {
+                syslogAppender.setFacility(facility);
+            }
+        }
+    }
+
+    private String severityOfAlert(int alertType) {
+        if (isCritical(alertType)) {
+            return "CRITICAL";
+        } else {
+            return "WARN";
+        }
+    }
+
+    private boolean isCritical(int alertType) {
+        for (int type : criticalAlerts) {
+            if (type == alertType) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public String getFacility() {
+        return _facility;
+    }
+
+    public String getSyslogHosts() {
+        return _syslogHosts;
+    }
+
+    public void setSyslogHosts(String syslogHosts) {
+        this._syslogHosts = syslogHosts;
+        this.setSyslogAppenders();
+    }
+
+    public String getDelimiter() {
+        return _delimiter;
+    }
+
+    public void setDelimiter(String delimiter) {
+        this._delimiter = delimiter;
+    }
+
+    public String getPairDelimiter() {
+        return _pairDelimiter;
+    }
+
+    public void setPairDelimiter(String pairDelimiter) {
+        this._pairDelimiter = pairDelimiter;
+    }
+
+    public String getKeyValueDelimiter() {
+        return _keyValueDelimiter;
+    }
+
+    public void setKeyValueDelimiter(String keyValueDelimiter) {
+        this._keyValueDelimiter = keyValueDelimiter;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java
----------------------------------------------------------------------
diff --git a/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java b/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java
new file mode 100644
index 0000000..68585ee
--- /dev/null
+++ b/plugins/alert-handlers/syslog-alerts/test/org/apache/cloudstack/syslog/AlertsSyslogAppenderTest.java
@@ -0,0 +1,61 @@
+// 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.syslog;
+
+import org.apache.log4j.PatternLayout;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.naming.ConfigurationException;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
+
+public class AlertsSyslogAppenderTest {
+    AlertsSyslogAppender _appender = new AlertsSyslogAppender();
+
+    @Before
+    public void setUp() throws ConfigurationException {
+        _appender.setLayout(new PatternLayout("%-5p [%c{3}] (%t:%x) %m%n"));
+        _appender.setFacility("LOCAL6");
+    }
+
+    @Test
+    public void setSyslogAppendersTest() {
+        _appender.setSyslogHosts("10.1.1.1,10.1.1.2");
+        assertEquals(" error Syslog Appenders list size not as expected ", 2, _appender._syslogAppenders.size());
+    }
+
+    @Test
+    public void setSyslogAppendersNegativeTest() {
+        //setting invalid IP for Syslog Hosts
+        _appender.setSyslogHosts("10.1.1.");
+        assertTrue(" list was expected to be empty", _appender._syslogAppenders.isEmpty());
+    }
+
+    @Test
+    public void appendTest() {
+        String message = "alertType:: 14 // dataCenterId:: 0 // podId:: 0 // clusterId:: null // message:: Management" +
+            " server node 127.0.0.1 is up";
+        _appender.parseMessage(message);
+        String createdMessage =  _appender.createSyslogMessage();
+        assertTrue(" message is not as expected ", createdMessage.contains("alertType:: managementNode" +
+            AlertsSyslogAppender.MESSAGE_DELIMITER_STRING + "message:: Management server node 127.0.0.1 is up"));
+        assertTrue("severity level not as expected ", createdMessage.contains("WARN"));
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7156ad/plugins/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/pom.xml b/plugins/pom.xml
index 39d9907..d7e8deb 100755
--- a/plugins/pom.xml
+++ b/plugins/pom.xml
@@ -59,6 +59,7 @@
     <module>storage/volume/solidfire</module>
     <module>storage/volume/default</module>
     <module>alert-handlers/snmp-alerts</module>
+    <module>alert-handlers/syslog-alerts</module>
   </modules>
 
   <dependencies>


[03/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-658 - Scaleup vm support for Xenserver
Added the framweork so that it can be extended for vmware and kvm as well.
Added unitests and marvin tests.


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

Branch: refs/heads/bvt
Commit: 3e4430d811d5e148c4fef1900bdd8dd07a38bdeb
Parents: f8b8f60
Author: Nitin Mehta <ni...@citrix.com>
Authored: Thu Mar 28 16:43:37 2013 +0530
Committer: Nitin Mehta <ni...@citrix.com>
Committed: Thu Mar 28 16:43:37 2013 +0530

----------------------------------------------------------------------
 api/src/com/cloud/agent/api/ScaleVmCommand.java    |    6 +-
 api/src/com/cloud/event/EventTypes.java            |    1 +
 api/src/com/cloud/vm/UserVmService.java            |   16 +-
 api/src/com/cloud/vm/VirtualMachine.java           |    2 +-
 .../cloudstack/api/command/user/vm/ScaleVMCmd.java |  110 +++++
 .../api/command/test/ScaleVMCmdTest.java           |  122 ++++++
 client/tomcatconf/commands.properties.in           |    1 +
 core/src/com/cloud/vm/VMInstanceVO.java            |    2 +-
 .../xen/resource/CitrixResourceBase.java           |   82 ++++
 .../xen/resource/XenServer56FP1Resource.java       |   11 +-
 .../xen/resource/CitrixResourceBaseTest.java       |  148 +++++++
 .../xenserver/Add-To-VCPUs-Params-Live.sh          |   33 ++
 scripts/vm/hypervisor/xenserver/vmops              |   13 +
 server/src/com/cloud/configuration/Config.java     |    3 +-
 .../src/com/cloud/server/ManagementServerImpl.java |    1 +
 server/src/com/cloud/vm/ItWorkVO.java              |    3 +-
 server/src/com/cloud/vm/UserVmManagerImpl.java     |   92 ++++-
 server/src/com/cloud/vm/VirtualMachineManager.java |   12 +
 .../com/cloud/vm/VirtualMachineManagerImpl.java    |  311 +++++++++++++--
 .../test/com/cloud/vm/MockUserVmManagerImpl.java   |   17 +-
 .../cloud/vm/MockVirtualMachineManagerImpl.java    |   17 +
 server/test/com/cloud/vm/UserVmManagerTest.java    |  192 +++++++++-
 .../cloud/vm/VirtualMachineManagerImplTest.java    |  208 ++++++++++
 test/integration/smoke/test_ScaleVm.py             |  221 ++++++++++
 24 files changed, 1545 insertions(+), 79 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/src/com/cloud/agent/api/ScaleVmCommand.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/ScaleVmCommand.java b/api/src/com/cloud/agent/api/ScaleVmCommand.java
index e5078d5..35d22ad 100644
--- a/api/src/com/cloud/agent/api/ScaleVmCommand.java
+++ b/api/src/com/cloud/agent/api/ScaleVmCommand.java
@@ -40,14 +40,14 @@ public class ScaleVmCommand extends Command {
 	}
 
 	public ScaleVmCommand(String vmName, int cpus,
-			Integer speed, long minRam, long maxRam) {
+			Integer speed, long minRam, long maxRam, boolean limitCpuUse) {
 		super();
 		this.vmName = vmName;
 		this.cpus = cpus;
-		//this.speed = speed;
+		this.speed = speed;
 		this.minRam = minRam;
 		this.maxRam = maxRam;
-		this.vm = new VirtualMachineTO(1L, vmName, null, cpus, null, minRam, maxRam, null, null, false, false, null);
+		this.vm = new VirtualMachineTO(1L, vmName, null, cpus, speed, minRam, maxRam, null, null, false, false, null);
 		/*vm.setName(vmName);
 		vm.setCpus(cpus);
 		vm.setRam(minRam, maxRam);*/

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/src/com/cloud/event/EventTypes.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java
index 6fdd28c..2e961e5 100755
--- a/api/src/com/cloud/event/EventTypes.java
+++ b/api/src/com/cloud/event/EventTypes.java
@@ -59,6 +59,7 @@ public class EventTypes {
     public static final String EVENT_VM_REBOOT = "VM.REBOOT";
     public static final String EVENT_VM_UPDATE = "VM.UPDATE";
     public static final String EVENT_VM_UPGRADE = "VM.UPGRADE";
+    public static final String EVENT_VM_SCALE = "VM.SCALE";
     public static final String EVENT_VM_RESETPASSWORD = "VM.RESETPASSWORD";
     public static final String EVENT_VM_RESETSSHKEY = "VM.RESETSSHKEY";
     public static final String EVENT_VM_MIGRATE = "VM.MIGRATE";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/src/com/cloud/vm/UserVmService.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java
index 9d6b221..2c33d41 100755
--- a/api/src/com/cloud/vm/UserVmService.java
+++ b/api/src/com/cloud/vm/UserVmService.java
@@ -23,18 +23,7 @@ import javax.naming.InsufficientResourcesException;
 
 import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
 import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
-import org.apache.cloudstack.api.command.user.vm.AddNicToVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DeployVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RemoveNicFromVMCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
-import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
-import org.apache.cloudstack.api.command.user.vm.StartVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateDefaultNicForVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
+import org.apache.cloudstack.api.command.user.vm.*;
 import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
 import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
 import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
@@ -402,4 +391,7 @@ public interface UserVmService {
     VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool);
 
     UserVm restoreVM(RestoreVMCmd cmd);
+
+    UserVm upgradeVirtualMachine(ScaleVMCmd scaleVMCmd) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException;
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/src/com/cloud/vm/VirtualMachine.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/vm/VirtualMachine.java b/api/src/com/cloud/vm/VirtualMachine.java
index 4300dd5..8f807d4 100755
--- a/api/src/com/cloud/vm/VirtualMachine.java
+++ b/api/src/com/cloud/vm/VirtualMachine.java
@@ -176,7 +176,7 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, I
         AgentReportShutdowned,
         AgentReportMigrated,
         RevertRequested,
-        SnapshotRequested
+        SnapshotRequested,
     };
 
     public enum Type {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
new file mode 100644
index 0000000..4fc65c3
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/ScaleVMCmd.java
@@ -0,0 +1,110 @@
+// 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.user.vm;
+
+import com.cloud.exception.*;
+import com.cloud.user.Account;
+import com.cloud.user.UserContext;
+import com.cloud.uservm.UserVm;
+import org.apache.cloudstack.api.*;
+import org.apache.cloudstack.api.response.ServiceOfferingResponse;
+import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.log4j.Logger;
+
+
+@APICommand(name = "scaleVirtualMachine", description="Scales the virtual machine to a new service offering.", responseObject=UserVmResponse.class)
+public class ScaleVMCmd extends BaseCmd {
+    public static final Logger s_logger = Logger.getLogger(ScaleVMCmd.class.getName());
+    private static final String s_name = "scalevirtualmachineresponse";
+
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+
+    @ACL
+    @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class,
+            required=true, description="The ID of the virtual machine")
+    private Long id;
+
+    @ACL
+    @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class,
+            required=true, description="the ID of the service offering for the virtual machine")
+    private Long serviceOfferingId;
+
+    /////////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public Long getId() {
+        return id;
+    }
+
+    public Long getServiceOfferingId() {
+        return serviceOfferingId;
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    public static String getResultObjectName() {
+        return "virtualmachine";
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        UserVm userVm = _entityMgr.findById(UserVm.class, getId());
+        if (userVm != null) {
+            return userVm.getAccountId();
+        }
+
+        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
+    }
+
+    @Override
+    public void execute(){
+        //UserContext.current().setEventDetails("Vm Id: "+getId());
+        UserVm result = null;
+        try {
+            result = _userVmService.upgradeVirtualMachine(this);
+        } catch (ResourceUnavailableException ex) {
+            s_logger.warn("Exception: ", ex);
+            throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
+        } catch (ConcurrentOperationException ex) {
+            s_logger.warn("Exception: ", ex);
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
+        } catch (ManagementServerException ex) {
+            s_logger.warn("Exception: ", ex);
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
+        } catch (VirtualMachineMigrationException ex) {
+            s_logger.warn("Exception: ", ex);
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
+        }
+        if (result != null){
+            UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0);
+            response.setResponseName(getCommandName());
+            this.setResponseObject(response);
+        } else {
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to scale vm");
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/api/test/org/apache/cloudstack/api/command/test/ScaleVMCmdTest.java
----------------------------------------------------------------------
diff --git a/api/test/org/apache/cloudstack/api/command/test/ScaleVMCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/ScaleVMCmdTest.java
new file mode 100644
index 0000000..301fa02
--- /dev/null
+++ b/api/test/org/apache/cloudstack/api/command/test/ScaleVMCmdTest.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.api.command.test;
+
+import com.cloud.user.Account;
+import com.cloud.user.UserContext;
+import com.cloud.uservm.UserVm;
+import com.cloud.vm.UserVmService;
+import junit.framework.Assert;
+import junit.framework.TestCase;
+import org.apache.cloudstack.api.ResponseGenerator;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.command.admin.region.AddRegionCmd;
+import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
+import org.apache.cloudstack.api.response.RegionResponse;
+import org.apache.cloudstack.api.response.UserVmResponse;
+import org.apache.cloudstack.region.Region;
+import org.apache.cloudstack.region.RegionService;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.Mockito;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+
+public class ScaleVMCmdTest extends TestCase{
+
+    private ScaleVMCmd scaleVMCmd;
+    private ResponseGenerator responseGenerator;
+
+    @Rule
+    public ExpectedException expectedException = ExpectedException.none();
+
+    @Before
+    public void setUp() {
+
+        scaleVMCmd = new ScaleVMCmd(){
+            @Override
+            public Long getId() {
+                return 2L;
+            }
+        };
+
+       //Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
+       //UserContext.registerContext(1, account, null, true);
+
+
+    }
+
+
+    @Test
+    public void testCreateSuccess() {
+
+        UserVmService userVmService = Mockito.mock(UserVmService.class);
+
+        UserVm uservm = Mockito.mock(UserVm.class);
+        try {
+            Mockito.when(
+                    userVmService.upgradeVirtualMachine(scaleVMCmd))
+                    .thenReturn(uservm);
+        }catch (Exception e){
+            Assert.fail("Received exception when success expected " +e.getMessage());
+        }
+
+        scaleVMCmd._userVmService = userVmService;
+        responseGenerator = Mockito.mock(ResponseGenerator.class);
+
+        UserVmResponse userVmResponse = Mockito.mock(UserVmResponse.class);
+        List<UserVmResponse> responseList = new ArrayList<UserVmResponse>();
+        responseList.add(userVmResponse);
+
+        Mockito.when(responseGenerator.createUserVmResponse("virtualmachine",uservm))
+                .thenReturn(responseList);
+
+        scaleVMCmd._responseGenerator = responseGenerator;
+        scaleVMCmd.execute();
+
+    }
+
+    @Test
+    public void testCreateFailure() {
+
+        UserVmService userVmService = Mockito.mock(UserVmService.class);
+
+        try {
+            UserVm uservm = Mockito.mock(UserVm.class);
+            Mockito.when(
+                    userVmService.upgradeVirtualMachine(scaleVMCmd))
+                    .thenReturn(null);
+        }catch (Exception e){
+            Assert.fail("Received exception when success expected " +e.getMessage());
+        }
+
+        scaleVMCmd._userVmService = userVmService;
+
+        try {
+            scaleVMCmd.execute();
+        } catch (ServerApiException exception) {
+            Assert.assertEquals("Failed to scale vm",
+                    exception.getDescription());
+        }
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/client/tomcatconf/commands.properties.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index 3b3ffdf..163c2ce 100644
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -66,6 +66,7 @@ listVirtualMachines=15
 getVMPassword=15
 restoreVirtualMachine=15
 changeServiceForVirtualMachine=15
+scaleVirtualMachine=15
 assignVirtualMachine=1
 migrateVirtualMachine=1
 recoverVirtualMachine=7

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/core/src/com/cloud/vm/VMInstanceVO.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/vm/VMInstanceVO.java b/core/src/com/cloud/vm/VMInstanceVO.java
index 6149e43..77e9c02 100644
--- a/core/src/com/cloud/vm/VMInstanceVO.java
+++ b/core/src/com/cloud/vm/VMInstanceVO.java
@@ -480,4 +480,4 @@ public class VMInstanceVO implements VirtualMachine, FiniteStateObject<State, Vi
 		return diskOfferingId;
 	}
 
-}
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 52d992f..d2f3f69 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -53,6 +53,7 @@ import javax.ejb.Local;
 import javax.naming.ConfigurationException;
 import javax.xml.parsers.DocumentBuilderFactory;
 
+import com.cloud.agent.api.*;
 import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
 import com.cloud.agent.api.to.*;
 import com.cloud.network.rules.FirewallRule;
@@ -600,12 +601,93 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
             return execute((RevertToVMSnapshotCommand)cmd);
         } else if (clazz == NetworkRulesVmSecondaryIpCommand.class) {
             return execute((NetworkRulesVmSecondaryIpCommand)cmd);
+        } else if (clazz == ScaleVmCommand.class) {
+            return execute((ScaleVmCommand) cmd);
         } else {
             return Answer.createUnsupportedCommandAnswer(cmd);
         }
     }
 
+    protected void scaleVM(Connection conn, VM vm, VirtualMachineTO vmSpec, Host host) throws XenAPIException, XmlRpcException {
 
+        vm.setMemoryDynamicRange(conn, vmSpec.getMinRam() * 1024 * 1024, vmSpec.getMaxRam() * 1024 * 1024);
+        vm.setVCPUsNumberLive(conn, (long)vmSpec.getCpus());
+
+        Integer speed = vmSpec.getSpeed();
+        if (speed != null) {
+
+            int cpuWeight = _maxWeight; //cpu_weight
+
+            // weight based allocation
+
+            cpuWeight = (int)((speed*0.99) / _host.speed * _maxWeight);
+            if (cpuWeight > _maxWeight) {
+                cpuWeight = _maxWeight;
+            }
+
+            if (vmSpec.getLimitCpuUse()) {
+                long utilization = 0; // max CPU cap, default is unlimited
+                utilization = ((long)speed * 100 * vmSpec.getCpus()) / _host.speed ;
+                vm.addToVCPUsParamsLive(conn, "cap", Long.toString(utilization));
+            }
+            //vm.addToVCPUsParamsLive(conn, "weight", Integer.toString(cpuWeight));
+            callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", Integer.toString(cpuWeight), "vmname", vmSpec.getName() );
+        }
+    }
+
+    public ScaleVmAnswer execute(ScaleVmCommand cmd) {
+        VirtualMachineTO vmSpec = cmd.getVirtualMachine();
+        String vmName = vmSpec.getName();
+        try {
+            Connection conn = getConnection();
+            Set<VM> vms = VM.getByNameLabel(conn, vmName);
+            Host host = Host.getByUuid(conn, _host.uuid);
+            // stop vm which is running on this host or is in halted state
+            Iterator<VM> iter = vms.iterator();
+            while ( iter.hasNext() ) {
+                VM vm = iter.next();
+                VM.Record vmr = vm.getRecord(conn);
+
+                if ((vmr.powerState == VmPowerState.HALTED) || (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid))) {
+                    iter.remove();
+                }
+            }
+
+            if (vms.size() == 0) {
+                s_logger.info("No running VM " + vmName +" exists on XenServer" + _host.uuid);
+                return new ScaleVmAnswer(cmd, false, "VM does not exist");
+            }
+
+            for (VM vm : vms) {
+                VM.Record vmr = vm.getRecord(conn);
+                try {
+                    scaleVM(conn, vm, vmSpec, host);
+
+                } catch (Exception e) {
+                    String msg = "Catch exception " + e.getClass().getName() + " when scaling VM:" + vmName + " due to " + e.toString();
+                    s_logger.debug(msg);
+                    return new ScaleVmAnswer(cmd, false, msg);
+                }
+
+            }
+            String msg = "scaling VM " + vmName + " is successful on host " + host;
+            s_logger.debug(msg);
+            return new ScaleVmAnswer(cmd, true, msg);
+
+        } catch (XenAPIException e) {
+            String msg = "Upgrade Vm " + vmName + " fail due to " + e.toString();
+            s_logger.warn(msg, e);
+            return new ScaleVmAnswer(cmd, false, msg);
+        } catch (XmlRpcException e) {
+            String msg = "Upgrade Vm " + vmName + " fail due to " + e.getMessage();
+            s_logger.warn(msg, e);
+            return new ScaleVmAnswer(cmd, false, msg);
+        } catch (Exception e) {
+            String msg = "Unable to upgrade " + vmName + " due to " + e.getMessage();
+            s_logger.warn(msg, e);
+            return new ScaleVmAnswer(cmd, false, msg);
+        }
+    }
 
     private Answer execute(RevertToVMSnapshotCommand cmd) {
         String vmName = cmd.getVmName();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56FP1Resource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56FP1Resource.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56FP1Resource.java
index 7040311..d64e173 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56FP1Resource.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/XenServer56FP1Resource.java
@@ -138,9 +138,14 @@ public class XenServer56FP1Resource extends XenServer56Resource {
         record.actionsAfterShutdown = Types.OnNormalExit.DESTROY;
         record.memoryDynamicMax = vmSpec.getMaxRam();
         record.memoryDynamicMin = vmSpec.getMinRam();
-        record.memoryStaticMax = vmSpec.getMaxRam();
-        record.memoryStaticMin = vmSpec.getMinRam();
-        record.VCPUsMax = (long) vmSpec.getCpus();
+        record.memoryStaticMax = 8589934592L; //128GB
+        record.memoryStaticMin = 134217728L; //128MB
+        if (guestOsTypeName.toLowerCase().contains("windows")) {
+            record.VCPUsMax = (long) vmSpec.getCpus();
+        } else {
+            record.VCPUsMax = 32L;
+        }
+
         record.VCPUsAtStartup = (long) vmSpec.getCpus();
         record.consoles.clear();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java b/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java
new file mode 100644
index 0000000..7392cb1
--- /dev/null
+++ b/plugins/hypervisors/xen/test/com/cloud/hypervisor/xen/resource/CitrixResourceBaseTest.java
@@ -0,0 +1,148 @@
+/*
+ * 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.xen.resource;
+
+import org.junit.Test;
+import org.junit.Before;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.MockitoAnnotations;
+import static org.mockito.Mockito.*;
+
+import com.cloud.hypervisor.xen.resource.CitrixResourceBase.XsHost;
+import com.cloud.agent.api.ScaleVmCommand;
+import com.cloud.agent.api.to.VirtualMachineTO;
+import com.cloud.agent.api.ScaleVmAnswer;
+import com.xensource.xenapi.*;
+import org.apache.xmlrpc.XmlRpcException;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.Iterator;
+
+
+
+
+public class CitrixResourceBaseTest {
+
+    @Spy CitrixResourceBase _resource = new CitrixResourceBase() {
+
+        @Override
+        public ScaleVmAnswer execute(ScaleVmCommand cmd) {
+            return super.execute(cmd);
+        }
+        public String callHostPlugin(Connection conn, String plugin, String cmd, String... params) {
+            return "Success";
+        }
+        @Override
+        protected void scaleVM(Connection conn, VM vm, VirtualMachineTO vmSpec, Host host) throws Types.XenAPIException, XmlRpcException {
+            _host.speed = 500;
+            super.scaleVM(conn, vm, vmSpec, host);
+        }
+
+
+    };
+    @Mock XsHost _host;
+    @Mock Host host;
+    @Mock ScaleVmCommand cmd;
+    @Mock VirtualMachineTO vmSpec;
+    @Mock Connection conn;
+    @Mock VM vm;
+
+    @Before
+    public void setup(){
+
+        MockitoAnnotations.initMocks(this);
+
+        doReturn(vmSpec).when(cmd).getVirtualMachine();
+        doReturn("i-2-3-VM").when(vmSpec).getName();
+
+    }
+
+
+    // Expecting XmlRpcException while trying to get the record of vm using connection
+    @Test(expected = XmlRpcException.class)
+    public void testScaleVMF1()  throws
+            Types.BadServerResponse,
+            Types.XenAPIException,
+            XmlRpcException {
+        doReturn(conn).when(_resource).getConnection();
+        Set<VM> vms = (Set<VM> )mock(Set.class);
+
+        Iterator iter =  mock(Iterator.class);
+        doReturn(iter).when(vms).iterator();
+        when(iter.hasNext()).thenReturn(true).thenReturn(false);
+        doReturn(vm).when(iter).next();
+        VM.Record vmr = mock(VM.Record.class);
+        when(vm.getRecord(conn)).thenThrow(new XmlRpcException("XmlRpcException"));
+        when(vm.getRecord(conn)).thenReturn(vmr);
+        vmr.powerState = Types.VmPowerState.RUNNING;
+        vmr.residentOn = mock(Host.class);
+        XenAPIObject object = mock(XenAPIObject.class);
+        doReturn(new String("OpaqueRef:NULL")).when(object).toWireString();
+        doNothing().when(_resource).scaleVM(conn, vm, vmSpec, host);
+
+        _resource.execute(cmd);
+        verify(iter, times(2)).hasNext();
+        verify(iter, times(2)).next();
+
+    }
+
+    // Test to scale vm "i-2-3-VM" cpu-cap disabled
+    @Test
+    public void testScaleVMF2() throws Types.XenAPIException, XmlRpcException {
+
+        doReturn(null).when(vm).setMemoryDynamicRangeAsync(conn, 536870912L, 536870912L);
+        doReturn(1).when(vmSpec).getCpus();
+        doNothing().when(vm).setVCPUsNumberLive(conn, 1L);
+        doReturn(500).when(vmSpec).getSpeed();
+        doReturn(false).when(vmSpec).getLimitCpuUse();
+        Map<String, String> args = (Map<String, String>)mock(HashMap.class);
+        when(host.callPlugin(conn, "vmops", "add_to_VCPUs_params_live", args)).thenReturn("Success");
+        doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
+
+        _resource.scaleVM(conn, vm, vmSpec, host);
+
+        verify(vmSpec, times(1)).getLimitCpuUse();
+        verify(_resource, times(1)).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
+    }
+
+    // Test to scale vm "i-2-3-VM" cpu-cap enabled
+    @Test
+    public void testScaleVMF3() throws Types.XenAPIException, XmlRpcException {
+
+        doReturn(null).when(vm).setMemoryDynamicRangeAsync(conn, 536870912L, 536870912L);
+        doReturn(1).when(vmSpec).getCpus();
+        doNothing().when(vm).setVCPUsNumberLive(conn, 1L);
+        doReturn(500).when(vmSpec).getSpeed();
+        doReturn(true).when(vmSpec).getLimitCpuUse();
+        doNothing().when(vm).addToVCPUsParamsLive(conn, "cap", "100");
+        Map<String, String> args = (Map<String, String>)mock(HashMap.class);
+        when(host.callPlugin(conn, "vmops", "add_to_VCPUs_params_live", args)).thenReturn("Success");
+        doReturn(null).when(_resource).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
+
+        _resource.scaleVM(conn, vm, vmSpec, host);
+
+        verify(vmSpec, times(1)).getLimitCpuUse();
+        verify(_resource, times(1)).callHostPlugin(conn, "vmops", "add_to_VCPUs_params_live", "key", "weight", "value", "253", "vmname", "i-2-3-VM");
+        verify(vm, times(1)).addToVCPUsParamsLive(conn, "cap", "100");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/scripts/vm/hypervisor/xenserver/Add-To-VCPUs-Params-Live.sh
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/Add-To-VCPUs-Params-Live.sh b/scripts/vm/hypervisor/xenserver/Add-To-VCPUs-Params-Live.sh
new file mode 100644
index 0000000..0fadcd8
--- /dev/null
+++ b/scripts/vm/hypervisor/xenserver/Add-To-VCPUs-Params-Live.sh
@@ -0,0 +1,33 @@
+#!/bin/sh
+# 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.
+
+set -x
+
+vmname=$1
+key=$2
+value=$3
+uuid=`xe vm-list name-label=$vmname | grep uuid | awk '{print $NF}'`
+if [[ $key == "weight" ]]
+then
+    xe vm-param-set VCPUs-params:weight=$value uuid=$uuid
+fi
+if [[ $key == "cap" ]]
+then
+    xe vm-param-set VCPUs-params:cap=$value uuid=$uuid
+fi
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/scripts/vm/hypervisor/xenserver/vmops
----------------------------------------------------------------------
diff --git a/scripts/vm/hypervisor/xenserver/vmops b/scripts/vm/hypervisor/xenserver/vmops
index 31c9a59..30b5300 100755
--- a/scripts/vm/hypervisor/xenserver/vmops
+++ b/scripts/vm/hypervisor/xenserver/vmops
@@ -43,6 +43,18 @@ def echo(fn):
     return wrapped
 
 @echo
+def add_to_VCPUs_params_live(session, args):
+    key = args['key']
+    value = args['value']
+    vmname = args['vmname']
+    try:
+        cmd = ["bash", "/opt/xensource/bin/Add-To-VCPUs-Params-Live.sh", vmname, key, value]
+        txt = util.pread2(cmd)
+    except:
+        return 'false'
+    return 'true'
+
+@echo
 def gethostvmstats(session, args):
     collect_host_stats = args['collectHostStats']
     consolidation_function = args['consolidationFunction']
@@ -1661,6 +1673,7 @@ if __name__ == "__main__":
                             "default_network_rules_systemvm":default_network_rules_systemvm, 
                             "network_rules_vmSecondaryIp":network_rules_vmSecondaryIp,
                             "get_rule_logs_for_vms":get_rule_logs_for_vms, 
+			    "add_to_VCPUs_params_live":add_to_VCPUs_params_live,
                             "setLinkLocalIP":setLinkLocalIP,
                             "cleanup_rules":cleanup_rules,
                             "bumpUpPriority":bumpUpPriority,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/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 1a57a64..ba4ae62 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -177,7 +177,8 @@ public enum Config {
 	RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null),
     RouterExtraPublicNics("Advanced", NetworkManager.class, Integer.class, "router.extra.public.nics", "2", "specify extra public nics used for virtual router(up to 5)", "0-5"),
 	StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null),
-	StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
+    ScaleRetry("Advanced", AgentManager.class, Integer.class, "scale.retry", "2", "Number of times to retry scaling up the vm", null),
+    StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null),
 	StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null),
 	StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null),
 	UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null),

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/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 f80e0c2..ecd7751 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -2115,6 +2115,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
         cmdList.add(DestroyVMCmd.class);
         cmdList.add(GetVMPasswordCmd.class);
         cmdList.add(ListVMsCmd.class);
+        cmdList.add(ScaleVMCmd.class);
         cmdList.add(RebootVMCmd.class);
         cmdList.add(RemoveNicFromVMCmd.class);
         cmdList.add(ResetVMPasswordCmd.class);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/src/com/cloud/vm/ItWorkVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/ItWorkVO.java b/server/src/com/cloud/vm/ItWorkVO.java
index 6f53495..d218880 100644
--- a/server/src/com/cloud/vm/ItWorkVO.java
+++ b/server/src/com/cloud/vm/ItWorkVO.java
@@ -41,7 +41,8 @@ public class ItWorkVO {
         Started,
         Release,
         Done,
-        Migrating
+        Migrating,
+        Reconfiguring
     }
     
     @Id

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 82a69bd..6e9cd43 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -32,22 +32,12 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import com.cloud.api.ApiDBUtils;
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
 import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
-import org.apache.cloudstack.api.command.user.vm.AddNicToVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DeployVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RemoveNicFromVMCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
-import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
-import org.apache.cloudstack.api.command.user.vm.StartVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateDefaultNicForVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
+import org.apache.cloudstack.api.command.user.vm.*;
 import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
 import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
 import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity;
@@ -349,7 +339,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     @Inject
     protected SecurityGroupDao _securityGroupDao;
     @Inject
-    protected CapacityManager _capacityMgr;;
+    protected CapacityManager _capacityMgr;
     @Inject
     protected VMInstanceDao _vmInstanceDao;
     @Inject
@@ -397,6 +387,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     protected String _instance;
     protected String _zone;
     protected boolean _instanceNameFlag;
+    protected int _scaleRetry;
 
     @Inject ConfigurationDao _configDao;
     private int _createprivatetemplatefromvolumewait;
@@ -1048,6 +1039,78 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     }
 
     @Override
+    @ActionEvent(eventType = EventTypes.EVENT_VM_SCALE, eventDescription = "scaling Vm")
+    public UserVm
+    upgradeVirtualMachine(ScaleVMCmd cmd) throws InvalidParameterValueException {
+        Long vmId = cmd.getId();
+        Long newServiceOfferingId = cmd.getServiceOfferingId();
+        Account caller = UserContext.current().getCaller();
+
+        // Verify input parameters
+        VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
+        if(vmInstance.getHypervisorType() != HypervisorType.XenServer){
+            throw new InvalidParameterValueException("This operation not permitted for this hypervisor of the vm");
+        }
+
+        _accountMgr.checkAccess(caller, null, true, vmInstance);
+
+        // Check that the specified service offering ID is valid
+        _itMgr.checkIfCanUpgrade(vmInstance, newServiceOfferingId);
+
+        //Check if its a scale "up"
+        ServiceOffering newServiceOffering = _configMgr.getServiceOffering(newServiceOfferingId);
+        ServiceOffering oldServiceOffering = _configMgr.getServiceOffering(vmInstance.getServiceOfferingId());
+        if(newServiceOffering.getSpeed() <= oldServiceOffering.getSpeed()
+                && newServiceOffering.getRamSize() <= oldServiceOffering.getRamSize()){
+            throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering should have both cpu and memory greater than the old values");
+        }
+
+        // Dynamically upgrade the running vms
+        if(vmInstance.getState().equals(State.Running)){
+            boolean success = false;
+            int retry = _scaleRetry;
+            while (retry-- != 0) { // It's != so that it can match -1.
+                try{
+                    // #1 Check existing host has capacity
+                    boolean existingHostHasCapacity = _capacityMgr.checkIfHostHasCapacity(vmInstance.getHostId(), newServiceOffering.getSpeed() - oldServiceOffering.getSpeed(),
+                            (newServiceOffering.getRamSize() - oldServiceOffering.getRamSize()) * 1024L * 1024L, false, ApiDBUtils.getCpuOverprovisioningFactor(), 1f,  false); // TO DO fill it with mem.
+
+                    // #2 migrate the vm if host doesn't have capacity
+                    if (!existingHostHasCapacity){
+                        vmInstance = _itMgr.findHostAndMigrate(vmInstance.getType(), vmInstance, newServiceOfferingId);
+                    }
+
+                    // #3 scale the vm now
+                    _itMgr.upgradeVmDb(vmId, newServiceOfferingId);
+                    vmInstance = _vmInstanceDao.findById(vmId);
+                    vmInstance = _itMgr.reConfigureVm(vmInstance, oldServiceOffering, existingHostHasCapacity);
+                    success = true;
+                    return _vmDao.findById(vmInstance.getId());
+                }catch(InsufficientCapacityException e ){
+                    s_logger.warn("Received exception while scaling ",e);
+                } catch (ResourceUnavailableException e) {
+                    s_logger.warn("Received exception while scaling ",e);
+                } catch (ConcurrentOperationException e) {
+                    s_logger.warn("Received exception while scaling ",e);
+                } catch (VirtualMachineMigrationException e) {
+                    s_logger.warn("Received exception while scaling ",e);
+                } catch (ManagementServerException e) {
+                    s_logger.warn("Received exception while scaling ",e);
+                }finally{
+                    if(!success){
+                        _itMgr.upgradeVmDb(vmId, oldServiceOffering.getId()); // rollback
+                    }
+                }
+            }
+            if (!success)
+                return null;
+        }
+
+        return _vmDao.findById(vmInstance.getId());
+
+    }
+
+    @Override
     public HashMap<Long, VmStatsEntry> getVirtualMachineStatistics(long hostId,
             String hostName, List<Long> vmIds) throws CloudRuntimeException {
         HashMap<Long, VmStatsEntry> vmStatsById = new HashMap<Long, VmStatsEntry>();
@@ -1240,6 +1303,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                 new UserVmStateListener(_usageEventDao, _networkDao, _nicDao));
 
         value = _configDao.getValue(Config.SetVmInternalNameUsingDisplayName.key());
+
         if(value == null) {
             _instanceNameFlag = false;
         }
@@ -1248,6 +1312,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             _instanceNameFlag = Boolean.parseBoolean(value);
         }
 
+       _scaleRetry = NumbersUtil.parseInt(configs.get(Config.ScaleRetry.key()), 2);
+
         s_logger.info("User VM Manager is configured.");
 
         return true;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/src/com/cloud/vm/VirtualMachineManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/VirtualMachineManager.java b/server/src/com/cloud/vm/VirtualMachineManager.java
index 7b34f7f0..4a30d97 100644
--- a/server/src/com/cloud/vm/VirtualMachineManager.java
+++ b/server/src/com/cloud/vm/VirtualMachineManager.java
@@ -186,4 +186,16 @@ public interface VirtualMachineManager extends Manager {
      */
     VirtualMachineTO toVmTO(VirtualMachineProfile<? extends VMInstanceVO> profile);
 
+
+    VMInstanceVO reConfigureVm(VMInstanceVO vm, ServiceOffering newServiceOffering, boolean sameHost)
+            throws ResourceUnavailableException, ConcurrentOperationException;
+
+    VMInstanceVO findHostAndMigrate(VirtualMachine.Type vmType, VMInstanceVO vm, Long newSvcOfferingId) throws InsufficientCapacityException,
+            ConcurrentOperationException, ResourceUnavailableException,
+            VirtualMachineMigrationException, ManagementServerException;
+
+    <T extends VMInstanceVO> T migrateForScale(T vm, long srcHostId, DeployDestination dest, Long newSvcOfferingId)
+            throws ResourceUnavailableException, ConcurrentOperationException,
+            ManagementServerException, VirtualMachineMigrationException;
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
index 0aeef0e..a6d0b1b 100755
--- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -36,37 +36,18 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import com.cloud.capacity.CapacityManager;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 
 import com.cloud.dc.*;
+import com.cloud.agent.api.*;
 import org.apache.log4j.Logger;
 
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.AgentManager.OnError;
 import com.cloud.agent.Listener;
-import com.cloud.agent.api.AgentControlAnswer;
-import com.cloud.agent.api.AgentControlCommand;
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.CheckVirtualMachineAnswer;
-import com.cloud.agent.api.CheckVirtualMachineCommand;
-import com.cloud.agent.api.ClusterSyncAnswer;
-import com.cloud.agent.api.ClusterSyncCommand;
-import com.cloud.agent.api.Command;
-import com.cloud.agent.api.MigrateAnswer;
-import com.cloud.agent.api.MigrateCommand;
-import com.cloud.agent.api.PingRoutingCommand;
-import com.cloud.agent.api.PrepareForMigrationAnswer;
-import com.cloud.agent.api.PrepareForMigrationCommand;
-import com.cloud.agent.api.RebootAnswer;
-import com.cloud.agent.api.RebootCommand;
-import com.cloud.agent.api.StartAnswer;
-import com.cloud.agent.api.StartCommand;
-import com.cloud.agent.api.StartupCommand;
-import com.cloud.agent.api.StartupRoutingCommand;
 import com.cloud.agent.api.StartupRoutingCommand.VmState;
-import com.cloud.agent.api.StopAnswer;
-import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.manager.Commands;
@@ -195,6 +176,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     @Inject
     protected UserVmDao _userVmDao;
     @Inject
+    protected CapacityManager _capacityMgr;
+    @Inject
     protected NicDao _nicsDao;
     @Inject
     protected AccountManager _accountMgr;
@@ -2422,13 +2405,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         if (newServiceOffering == null) {
             throw new InvalidParameterValueException("Unable to find a service offering with id " + newServiceOfferingId);
         }
-		
-        // Check that the VM is stopped
-        if (!vmInstance.getState().equals(State.Stopped)) {
+
+        // Check that the VM is stopped / running
+        if (!(vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Running) )) {
             s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
-            throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " +
-                    "in state " + vmInstance.getState()
-                    + "; make sure the virtual machine is stopped and not in an error state before upgrading.");
+            throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState()
+                    + "; make sure the virtual machine is stopped/running");
         }
 
         // Check if the service offering being upgraded to is what the VM is already running with
@@ -2679,4 +2661,277 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         return true;
     }
 
-}
+    @Override
+    public VMInstanceVO findHostAndMigrate(VirtualMachine.Type vmType, VMInstanceVO vm, Long newSvcOfferingId)
+            throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, VirtualMachineMigrationException, ManagementServerException {
+
+        VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
+
+        Long srcHostId = vm.getHostId();
+        Long oldSvcOfferingId = vm.getServiceOfferingId();
+        if (srcHostId == null) {
+            throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id");
+        }
+        Host host = _hostDao.findById(srcHostId);
+        DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null);
+        ExcludeList excludes = new ExcludeList();
+        excludes.addHost(vm.getHostId());
+        vm.setServiceOfferingId(newSvcOfferingId); // Need to find the destination host based on new svc offering
+
+        DeployDestination dest = null;
+
+        for (DeploymentPlanner planner : _planners) {
+            if (planner.canHandle(profile, plan, excludes)) {
+                dest = planner.plan(profile, plan, excludes);
+            } else {
+                continue;
+            }
+
+            if (dest != null) {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Planner " + planner + " found " + dest + " for scaling the vm to.");
+                }
+                break;
+            }
+            if (s_logger.isDebugEnabled()) {
+                s_logger.debug("Planner " + planner + " was unable to find anything.");
+            }
+        }
+
+        if (dest == null) {
+            throw new InsufficientServerCapacityException("Unable to find a server to scale the vm to.", host.getClusterId());
+        }
+
+        excludes.addHost(dest.getHost().getId());
+        VMInstanceVO vmInstance = null;
+        try {
+            vmInstance = migrateForScale(vm, srcHostId, dest, oldSvcOfferingId);
+        } catch (ResourceUnavailableException e) {
+            s_logger.debug("Unable to migrate to unavailable " + dest);
+            throw e;
+        } catch (ConcurrentOperationException e) {
+            s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
+            throw e;
+        } catch (ManagementServerException e) {
+            s_logger.debug("Unable to migrate VM: " + e.getMessage());
+            throw e;
+        } catch (VirtualMachineMigrationException e) {
+            s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage());
+            if (vm.getState() == State.Starting) {
+                s_logger.debug("VM seems to be still Starting, we should retry migration later");
+                throw e;
+            } else {
+                s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString());
+            }
+        }
+        if (vmInstance != null) {
+            return vmInstance;
+        }else{
+            return null;
+        }
+    }
+
+        @Override
+        public <T extends VMInstanceVO> T migrateForScale(T vm, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
+                VirtualMachineMigrationException {
+            s_logger.info("Migrating " + vm + " to " + dest);
+
+            Long newSvcOfferingId = vm.getServiceOfferingId();
+            long dstHostId = dest.getHost().getId();
+            Host fromHost = _hostDao.findById(srcHostId);
+            if (fromHost == null) {
+                s_logger.info("Unable to find the host to migrate from: " + srcHostId);
+                throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
+            }
+
+            if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
+                s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
+                throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
+            }
+
+            VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
+
+            long vmId = vm.getId();
+            vm = vmGuru.findById(vmId);
+            if (vm == null) {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Unable to find the vm " + vm);
+                }
+                throw new ManagementServerException("Unable to find a virtual machine with id " + vmId);
+            }
+
+            if (vm.getState() != State.Running) {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
+                }
+                throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
+            }
+
+            short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
+            if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
+                alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
+            } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
+                alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
+            }
+
+            VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
+            _networkMgr.prepareNicForMigration(profile, dest);
+            this.volumeMgr.prepareForMigration(profile, dest);
+
+            VirtualMachineTO to = toVmTO(profile);
+            PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
+
+            ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
+            work.setStep(Step.Prepare);
+            work.setResourceType(ItWorkVO.ResourceType.Host);
+            work.setResourceId(dstHostId);
+            work = _workDao.persist(work);
+
+            PrepareForMigrationAnswer pfma = null;
+            try {
+                pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc);
+                if (!pfma.getResult()) {
+                    String msg = "Unable to prepare for migration due to " + pfma.getDetails();
+                    pfma = null;
+                    throw new AgentUnavailableException(msg, dstHostId);
+                }
+            } catch (OperationTimedoutException e1) {
+                throw new AgentUnavailableException("Operation timed out", dstHostId);
+            } finally {
+                if (pfma == null) {
+                    work.setStep(Step.Done);
+                    _workDao.update(work.getId(), work);
+                }
+            }
+
+            vm.setLastHostId(srcHostId);
+            try {
+                if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
+                    s_logger.info("Migration cancelled because state has changed: " + vm);
+                    throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
+                }
+            } catch (NoTransitionException e1) {
+                s_logger.info("Migration cancelled because " + e1.getMessage());
+                throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
+            }
+
+            boolean migrated = false;
+            try {
+                boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
+                MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
+                mc.setHostGuid(dest.getHost().getGuid());
+
+                try {
+                    MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc);
+                    if (!ma.getResult()) {
+                        s_logger.error("Unable to migrate due to " + ma.getDetails());
+                        return null;
+                    }
+                } catch (OperationTimedoutException e) {
+                    if (e.isActive()) {
+                        s_logger.warn("Active migration command so scheduling a restart for " + vm);
+                        _haMgr.scheduleRestart(vm, true);
+                    }
+                    throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
+                }
+
+                try {
+                    long newServiceOfferingId = vm.getServiceOfferingId();
+                    vm.setServiceOfferingId(oldSvcOfferingId); // release capacity for the old service offering only
+                    if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
+                        throw new ConcurrentOperationException("Unable to change the state for " + vm);
+                    }
+                    vm.setServiceOfferingId(newServiceOfferingId);
+                } catch (NoTransitionException e1) {
+                    throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
+                }
+
+                try {
+                    if (!checkVmOnHost(vm, dstHostId)) {
+                        s_logger.error("Unable to complete migration for " + vm);
+                        try {
+                            _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
+                        } catch (AgentUnavailableException e) {
+                            s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
+                        }
+                        cleanup(vmGuru, new VirtualMachineProfileImpl<T>(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
+                        return null;
+                    }
+                } catch (OperationTimedoutException e) {
+                }
+
+                migrated = true;
+                return vm;
+            } finally {
+                if (!migrated) {
+                    s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
+
+                    _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone "
+                            + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed.  Please check logs.");
+                    try {
+                        _agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
+                    } catch (AgentUnavailableException ae) {
+                        s_logger.info("Looks like the destination Host is unavailable for cleanup");
+                    }
+
+                    try {
+                        stateTransitTo(vm, Event.OperationFailed, srcHostId);
+                    } catch (NoTransitionException e) {
+                        s_logger.warn(e.getMessage());
+                    }
+                }
+
+                work.setStep(Step.Done);
+                _workDao.update(work.getId(), work);
+            }
+        }
+    @Override
+    public VMInstanceVO reConfigureVm(VMInstanceVO vm , ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException, ConcurrentOperationException {
+
+        long newServiceofferingId = vm.getServiceOfferingId();
+        ServiceOffering newServiceOffering = _configMgr.getServiceOffering(newServiceofferingId);
+        ScaleVmCommand reconfigureCmd = new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(),
+                newServiceOffering.getSpeed(), newServiceOffering.getRamSize(), newServiceOffering.getRamSize(), newServiceOffering.getLimitCpuUse());
+
+        Long dstHostId = vm.getHostId();
+        ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId());
+        work.setStep(Step.Prepare);
+        work.setResourceType(ItWorkVO.ResourceType.Host);
+        work.setResourceId(vm.getHostId());
+        work = _workDao.persist(work);
+        boolean success = false;
+        try {
+            if(reconfiguringOnExistingHost){
+                vm.setServiceOfferingId(oldServiceOffering.getId());
+                _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); //release the old capacity
+                vm.setServiceOfferingId(newServiceofferingId);
+                _capacityMgr.allocateVmCapacity(vm, false); // lock the new capacity
+            }
+
+            Answer reconfigureAnswer = _agentMgr.send(vm.getHostId(), reconfigureCmd);
+            if (reconfigureAnswer == null || !reconfigureAnswer.getResult()) {
+                s_logger.error("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
+                throw new CloudRuntimeException("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
+            }
+
+            success = true;
+        } catch (OperationTimedoutException e) {
+            throw new AgentUnavailableException("Operation timed out on reconfiguring " + vm, dstHostId);
+        } catch (AgentUnavailableException e) {
+            throw e;
+        } finally{
+           // work.setStep(Step.Done);
+            //_workDao.update(work.getId(), work);
+            if(!success){
+                _capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); // release the new capacity
+                vm.setServiceOfferingId(oldServiceOffering.getId());
+                _capacityMgr.allocateVmCapacity(vm, false); // allocate the old capacity
+            }
+        }
+
+        return vm;
+
+    }
+
+
+    }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/test/com/cloud/vm/MockUserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/MockUserVmManagerImpl.java b/server/test/com/cloud/vm/MockUserVmManagerImpl.java
index 09825a8..dd8dd83 100644
--- a/server/test/com/cloud/vm/MockUserVmManagerImpl.java
+++ b/server/test/com/cloud/vm/MockUserVmManagerImpl.java
@@ -25,18 +25,7 @@ import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
 import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd;
-import org.apache.cloudstack.api.command.user.vm.AddNicToVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DeployVMCmd;
-import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RebootVMCmd;
-import org.apache.cloudstack.api.command.user.vm.RemoveNicFromVMCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd;
-import org.apache.cloudstack.api.command.user.vm.ResetVMSSHKeyCmd;
-import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
-import org.apache.cloudstack.api.command.user.vm.StartVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateDefaultNicForVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd;
-import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
+import org.apache.cloudstack.api.command.user.vm.*;
 import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
 import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
 import org.springframework.stereotype.Component;
@@ -391,6 +380,10 @@ public class MockUserVmManagerImpl extends ManagerBase implements UserVmManager,
         return null;
     }
 
+    @Override
+    public UserVm upgradeVirtualMachine(ScaleVMCmd scaleVMCmd) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
+        return null;  //To change body of implemented methods use File | Settings | File Templates.
+    }
 
 
     @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/test/com/cloud/vm/MockVirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/MockVirtualMachineManagerImpl.java b/server/test/com/cloud/vm/MockVirtualMachineManagerImpl.java
index 612c70d..4917e77 100755
--- a/server/test/com/cloud/vm/MockVirtualMachineManagerImpl.java
+++ b/server/test/com/cloud/vm/MockVirtualMachineManagerImpl.java
@@ -265,6 +265,23 @@ public class MockVirtualMachineManagerImpl extends ManagerBase implements Virtua
         return null;
     }
 
+    @Override
+    public VMInstanceVO reConfigureVm(VMInstanceVO vm, ServiceOffering newServiceOffering, boolean sameHost) throws ResourceUnavailableException, ConcurrentOperationException {
+        return null;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    @Override
+    public VMInstanceVO findHostAndMigrate(VirtualMachine.Type vmType, VMInstanceVO vm, Long newSvcOfferingId) throws InsufficientCapacityException,
+            ConcurrentOperationException, ResourceUnavailableException,
+            VirtualMachineMigrationException, ManagementServerException{
+        return null;
+    }
+
+    @Override
+    public <T extends VMInstanceVO> T migrateForScale(T vm, long srcHostId, DeployDestination dest, Long newSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
+        return null;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+
     /* (non-Javadoc)
      * @see com.cloud.vm.VirtualMachineManager#addVmToNetwork(com.cloud.vm.VirtualMachine, com.cloud.network.Network, com.cloud.vm.NicProfile)
      */

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/test/com/cloud/vm/UserVmManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/UserVmManagerTest.java b/server/test/com/cloud/vm/UserVmManagerTest.java
index 0795a35..bb1c07b 100755
--- a/server/test/com/cloud/vm/UserVmManagerTest.java
+++ b/server/test/com/cloud/vm/UserVmManagerTest.java
@@ -17,10 +17,21 @@
 
 package com.cloud.vm;
 
+import java.lang.reflect.Field;
 import java.util.List;
 
+import com.cloud.api.ApiDBUtils;
+import com.cloud.capacity.CapacityManager;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.hypervisor.Hypervisor;
+import com.cloud.offering.ServiceOffering;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.user.*;
+import com.cloud.vm.dao.VMInstanceDao;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
+import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
 import org.apache.log4j.Logger;
 import org.junit.Test;
 import org.junit.Before;
@@ -39,10 +50,6 @@ import com.cloud.storage.VolumeManager;
 import com.cloud.storage.VolumeVO;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VolumeDao;
-import com.cloud.user.Account;
-import com.cloud.user.AccountManager;
-import com.cloud.user.AccountVO;
-import com.cloud.user.UserVO;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.user.dao.UserDao;
 import com.cloud.utils.exception.CloudRuntimeException;
@@ -57,15 +64,21 @@ public class UserVmManagerTest {
     @Mock VolumeManager _storageMgr;
     @Mock Account _account;
     @Mock AccountManager _accountMgr;
+    @Mock ConfigurationManager _configMgr;
+    @Mock CapacityManager _capacityMgr;
     @Mock AccountDao _accountDao;
+    @Mock
+    ConfigurationDao _configDao;
     @Mock UserDao _userDao;
     @Mock UserVmDao _vmDao;
+    @Mock VMInstanceDao _vmInstanceDao;
     @Mock VMTemplateDao _templateDao;
     @Mock VolumeDao _volsDao;
     @Mock RestoreVMCmd _restoreVMCmd;
     @Mock AccountVO _accountMock;
     @Mock UserVO _userMock;
     @Mock UserVmVO _vmMock;
+    @Mock VMInstanceVO _vmInstance;
     @Mock VMTemplateVO _templateMock;
     @Mock VolumeVO _volumeMock;
     @Mock List<VolumeVO> _rootVols;
@@ -74,6 +87,7 @@ public class UserVmManagerTest {
         MockitoAnnotations.initMocks(this);
 
         _userVmMgr._vmDao = _vmDao;
+        _userVmMgr._vmInstanceDao = _vmInstanceDao;
         _userVmMgr._templateDao = _templateDao;
         _userVmMgr._volsDao = _volsDao;
         _userVmMgr._itMgr = _itMgr;
@@ -81,6 +95,9 @@ public class UserVmManagerTest {
         _userVmMgr._accountDao = _accountDao;
         _userVmMgr._userDao = _userDao;
         _userVmMgr._accountMgr = _accountMgr;
+        _userVmMgr._configMgr = _configMgr;
+        _userVmMgr._capacityMgr = _capacityMgr;
+        _userVmMgr._scaleRetry = 2;
 
         doReturn(3L).when(_account).getId();
         doReturn(8L).when(_vmMock).getAccountId();
@@ -88,6 +105,8 @@ public class UserVmManagerTest {
         when(_userDao.findById(anyLong())).thenReturn(_userMock);
         doReturn(Account.State.enabled).when(_account).getState();
         when(_vmMock.getId()).thenReturn(314L);
+        when(_vmInstance.getId()).thenReturn(1L);
+        when(_vmInstance.getServiceOfferingId()).thenReturn(2L);
 
     }
 
@@ -179,4 +198,169 @@ public class UserVmManagerTest {
 
     }
 
+    // Test scaleVm on incompatible HV.
+    @Test(expected=InvalidParameterValueException.class)
+    public void testScaleVMF1()  throws Exception {
+
+        ScaleVMCmd cmd = new ScaleVMCmd();
+        Class<?> _class = cmd.getClass();
+
+        Field idField = _class.getDeclaredField("id");
+        idField.setAccessible(true);
+        idField.set(cmd, 1L);
+
+        Field serviceOfferingIdField = _class.getDeclaredField("serviceOfferingId");
+        serviceOfferingIdField.setAccessible(true);
+        serviceOfferingIdField.set(cmd, 1L);
+
+       // UserContext.current().setEventDetails("Vm Id: "+getId());
+        Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
+        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
+       UserContext.registerContext(1, account, null, true);
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+
+        _userVmMgr.upgradeVirtualMachine(cmd);
+
+    }
+
+    // Test scaleVm on incompatible HV.
+    @Test(expected=InvalidParameterValueException.class)
+    public void testScaleVMF2()  throws Exception {
+
+        ScaleVMCmd cmd = new ScaleVMCmd();
+        Class<?> _class = cmd.getClass();
+
+        Field idField = _class.getDeclaredField("id");
+        idField.setAccessible(true);
+        idField.set(cmd, 1L);
+
+        Field serviceOfferingIdField = _class.getDeclaredField("serviceOfferingId");
+        serviceOfferingIdField.setAccessible(true);
+        serviceOfferingIdField.set(cmd, 1L);
+
+        //UserContext.current().setEventDetails("Vm Id: "+getId());
+       // Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, 1);
+        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
+       // UserContext.registerContext(1, account, null, true);
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
+
+
+        doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock);
+
+        doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, cmd.getServiceOfferingId());
+
+
+        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
+        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+
+        when(_configMgr.getServiceOffering(anyLong())).thenReturn(so1);
+        when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
+
+        _userVmMgr.upgradeVirtualMachine(cmd);
+
+    }
+
+    // Test scaleVm for Stopped vm. Full positive test.
+    @Test
+    public void testScaleVMF3()  throws Exception {
+
+        ScaleVMCmd cmd = new ScaleVMCmd();
+        Class<?> _class = cmd.getClass();
+
+        Field idField = _class.getDeclaredField("id");
+        idField.setAccessible(true);
+        idField.set(cmd, 1L);
+
+        Field serviceOfferingIdField = _class.getDeclaredField("serviceOfferingId");
+        serviceOfferingIdField.setAccessible(true);
+        serviceOfferingIdField.set(cmd, 1L);
+
+        //UserContext.current().setEventDetails("Vm Id: "+getId());
+        //Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, 1);
+        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
+        //UserContext.registerContext(1, account, null, true);
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
+
+
+        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
+        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+
+        when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
+        when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
+
+        doReturn(VirtualMachine.State.Stopped).when(_vmInstance).getState();
+
+        doReturn(true).when(_itMgr).upgradeVmDb(anyLong(),anyLong());
+
+        when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
+
+        _userVmMgr.upgradeVirtualMachine(cmd);
+
+    }
+
+    // Test scaleVm for Running vm. Full positive test.
+    public void testScaleVMF4()  throws Exception {
+
+        ScaleVMCmd cmd = new ScaleVMCmd();
+        Class<?> _class = cmd.getClass();
+
+        Field idField = _class.getDeclaredField("id");
+        idField.setAccessible(true);
+        idField.set(cmd, 1L);
+
+        Field serviceOfferingIdField = _class.getDeclaredField("serviceOfferingId");
+        serviceOfferingIdField.setAccessible(true);
+        serviceOfferingIdField.set(cmd, 1L);
+
+        //UserContext.current().setEventDetails("Vm Id: "+getId());
+        //Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, 1);
+        //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
+        //UserContext.registerContext(1, account, null, true);
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
+
+        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
+        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+
+        when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
+        when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
+
+        doReturn(VirtualMachine.State.Running).when(_vmInstance).getState();
+
+        //when(ApiDBUtils.getCpuOverprovisioningFactor()).thenReturn(3f);
+        when(_capacityMgr.checkIfHostHasCapacity(anyLong(), anyInt(), anyLong(), anyBoolean(), anyFloat(), anyFloat(),  anyBoolean())).thenReturn(false);
+        when(_itMgr.reConfigureVm(_vmInstance, so1, false)).thenReturn(_vmInstance);
+
+        doReturn(true).when(_itMgr).upgradeVmDb(anyLong(), anyLong());
+
+        when(_vmDao.findById(anyLong())).thenReturn(_vmMock);
+
+        _userVmMgr.upgradeVirtualMachine(cmd);
+
+    }
+
+    private ServiceOfferingVO getSvcoffering(int ramSize){
+
+        long id  = 4L;
+        String name = "name";
+        String displayText = "displayText";
+        int cpu = 1;
+        //int ramSize = 256;
+        int speed = 128;
+
+        boolean ha = false;
+        boolean useLocalStorage = false;
+
+        ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, useLocalStorage, false, null, false, null, false);
+        return serviceOffering;
+    }
+
+
+
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3e4430d8/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java b/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
new file mode 100644
index 0000000..322f051
--- /dev/null
+++ b/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
@@ -0,0 +1,208 @@
+// 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.vm;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ScaleVmAnswer;
+import com.cloud.agent.api.ScaleVmCommand;
+import com.cloud.capacity.CapacityManager;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.VolumeManager;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.user.*;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.user.dao.UserDao;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.dao.UserVmDao;
+import com.cloud.vm.dao.VMInstanceDao;
+import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
+import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
+import org.junit.Test;
+import org.junit.Before;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+import static org.mockito.Mockito.*;
+
+
+import java.lang.reflect.Field;
+import java.util.List;
+
+public class VirtualMachineManagerImplTest {
+
+
+        @Spy VirtualMachineManagerImpl _vmMgr = new VirtualMachineManagerImpl();
+        @Mock
+        VolumeManager _storageMgr;
+        @Mock
+        Account _account;
+        @Mock
+        AccountManager _accountMgr;
+        @Mock
+        ConfigurationManager _configMgr;
+        @Mock
+        CapacityManager _capacityMgr;
+        @Mock
+        AgentManager _agentMgr;
+        @Mock
+        AccountDao _accountDao;
+        @Mock
+        ConfigurationDao _configDao;
+        @Mock
+        HostDao _hostDao;
+        @Mock
+        UserDao _userDao;
+        @Mock
+        UserVmDao _vmDao;
+        @Mock
+        ItWorkDao _workDao;
+        @Mock
+        VMInstanceDao _vmInstanceDao;
+        @Mock
+        VMTemplateDao _templateDao;
+        @Mock
+        VolumeDao _volsDao;
+        @Mock
+        RestoreVMCmd _restoreVMCmd;
+        @Mock
+        AccountVO _accountMock;
+        @Mock
+        UserVO _userMock;
+        @Mock
+        UserVmVO _vmMock;
+        @Mock
+        VMInstanceVO _vmInstance;
+        @Mock
+        HostVO _host;
+        @Mock
+        VMTemplateVO _templateMock;
+        @Mock
+        VolumeVO _volumeMock;
+        @Mock
+        List<VolumeVO> _rootVols;
+        @Mock
+        ItWorkVO _work;
+        @Before
+        public void setup(){
+            MockitoAnnotations.initMocks(this);
+
+            _vmMgr._templateDao = _templateDao;
+            _vmMgr._volsDao = _volsDao;
+            _vmMgr.volumeMgr = _storageMgr;
+            _vmMgr._accountDao = _accountDao;
+            _vmMgr._userDao = _userDao;
+            _vmMgr._accountMgr = _accountMgr;
+            _vmMgr._configMgr = _configMgr;
+            _vmMgr._capacityMgr = _capacityMgr;
+            _vmMgr._hostDao = _hostDao;
+            _vmMgr._nodeId = 1L;
+            _vmMgr._workDao = _workDao;
+            _vmMgr._agentMgr = _agentMgr;
+
+            when(_vmMock.getId()).thenReturn(314l);
+            when(_vmInstance.getId()).thenReturn(1L);
+            when(_vmInstance.getServiceOfferingId()).thenReturn(2L);
+            when(_vmInstance.getInstanceName()).thenReturn("myVm");
+            when(_vmInstance.getHostId()).thenReturn(2L);
+            when(_vmInstance.getType()).thenReturn(VirtualMachine.Type.User);
+            when(_host.getId()).thenReturn(1L);
+            when(_hostDao.findById(anyLong())).thenReturn(null);
+            when(_configMgr.getServiceOffering(anyLong())).thenReturn(getSvcoffering(512));
+            when(_workDao.persist(_work)).thenReturn(_work);
+            when(_workDao.update("1", _work)).thenReturn(true);
+            when(_work.getId()).thenReturn("1");
+            doNothing().when(_work).setStep(ItWorkVO.Step.Done);
+            //doNothing().when(_volsDao).detachVolume(anyLong());
+            //when(_work.setStep(ItWorkVO.Step.Done)).thenReturn("1");
+
+        }
+
+
+    @Test(expected=CloudRuntimeException.class)
+    public void testScaleVM1()  throws Exception {
+
+
+        DeployDestination dest = new DeployDestination(null, null, null, _host);
+        long l = 1L;
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        _vmMgr.migrateForScale(_vmInstance, l, dest, l);
+
+    }
+
+    @Test (expected=CloudRuntimeException.class)
+    public void testScaleVM2()  throws Exception {
+
+        DeployDestination dest = new DeployDestination(null, null, null, _host);
+        long l = 1L;
+
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        ServiceOfferingVO newServiceOffering = getSvcoffering(512);
+        ScaleVmCommand reconfigureCmd = new ScaleVmCommand("myVmName", newServiceOffering.getCpu(),
+                newServiceOffering.getSpeed(), newServiceOffering.getRamSize(), newServiceOffering.getRamSize(), newServiceOffering.getLimitCpuUse());
+        Answer answer = new ScaleVmAnswer(reconfigureCmd, true, "details");
+        when(_agentMgr.send(2l, reconfigureCmd)).thenReturn(null);
+        _vmMgr.reConfigureVm(_vmInstance, getSvcoffering(256), false);
+
+    }
+
+    @Test (expected=CloudRuntimeException.class)
+    public void testScaleVM3()  throws Exception {
+
+        /*VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
+
+        Long srcHostId = vm.getHostId();
+        Long oldSvcOfferingId = vm.getServiceOfferingId();
+        if (srcHostId == null) {
+            throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id");
+        }*/
+
+        when(_vmInstance.getHostId()).thenReturn(null);
+        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
+        _vmMgr.findHostAndMigrate(VirtualMachine.Type.User, _vmInstance, 2l);
+
+    }
+
+
+    private ServiceOfferingVO getSvcoffering(int ramSize){
+
+        long id  = 4L;
+        String name = "name";
+        String displayText = "displayText";
+        int cpu = 1;
+        //int ramSize = 256;
+        int speed = 128;
+
+        boolean ha = false;
+        boolean useLocalStorage = false;
+
+        ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, useLocalStorage, false, null, false, null, false);
+        return serviceOffering;
+    }
+
+
+}


[20/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1834: Events are not generated for registerUserKeys(),
Enabling account and Editing account.


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

Branch: refs/heads/bvt
Commit: 48311363d600264cb3542992a615706cb92f90ad
Parents: b585fa1
Author: Murali Reddy <mu...@citrix.com>
Authored: Fri Mar 29 15:53:21 2013 +0530
Committer: Murali Reddy <mu...@citrix.com>
Committed: Fri Mar 29 15:54:00 2013 +0530

----------------------------------------------------------------------
 api/src/com/cloud/event/EventTypes.java            |    5 +++++
 .../src/com/cloud/server/ManagementServerImpl.java |    1 +
 server/src/com/cloud/user/AccountManagerImpl.java  |    2 ++
 3 files changed, 8 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/48311363/api/src/com/cloud/event/EventTypes.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java
index 2e961e5..704a1bf 100755
--- a/api/src/com/cloud/event/EventTypes.java
+++ b/api/src/com/cloud/event/EventTypes.java
@@ -122,9 +122,11 @@ public class EventTypes {
     public static final String EVENT_GLOBAL_LOAD_BALANCER_DELETE = "GLOBAL.LB.DELETE";
 
     // Account events
+    public static final String EVENT_ACCOUNT_ENABLE = "ACCOUNT.ENABLE";
     public static final String EVENT_ACCOUNT_DISABLE = "ACCOUNT.DISABLE";
     public static final String EVENT_ACCOUNT_CREATE = "ACCOUNT.CREATE";
     public static final String EVENT_ACCOUNT_DELETE = "ACCOUNT.DELETE";
+    public static final String EVENT_ACCOUNT_UPDATE = "ACCOUNT.UPDATE";
     public static final String EVENT_ACCOUNT_MARK_DEFAULT_ZONE = "ACCOUNT.MARK.DEFAULT.ZONE";
 
     // UserVO Events
@@ -137,6 +139,9 @@ public class EventTypes {
     public static final String EVENT_USER_ENABLE = "USER.ENABLE";
     public static final String EVENT_USER_LOCK = "USER.LOCK";
 
+    //registering SSH keypair events
+    public static final String EVENT_REGISTER_SSH_KEYPAIR = "REGISTER.SSH.KEYPAIR";
+
     // Template Events
     public static final String EVENT_TEMPLATE_CREATE = "TEMPLATE.CREATE";
     public static final String EVENT_TEMPLATE_DELETE = "TEMPLATE.DELETE";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/48311363/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 ecd7751..26bc18d 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -3005,6 +3005,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
     }
 
     @Override
+    @ActionEvent(eventType = EventTypes.EVENT_REGISTER_SSH_KEYPAIR, eventDescription = "registering ssh keypair", async = true)
     public SSHKeyPair registerSSHKeyPair(RegisterSSHKeyPairCmd cmd) {
         Account caller = UserContext.current().getCaller();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/48311363/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java
index b69f314..77864fd 100755
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -1172,6 +1172,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     }
 
     @Override
+    @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_ENABLE, eventDescription = "enabling account", async = true)
     public AccountVO enableAccount(String accountName, Long domainId, Long accountId) {
 
         // Check if account exists
@@ -1262,6 +1263,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
     @Override
     @DB
+    @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_UPDATE, eventDescription = "updating account", async = true)
     public AccountVO updateAccount(UpdateAccountCmd cmd) {
         Long accountId = cmd.getId();
         Long domainId = cmd.getDomainId();


[14/25] CLOUDSTACK-1156: Limit Primary and Secondary storage for domain/accounts

Posted by ts...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
index 0bc89e3..7ed6f3f 100755
--- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
+++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
@@ -64,6 +64,7 @@ import com.cloud.event.UsageEventUtils;
 import com.cloud.event.dao.UsageEventDao;
 import com.cloud.exception.AgentUnavailableException;
 import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceAllocationException;
 import com.cloud.exception.StorageUnavailableException;
 import com.cloud.host.Host;
 import com.cloud.host.HostVO;
@@ -97,7 +98,9 @@ import com.cloud.storage.template.TemplateConstants;
 import com.cloud.storage.template.TemplateInfo;
 import com.cloud.template.TemplateManager;
 import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
 import com.cloud.user.ResourceLimitService;
+import com.cloud.utils.UriUtils;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.JoinBuilder;
@@ -177,6 +180,8 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
     protected ResourceLimitService _resourceLimitMgr;
     @Inject
     protected UserVmDao _userVmDao;
+    @Inject
+    protected AccountManager _accountMgr;
 
 	private Boolean _sslCopy = new Boolean(false);
 	private String _copyAuthPasswd;
@@ -289,7 +294,7 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
                  s_logger.warn("There is no secondary storage VM for secondary storage host " + destServer.getName());
                  return false;
             }
-            DownloadListener dl = new DownloadListener(ssAhost, destServer, template, _timer, _vmTemplateHostDao, destTmpltHost.getId(), this, dcmd, _templateDao);
+            DownloadListener dl = new DownloadListener(ssAhost, destServer, template, _timer, _vmTemplateHostDao, destTmpltHost.getId(), this, dcmd, _templateDao, _resourceLimitMgr, _alertMgr, _accountMgr);
             if (downloadJobExists) {
                 dl.setCurrState(destTmpltHost.getDownloadState());
             }
@@ -376,7 +381,7 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
 	             s_logger.warn("There is no secondary storage VM for secondary storage host " + sserver.getName());
 	             return;
 			}
-			DownloadListener dl = new DownloadListener(ssAhost, sserver, template, _timer, _vmTemplateHostDao, vmTemplateHost.getId(), this, dcmd, _templateDao);
+			DownloadListener dl = new DownloadListener(ssAhost, sserver, template, _timer, _vmTemplateHostDao, vmTemplateHost.getId(), this, dcmd, _templateDao, _resourceLimitMgr, _alertMgr, _accountMgr);
 			if (downloadJobExists) {
 				dl.setCurrState(vmTemplateHost.getDownloadState());
 	 		}
@@ -465,7 +470,7 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
 	             return;
 			}
 			DownloadListener dl = new DownloadListener(ssvm, sserver, volume, _timer, _volumeHostDao, volumeHost.getId(),
-					this, dcmd, _volumeDao, _storageMgr);
+					this, dcmd, _volumeDao, _storageMgr, _resourceLimitMgr, _alertMgr, _accountMgr);
 			
 			if (downloadJobExists) {
 				dl.setCurrState(volumeHost.getDownloadState());
@@ -561,18 +566,21 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
             else{
                 s_logger.warn("Failed to get size for volume" + volume.getName());
             }
-            String eventType = EventTypes.EVENT_VOLUME_UPLOAD;            
+            String eventType = EventTypes.EVENT_VOLUME_UPLOAD;
             if(volume.getAccountId() != Account.ACCOUNT_ID_SYSTEM){
                 UsageEventUtils.publishUsageEvent(eventType, volume.getAccountId(), host.getDataCenterId(),
                         volume.getId(), volume.getName(), null, 0l, size, volume.getClass().getName(), volume.getUuid());
             }
         }else if (dnldStatus == Status.DOWNLOAD_ERROR || dnldStatus == Status.ABANDONED || dnldStatus == Status.UNKNOWN){
-            //Decrement the volume count
-        	_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), com.cloud.configuration.Resource.ResourceType.volume);
+            //Decrement the volume and secondary storage space count
+            _resourceLimitMgr.decrementResourceCount(volume.getAccountId(),
+                    com.cloud.configuration.Resource.ResourceType.volume);
+            _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(),
+                    com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
         }
-        txn.commit();		
+        txn.commit();
 	}
-	
+
 	@Override
     public void handleSysTemplateDownload(HostVO host) {
 	    List<HypervisorType> hypers = _resourceMgr.listAvailHypervisorInZone(host.getId(), host.getDataCenterId());
@@ -748,6 +756,22 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
                         volume.setSize(volInfo.getSize());
                         _volumeDao.update(volumeHost.getVolumeId(), volume);
                     }
+
+                    if (volInfo.getSize() > 0) {
+                        try {
+                            String url = _volumeHostDao.findByVolumeId(volume.getId()).getDownloadUrl();
+                            _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()),
+                                    com.cloud.configuration.Resource.ResourceType.secondary_storage,
+                                    volInfo.getSize() - UriUtils.getRemoteSize(url));
+                        } catch (ResourceAllocationException e) {
+                            s_logger.warn(e.getMessage());
+                            _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, volume.getDataCenterId(),
+                                    volume.getPodId(), e.getMessage(), e.getMessage());
+                        } finally {
+                            _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(),
+                                    com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                        }
+                    }
                 }
                 continue;
         	}
@@ -857,6 +881,22 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
                         tmpltHost.setSize(tmpltInfo.getSize());
                         tmpltHost.setPhysicalSize(tmpltInfo.getPhysicalSize());
                         tmpltHost.setLastUpdated(new Date());
+
+                        if (tmpltInfo.getSize() > 0) {
+                            long accountId = tmplt.getAccountId();
+                            try {
+                                _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(accountId),
+                                        com.cloud.configuration.Resource.ResourceType.secondary_storage,
+                                        tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl()));
+                            } catch (ResourceAllocationException e) {
+                                s_logger.warn(e.getMessage());
+                                _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, ssHost.getDataCenterId(),
+                                        null, e.getMessage(), e.getMessage());
+                            } finally {
+                                _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(),
+                                        com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                            }
+                        }
                     }
                     _vmTemplateHostDao.update(tmpltHost.getId(), tmpltHost);
                 } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
index bacca01..3a453d5 100755
--- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
@@ -123,20 +123,8 @@ import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.dao.UserVmDao;
-
-import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd;
-import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd;
-import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd;
-import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd;
-import org.apache.log4j.Logger;
-
-import javax.ejb.Local;
-import javax.naming.ConfigurationException;
-import java.util.*;
-import com.cloud.vm.snapshot.VMSnapshot;
 import com.cloud.vm.snapshot.dao.VMSnapshotDao;
 
-
 @Component
 @Local(value = { SnapshotManager.class, SnapshotService.class })
 public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, SnapshotService {
@@ -209,6 +197,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
     private int _totalRetries;
     private int _pauseInterval;
     private int _backupsnapshotwait;
+    Boolean backup;
 
     protected SearchBuilder<SnapshotVO> PolicySnapshotSearch;
     protected SearchBuilder<SnapshotPolicyVO> PoliciesForSnapSearch;
@@ -307,16 +296,21 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         					volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
         		}
 
-        		_resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
+                _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
         	}
-        	
-        	Boolean backup = Boolean.parseBoolean(this._configDao.getValue(Config.BackupSnapshotAferTakingSnapshot.toString()));
         	if (backup) {
         		this.backupSnapshot(snapshotId);
         	}
         } catch(Exception e) {
-        	s_logger.debug("Failed to create snapshot", e);
-        	throw new CloudRuntimeException("Failed to create snapshot", e);
+            s_logger.debug("Failed to create snapshot", e);
+            if (backup) {
+                _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage,
+                        new Long(volume.getSize()));
+            } else {
+                _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.primary_storage,
+                        new Long(volume.getSize()));
+            }
+            throw new CloudRuntimeException("Failed to create snapshot", e);
         }
 
         return snapshot;
@@ -539,7 +533,9 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         					snapshotCheck.getDataCenterId(), snapshotId, snapshotCheck.getName(), null, null, 0L,
         					snapshotCheck.getClass().getName(), snapshotCheck.getUuid());
         		}
-        		_resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.snapshot);
+                _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.snapshot);
+                _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.secondary_storage,
+                        new Long(snapshotCheck.getSize()));
         	}
         	return result;
         } catch (Exception e) {
@@ -745,6 +741,8 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
                 if (_snapshotDao.expunge(snapshot.getId())) {
                     if (snapshot.getRecurringType() == Type.MANUAL) {
                         _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.snapshot);
+                        _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage,
+                                new Long(snapshot.getSize()));
                     }
 
                     // Log event after successful deletion
@@ -995,23 +993,29 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
 
         ClusterVO cluster = _clusterDao.findById(storagePoolVO.getClusterId());
         if (cluster != null && cluster.getHypervisorType() == HypervisorType.Ovm) {
-        	throw new InvalidParameterValueException("Ovm won't support taking snapshot");
+            throw new InvalidParameterValueException("Ovm won't support taking snapshot");
         }
-        
+
         // Verify permissions
         _accountMgr.checkAccess(caller, null, true, volume);
         Type snapshotType = getSnapshotType(policyId);
         Account owner = _accountMgr.getAccount(volume.getAccountId());
+
         try{
-        	_resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
-        } catch (ResourceAllocationException e){
-        	if (snapshotType != Type.MANUAL){
-        		String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots";
-        		s_logger.warn(msg);
-        		_alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg, 
-        				"Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit");
-        	}
-        	throw e;
+            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
+            if (backup) {
+                _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize()));
+            } else {
+                _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long(volume.getSize()));
+            }
+        } catch (ResourceAllocationException e) {
+            if (snapshotType != Type.MANUAL){
+                String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots";
+                s_logger.warn(msg);
+                _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg,
+                        "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit");
+            }
+            throw e;
         }
 
         // Determine the name for this snapshot
@@ -1034,6 +1038,13 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         if (snapshot == null) {
             throw new CloudRuntimeException("Failed to create snapshot for volume: "+volumeId);
         }
+        if (backup) {
+            _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage,
+                    new Long(volume.getSize()));
+        } else {
+            _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                    new Long(volume.getSize()));
+        }
         return snapshot;
     }
 
@@ -1042,6 +1053,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
  
         String value = _configDao.getValue(Config.BackupSnapshotWait.toString());
         _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue()));
+        backup = Boolean.parseBoolean(this._configDao.getValue(Config.BackupSnapshotAferTakingSnapshot.toString()));
 
         Type.HOURLY.setMax(NumbersUtil.parseInt(_configDao.getValue("snapshot.max.hourly"), HOURLYMAX));
         Type.DAILY.setMax(NumbersUtil.parseInt(_configDao.getValue("snapshot.max.daily"), DAILYMAX));

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/template/HypervisorTemplateAdapter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/HypervisorTemplateAdapter.java b/server/src/com/cloud/template/HypervisorTemplateAdapter.java
index 1426421..a0444e5 100755
--- a/server/src/com/cloud/template/HypervisorTemplateAdapter.java
+++ b/server/src/com/cloud/template/HypervisorTemplateAdapter.java
@@ -39,7 +39,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.ImageDataFactory;
 import org.apache.cloudstack.engine.subsystem.api.storage.ImageService;
 import org.apache.cloudstack.framework.async.AsyncCallFuture;
 import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
 
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.api.Answer;
@@ -61,20 +60,11 @@ import com.cloud.storage.VMTemplateZoneVO;
 import com.cloud.storage.download.DownloadMonitor;
 import com.cloud.storage.secondary.SecondaryStorageVmManager;
 import com.cloud.user.Account;
+import com.cloud.utils.UriUtils;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.UserVmVO;
 
-import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
-import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
-import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
-import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
-import org.apache.log4j.Logger;
-
-import javax.ejb.Local;
-import java.net.*;
-import java.util.List;
-
 @Local(value=TemplateAdapter.class)
 public class HypervisorTemplateAdapter extends TemplateAdapterBase implements TemplateAdapter {
 	private final static Logger s_logger = Logger.getLogger(HypervisorTemplateAdapter.class);
@@ -134,6 +124,9 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase implements Te
         }
 
 		profile.setUrl(validateUrl(url));
+		// Check that the resource limit for secondary storage won't be exceeded
+		_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
+		        ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
 		return profile;
 	}
 
@@ -160,6 +153,9 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase implements Te
 		}
 
 		profile.setUrl(validateUrl(url));
+		// Check that the resource limit for secondary storage won't be exceeded
+		_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()),
+		        ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
 		return profile;
 	}
 
@@ -183,10 +179,11 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase implements Te
             s_logger.debug("create template Failed", e);
             throw new CloudRuntimeException("create template Failed", e);
         }
-		_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
-
+        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
+        _resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.secondary_storage,
+                UriUtils.getRemoteSize(profile.getUrl()));
         return template;
-	}
+    }
 
 	@Override @DB
 	public boolean delete(TemplateProfile profile) {
@@ -294,8 +291,10 @@ public class HypervisorTemplateAdapter extends TemplateAdapterBase implements Te
 					s_logger.debug("Failed to acquire lock when deleting template with ID: " + templateId);
 					success = false;
 				} else if (_tmpltDao.remove(templateId)) {
-					// Decrement the number of templates
+				    // Decrement the number of templates and total secondary storage space used by the account
 				    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
+				    _resourceLimitMgr.recalculateResourceCount(accountId, account.getDomainId(),
+				            ResourceType.secondary_storage.getOrdinal());
 				}
 
 			} finally {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java
index d843dbc..2892e00 100755
--- a/server/src/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/com/cloud/template/TemplateManagerImpl.java
@@ -893,16 +893,19 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
     @Override
     @DB
     public boolean copy(long userId, VMTemplateVO template, HostVO srcSecHost, DataCenterVO srcZone, DataCenterVO dstZone) throws StorageUnavailableException, ResourceAllocationException {
-    	List<HostVO> dstSecHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dstZone.getId());
-    	long tmpltId = template.getId();
+        List<HostVO> dstSecHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dstZone.getId());
+        long tmpltId = template.getId();
         long dstZoneId = dstZone.getId();
-    	if (dstSecHosts == null || dstSecHosts.isEmpty() ) {
-    		throw new StorageUnavailableException("Destination zone is not ready", DataCenter.class, dstZone.getId());
-    	}
+        if (dstSecHosts == null || dstSecHosts.isEmpty() ) {
+            throw new StorageUnavailableException("Destination zone is not ready", DataCenter.class, dstZone.getId());
+        }
         AccountVO account = _accountDao.findById(template.getAccountId());
+        VMTemplateHostVO srcTmpltHost = _tmpltHostDao.findByHostTemplate(srcSecHost.getId(), tmpltId);
+
         _resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
-               
-        // Event details        
+        _resourceLimitMgr.checkResourceLimit(account, ResourceType.secondary_storage, new Long(srcTmpltHost.getSize()));
+
+        // Event details
         String copyEventType;
         String createEventType;
         if (template.getFormat().equals(ImageFormat.ISO)){
@@ -912,12 +915,10 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             copyEventType = EventTypes.EVENT_TEMPLATE_COPY;
             createEventType = EventTypes.EVENT_TEMPLATE_CREATE;
         }
-        
-        
+
         Transaction txn = Transaction.currentTxn();
         txn.start();
-        
-        VMTemplateHostVO srcTmpltHost = _tmpltHostDao.findByHostTemplate(srcSecHost.getId(), tmpltId);
+
         for ( HostVO dstSecHost : dstSecHosts ) {
             VMTemplateHostVO dstTmpltHost = null;
             try {
@@ -948,7 +949,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             } finally {
             	txn.commit();
             }
-            
+
             if(_downloadMonitor.copyTemplate(template, srcSecHost, dstSecHost) ) {
                 _tmpltDao.addTemplateToZone(template, dstZoneId);
             	
@@ -1711,6 +1712,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
         VMTemplateVO privateTemplate = null;
         Long accountId = null;
         SnapshotVO snapshot = null;
+        VolumeVO volume = null;
 
         try {
             TemplateInfo tmplInfo = this.tmplFactory.getTemplate(templateId);
@@ -1725,6 +1727,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
                 SnapshotInfo snapInfo = this.snapshotFactory.getSnapshot(snapshotId);
                 future = this.imageSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store.get(0));
             } else if (volumeId != null) {
+               volume = _volumeDao.findById(volumeId);
                VolumeInfo volInfo = this.volFactory.getVolume(volumeId);
                future = this.imageSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store.get(0));
             } else {
@@ -1757,7 +1760,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
                 s_logger.debug("Failed to create template", e);
                 throw new CloudRuntimeException("Failed to create template", e);
             }
-            
+
         } finally {
             /*if (snapshot != null && snapshot.getSwiftId() != null
                     && secondaryStorageURL != null && zoneId != null
@@ -1773,8 +1776,9 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
 
                 // decrement resource count
                 if (accountId != null) {
-                    _resourceLimitMgr.decrementResourceCount(accountId,
-                            ResourceType.template);
+                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
+                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage,
+                            new Long(volume != null ? volume.getSize() : snapshot.getSize()));
                 }
                 txn.commit();
             }
@@ -1854,6 +1858,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
 
         HypervisorType hyperType;
         VolumeVO volume = null;
+        SnapshotVO snapshot = null;
         VMTemplateVO privateTemplate = null;
         if (volumeId != null) { // create template from volume
             volume = this._volumeDao.findById(volumeId);
@@ -1879,7 +1884,7 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             }
             hyperType = this._volumeDao.getHypervisorType(volumeId);
         } else { // create template from snapshot
-            SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
+            snapshot = _snapshotDao.findById(snapshotId);
             if (snapshot == null) {
                 throw new InvalidParameterValueException(
                         "Failed to create private template record, unable to find snapshot "
@@ -1911,8 +1916,9 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
             hyperType = snapshot.getHypervisorType();
         }
 
-        _resourceLimitMgr.checkResourceLimit(templateOwner,
-                ResourceType.template);
+        _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
+        _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage,
+                new Long(volume != null ? volume.getSize() : snapshot.getSize()));
 
         if (!isAdmin || featured == null) {
             featured = Boolean.FALSE;
@@ -1973,8 +1979,9 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
                 this._templateDetailsDao.persist(template.getId(), cmd.getDetails());
             }
 
-            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(),
-                    ResourceType.template);
+            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
+            _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.secondary_storage,
+                    new Long(volume != null ? volume.getSize() : snapshot.getSize()));
         }
 
         if (template != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 6e9cd43..24bce8b 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -3571,8 +3571,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
         DataCenterVO zone = _dcDao.findById(vm.getDataCenterId());
 
-        // Get serviceOffering for Virtual Machine
+        // Get serviceOffering and Volumes for Virtual Machine
         ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId());
+        List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
 
         //Remove vm from instance group
         removeInstanceFromInstanceGroup(cmd.getVmId());
@@ -3580,9 +3581,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         // VV 2: check if account/domain is with in resource limits to create a new vm
         resourceLimitCheck(newAccount, new Long(offering.getCpu()), new Long(offering.getRamSize()));
 
-        // VV 3: check if volumes are with in resource limits
+        // VV 3: check if volumes and primary storage space are with in resource limits
         _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume,
                 _volsDao.findByInstance(cmd.getVmId()).size());
+        Long totalVolumesSize = (long) 0;
+        for (VolumeVO volume : volumes) {
+            totalVolumesSize += volume.getSize();
+        }
+        _resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.primary_storage, totalVolumesSize);
 
         // VV 4: Check if new owner can use the vm template
         VirtualMachineTemplate template = _templateDao.findById(vm
@@ -3614,14 +3620,17 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         _vmDao.persist(vm);
 
         // OS 2: update volume
-        List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
         for (VolumeVO volume : volumes) {
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(),
                     volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid());
             _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
+            _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage,
+                    new Long(volume.getSize()));
             volume.setAccountId(newAccount.getAccountId());
             _volsDao.persist(volume);
             _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
+            _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage,
+                    new Long(volume.getSize()));
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(),
                     volume.getDataCenterId(), volume.getId(), volume.getName(),
                     volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(),

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/test/com/cloud/resourcelimit/ResourceLimitManagerImplTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/resourcelimit/ResourceLimitManagerImplTest.java b/server/test/com/cloud/resourcelimit/ResourceLimitManagerImplTest.java
index d311ad3..4d2fd7d 100644
--- a/server/test/com/cloud/resourcelimit/ResourceLimitManagerImplTest.java
+++ b/server/test/com/cloud/resourcelimit/ResourceLimitManagerImplTest.java
@@ -16,8 +16,6 @@
 // under the License.
 package com.cloud.resourcelimit;
 
-import javax.inject.Inject;
-
 import junit.framework.TestCase;
 
 import org.apache.log4j.Logger;
@@ -72,11 +70,23 @@ public class ResourceLimitManagerImplTest  extends TestCase{
         // update resource Limit for a domain for resource_type = 8 (CPU)
         resourceLimitServiceCall(null, (long) 1, 8, (long) 40);
 
-        // update resource Limit for an account for resource_type = 9 (Memory)
+        // update resource Limit for an account for resource_type = 9 (Memory (in MiB))
         resourceLimitServiceCall((long) 1, (long) 1, 9, (long) 4096);
 
-        // update resource Limit for a domain for resource_type = 9 (Memory)
+        // update resource Limit for a domain for resource_type = 9 (Memory (in MiB))
         resourceLimitServiceCall(null, (long) 1, 9, (long) 10240);
+
+        // update resource Limit for an account for resource_type = 10 (Primary storage (in GiB))
+        resourceLimitServiceCall((long) 1, (long) 1, 10, (long) 200);
+
+        // update resource Limit for a domain for resource_type = 10 (Primary storage (in GiB))
+        resourceLimitServiceCall(null, (long) 1, 10, (long) 200);
+
+        // update resource Limit for an account for resource_type = 11 (Secondary storage (in GiB))
+        resourceLimitServiceCall((long) 1, (long) 1, 10, (long) 400);
+
+        // update resource Limit for a domain for resource_type = 11 (Secondary storage (in GiB))
+        resourceLimitServiceCall(null, (long) 1, 10, (long) 400);
     }
 
     private void resourceLimitServiceCall(Long accountId, Long domainId, Integer resourceType, Long max) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
index b9fc861..367ca45 100644
--- a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
+++ b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java
@@ -133,6 +133,14 @@ public class MockResourceLimitManagerImpl extends ManagerBase implements Resourc
     }
 
     /* (non-Javadoc)
+     * @see com.cloud.user.ResourceLimitService#calculateSecondaryStorageForAccount(long)
+     */
+    public long calculateSecondaryStorageForAccount(long accountId) {
+        // TODO Auto-generated method stub
+        return 0;
+    }
+
+    /* (non-Javadoc)
      * @see com.cloud.user.ResourceLimitService#getResourceCount(com.cloud.user.Account, com.cloud.configuration.Resource.ResourceType)
      */
     @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/setup/db/db/schema-40to410.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql
index 60ad025..3dae1cc 100644
--- a/setup/db/db/schema-40to410.sql
+++ b/setup/db/db/schema-40to410.sql
@@ -263,14 +263,6 @@ CREATE TABLE  `cloud`.`region` (
 
 INSERT INTO `cloud`.`region` values ('1','Local','http://localhost:8080/client/');
 
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.cpus', '40', 'The default maximum number of cpu cores that can be used for an account');
-
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.memory', '40960', 'The default maximum memory (in MB) that can be used for an account');
-
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.cpus', '40', 'The default maximum number of cpu cores that can be used for a project');
-
-INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.memory', '40960', 'The default maximum memory (in MB) that can be used for a project');
-
 ALTER TABLE `cloud_usage`.`account` ADD COLUMN `region_id` int unsigned NOT NULL DEFAULT '1';
 
 CREATE TABLE `cloud`.`nicira_nvp_router_map` (
@@ -1293,10 +1285,6 @@ CREATE VIEW `cloud`.`account_view` AS
         projectcount.count projectTotal,
         networklimit.max networkLimit,
         networkcount.count networkTotal,
-        cpulimit.max cpuLimit,
-        cpucount.count cpuTotal,
-        memorylimit.max memoryLimit,
-        memorycount.count memoryTotal,
         async_job.id job_id,
         async_job.uuid job_uuid,
         async_job.job_status job_status,
@@ -1365,18 +1353,6 @@ CREATE VIEW `cloud`.`account_view` AS
         `cloud`.`resource_count` networkcount ON account.id = networkcount.account_id
             and networkcount.type = 'network'
             left join
-        `cloud`.`resource_limit` cpulimit ON account.id = cpulimit.account_id
-            and cpulimit.type = 'cpu'
-            left join
-        `cloud`.`resource_count` cpucount ON account.id = cpucount.account_id
-            and cpucount.type = 'cpu'
-            left join
-        `cloud`.`resource_limit` memorylimit ON account.id = memorylimit.account_id
-            and memorylimit.type = 'memory'
-            left join
-        `cloud`.`resource_count` memorycount ON account.id = memorycount.account_id
-            and memorycount.type = 'memory'
-            left join
         `cloud`.`async_job` ON async_job.instance_id = account.id
             and async_job.instance_type = 'Account'
             and async_job.job_status = 0;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/setup/db/db/schema-410to420.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-410to420.sql b/setup/db/db/schema-410to420.sql
index 9eed0a6..f1e24fa 100644
--- a/setup/db/db/schema-410to420.sql
+++ b/setup/db/db/schema-410to420.sql
@@ -202,7 +202,6 @@ CREATE VIEW `cloud`.`event_view` AS
             left join
         `cloud`.`event` eve ON event.start_id = eve.id;
 
-
 ALTER TABLE `cloud`.`region` ADD COLUMN `gslb_service_enabled` tinyint(1) unsigned NOT NULL DEFAULT 1 COMMENT 'Is GSLB service enalbed in the Region';
 
 ALTER TABLE `cloud`.`external_load_balancer_devices` ADD COLUMN `is_gslb_provider` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if load balancer appliance is acting as gslb service provider in the zone';
@@ -239,3 +238,155 @@ CREATE TABLE `cloud`.`global_load_balancer_lb_rule_map` (
   CONSTRAINT `fk_gslb_rule_id` FOREIGN KEY(`gslb_rule_id`) REFERENCES `global_load_balancing_rules`(`id`) ON DELETE CASCADE,
   CONSTRAINT `fk_lb_rule_id` FOREIGN KEY(`lb_rule_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.cpus', '40', 'The default maximum number of cpu cores that can be used for an account');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.memory', '40960', 'The default maximum memory (in MiB) that can be used for an account');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.primary.storage', '200', 'The default maximum primary storage space (in GiB) that can be used for an account');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Account Defaults', 'DEFAULT', 'management-server', 'max.account.secondary.storage', '400', 'The default maximum secondary storage space (in GiB) that can be used for an account');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.cpus', '40', 'The default maximum number of cpu cores that can be used for a project');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.memory', '40960', 'The default maximum memory (in MiB) that can be used for a project');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.primary.storage', '200', 'The default maximum primary storage space (in GiB) that can be used for a project');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Project Defaults', 'DEFAULT', 'management-server', 'max.project.secondary.storage', '400', 'The default maximum secondary storage space (in GiB) that can be used for a project');
+
+DROP VIEW IF EXISTS `cloud`.`account_view`;
+CREATE VIEW `cloud`.`account_view` AS
+    select
+        account.id,
+        account.uuid,
+        account.account_name,
+        account.type,
+        account.state,
+        account.removed,
+        account.cleanup_needed,
+        account.network_domain,
+        domain.id domain_id,
+        domain.uuid domain_uuid,
+        domain.name domain_name,
+        domain.path domain_path,
+        data_center.id data_center_id,
+        data_center.uuid data_center_uuid,
+        data_center.name data_center_name,
+        account_netstats_view.bytesReceived,
+        account_netstats_view.bytesSent,
+        vmlimit.max vmLimit,
+        vmcount.count vmTotal,
+        runningvm.vmcount runningVms,
+        stoppedvm.vmcount stoppedVms,
+        iplimit.max ipLimit,
+        ipcount.count ipTotal,
+        free_ip_view.free_ip ipFree,
+        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,
+        async_job.id job_id,
+        async_job.uuid job_uuid,
+        async_job.job_status job_status,
+        async_job.account_id job_account_id
+    from
+        `cloud`.`free_ip_view`,
+        `cloud`.`account`
+            inner join
+        `cloud`.`domain` ON account.domain_id = domain.id
+            left join
+        `cloud`.`data_center` ON account.default_zone_id = data_center.id
+            left join
+        `cloud`.`account_netstats_view` ON account.id = account_netstats_view.account_id
+            left join
+        `cloud`.`resource_limit` vmlimit ON account.id = vmlimit.account_id
+            and vmlimit.type = 'user_vm'
+            left join
+        `cloud`.`resource_count` vmcount ON account.id = vmcount.account_id
+            and vmcount.type = 'user_vm'
+            left join
+        `cloud`.`account_vmstats_view` runningvm ON account.id = runningvm.account_id
+            and runningvm.state = 'Running'
+            left join
+        `cloud`.`account_vmstats_view` stoppedvm ON account.id = stoppedvm.account_id
+           and stoppedvm.state = 'Stopped'
+            left join
+        `cloud`.`resource_limit` iplimit ON account.id = iplimit.account_id
+            and iplimit.type = 'public_ip'
+            left join
+        `cloud`.`resource_count` ipcount ON account.id = ipcount.account_id
+            and ipcount.type = 'public_ip'
+            left join
+        `cloud`.`resource_limit` volumelimit ON account.id = volumelimit.account_id
+            and volumelimit.type = 'volume'
+            left join
+        `cloud`.`resource_count` volumecount ON account.id = volumecount.account_id
+            and volumecount.type = 'volume'
+            left join
+        `cloud`.`resource_limit` snapshotlimit ON account.id = snapshotlimit.account_id
+            and snapshotlimit.type = 'snapshot'
+            left join
+        `cloud`.`resource_count` snapshotcount ON account.id = snapshotcount.account_id
+            and snapshotcount.type = 'snapshot'
+            left join
+        `cloud`.`resource_limit` templatelimit ON account.id = templatelimit.account_id
+            and templatelimit.type = 'template'
+            left join
+        `cloud`.`resource_count` templatecount ON account.id = templatecount.account_id
+            and templatecount.type = 'template'
+            left join
+        `cloud`.`resource_limit` vpclimit ON account.id = vpclimit.account_id
+            and vpclimit.type = 'vpc'
+            left join
+        `cloud`.`resource_count` vpccount ON account.id = vpccount.account_id
+            and vpccount.type = 'vpc'
+            left join
+        `cloud`.`resource_limit` projectlimit ON account.id = projectlimit.account_id
+            and projectlimit.type = 'project'
+            left join
+        `cloud`.`resource_count` projectcount ON account.id = projectcount.account_id
+            and projectcount.type = 'project'
+            left join
+        `cloud`.`resource_limit` networklimit ON account.id = networklimit.account_id
+            and networklimit.type = 'network'
+            left join
+        `cloud`.`resource_count` networkcount ON account.id = networkcount.account_id
+            and networkcount.type = 'network'
+            left join
+        `cloud`.`resource_limit` cpulimit ON account.id = cpulimit.account_id
+            and cpulimit.type = 'cpu'
+            left join
+        `cloud`.`resource_count` cpucount ON account.id = cpucount.account_id
+            and cpucount.type = 'cpu'
+            left join
+        `cloud`.`resource_limit` memorylimit ON account.id = memorylimit.account_id
+            and memorylimit.type = 'memory'
+            left join
+        `cloud`.`resource_count` memorycount ON account.id = memorycount.account_id
+            and memorycount.type = 'memory'
+            left join
+        `cloud`.`resource_limit` primary_storage_limit ON account.id = primary_storage_limit.account_id
+            and primary_storage_limit.type = 'primary_storage'
+            left join
+        `cloud`.`resource_count` primary_storage_count ON account.id = primary_storage_count.account_id
+            and primary_storage_count.type = 'primary_storage'
+            left join
+        `cloud`.`resource_limit` secondary_storage_limit ON account.id = secondary_storage_limit.account_id
+            and secondary_storage_limit.type = 'secondary_storage'
+            left join
+        `cloud`.`resource_count` secondary_storage_count ON account.id = secondary_storage_count.account_id
+            and secondary_storage_count.type = 'secondary_storage'
+            left join
+        `cloud`.`async_job` ON async_job.instance_id = account.id
+            and async_job.instance_type = 'Account'
+            and async_job.job_status = 0;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/18695276/utils/src/com/cloud/utils/UriUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/UriUtils.java b/utils/src/com/cloud/utils/UriUtils.java
index a8b5ccb..3bcee7a 100644
--- a/utils/src/com/cloud/utils/UriUtils.java
+++ b/utils/src/com/cloud/utils/UriUtils.java
@@ -17,10 +17,14 @@
 package com.cloud.utils;
 
 import java.io.File;
+import java.io.IOException;
+import java.net.HttpURLConnection;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URLEncoder;
 
+import javax.net.ssl.HttpsURLConnection;
+
 import com.cloud.utils.exception.CloudRuntimeException;
 
 public class UriUtils {
@@ -78,4 +82,33 @@ public class UriUtils {
         // no need to do URL component encoding
         return url;
     }
+
+    // Get the size of a file from URL response header.
+    public static Long getRemoteSize(String url) {
+        Long remoteSize = (long) 0;
+        HttpURLConnection httpConn = null;
+        HttpsURLConnection httpsConn = null;
+        try {
+            URI uri = new URI(url);
+            if(uri.getScheme().equalsIgnoreCase("http")) {
+                httpConn = (HttpURLConnection) uri.toURL().openConnection();
+                remoteSize = Long.parseLong(httpConn.getHeaderField("content-length"));
+            }
+            else if(uri.getScheme().equalsIgnoreCase("https")) {
+                httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
+                remoteSize = Long.parseLong(httpsConn.getHeaderField("content-length"));
+            }
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException("Invalid URL " + url);
+        } catch (IOException e) {
+            throw new IllegalArgumentException("Unable to establish connection with URL " + url);
+        } finally {
+            if (httpConn != null) {
+                httpConn.disconnect();
+            } else if (httpsConn != null) {
+                httpsConn.disconnect();
+            }
+        }
+        return remoteSize;
+    }
 }


[04/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1381
Fixed inconsistency in cluster limit check for Vmware clusters.
While adding a new Vmware cluster limit check done correctly but while adding a host to an existing cluster there was an issue with limit check.


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

Branch: refs/heads/bvt
Commit: c502b4670328b6b950630e84b4a7d3fd4bcb96ca
Parents: 3e4430d
Author: Koushik Das <ko...@citrix.com>
Authored: Thu Mar 28 17:26:12 2013 +0530
Committer: Koushik Das <ko...@citrix.com>
Committed: Thu Mar 28 17:26:12 2013 +0530

----------------------------------------------------------------------
 .../hypervisor/vmware/VmwareServerDiscoverer.java  |   12 ++++++------
 .../vmware/manager/VmwareManagerImpl.java          |    8 ++++----
 2 files changed, 10 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c502b467/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
index 94ba97d..2b3eba6 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
@@ -135,14 +135,14 @@ public class VmwareServerDiscoverer extends DiscovererBase implements
 			return null;
 		}
 
-		List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
+        List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
         if (hosts != null && hosts.size() > 0) {
             int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(hosts.get(0).getHypervisorType(), hosts.get(0).getHypervisorVersion());
-            if (hosts.size() > maxHostsPerCluster) {
-                   String msg = "VMware cluster " + cluster.getName() + " is too big to add new host now. (current configured cluster size: " + maxHostsPerCluster + ")";
-			s_logger.error(msg);
-			throw new DiscoveredWithErrorException(msg);
-		}
+            if (hosts.size() >= maxHostsPerCluster) {
+                String msg = "VMware cluster " + cluster.getName() + " is too big to add new host, current size: " + hosts.size() + ", max. size: " + maxHostsPerCluster;
+                s_logger.error(msg);
+                throw new DiscoveredWithErrorException(msg);
+            }
         }
 
 		String privateTrafficLabel = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c502b467/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
index 9d29abf..b2e3768 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java
@@ -355,10 +355,10 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
                     String version = about.getApiVersion();
                     int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(HypervisorType.VMware, version);
                     if (hosts.size() > maxHostsPerCluster) {
-                        String msg = "vCenter cluster size is too big (current configured cluster size: " + maxHostsPerCluster + ")";
-                    s_logger.error(msg);
-                    throw new DiscoveredWithErrorException(msg);
-                }
+                        String msg = "Failed to add VMware cluster as size is too big, current size: " + hosts.size() + ", max. size: " + maxHostsPerCluster;
+                        s_logger.error(msg);
+                        throw new DiscoveredWithErrorException(msg);
+                    }
                 }
 
                 for(ManagedObjectReference morHost: hosts) {


[19/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
removing @Autowired, which is not JSR complaint.

initializing the bean 'GlobalLoadBalancingRulesServiceImpl' through the componentContext.xml


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

Branch: refs/heads/bvt
Commit: b585fa11c13bb7d548b2c16ba1ed1057a1b55f3f
Parents: 6a7156a
Author: Murali Reddy <mu...@citrix.com>
Authored: Fri Mar 29 14:02:57 2013 +0530
Committer: Murali Reddy <mu...@citrix.com>
Committed: Fri Mar 29 15:53:59 2013 +0530

----------------------------------------------------------------------
 client/tomcatconf/componentContext.xml.in          |    2 ++
 client/tomcatconf/nonossComponentContext.xml.in    |    5 +++++
 .../gslb/GlobalLoadBalancingRulesServiceImpl.java  |    9 ++++-----
 3 files changed, 11 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b585fa11/client/tomcatconf/componentContext.xml.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/componentContext.xml.in b/client/tomcatconf/componentContext.xml.in
index a98a41f..3f8277a 100644
--- a/client/tomcatconf/componentContext.xml.in
+++ b/client/tomcatconf/componentContext.xml.in
@@ -333,4 +333,6 @@
   <bean id="ClassicalPrimaryDataStoreProvider" class="org.apache.cloudstack.storage.datastore.provider.CloudStackPrimaryDataStoreProviderImpl">
   </bean>
   
+  <bean id="GlobalLoadBalancingRulesServiceImpl" class ="org.apache.cloudstack.region.gslb.GlobalLoadBalancingRulesServiceImpl" />
+
 </beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b585fa11/client/tomcatconf/nonossComponentContext.xml.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/nonossComponentContext.xml.in b/client/tomcatconf/nonossComponentContext.xml.in
index 1cc1722..97a4f28 100644
--- a/client/tomcatconf/nonossComponentContext.xml.in
+++ b/client/tomcatconf/nonossComponentContext.xml.in
@@ -47,6 +47,11 @@
     </property>
   </bean>
  
+  <bean id="GlobalLoadBalancingRulesServiceImpl" class ="org.apache.cloudstack.region.gslb.GlobalLoadBalancingRulesServiceImpl" >
+    <property name="GslbServiceProvider">
+      <ref bean="Netscaler"/>
+    </property>
+  </bean>
   <bean id ="AccountManagerImpl" class="com.cloud.user.AccountManagerImpl">
     <property name="UserAuthenticators">
         <list>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b585fa11/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
index 9cc10aa..696e6e9 100644
--- a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
+++ b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
@@ -44,8 +44,6 @@ import org.apache.cloudstack.api.command.user.region.ha.gslb.*;
 import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.region.dao.RegionDao;
 import org.apache.log4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
 
 import javax.ejb.Local;
 import javax.inject.Inject;
@@ -54,7 +52,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-@Component
 @Local(value = {GlobalLoadBalancingRulesService.class})
 public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingRulesService {
 
@@ -80,9 +77,11 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
     IPAddressDao _ipAddressDao;
     @Inject
     AgentManager _agentMgr;
-    @Autowired(required=false)
-    protected GslbServiceProvider _gslbProvider;
 
+    protected GslbServiceProvider _gslbProvider=null;
+    public void setGslbServiceProvider(GslbServiceProvider provider) {
+        this._gslbProvider = provider;
+    }
 
     @Override
     @DB


[07/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1616: cloudstack UI - Infrastructure menu - zone detail - create network - correct IPv6 parameter names passed to API call.


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

Branch: refs/heads/bvt
Commit: 0f3b7ef225dd4997801789fe05a3088c967fdc87
Parents: c52d04c
Author: Jessica Wang <je...@citrix.com>
Authored: Thu Mar 28 11:29:38 2013 -0700
Committer: Jessica Wang <je...@citrix.com>
Committed: Thu Mar 28 11:30:24 2013 -0700

----------------------------------------------------------------------
 ui/scripts/system.js |    8 ++++----
 1 files changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0f3b7ef2/ui/scripts/system.js
----------------------------------------------------------------------
diff --git a/ui/scripts/system.js b/ui/scripts/system.js
index 92d9865..8c5a6bb 100644
--- a/ui/scripts/system.js
+++ b/ui/scripts/system.js
@@ -1481,13 +1481,13 @@
 												
 												//IPv6 (begin)
 											    if(args.data.ip6gateway != null && args.data.ip6gateway.length > 0)
-												  array1.push("&gateway=" + args.data.ip6gateway);
+												  array1.push("&ip6gateway=" + args.data.ip6gateway);
 												if(args.data.ip6cidr != null && args.data.ip6cidr.length > 0)
-												  array1.push("&netmask=" + args.data.ip6cidr);
+												  array1.push("&ip6cidr=" + args.data.ip6cidr);
 												if(($form.find('.form-item[rel=startipv6]').css("display") != "none") && (args.data.startipv6 != null && args.data.startipv6.length > 0))
-												  array1.push("&startip=" + args.data.startipv6);
+												  array1.push("&startipv6=" + args.data.startipv6);
 												if(($form.find('.form-item[rel=endipv6]').css("display") != "none") && (args.data.endipv6 != null && args.data.endipv6.length > 0))
-												  array1.push("&endip=" + args.data.endipv6);
+												  array1.push("&endipv6=" + args.data.endipv6);
 												//IPv6 (end)
 												
 												if(args.data.networkdomain != null && args.data.networkdomain.length > 0)


[11/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1840: cloudstack UI - VM Wizard - fix a bug that the first parameter in jQuery.grep() should not be null.


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

Branch: refs/heads/bvt
Commit: 4534dafba120914d4d78482f1485fe4895a69211
Parents: e3f67d1
Author: Jessica Wang <je...@citrix.com>
Authored: Thu Mar 28 16:23:05 2013 -0700
Committer: Jessica Wang <je...@citrix.com>
Committed: Thu Mar 28 16:23:34 2013 -0700

----------------------------------------------------------------------
 ui/scripts/instanceWizard.js |   60 +++++++++++++++++++++++++++---------
 1 files changed, 45 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4534dafb/ui/scripts/instanceWizard.js
----------------------------------------------------------------------
diff --git a/ui/scripts/instanceWizard.js b/ui/scripts/instanceWizard.js
index 75d45aa..e1aeafd 100644
--- a/ui/scripts/instanceWizard.js
+++ b/ui/scripts/instanceWizard.js
@@ -128,10 +128,15 @@
           dataType: "json",
           async: false,
           success: function(json) {										  
-            featuredTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
-              if($.inArray(item.hypervisor, hypervisorArray) > -1)
-                return true;
-            });	
+            if(json.listtemplatesresponse.template == null) {
+						  featuredTemplateObjs = null;
+						}
+						else {
+							featuredTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
+								if($.inArray(item.hypervisor, hypervisorArray) > -1)
+									return true;
+							});	
+						}
           }
         });
         $.ajax({
@@ -139,10 +144,15 @@
           dataType: "json",
           async: false,
           success: function(json) {
-            communityTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
-              if($.inArray(item.hypervisor, hypervisorArray) > -1)
-                return true;
-            });	
+					  if(json.listtemplatesresponse.template == null) {
+						  communityTemplateObjs = null;
+						}
+						else {
+							communityTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
+								if($.inArray(item.hypervisor, hypervisorArray) > -1)
+									return true;
+							});	
+						}
           }
         });
         $.ajax({
@@ -150,10 +160,15 @@
           dataType: "json",
           async: false,
           success: function(json) {
-            myTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
-              if($.inArray(item.hypervisor, hypervisorArray) > -1)
-                return true;
-            });	
+					  if(json.listtemplatesresponse.template == null) {
+						  myTemplateObjs = null;
+						}
+						else {
+							myTemplateObjs = $.grep(json.listtemplatesresponse.template, function(item, index) {											  
+								if($.inArray(item.hypervisor, hypervisorArray) > -1)
+									return true;
+							});	
+						}
           }
         });
       } else if (selectedTemplate == 'select-iso') {
@@ -162,7 +177,12 @@
           dataType: "json",
           async: false,
           success: function(json) {
-            featuredIsoObjs = json.listisosresponse.iso;
+					  if(json.listisosresponse.iso == null) {
+						  featuredIsoObjs = null;
+						}
+						else {					
+              featuredIsoObjs = json.listisosresponse.iso;
+						}
           }
         });
         $.ajax({
@@ -170,7 +190,12 @@
           dataType: "json",
           async: false,
           success: function(json) {
-            communityIsoObjs = json.listisosresponse.iso;
+					  if(json.listisosresponse.iso == null) {
+						  communityIsoObjs = null;
+						}
+						else {					 
+              communityIsoObjs = json.listisosresponse.iso;
+						}
           }
         });
         $.ajax({
@@ -178,7 +203,12 @@
           dataType: "json",
           async: false,
           success: function(json) {
-            myIsoObjs = json.listisosresponse.iso;
+					  if(json.listisosresponse.iso == null) {
+						  myIsoObjs = null;
+						}
+						else {					
+              myIsoObjs = json.listisosresponse.iso;
+						}
           }
         });
       }


[06/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
Correct a naming typo.

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

Branch: refs/heads/bvt
Commit: c52d04cd63e88dbdd8dbcca18038822c89778982
Parents: c8fd16c
Author: Min Chen <mi...@citrix.com>
Authored: Thu Mar 28 10:23:55 2013 -0700
Committer: Min Chen <mi...@citrix.com>
Committed: Thu Mar 28 10:23:55 2013 -0700

----------------------------------------------------------------------
 .../snapshot/strategy/AncientSnapshotStrategy.java |  608 +++++++++++++++
 .../snapshot/strategy/AncientSnasphotStrategy.java |  608 ---------------
 2 files changed, 608 insertions(+), 608 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c52d04cd/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnapshotStrategy.java
----------------------------------------------------------------------
diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnapshotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnapshotStrategy.java
new file mode 100644
index 0000000..9e666d2
--- /dev/null
+++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnapshotStrategy.java
@@ -0,0 +1,608 @@
+// 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.snapshot.strategy;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectType;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreRole;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
+import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
+import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
+import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
+import org.apache.cloudstack.framework.async.AsyncCallFuture;
+import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
+import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
+import org.apache.cloudstack.framework.async.AsyncRpcConext;
+import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.motion.DataMotionService;
+import org.apache.cloudstack.storage.snapshot.SnapshotObject;
+import org.apache.cloudstack.storage.snapshot.SnapshotStateMachineManager;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.BackupSnapshotAnswer;
+import com.cloud.agent.api.DeleteSnapshotBackupCommand;
+import com.cloud.agent.api.to.S3TO;
+import com.cloud.agent.api.to.SwiftTO;
+import com.cloud.configuration.Resource.ResourceType;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.dc.ClusterVO;
+import com.cloud.dc.dao.ClusterDao;
+import com.cloud.event.EventTypes;
+import com.cloud.event.UsageEventUtils;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.resource.ResourceManager;
+import com.cloud.storage.Snapshot;
+import com.cloud.storage.SnapshotVO;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.VolumeManager;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.SnapshotDao;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.storage.s3.S3Manager;
+import com.cloud.storage.snapshot.SnapshotManager;
+import com.cloud.storage.swift.SwiftManager;
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.fsm.NoTransitionException;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.VirtualMachine.State;
+import com.cloud.vm.dao.UserVmDao;
+import com.cloud.vm.snapshot.VMSnapshot;
+import com.cloud.vm.snapshot.VMSnapshotVO;
+import com.cloud.vm.snapshot.dao.VMSnapshotDao;
+
+@Component
+public class AncientSnapshotStrategy implements SnapshotStrategy {
+	private static final Logger s_logger = Logger.getLogger(AncientSnapshotStrategy.class);
+	@Inject
+	protected VolumeDao _volsDao;
+	@Inject
+	protected UserVmDao _vmDao;
+	@Inject
+	protected PrimaryDataStoreDao _storagePoolDao;
+	@Inject
+	protected ClusterDao _clusterDao;
+	@Inject
+	protected SnapshotDao snapshotDao;
+	@Inject
+	private ResourceManager _resourceMgr;
+	@Inject
+	protected SnapshotDao _snapshotDao;
+	@Inject
+	protected SnapshotManager snapshotMgr;
+	@Inject
+	protected VolumeManager volumeMgr;
+	@Inject
+	private ConfigurationDao _configDao;
+	@Inject
+	protected SnapshotStateMachineManager stateMachineManager;
+	@Inject
+	private VolumeDao volumeDao;
+	@Inject
+	SnapshotDataFactory snapshotfactory;
+	@Inject
+	DataStoreManager dataStoreMgr;
+	@Inject
+	DataMotionService motionSrv;
+	@Inject
+	ObjectInDataStoreManager objInStoreMgr;
+	@Inject
+	VMSnapshotDao _vmSnapshotDao;
+
+
+	@Override
+	public boolean canHandle(SnapshotInfo snapshot) {
+		return true;
+	}
+
+	static private class CreateSnapshotContext<T> extends AsyncRpcConext<T> {
+		final VolumeInfo volume;
+		final SnapshotInfo snapshot;
+		final AsyncCallFuture<SnapshotResult> future;
+		public CreateSnapshotContext(AsyncCompletionCallback<T> callback, VolumeInfo volume,
+				SnapshotInfo snapshot,
+				AsyncCallFuture<SnapshotResult> future) {
+			super(callback);
+			this.volume = volume;
+			this.snapshot = snapshot;
+			this.future = future;
+		}
+	}
+	
+	static private class DeleteSnapshotContext<T> extends AsyncRpcConext<T> {
+		final SnapshotInfo snapshot;
+		final AsyncCallFuture<SnapshotResult> future;
+		public DeleteSnapshotContext(AsyncCompletionCallback<T> callback, SnapshotInfo snapshot,
+				AsyncCallFuture<SnapshotResult> future) {
+			super(callback);
+			this.snapshot = snapshot;
+			this.future = future;
+		}
+		
+	}
+
+	static private class CopySnapshotContext<T> extends AsyncRpcConext<T> {
+		final SnapshotInfo srcSnapshot;
+		final SnapshotInfo destSnapshot;
+		final AsyncCallFuture<SnapshotResult> future;
+		public CopySnapshotContext(AsyncCompletionCallback<T> callback,
+				SnapshotInfo srcSnapshot,
+				SnapshotInfo destSnapshot,
+				AsyncCallFuture<SnapshotResult> future) {
+			super(callback);
+			this.srcSnapshot = srcSnapshot;
+			this.destSnapshot = destSnapshot;
+			this.future = future;
+		}
+
+	}
+
+	protected Void createSnapshotAsyncCallback(AsyncCallbackDispatcher<AncientSnapshotStrategy, CreateCmdResult> callback, 
+			CreateSnapshotContext<CreateCmdResult> context) {
+		CreateCmdResult result = callback.getResult();
+		SnapshotObject snapshot = (SnapshotObject)context.snapshot;
+		VolumeInfo volume = context.volume;
+		AsyncCallFuture<SnapshotResult> future = context.future;
+		SnapshotResult snapResult = new SnapshotResult(snapshot);
+		if (result.isFailed()) {
+			s_logger.debug("create snapshot " + context.snapshot.getName() + " failed: " + result.getResult());
+			try {
+				snapshot.processEvent(Snapshot.Event.OperationFailed);
+			} catch (NoTransitionException nte) {
+				s_logger.debug("Failed to update snapshot state due to " + nte.getMessage());
+			}
+
+
+			snapResult.setResult(result.getResult());
+			future.complete(snapResult);
+			return null;
+		}
+
+		try {
+			SnapshotVO preSnapshotVO = this.snapshotMgr.getParentSnapshot(volume, snapshot);
+			String preSnapshotPath = null;
+			if (preSnapshotVO != null) {
+			    preSnapshotPath = preSnapshotVO.getPath();
+			}
+			SnapshotVO snapshotVO = this.snapshotDao.findById(snapshot.getId());
+			// The snapshot was successfully created
+			if (preSnapshotPath != null && preSnapshotPath.equals(result.getPath())) {
+				// empty snapshot
+				s_logger.debug("CreateSnapshot: this is empty snapshot ");
+
+				snapshotVO.setPath(preSnapshotPath);
+				snapshotVO.setBackupSnapshotId(preSnapshotVO.getBackupSnapshotId());
+				snapshotVO.setSwiftId(preSnapshotVO.getSwiftId());
+				snapshotVO.setPrevSnapshotId(preSnapshotVO.getId());
+				snapshotVO.setSecHostId(preSnapshotVO.getSecHostId());
+				snapshot.processEvent(Snapshot.Event.OperationNotPerformed);
+			} else {
+				long preSnapshotId = 0;
+
+				if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) {
+					preSnapshotId = preSnapshotVO.getId();
+					int _deltaSnapshotMax = NumbersUtil.parseInt(_configDao.getValue("snapshot.delta.max"), SnapshotManager.DELTAMAX);
+					int deltaSnap = _deltaSnapshotMax;
+
+					int i;
+					for (i = 1; i < deltaSnap; i++) {
+						String prevBackupUuid = preSnapshotVO.getBackupSnapshotId();
+						// previous snapshot doesn't have backup, create a full snapshot
+						if (prevBackupUuid == null) {
+							preSnapshotId = 0;
+							break;
+						}
+						long preSSId = preSnapshotVO.getPrevSnapshotId();
+						if (preSSId == 0) {
+							break;
+						}
+						preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preSSId);
+					}
+					if (i >= deltaSnap) {
+						preSnapshotId = 0;
+					}
+				}
+
+				//If the volume is moved around, backup a full snapshot to secondary storage
+				if (volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId())) {
+					preSnapshotId = 0;
+					//TODO: fix this hack
+					VolumeVO volumeVO = this.volumeDao.findById(volume.getId());
+					volumeVO.setLastPoolId(volume.getPoolId());
+					this.volumeDao.update(volume.getId(), volumeVO);
+				}
+
+				snapshot.setPath(result.getPath());
+				snapshot.setPrevSnapshotId(preSnapshotId);
+
+				snapshot.processEvent(Snapshot.Event.OperationSucceeded);
+				snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(snapshot.getId()));
+			} 
+		} catch (Exception e) {
+			s_logger.debug("Failed to create snapshot: ", e);
+			snapResult.setResult(e.toString());
+			try {
+                snapshot.processEvent(Snapshot.Event.OperationFailed);
+            } catch (NoTransitionException e1) {
+                s_logger.debug("Failed to change snapshot state: " + e1.toString());
+            }
+		}
+
+		future.complete(snapResult);
+		return null;
+	} 
+
+	class SnapshotResult extends CommandResult {
+		SnapshotInfo snashot;
+		public SnapshotResult(SnapshotInfo snapshot) {
+			this.snashot = snapshot;
+		}
+	}
+
+	protected SnapshotInfo createSnapshotOnPrimary(VolumeInfo volume, Long snapshotId) {
+		SnapshotObject snapshot = (SnapshotObject)this.snapshotfactory.getSnapshot(snapshotId);
+		if (snapshot == null) {
+			throw new CloudRuntimeException("Can not find snapshot " + snapshotId);
+		}
+
+		try {
+			snapshot.processEvent(Snapshot.Event.CreateRequested);
+		} catch (NoTransitionException nte) {
+			s_logger.debug("Failed to update snapshot state due to " + nte.getMessage());
+			throw new CloudRuntimeException("Failed to update snapshot state due to " + nte.getMessage());
+		}
+
+		AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
+		try {
+		    CreateSnapshotContext<CommandResult> context = new CreateSnapshotContext<CommandResult>(
+		            null, volume, snapshot, future);
+		    AsyncCallbackDispatcher<AncientSnapshotStrategy, CreateCmdResult> caller = AsyncCallbackDispatcher
+		            .create(this);
+		    caller.setCallback(
+		            caller.getTarget().createSnapshotAsyncCallback(null, null))
+		            .setContext(context);
+		    PrimaryDataStoreDriver primaryStore = (PrimaryDataStoreDriver)volume.getDataStore().getDriver();
+		    primaryStore.takeSnapshot(snapshot, caller);
+		} catch (Exception e) {
+		    s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e);
+		    try {
+                snapshot.processEvent(Snapshot.Event.OperationFailed);
+            } catch (NoTransitionException e1) {
+                s_logger.debug("Failed to change state for event: OperationFailed" , e);
+            }
+		    throw new CloudRuntimeException("Failed to take snapshot" + snapshot.getId());
+		}
+		
+		SnapshotResult result;
+		
+		try {
+			result = future.get();
+			if (result.isFailed()) {
+				s_logger.debug("Failed to create snapshot:" + result.getResult());
+				throw new CloudRuntimeException(result.getResult());
+			}
+			return result.snashot;
+		} catch (InterruptedException e) {
+			s_logger.debug("Failed to create snapshot", e);
+			throw new CloudRuntimeException("Failed to create snapshot", e);
+		} catch (ExecutionException e) {
+			s_logger.debug("Failed to create snapshot", e);
+			throw new CloudRuntimeException("Failed to create snapshot", e);
+		}
+
+	}
+
+	private boolean hostSupportSnapsthot(HostVO host) {
+		if (host.getHypervisorType() != HypervisorType.KVM) {
+			return true;
+		}
+		// Determine host capabilities
+		String caps = host.getCapabilities();
+
+		if (caps != null) {
+			String[] tokens = caps.split(",");
+			for (String token : tokens) {
+				if (token.contains("snapshot")) {
+					return true;
+				}
+			}
+		}
+		return false;
+	}
+
+	protected boolean supportedByHypervisor(VolumeInfo volume) {
+		if (volume.getHypervisorType().equals(HypervisorType.KVM)) {
+			StoragePool storagePool = (StoragePool)volume.getDataStore();
+			ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId());
+			List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(cluster.getId());
+			if (hosts != null && !hosts.isEmpty()) {
+				HostVO host = hosts.get(0);
+				if (!hostSupportSnapsthot(host)) {
+					throw new CloudRuntimeException("KVM Snapshot is not supported on cluster: " + host.getId());
+				}
+			}
+		}
+
+		// if volume is attached to a vm in destroyed or expunging state; disallow
+		if (volume.getInstanceId() != null) {
+			UserVmVO userVm = _vmDao.findById(volume.getInstanceId());
+			if (userVm != null) {
+				if (userVm.getState().equals(State.Destroyed) || userVm.getState().equals(State.Expunging)) {
+					throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volume.getId() + " is associated with vm:" + userVm.getInstanceName() + " is in "
+							+ userVm.getState().toString() + " state");
+				}
+
+				if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) {
+					List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating,  Snapshot.State.CreatedOnPrimary,  Snapshot.State.BackingUp);
+					if(activeSnapshots.size() > 1)
+						throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later");
+				}
+				
+				List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(userVm.getId(),
+                        VMSnapshot.State.Creating, VMSnapshot.State.Reverting, VMSnapshot.State.Expunging);
+                if (activeVMSnapshots.size() > 0) {
+                    throw new CloudRuntimeException(
+                            "There is other active vm snapshot tasks on the instance to which the volume is attached, please try again later");
+                }           
+			}
+		}
+
+		return true;
+	}
+
+	@Override
+	public SnapshotInfo takeSnapshot(VolumeInfo volume, Long snapshotId) {
+
+		supportedByHypervisor(volume);
+
+		SnapshotInfo snapshot = createSnapshotOnPrimary(volume, snapshotId);
+		return snapshot;
+	}
+
+	@Override
+	public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) {
+		SnapshotObject snapObj = (SnapshotObject)snapshot;
+		AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
+		SnapshotResult result = new SnapshotResult(snapshot);
+		try {
+
+			snapObj.processEvent(Snapshot.Event.BackupToSecondary);
+
+			ZoneScope scope = new ZoneScope(snapshot.getDataCenterId());
+			List<DataStore> stores = this.dataStoreMgr.getImageStores(scope);
+			if (stores.size() != 1) {
+				throw new CloudRuntimeException("find out more than one image stores");
+			}
+
+			DataStore imageStore = stores.get(0);
+			SnapshotInfo snapshotOnImageStore = (SnapshotInfo)imageStore.create(snapshot);
+
+			snapshotOnImageStore.processEvent(Event.CreateOnlyRequested);
+			CopySnapshotContext<CommandResult> context = new CopySnapshotContext<CommandResult>(null, snapshot,
+					snapshotOnImageStore, future);
+			AsyncCallbackDispatcher<AncientSnapshotStrategy, CopyCommandResult> caller = AsyncCallbackDispatcher
+					.create(this);
+			caller.setCallback(
+					caller.getTarget().copySnapshotAsyncCallback(null, null))
+					.setContext(context);
+			this.motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller);
+		} catch (Exception e) {
+			s_logger.debug("Failed to copy snapshot", e);
+			result.setResult("Failed to copy snapshot:" +e.toString());
+			try {
+                snapObj.processEvent(Snapshot.Event.OperationFailed);
+            } catch (NoTransitionException e1) {
+                s_logger.debug("Failed to change state: " + e1.toString());
+            }
+			future.complete(result);
+		}
+
+		try {
+			SnapshotResult res = future.get();
+			SnapshotInfo destSnapshot = res.snashot;
+			return destSnapshot;
+		} catch (InterruptedException e) {
+			s_logger.debug("failed copy snapshot", e);
+			throw new CloudRuntimeException("Failed to copy snapshot" , e);
+		} catch (ExecutionException e) {
+			s_logger.debug("Failed to copy snapshot", e);
+			throw new CloudRuntimeException("Failed to copy snapshot" , e);
+		}
+
+	}
+
+	protected Void copySnapshotAsyncCallback(AsyncCallbackDispatcher<AncientSnapshotStrategy, CopyCommandResult> callback, 
+			CopySnapshotContext<CommandResult> context) {
+		CopyCommandResult result = callback.getResult();
+		SnapshotInfo destSnapshot = context.destSnapshot;
+		SnapshotObject srcSnapshot = (SnapshotObject)context.srcSnapshot;
+		AsyncCallFuture<SnapshotResult> future = context.future;
+		SnapshotResult snapResult = new SnapshotResult(destSnapshot);
+		if (result.isFailed()) {
+			snapResult.setResult(result.getResult());
+			future.complete(snapResult);
+			return null;
+		}
+
+		try {
+			BackupSnapshotAnswer answer = (BackupSnapshotAnswer)result.getAnswer();
+			
+			DataObjectInStore dataInStore =  objInStoreMgr.findObject(destSnapshot, destSnapshot.getDataStore());
+			dataInStore.setInstallPath(answer.getBackupSnapshotName());
+			objInStoreMgr.update(destSnapshot, Event.OperationSuccessed);
+			
+			srcSnapshot.processEvent(Snapshot.Event.OperationSucceeded);
+			snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(destSnapshot.getId()));
+			future.complete(snapResult);
+		} catch (Exception e) {
+			s_logger.debug("Failed to update snapshot state", e);
+			snapResult.setResult(e.toString());
+			future.complete(snapResult);
+		}
+		return null;
+	}
+
+	@DB
+	protected boolean destroySnapshotBackUp(SnapshotVO snapshot) {
+		DataStore store = objInStoreMgr.findStore(snapshot.getUuid(), DataObjectType.SNAPSHOT, DataStoreRole.Image);
+		if (store == null) {
+			s_logger.debug("Can't find snapshot" + snapshot.getId() + " backed up into image store");
+			return false;
+		}
+
+		try {
+			SnapshotInfo snapshotInfo = this.snapshotfactory.getSnapshot(snapshot.getId(), store);
+			snapshotInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested);
+			
+			AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
+			DeleteSnapshotContext<CommandResult> context = new DeleteSnapshotContext<CommandResult>(null,
+					snapshotInfo, future);
+			AsyncCallbackDispatcher<AncientSnapshotStrategy, CommandResult> caller = AsyncCallbackDispatcher
+					.create(this);
+			caller.setCallback(
+					caller.getTarget().deleteSnapshotCallback(null, null))
+					.setContext(context);
+			
+			store.getDriver().deleteAsync(snapshotInfo, caller);
+			
+			SnapshotResult result = future.get();
+			if (result.isFailed()) {
+				s_logger.debug("Failed to delete snapsoht: " + result.getResult());
+			}
+			return result.isSuccess();
+		} catch (Exception e) {
+			s_logger.debug("Failed to delete snapshot", e);
+			return false;
+		}
+	}
+	
+	protected Void deleteSnapshotCallback(AsyncCallbackDispatcher<AncientSnapshotStrategy, CommandResult> callback, 
+			DeleteSnapshotContext<CommandResult> context) {
+		CommandResult result = callback.getResult();
+		AsyncCallFuture<SnapshotResult> future = context.future;
+		SnapshotInfo snapshot = context.snapshot;
+		if (result.isFailed()) {
+			s_logger.debug("delete snapshot failed" + result.getResult());
+			snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed);
+			SnapshotResult res = new SnapshotResult(context.snapshot);
+			future.complete(res);
+			return null;
+		}
+		snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed);
+		SnapshotResult res = new SnapshotResult(context.snapshot);
+		future.complete(res);
+		return null;
+	}
+
+	@Override
+	public boolean deleteSnapshot(SnapshotInfo snapInfo) {
+		Long snapshotId = snapInfo.getId();
+		SnapshotObject snapshot = (SnapshotObject)snapInfo;
+
+		if (!Snapshot.State.BackedUp.equals(snapshot.getState())) {
+			throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status");
+		}
+		
+		if (s_logger.isDebugEnabled()) {
+			s_logger.debug("Calling deleteSnapshot for snapshotId: " + snapshotId);
+		}
+		SnapshotVO lastSnapshot = null;
+		if (snapshot.getBackupSnapshotId() != null) {
+			List<SnapshotVO> snaps = _snapshotDao.listByBackupUuid(snapshot.getVolumeId(), snapshot.getBackupSnapshotId());
+			if (snaps != null && snaps.size() > 1) {
+				snapshot.setBackupSnapshotId(null);
+				SnapshotVO snapshotVO = this._snapshotDao.findById(snapshotId);
+				_snapshotDao.update(snapshot.getId(), snapshotVO);
+			}
+		}
+		
+		_snapshotDao.remove(snapshotId);
+
+		long lastId = snapshotId;
+		boolean destroy = false;
+		while (true) {
+			lastSnapshot = _snapshotDao.findNextSnapshot(lastId);
+			if (lastSnapshot == null) {
+				// if all snapshots after this snapshot in this chain are removed, remove those snapshots.
+				destroy = true;
+				break;
+			}
+			if (lastSnapshot.getRemoved() == null) {
+				// if there is one child not removed, then can not remove back up snapshot.
+				break;
+			}
+			lastId = lastSnapshot.getId();
+		}
+		if (destroy) {
+			lastSnapshot = _snapshotDao.findByIdIncludingRemoved(lastId);
+			while (lastSnapshot.getRemoved() != null) {
+				String BackupSnapshotId = lastSnapshot.getBackupSnapshotId();
+				if (BackupSnapshotId != null) {
+					List<SnapshotVO> snaps = _snapshotDao.listByBackupUuid(lastSnapshot.getVolumeId(), BackupSnapshotId);
+					if (snaps != null && snaps.size() > 1) {
+						lastSnapshot.setBackupSnapshotId(null);
+						_snapshotDao.update(lastSnapshot.getId(), lastSnapshot);
+					} else {
+						if (destroySnapshotBackUp(lastSnapshot)) {
+
+						} else {
+							s_logger.debug("Destroying snapshot backup failed " + lastSnapshot);
+							break;
+						}
+					}
+				}
+				lastId = lastSnapshot.getPrevSnapshotId();
+				if (lastId == 0) {
+					break;
+				}
+				lastSnapshot = _snapshotDao.findByIdIncludingRemoved(lastId);
+			}
+		}
+		return true;
+
+	}
+
+	@Override
+	public boolean revertSnapshot(SnapshotInfo snapshot) {
+		// TODO Auto-generated method stub
+		return false;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c52d04cd/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnasphotStrategy.java
----------------------------------------------------------------------
diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnasphotStrategy.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnasphotStrategy.java
deleted file mode 100644
index ea3b0af..0000000
--- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/strategy/AncientSnasphotStrategy.java
+++ /dev/null
@@ -1,608 +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.storage.snapshot.strategy;
-
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
-import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult;
-import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectType;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreRole;
-import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
-import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
-import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
-import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
-import org.apache.cloudstack.framework.async.AsyncCallFuture;
-import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
-import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
-import org.apache.cloudstack.framework.async.AsyncRpcConext;
-import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
-import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
-import org.apache.cloudstack.storage.motion.DataMotionService;
-import org.apache.cloudstack.storage.snapshot.SnapshotObject;
-import org.apache.cloudstack.storage.snapshot.SnapshotStateMachineManager;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
-import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.BackupSnapshotAnswer;
-import com.cloud.agent.api.DeleteSnapshotBackupCommand;
-import com.cloud.agent.api.to.S3TO;
-import com.cloud.agent.api.to.SwiftTO;
-import com.cloud.configuration.Resource.ResourceType;
-import com.cloud.configuration.dao.ConfigurationDao;
-import com.cloud.dc.ClusterVO;
-import com.cloud.dc.dao.ClusterDao;
-import com.cloud.event.EventTypes;
-import com.cloud.event.UsageEventUtils;
-import com.cloud.exception.InvalidParameterValueException;
-import com.cloud.host.HostVO;
-import com.cloud.hypervisor.Hypervisor.HypervisorType;
-import com.cloud.resource.ResourceManager;
-import com.cloud.storage.Snapshot;
-import com.cloud.storage.SnapshotVO;
-import com.cloud.storage.StoragePool;
-import com.cloud.storage.VolumeManager;
-import com.cloud.storage.VolumeVO;
-import com.cloud.storage.dao.SnapshotDao;
-import com.cloud.storage.dao.VolumeDao;
-import com.cloud.storage.s3.S3Manager;
-import com.cloud.storage.snapshot.SnapshotManager;
-import com.cloud.storage.swift.SwiftManager;
-import com.cloud.utils.NumbersUtil;
-import com.cloud.utils.db.DB;
-import com.cloud.utils.db.Transaction;
-import com.cloud.utils.exception.CloudRuntimeException;
-import com.cloud.utils.fsm.NoTransitionException;
-import com.cloud.vm.UserVmVO;
-import com.cloud.vm.VirtualMachine.State;
-import com.cloud.vm.dao.UserVmDao;
-import com.cloud.vm.snapshot.VMSnapshot;
-import com.cloud.vm.snapshot.VMSnapshotVO;
-import com.cloud.vm.snapshot.dao.VMSnapshotDao;
-
-@Component
-public class AncientSnasphotStrategy implements SnapshotStrategy {
-	private static final Logger s_logger = Logger.getLogger(AncientSnasphotStrategy.class);
-	@Inject
-	protected VolumeDao _volsDao;
-	@Inject
-	protected UserVmDao _vmDao;
-	@Inject
-	protected PrimaryDataStoreDao _storagePoolDao;
-	@Inject
-	protected ClusterDao _clusterDao;
-	@Inject
-	protected SnapshotDao snapshotDao;
-	@Inject
-	private ResourceManager _resourceMgr;
-	@Inject
-	protected SnapshotDao _snapshotDao;
-	@Inject
-	protected SnapshotManager snapshotMgr;
-	@Inject
-	protected VolumeManager volumeMgr;
-	@Inject
-	private ConfigurationDao _configDao;
-	@Inject
-	protected SnapshotStateMachineManager stateMachineManager;
-	@Inject
-	private VolumeDao volumeDao;
-	@Inject
-	SnapshotDataFactory snapshotfactory;
-	@Inject
-	DataStoreManager dataStoreMgr;
-	@Inject
-	DataMotionService motionSrv;
-	@Inject
-	ObjectInDataStoreManager objInStoreMgr;
-	@Inject
-	VMSnapshotDao _vmSnapshotDao;
-
-
-	@Override
-	public boolean canHandle(SnapshotInfo snapshot) {
-		return true;
-	}
-
-	static private class CreateSnapshotContext<T> extends AsyncRpcConext<T> {
-		final VolumeInfo volume;
-		final SnapshotInfo snapshot;
-		final AsyncCallFuture<SnapshotResult> future;
-		public CreateSnapshotContext(AsyncCompletionCallback<T> callback, VolumeInfo volume,
-				SnapshotInfo snapshot,
-				AsyncCallFuture<SnapshotResult> future) {
-			super(callback);
-			this.volume = volume;
-			this.snapshot = snapshot;
-			this.future = future;
-		}
-	}
-	
-	static private class DeleteSnapshotContext<T> extends AsyncRpcConext<T> {
-		final SnapshotInfo snapshot;
-		final AsyncCallFuture<SnapshotResult> future;
-		public DeleteSnapshotContext(AsyncCompletionCallback<T> callback, SnapshotInfo snapshot,
-				AsyncCallFuture<SnapshotResult> future) {
-			super(callback);
-			this.snapshot = snapshot;
-			this.future = future;
-		}
-		
-	}
-
-	static private class CopySnapshotContext<T> extends AsyncRpcConext<T> {
-		final SnapshotInfo srcSnapshot;
-		final SnapshotInfo destSnapshot;
-		final AsyncCallFuture<SnapshotResult> future;
-		public CopySnapshotContext(AsyncCompletionCallback<T> callback,
-				SnapshotInfo srcSnapshot,
-				SnapshotInfo destSnapshot,
-				AsyncCallFuture<SnapshotResult> future) {
-			super(callback);
-			this.srcSnapshot = srcSnapshot;
-			this.destSnapshot = destSnapshot;
-			this.future = future;
-		}
-
-	}
-
-	protected Void createSnapshotAsyncCallback(AsyncCallbackDispatcher<AncientSnasphotStrategy, CreateCmdResult> callback, 
-			CreateSnapshotContext<CreateCmdResult> context) {
-		CreateCmdResult result = callback.getResult();
-		SnapshotObject snapshot = (SnapshotObject)context.snapshot;
-		VolumeInfo volume = context.volume;
-		AsyncCallFuture<SnapshotResult> future = context.future;
-		SnapshotResult snapResult = new SnapshotResult(snapshot);
-		if (result.isFailed()) {
-			s_logger.debug("create snapshot " + context.snapshot.getName() + " failed: " + result.getResult());
-			try {
-				snapshot.processEvent(Snapshot.Event.OperationFailed);
-			} catch (NoTransitionException nte) {
-				s_logger.debug("Failed to update snapshot state due to " + nte.getMessage());
-			}
-
-
-			snapResult.setResult(result.getResult());
-			future.complete(snapResult);
-			return null;
-		}
-
-		try {
-			SnapshotVO preSnapshotVO = this.snapshotMgr.getParentSnapshot(volume, snapshot);
-			String preSnapshotPath = null;
-			if (preSnapshotVO != null) {
-			    preSnapshotPath = preSnapshotVO.getPath();
-			}
-			SnapshotVO snapshotVO = this.snapshotDao.findById(snapshot.getId());
-			// The snapshot was successfully created
-			if (preSnapshotPath != null && preSnapshotPath.equals(result.getPath())) {
-				// empty snapshot
-				s_logger.debug("CreateSnapshot: this is empty snapshot ");
-
-				snapshotVO.setPath(preSnapshotPath);
-				snapshotVO.setBackupSnapshotId(preSnapshotVO.getBackupSnapshotId());
-				snapshotVO.setSwiftId(preSnapshotVO.getSwiftId());
-				snapshotVO.setPrevSnapshotId(preSnapshotVO.getId());
-				snapshotVO.setSecHostId(preSnapshotVO.getSecHostId());
-				snapshot.processEvent(Snapshot.Event.OperationNotPerformed);
-			} else {
-				long preSnapshotId = 0;
-
-				if (preSnapshotVO != null && preSnapshotVO.getBackupSnapshotId() != null) {
-					preSnapshotId = preSnapshotVO.getId();
-					int _deltaSnapshotMax = NumbersUtil.parseInt(_configDao.getValue("snapshot.delta.max"), SnapshotManager.DELTAMAX);
-					int deltaSnap = _deltaSnapshotMax;
-
-					int i;
-					for (i = 1; i < deltaSnap; i++) {
-						String prevBackupUuid = preSnapshotVO.getBackupSnapshotId();
-						// previous snapshot doesn't have backup, create a full snapshot
-						if (prevBackupUuid == null) {
-							preSnapshotId = 0;
-							break;
-						}
-						long preSSId = preSnapshotVO.getPrevSnapshotId();
-						if (preSSId == 0) {
-							break;
-						}
-						preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preSSId);
-					}
-					if (i >= deltaSnap) {
-						preSnapshotId = 0;
-					}
-				}
-
-				//If the volume is moved around, backup a full snapshot to secondary storage
-				if (volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId())) {
-					preSnapshotId = 0;
-					//TODO: fix this hack
-					VolumeVO volumeVO = this.volumeDao.findById(volume.getId());
-					volumeVO.setLastPoolId(volume.getPoolId());
-					this.volumeDao.update(volume.getId(), volumeVO);
-				}
-
-				snapshot.setPath(result.getPath());
-				snapshot.setPrevSnapshotId(preSnapshotId);
-
-				snapshot.processEvent(Snapshot.Event.OperationSucceeded);
-				snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(snapshot.getId()));
-			} 
-		} catch (Exception e) {
-			s_logger.debug("Failed to create snapshot: ", e);
-			snapResult.setResult(e.toString());
-			try {
-                snapshot.processEvent(Snapshot.Event.OperationFailed);
-            } catch (NoTransitionException e1) {
-                s_logger.debug("Failed to change snapshot state: " + e1.toString());
-            }
-		}
-
-		future.complete(snapResult);
-		return null;
-	} 
-
-	class SnapshotResult extends CommandResult {
-		SnapshotInfo snashot;
-		public SnapshotResult(SnapshotInfo snapshot) {
-			this.snashot = snapshot;
-		}
-	}
-
-	protected SnapshotInfo createSnapshotOnPrimary(VolumeInfo volume, Long snapshotId) {
-		SnapshotObject snapshot = (SnapshotObject)this.snapshotfactory.getSnapshot(snapshotId);
-		if (snapshot == null) {
-			throw new CloudRuntimeException("Can not find snapshot " + snapshotId);
-		}
-
-		try {
-			snapshot.processEvent(Snapshot.Event.CreateRequested);
-		} catch (NoTransitionException nte) {
-			s_logger.debug("Failed to update snapshot state due to " + nte.getMessage());
-			throw new CloudRuntimeException("Failed to update snapshot state due to " + nte.getMessage());
-		}
-
-		AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
-		try {
-		    CreateSnapshotContext<CommandResult> context = new CreateSnapshotContext<CommandResult>(
-		            null, volume, snapshot, future);
-		    AsyncCallbackDispatcher<AncientSnasphotStrategy, CreateCmdResult> caller = AsyncCallbackDispatcher
-		            .create(this);
-		    caller.setCallback(
-		            caller.getTarget().createSnapshotAsyncCallback(null, null))
-		            .setContext(context);
-		    PrimaryDataStoreDriver primaryStore = (PrimaryDataStoreDriver)volume.getDataStore().getDriver();
-		    primaryStore.takeSnapshot(snapshot, caller);
-		} catch (Exception e) {
-		    s_logger.debug("Failed to take snapshot: " + snapshot.getId(), e);
-		    try {
-                snapshot.processEvent(Snapshot.Event.OperationFailed);
-            } catch (NoTransitionException e1) {
-                s_logger.debug("Failed to change state for event: OperationFailed" , e);
-            }
-		    throw new CloudRuntimeException("Failed to take snapshot" + snapshot.getId());
-		}
-		
-		SnapshotResult result;
-		
-		try {
-			result = future.get();
-			if (result.isFailed()) {
-				s_logger.debug("Failed to create snapshot:" + result.getResult());
-				throw new CloudRuntimeException(result.getResult());
-			}
-			return result.snashot;
-		} catch (InterruptedException e) {
-			s_logger.debug("Failed to create snapshot", e);
-			throw new CloudRuntimeException("Failed to create snapshot", e);
-		} catch (ExecutionException e) {
-			s_logger.debug("Failed to create snapshot", e);
-			throw new CloudRuntimeException("Failed to create snapshot", e);
-		}
-
-	}
-
-	private boolean hostSupportSnapsthot(HostVO host) {
-		if (host.getHypervisorType() != HypervisorType.KVM) {
-			return true;
-		}
-		// Determine host capabilities
-		String caps = host.getCapabilities();
-
-		if (caps != null) {
-			String[] tokens = caps.split(",");
-			for (String token : tokens) {
-				if (token.contains("snapshot")) {
-					return true;
-				}
-			}
-		}
-		return false;
-	}
-
-	protected boolean supportedByHypervisor(VolumeInfo volume) {
-		if (volume.getHypervisorType().equals(HypervisorType.KVM)) {
-			StoragePool storagePool = (StoragePool)volume.getDataStore();
-			ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId());
-			List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(cluster.getId());
-			if (hosts != null && !hosts.isEmpty()) {
-				HostVO host = hosts.get(0);
-				if (!hostSupportSnapsthot(host)) {
-					throw new CloudRuntimeException("KVM Snapshot is not supported on cluster: " + host.getId());
-				}
-			}
-		}
-
-		// if volume is attached to a vm in destroyed or expunging state; disallow
-		if (volume.getInstanceId() != null) {
-			UserVmVO userVm = _vmDao.findById(volume.getInstanceId());
-			if (userVm != null) {
-				if (userVm.getState().equals(State.Destroyed) || userVm.getState().equals(State.Expunging)) {
-					throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volume.getId() + " is associated with vm:" + userVm.getInstanceName() + " is in "
-							+ userVm.getState().toString() + " state");
-				}
-
-				if(userVm.getHypervisorType() == HypervisorType.VMware || userVm.getHypervisorType() == HypervisorType.KVM) {
-					List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(), Snapshot.State.Creating,  Snapshot.State.CreatedOnPrimary,  Snapshot.State.BackingUp);
-					if(activeSnapshots.size() > 1)
-						throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later");
-				}
-				
-				List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(userVm.getId(),
-                        VMSnapshot.State.Creating, VMSnapshot.State.Reverting, VMSnapshot.State.Expunging);
-                if (activeVMSnapshots.size() > 0) {
-                    throw new CloudRuntimeException(
-                            "There is other active vm snapshot tasks on the instance to which the volume is attached, please try again later");
-                }           
-			}
-		}
-
-		return true;
-	}
-
-	@Override
-	public SnapshotInfo takeSnapshot(VolumeInfo volume, Long snapshotId) {
-
-		supportedByHypervisor(volume);
-
-		SnapshotInfo snapshot = createSnapshotOnPrimary(volume, snapshotId);
-		return snapshot;
-	}
-
-	@Override
-	public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) {
-		SnapshotObject snapObj = (SnapshotObject)snapshot;
-		AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
-		SnapshotResult result = new SnapshotResult(snapshot);
-		try {
-
-			snapObj.processEvent(Snapshot.Event.BackupToSecondary);
-
-			ZoneScope scope = new ZoneScope(snapshot.getDataCenterId());
-			List<DataStore> stores = this.dataStoreMgr.getImageStores(scope);
-			if (stores.size() != 1) {
-				throw new CloudRuntimeException("find out more than one image stores");
-			}
-
-			DataStore imageStore = stores.get(0);
-			SnapshotInfo snapshotOnImageStore = (SnapshotInfo)imageStore.create(snapshot);
-
-			snapshotOnImageStore.processEvent(Event.CreateOnlyRequested);
-			CopySnapshotContext<CommandResult> context = new CopySnapshotContext<CommandResult>(null, snapshot,
-					snapshotOnImageStore, future);
-			AsyncCallbackDispatcher<AncientSnasphotStrategy, CopyCommandResult> caller = AsyncCallbackDispatcher
-					.create(this);
-			caller.setCallback(
-					caller.getTarget().copySnapshotAsyncCallback(null, null))
-					.setContext(context);
-			this.motionSrv.copyAsync(snapshot, snapshotOnImageStore, caller);
-		} catch (Exception e) {
-			s_logger.debug("Failed to copy snapshot", e);
-			result.setResult("Failed to copy snapshot:" +e.toString());
-			try {
-                snapObj.processEvent(Snapshot.Event.OperationFailed);
-            } catch (NoTransitionException e1) {
-                s_logger.debug("Failed to change state: " + e1.toString());
-            }
-			future.complete(result);
-		}
-
-		try {
-			SnapshotResult res = future.get();
-			SnapshotInfo destSnapshot = res.snashot;
-			return destSnapshot;
-		} catch (InterruptedException e) {
-			s_logger.debug("failed copy snapshot", e);
-			throw new CloudRuntimeException("Failed to copy snapshot" , e);
-		} catch (ExecutionException e) {
-			s_logger.debug("Failed to copy snapshot", e);
-			throw new CloudRuntimeException("Failed to copy snapshot" , e);
-		}
-
-	}
-
-	protected Void copySnapshotAsyncCallback(AsyncCallbackDispatcher<AncientSnasphotStrategy, CopyCommandResult> callback, 
-			CopySnapshotContext<CommandResult> context) {
-		CopyCommandResult result = callback.getResult();
-		SnapshotInfo destSnapshot = context.destSnapshot;
-		SnapshotObject srcSnapshot = (SnapshotObject)context.srcSnapshot;
-		AsyncCallFuture<SnapshotResult> future = context.future;
-		SnapshotResult snapResult = new SnapshotResult(destSnapshot);
-		if (result.isFailed()) {
-			snapResult.setResult(result.getResult());
-			future.complete(snapResult);
-			return null;
-		}
-
-		try {
-			BackupSnapshotAnswer answer = (BackupSnapshotAnswer)result.getAnswer();
-			
-			DataObjectInStore dataInStore =  objInStoreMgr.findObject(destSnapshot, destSnapshot.getDataStore());
-			dataInStore.setInstallPath(answer.getBackupSnapshotName());
-			objInStoreMgr.update(destSnapshot, Event.OperationSuccessed);
-			
-			srcSnapshot.processEvent(Snapshot.Event.OperationSucceeded);
-			snapResult = new SnapshotResult(this.snapshotfactory.getSnapshot(destSnapshot.getId()));
-			future.complete(snapResult);
-		} catch (Exception e) {
-			s_logger.debug("Failed to update snapshot state", e);
-			snapResult.setResult(e.toString());
-			future.complete(snapResult);
-		}
-		return null;
-	}
-
-	@DB
-	protected boolean destroySnapshotBackUp(SnapshotVO snapshot) {
-		DataStore store = objInStoreMgr.findStore(snapshot.getUuid(), DataObjectType.SNAPSHOT, DataStoreRole.Image);
-		if (store == null) {
-			s_logger.debug("Can't find snapshot" + snapshot.getId() + " backed up into image store");
-			return false;
-		}
-
-		try {
-			SnapshotInfo snapshotInfo = this.snapshotfactory.getSnapshot(snapshot.getId(), store);
-			snapshotInfo.processEvent(ObjectInDataStoreStateMachine.Event.DestroyRequested);
-			
-			AsyncCallFuture<SnapshotResult> future = new AsyncCallFuture<SnapshotResult>();
-			DeleteSnapshotContext<CommandResult> context = new DeleteSnapshotContext<CommandResult>(null,
-					snapshotInfo, future);
-			AsyncCallbackDispatcher<AncientSnasphotStrategy, CommandResult> caller = AsyncCallbackDispatcher
-					.create(this);
-			caller.setCallback(
-					caller.getTarget().deleteSnapshotCallback(null, null))
-					.setContext(context);
-			
-			store.getDriver().deleteAsync(snapshotInfo, caller);
-			
-			SnapshotResult result = future.get();
-			if (result.isFailed()) {
-				s_logger.debug("Failed to delete snapsoht: " + result.getResult());
-			}
-			return result.isSuccess();
-		} catch (Exception e) {
-			s_logger.debug("Failed to delete snapshot", e);
-			return false;
-		}
-	}
-	
-	protected Void deleteSnapshotCallback(AsyncCallbackDispatcher<AncientSnasphotStrategy, CommandResult> callback, 
-			DeleteSnapshotContext<CommandResult> context) {
-		CommandResult result = callback.getResult();
-		AsyncCallFuture<SnapshotResult> future = context.future;
-		SnapshotInfo snapshot = context.snapshot;
-		if (result.isFailed()) {
-			s_logger.debug("delete snapshot failed" + result.getResult());
-			snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed);
-			SnapshotResult res = new SnapshotResult(context.snapshot);
-			future.complete(res);
-			return null;
-		}
-		snapshot.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed);
-		SnapshotResult res = new SnapshotResult(context.snapshot);
-		future.complete(res);
-		return null;
-	}
-
-	@Override
-	public boolean deleteSnapshot(SnapshotInfo snapInfo) {
-		Long snapshotId = snapInfo.getId();
-		SnapshotObject snapshot = (SnapshotObject)snapInfo;
-
-		if (!Snapshot.State.BackedUp.equals(snapshot.getState())) {
-			throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is not in BackedUp Status");
-		}
-		
-		if (s_logger.isDebugEnabled()) {
-			s_logger.debug("Calling deleteSnapshot for snapshotId: " + snapshotId);
-		}
-		SnapshotVO lastSnapshot = null;
-		if (snapshot.getBackupSnapshotId() != null) {
-			List<SnapshotVO> snaps = _snapshotDao.listByBackupUuid(snapshot.getVolumeId(), snapshot.getBackupSnapshotId());
-			if (snaps != null && snaps.size() > 1) {
-				snapshot.setBackupSnapshotId(null);
-				SnapshotVO snapshotVO = this._snapshotDao.findById(snapshotId);
-				_snapshotDao.update(snapshot.getId(), snapshotVO);
-			}
-		}
-		
-		_snapshotDao.remove(snapshotId);
-
-		long lastId = snapshotId;
-		boolean destroy = false;
-		while (true) {
-			lastSnapshot = _snapshotDao.findNextSnapshot(lastId);
-			if (lastSnapshot == null) {
-				// if all snapshots after this snapshot in this chain are removed, remove those snapshots.
-				destroy = true;
-				break;
-			}
-			if (lastSnapshot.getRemoved() == null) {
-				// if there is one child not removed, then can not remove back up snapshot.
-				break;
-			}
-			lastId = lastSnapshot.getId();
-		}
-		if (destroy) {
-			lastSnapshot = _snapshotDao.findByIdIncludingRemoved(lastId);
-			while (lastSnapshot.getRemoved() != null) {
-				String BackupSnapshotId = lastSnapshot.getBackupSnapshotId();
-				if (BackupSnapshotId != null) {
-					List<SnapshotVO> snaps = _snapshotDao.listByBackupUuid(lastSnapshot.getVolumeId(), BackupSnapshotId);
-					if (snaps != null && snaps.size() > 1) {
-						lastSnapshot.setBackupSnapshotId(null);
-						_snapshotDao.update(lastSnapshot.getId(), lastSnapshot);
-					} else {
-						if (destroySnapshotBackUp(lastSnapshot)) {
-
-						} else {
-							s_logger.debug("Destroying snapshot backup failed " + lastSnapshot);
-							break;
-						}
-					}
-				}
-				lastId = lastSnapshot.getPrevSnapshotId();
-				if (lastId == 0) {
-					break;
-				}
-				lastSnapshot = _snapshotDao.findByIdIncludingRemoved(lastId);
-			}
-		}
-		return true;
-
-	}
-
-	@Override
-	public boolean revertSnapshot(SnapshotInfo snapshot) {
-		// TODO Auto-generated method stub
-		return false;
-	}
-
-}


[16/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
api: Fix ListNicsCmd's s_name, it should have a response suffix

Signed-off-by: Rohit Yadav <bh...@apache.org>


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

Branch: refs/heads/bvt
Commit: 94de31ebada689a766809e0b73faf567a079c79a
Parents: 1869527
Author: Rohit Yadav <bh...@apache.org>
Authored: Fri Mar 29 11:44:40 2013 +0530
Committer: Rohit Yadav <bh...@apache.org>
Committed: Fri Mar 29 11:45:19 2013 +0530

----------------------------------------------------------------------
 .../api/command/user/vm/ListNicsCmd.java           |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/94de31eb/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
index 9af044e..4c4e1f7 100644
--- a/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListNicsCmd.java
@@ -44,7 +44,7 @@ import com.cloud.vm.NicSecondaryIp;
 @APICommand(name = "listNics", description = "list the vm nics  IP to NIC", responseObject = NicResponse.class)
 public class ListNicsCmd extends BaseListCmd {
     public static final Logger s_logger = Logger.getLogger(ListNicsCmd.class.getName());
-    private static final String s_name = "listnics";
+    private static final String s_name = "listnicsresponse";
 
     /////////////////////////////////////////////////////
     //////////////// API parameters /////////////////////


[05/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
Summary: Workaround for CLOUDSTACK-1831 and CLOUDSTACK-1672

Exclude the transient dependency on jaxb-impl 2.1.13 in cxf-bundle-jars.
VmWare code depends on the 2.0 version

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

Branch: refs/heads/bvt
Commit: c8fd16c03d9946e0591c3e0c67117372dee28a75
Parents: c502b46
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Mar 28 15:00:04 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Mar 28 15:00:04 2013 +0100

----------------------------------------------------------------------
 engine/api/pom.xml     |    4 ++++
 framework/rest/pom.xml |    4 ++++
 2 files changed, 8 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c8fd16c0/engine/api/pom.xml
----------------------------------------------------------------------
diff --git a/engine/api/pom.xml b/engine/api/pom.xml
index 7fc612f..1e8e8c3 100644
--- a/engine/api/pom.xml
+++ b/engine/api/pom.xml
@@ -44,6 +44,10 @@
           <groupId>org.eclipse.jetty</groupId>
           <artifactId>jetty-server</artifactId>
         </exclusion>
+        <exclusion>
+          <groupId>com.sun.xml.bind</groupId>
+          <artifactId>jaxb-impl</artifactId>
+        </exclusion>
       </exclusions>
     </dependency>
     <dependency>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c8fd16c0/framework/rest/pom.xml
----------------------------------------------------------------------
diff --git a/framework/rest/pom.xml b/framework/rest/pom.xml
index a783bc8..ab88405 100644
--- a/framework/rest/pom.xml
+++ b/framework/rest/pom.xml
@@ -71,6 +71,10 @@
           <groupId>org.apache.geronimo.specs</groupId>
           <artifactId>geronimo-servlet_3.0_spec</artifactId>
         </exclusion>
+        <exclusion>
+          <groupId>com.sun.xml.bind</groupId>
+          <artifactId>jaxb-impl</artifactId>
+        </exclusion>        
       </exclusions>
     </dependency>
   </dependencies>


[24/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-767:nTier Apps 2.0 : Allow more than one Private GW to a VPC


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

Branch: refs/heads/bvt
Commit: 690c31290bcbd138c1cf49a7f8ca72fbe8c33c24
Parents: 5a66ec3
Author: Pranav Saxena <pr...@citrix.com>
Authored: Fri Mar 29 18:00:42 2013 +0530
Committer: Pranav Saxena <pr...@citrix.com>
Committed: Fri Mar 29 18:00:42 2013 +0530

----------------------------------------------------------------------
 ui/scripts/vpc.js |   87 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 87 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/690c3129/ui/scripts/vpc.js
----------------------------------------------------------------------
diff --git a/ui/scripts/vpc.js b/ui/scripts/vpc.js
index 4281ca2..a4834f2 100644
--- a/ui/scripts/vpc.js
+++ b/ui/scripts/vpc.js
@@ -616,6 +616,7 @@
       }
     },
     gateways: {
+
       add: {
         preCheck: function(args) {          
 					if(isAdmin()) { //root-admin
@@ -732,6 +733,92 @@
               netmask: { label: 'label.netmask', validation: { required: true }},
               vlan: { label: 'label.vlan', validation: { required: true }}
             },
+
+         actions:{
+           add:{
+            label:'Add Private Gateway',
+            createForm:{
+                 title: 'label.add.new.gateway',
+                 desc: 'message.add.new.gateway.to.vpc',
+                 fields: {
+                     physicalnetworkid: {
+                     docID: 'helpVPCGatewayPhysicalNetwork',
+                     label: 'label.physical.network',
+                     select: function(args) {
+                                                                $.ajax({
+                                                                        url: createURL("listPhysicalNetworks"),
+                                                                        data: {
+                                                                          zoneid: args.context.vpc[0].zoneid
+                                                                        },
+                                                                        success: function(json) {
+                                                                                var objs = json.listphysicalnetworksresponse.physicalnetwork;
+                                                                                var items = [];
+                                                                                $(objs).each(function() {
+                                                                                        items.push({id: this.id, description: this.name});
+                                                                                });
+                                                                                args.response.success({data: items});
+                                                                        }
+                                                                });
+              }
+                                                },
+            vlan: {
+              label: 'label.vlan', validation: { required: true },
+              docID: 'helpVPCGatewayVLAN'
+            },
+            ipaddress: {
+              label: 'label.ip.address', validation: { required: true },
+              docID: 'helpVPCGatewayIP'
+            },
+            gateway: {
+              label: 'label.gateway', validation: { required: true },
+              docID: 'helpVPCGatewayGateway'
+            },
+            netmask: {
+              label: 'label.netmask', validation: { required: true },
+              docID: 'helpVPCGatewayNetmask'
+            }
+          }
+
+
+
+            },
+            action:function(args){
+                       $.ajax({
+            url: createURL('createPrivateGateway'),
+            data: {
+                                                  physicalnetworkid: args.data.physicalnetworkid,
+              vpcid: args.context.vpc[0].id,
+              ipaddress: args.data.ipaddress,
+              gateway: args.data.gateway,
+              netmask: args.data.netmask,
+              vlan: args.data.vlan
+            },
+            success: function(json) {
+              var jid = json.createprivategatewayresponse.jobid;
+              args.response.success(
+                {_custom:
+                 {jobId: jid,
+                  getUpdatedItem: function(json) {
+                    return json.queryasyncjobresultresponse.jobresult.privategateway;
+                  }
+                 }
+                }
+              );
+            },
+            error: function(json) {
+              args.response.error(parseXMLHttpResponse(json));
+            }
+          });
+               },
+
+          notification: {
+          poll: pollAsyncJobResult
+                   }
+
+
+             }
+           },
+
             dataProvider: function(args) {
               $.ajax({
                 url: createURL('listPrivateGateways'),


[25/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
Merge branch 'master' into bvt


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

Branch: refs/heads/bvt
Commit: 5727bd0eac086e653ec34bb6a17e9337da6deecc
Parents: 1ae4d7f 690c312
Author: Prasanna Santhanam <ts...@apache.org>
Authored: Fri Mar 29 18:10:14 2013 +0530
Committer: Prasanna Santhanam <ts...@apache.org>
Committed: Fri Mar 29 18:10:14 2013 +0530

----------------------------------------------------------------------
 api/src/com/cloud/agent/api/ScaleVmCommand.java    |    6 +-
 api/src/com/cloud/configuration/Resource.java      |    7 +-
 api/src/com/cloud/event/EventTypes.java            |    6 +
 api/src/com/cloud/storage/VolumeApiService.java    |    5 +-
 api/src/com/cloud/vm/UserVmService.java            |   16 +-
 api/src/com/cloud/vm/VirtualMachine.java           |    2 +-
 .../user/resource/UpdateResourceCountCmd.java      |    6 +-
 .../user/resource/UpdateResourceLimitCmd.java      |    6 +-
 .../api/command/user/vm/ListNicsCmd.java           |    2 +-
 .../cloudstack/api/command/user/vm/ScaleVMCmd.java |  110 +++
 .../api/command/user/volume/ResizeVolumeCmd.java   |    3 +-
 .../cloudstack/api/response/AccountResponse.java   |   54 ++-
 .../api/response/ResourceCountResponse.java        |    2 +-
 .../api/response/ResourceLimitResponse.java        |    2 +-
 .../api/command/test/ScaleVMCmdTest.java           |  122 +++
 .../WEB-INF/classes/resources/messages.properties  |    8 +
 client/pom.xml                                     |    5 +
 client/tomcatconf/commands.properties.in           |    1 +
 client/tomcatconf/componentContext.xml.in          |    2 +
 client/tomcatconf/log4j-cloud.xml.in               |   15 +
 client/tomcatconf/nonossComponentContext.xml.in    |    5 +
 core/src/com/cloud/vm/VMInstanceVO.java            |    2 +-
 engine/api/pom.xml                                 |    4 +
 .../snapshot/strategy/AncientSnapshotStrategy.java |  608 +++++++++++++++
 .../snapshot/strategy/AncientSnasphotStrategy.java |  608 ---------------
 framework/rest/pom.xml                             |    4 +
 packaging/centos63/cloud.spec                      |    3 +-
 plugins/alert-handlers/syslog-alerts/pom.xml       |   40 +
 .../cloudstack/syslog/AlertsSyslogAppender.java    |  336 ++++++++
 .../syslog/AlertsSyslogAppenderTest.java           |   61 ++
 .../manager/BareMetalTemplateAdapter.java          |   15 +-
 .../hypervisor/vmware/VmwareServerDiscoverer.java  |   12 +-
 .../vmware/manager/VmwareManagerImpl.java          |    8 +-
 .../xen/resource/CitrixResourceBase.java           |   82 ++
 .../xen/resource/XenServer56FP1Resource.java       |   11 +-
 .../xen/resource/CitrixResourceBaseTest.java       |  148 ++++
 plugins/pom.xml                                    |    1 +
 .../xenserver/Add-To-VCPUs-Params-Live.sh          |   33 +
 scripts/vm/hypervisor/xenserver/vmops              |   13 +
 .../cloud/agent/manager/ClusteredAgentAttache.java |   13 +-
 server/src/com/cloud/alert/AlertManagerImpl.java   |    3 +-
 server/src/com/cloud/api/ApiResponseHelper.java    |  149 +++-
 .../cloud/api/query/dao/AccountJoinDaoImpl.java    |   18 +
 .../src/com/cloud/api/query/vo/AccountJoinVO.java  |   54 ++
 server/src/com/cloud/configuration/Config.java     |    8 +-
 .../router/VirtualNetworkApplianceManagerImpl.java |   15 +-
 .../resourcelimit/ResourceLimitManagerImpl.java    |   97 ++-
 .../src/com/cloud/server/ManagementServerImpl.java |    2 +
 server/src/com/cloud/storage/VolumeManager.java    |    3 +-
 .../src/com/cloud/storage/VolumeManagerImpl.java   |   95 ++-
 server/src/com/cloud/storage/dao/SnapshotDao.java  |   12 +-
 .../src/com/cloud/storage/dao/SnapshotDaoImpl.java |   65 +-
 server/src/com/cloud/storage/dao/VolumeDao.java    |   66 +-
 .../src/com/cloud/storage/dao/VolumeDaoImpl.java   |   48 +-
 .../cloud/storage/download/DownloadListener.java   |   62 ++-
 .../storage/download/DownloadMonitorImpl.java      |   56 ++-
 .../storage/snapshot/SnapshotManagerImpl.java      |   70 +-
 .../cloud/template/HypervisorTemplateAdapter.java  |   29 +-
 .../com/cloud/template/TemplateManagerImpl.java    |   47 +-
 server/src/com/cloud/user/AccountManagerImpl.java  |    2 +
 server/src/com/cloud/vm/ItWorkVO.java              |    3 +-
 server/src/com/cloud/vm/UserVmManagerImpl.java     |  107 +++-
 server/src/com/cloud/vm/VirtualMachineManager.java |   12 +
 .../com/cloud/vm/VirtualMachineManagerImpl.java    |  311 +++++++-
 .../gslb/GlobalLoadBalancingRulesServiceImpl.java  |    8 +-
 .../ResourceLimitManagerImplTest.java              |   18 +-
 .../test/com/cloud/vm/MockUserVmManagerImpl.java   |   17 +-
 .../cloud/vm/MockVirtualMachineManagerImpl.java    |   17 +
 server/test/com/cloud/vm/UserVmManagerTest.java    |  192 +++++-
 .../cloud/vm/VirtualMachineManagerImplTest.java    |  208 +++++
 .../cloud/vpc/MockResourceLimitManagerImpl.java    |    8 +
 .../networkoffering/CreateNetworkOfferingTest.java |    6 -
 setup/db/db/schema-40to410.sql                     |   31 +-
 setup/db/db/schema-410to420.sql                    |  153 ++++-
 test/integration/smoke/test_ScaleVm.py             |  221 ++++++
 ui/dictionary.jsp                                  |    8 +
 ui/scripts/accounts.js                             |  137 +++-
 ui/scripts/domains.js                              |   92 +++
 ui/scripts/instanceWizard.js                       |   60 ++-
 ui/scripts/projects.js                             |   20 +-
 ui/scripts/storage.js                              |    8 +-
 ui/scripts/system.js                               |    8 +-
 ui/scripts/vpc.js                                  |   87 ++
 utils/src/com/cloud/utils/UriUtils.java            |   33 +
 84 files changed, 4038 insertions(+), 1015 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5727bd0e/client/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5727bd0e/client/tomcatconf/componentContext.xml.in
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5727bd0e/plugins/pom.xml
----------------------------------------------------------------------


[10/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1827: Fix redundant router update mechanism

There is a bug that if the smaller number ID RvR stop running, that pair of
RvR's status won't be updated. This patch fixed it.


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

Branch: refs/heads/bvt
Commit: e3f67d126d66c31e027c96b5524667884084053b
Parents: 86a153c
Author: Sheng Yang <sh...@citrix.com>
Authored: Thu Mar 28 15:02:45 2013 -0700
Committer: Sheng Yang <sh...@citrix.com>
Committed: Thu Mar 28 15:54:07 2013 -0700

----------------------------------------------------------------------
 .../router/VirtualNetworkApplianceManagerImpl.java |   15 ++++++++++++---
 1 files changed, 12 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e3f67d12/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index 45b11f7..78168b0 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -1277,13 +1277,22 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                      * We update the router pair which the lower id router owned by this mgmt server, in order
                      * to prevent duplicate update of router status from cluster mgmt servers
                      */
-                    DomainRouterVO router = routers.get(0);
-                    if (routers.get(1).getId() < router.getId()) {
-                        router = routers.get(1);
+                    DomainRouterVO router0 = routers.get(0);
+                    DomainRouterVO router1 = routers.get(1);
+                    DomainRouterVO router = router0;
+                    if ((router0.getId() < router1.getId()) && router0.getHostId() != null) {
+                    	router = router0;
+                    } else {
+                    	router = router1;
+                    }
+                    if (router.getHostId() == null) {
+                    	s_logger.debug("Skip router pair (" + router0.getInstanceName() + "," + router1.getInstanceName() + ") due to can't find host");
+                    	continue;
                     }
                     HostVO host = _hostDao.findById(router.getHostId());
                     if (host == null || host.getManagementServerId() == null ||
                             host.getManagementServerId() != ManagementServerNode.getManagementServerId()) {
+                    	s_logger.debug("Skip router pair (" + router0.getInstanceName() + "," + router1.getInstanceName() + ") due to not belong to this mgmt server");
                         continue;
                     }
                 updateRoutersRedundantState(routers);


[17/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1841: Missing `cloud`.`configuration` stmts in upgrade

Following global configurations introduced b/w 3.0.2 and 4.1 were
missed.

concurrent.snapshots.threshold.perhost | NULL
network.ipv6.search.retry.max | 10000
traffic.sentinel.exclude.zones |
traffic.sentinel.include.zones | EXTERNAL

Signed-off-by: Prasanna Santhanam <ts...@apache.org>


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

Branch: refs/heads/bvt
Commit: d13c18516a30d035e2251d187979e805670aab81
Parents: 94de31e
Author: Prasanna Santhanam <ts...@apache.org>
Authored: Fri Mar 29 13:25:20 2013 +0530
Committer: Prasanna Santhanam <ts...@apache.org>
Committed: Fri Mar 29 13:25:20 2013 +0530

----------------------------------------------------------------------
 setup/db/db/schema-40to410.sql |    7 +++++++
 1 files changed, 7 insertions(+), 0 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d13c1851/setup/db/db/schema-40to410.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-40to410.sql b/setup/db/db/schema-40to410.sql
index 3dae1cc..e333810 100644
--- a/setup/db/db/schema-40to410.sql
+++ b/setup/db/db/schema-40to410.sql
@@ -1652,3 +1652,10 @@ CREATE TABLE `cloud`.`ucs_manager` (
 
 
 SET foreign_key_checks = 1;
+
+UPDATE `cloud`.`configuration` SET value='KVM,XenServer,VMware,Ovm' WHERE name='hypervisor.list';
+
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'concurrent.snapshots.threshold.perhost' , NULL, 'Limit number of snapshots that can be handled concurrently; default is NULL - unlimited.');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network', 'DEFAULT', 'management-server', 'network.ipv6.search.retry.max' , 10000, 'The maximum number of retrying times to search for an available IPv6 address in the table');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Usage', 'DEFAULT', 'management-server', 'traffic.sentinel.exclude.zones' , '', 'Traffic going into specified list of zones is not metered');
+INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Usage', 'DEFAULT', 'management-server', 'traffic.sentinel.include.zones' , 'EXTERNAL', 'Traffic going into specified list of zones is metered. For metering all traffic leave this parameter empty');


[18/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1592:[UI] Add support to limit newly added resourcetypes


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

Branch: refs/heads/bvt
Commit: 2c176ab9ea6216b7c9da25ce0b0d2b34cbc2a776
Parents: d13c185
Author: Sanjay Tripathi <sa...@citrix.com>
Authored: Fri Mar 29 14:18:14 2013 +0530
Committer: Pranav Saxena <pr...@citrix.com>
Committed: Fri Mar 29 14:18:14 2013 +0530

----------------------------------------------------------------------
 .../WEB-INF/classes/resources/messages.properties  |    8 +
 ui/dictionary.jsp                                  |    8 +
 ui/scripts/accounts.js                             |  137 ++++++++++++++-
 ui/scripts/domains.js                              |   92 ++++++++++
 ui/scripts/projects.js                             |   20 ++-
 5 files changed, 254 insertions(+), 11 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c176ab9/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 66b32ac..da224eb 100644
--- a/client/WEB-INF/classes/resources/messages.properties
+++ b/client/WEB-INF/classes/resources/messages.properties
@@ -19,6 +19,14 @@
 #new labels (begin) **********************************************************************************************
 message.redirecting.region=Redirecting to region...
 label.use.vm.ip=Use VM IP:
+label.cpu.limits=CPU limits
+label.memory.limits=Memory limits (MiB)
+label.primary.storage.limits=Primary Storage limits (GiB)
+label.secondary.storage.limits=Secondary Storage limits (GiB)
+label.max.cpus=Max. CPU cores
+label.max.memory=Max. memory (MiB)
+label.max.primary.storage=Max. primary (GiB)
+label.max.secondary.storage=Max. secondary (GiB)
 label.menu.regions=Regions
 label.region=Region
 label.add.region=Add Region

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c176ab9/ui/dictionary.jsp
----------------------------------------------------------------------
diff --git a/ui/dictionary.jsp b/ui/dictionary.jsp
index cd8d732..d4f9078 100644
--- a/ui/dictionary.jsp
+++ b/ui/dictionary.jsp
@@ -27,6 +27,14 @@ under the License.
 dictionary = {
 'message.redirecting.region': '<fmt:message key="message.redirecting.region"/>',
 'label.use.vm.ip': '<fmt:message key="label.use.vm.ip"/>',
+'label.cpu.limits': '<fmt:message key="label.cpu.limits"/>',
+'label.memory.limits': '<fmt:message key="label.memory.limits"/>',
+'label.primary.storage.limits': '<fmt:message key="label.primary.storage.limits"/>',
+'label.secondary.storage.limits': '<fmt:message key="label.secondary.storage.limits"/>',
+'label.max.cpus': '<fmt:message key="label.max.cpus"/>',
+'label.max.memory': '<fmt:message key="label.max.memory"/>',
+'label.max.primary.storage': '<fmt:message key="label.max.primary.storage"/>',
+'label.max.secondary.storage': '<fmt:message key="label.max.secondary.storage"/>',
 'label.add.region': '<fmt:message key="label.add.region"/>',
 'label.remove.region': '<fmt:message key="label.remove.region"/>',
 'message.remove.region': '<fmt:message key="message.remove.region"/>',

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c176ab9/ui/scripts/accounts.js
----------------------------------------------------------------------
diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js
index 3403337..8353d70 100644
--- a/ui/scripts/accounts.js
+++ b/ui/scripts/accounts.js
@@ -409,6 +409,77 @@
 										});
 									}
 
+									if(args.data.cpuLimit != null) {
+									  var data = {
+										  resourceType: 8,
+											max: args.data.cpuLimit,
+											domainid: accountObj.domainid,
+											account: accountObj.name
+										};
+
+										$.ajax({
+											url: createURL('updateResourceLimit'),
+											data: data,
+											async: false,
+											success: function(json) {
+												accountObj["cpuLimit"] = args.data.cpuLimit;
+											}
+										});
+									}
+
+									if(args.data.memoryLimit != null) {
+									  var data = {
+										  resourceType: 9,
+											max: args.data.memoryLimit,
+											domainid: accountObj.domainid,
+											account: accountObj.name
+										};
+
+										$.ajax({
+											url: createURL('updateResourceLimit'),
+											data: data,
+											async: false,
+											success: function(json) {
+												accountObj["memoryLimit"] = args.data.memoryLimit;
+											}
+										});
+									}
+
+									if(args.data.primaryStorageLimit != null) {
+									  var data = {
+										  resourceType: 10,
+											max: args.data.primaryStorageLimit,
+											domainid: accountObj.domainid,
+											account: accountObj.name
+										};
+
+										$.ajax({
+											url: createURL('updateResourceLimit'),
+											data: data,
+											async: false,
+											success: function(json) {
+												accountObj["primaryStorageLimit"] = args.data.primaryStorageLimit;
+											}
+										});
+									}
+
+									if(args.data.secondaryStorageLimit != null) {
+										  var data = {
+											  resourceType: 11,
+												max: args.data.secondaryStorageLimit,
+												domainid: accountObj.domainid,
+												account: accountObj.name
+											};
+
+											$.ajax({
+												url: createURL('updateResourceLimit'),
+												data: data,
+												async: false,
+												success: function(json) {
+													accountObj["secondaryStorageLimit"] = args.data.secondaryStorageLimit;
+												}
+											});
+										}
                   args.response.success({data: accountObj});
                 }
               },
@@ -698,6 +769,42 @@
 												  return false;
 											}
                     },
+                    cpuLimit: {
+                      label: 'label.cpu.limits',
+                      isEditable: function(context) {
+  											  if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin
+  												  return true;
+  												else
+  												  return false;
+  											}
+                    },
+                    memoryLimit: {
+                      label: 'label.memory.limits',
+                      isEditable: function(context) {
+  											  if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin
+  												  return true;
+  												else
+  												  return false;
+  											}
+                    },
+                    primaryStorageLimit: {
+                      label: 'label.primary.storage.limits',
+                      isEditable: function(context) {
+  											  if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin
+  												  return true;
+  												else
+  												  return false;
+  											}
+                    },
+                    secondaryStorageLimit: {
+                      label: 'label.secondary.storage.limits',
+                      isEditable: function(context) {
+  											  if (context.accounts[0].accounttype == roleTypeUser || context.accounts[0].accounttype == roleTypeDomainAdmin) //updateResourceLimits is only allowed on account whose type is user or domain-admin
+  												  return true;
+  												else
+  												  return false;
+  											}
+                    },
 
                     vmtotal: { label: 'label.total.of.vm' },
                     iptotal: { label: 'label.total.of.ip' },
@@ -725,11 +832,11 @@
                 dataProvider: function(args) {
 								  var data = {
 									  id: args.context.accounts[0].id
-									};								
+									};
 									$.ajax({
 										url: createURL('listAccounts'),
-										data: data,					
-										success: function(json) {		
+										data: data,
+										success: function(json) {
 											var accountObj = json.listaccountsresponse.account[0];
                       var data = {
 											  domainid: accountObj.domainid,
@@ -737,7 +844,7 @@
 											};
 											$.ajax({
 												url: createURL('listResourceLimits'),
-												data: data,											
+												data: data,
 												success: function(json) {
 													var limits = json.listresourcelimitsresponse.resourcelimit;													
 													if (limits != null) {
@@ -759,22 +866,34 @@
 															case "4":
 																accountObj["templateLimit"] = limit.max;
 																break;
-                              case "7":
+															case "7":
 																accountObj["vpcLimit"] = limit.max;
 																break;
+															case "8":
+																accountObj["cpuLimit"] = limit.max;
+																break;
+															case "9":
+																accountObj["memoryLimit"] = limit.max;
+																break;
+															case "10":
+																accountObj["primaryStorageLimit"] = limit.max;
+																break;
+															case "11":
+																accountObj["secondaryStorageLimit"] = limit.max;
+																break;
 															}
 														}
-													}																										
+													}
 													args.response.success(
 														{
 															actionFilter: accountActionfilter,
 															data: accountObj 
 														}
-													);							
+													);
 												}
-											});											
+											});
 										}
-									});		
+									});
                 }
               }
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c176ab9/ui/scripts/domains.js
----------------------------------------------------------------------
diff --git a/ui/scripts/domains.js b/ui/scripts/domains.js
index 991e37d..8ee0ee6 100644
--- a/ui/scripts/domains.js
+++ b/ui/scripts/domains.js
@@ -184,6 +184,50 @@
 								});
 							}
 
+              if(args.data.cpuLimit != null) {
+								$.ajax({
+									url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=8&max=" + args.data.cpuLimit),
+									dataType: "json",
+									async: false,
+									success: function(json) {
+										domainObj["cpuLimit"] = args.data.cpuLimit;
+									}
+								});
+							}
+
+              if(args.data.memoryLimit != null) {
+								$.ajax({
+									url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=9&max=" + args.data.memoryLimit),
+									dataType: "json",
+									async: false,
+									success: function(json) {
+										domainObj["memoryLimit"] = args.data.memoryLimit;
+									}
+								});
+							}
+
+              if(args.data.primaryStorageLimit != null) {
+								$.ajax({
+									url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=10&max=" + args.data.primaryStorageLimit),
+									dataType: "json",
+									async: false,
+									success: function(json) {
+										domainObj["primaryStorageLimit"] = args.data.primaryStorageLimit;
+									}
+								});
+							}
+
+              if(args.data.secondaryStorageLimit != null) {
+								$.ajax({
+									url: createURL("updateResourceLimit&domainid=" + args.context.domains[0].id + "&resourceType=11&max=" + args.data.secondaryStorageLimit),
+									dataType: "json",
+									async: false,
+									success: function(json) {
+										domainObj["secondaryStorageLimit"] = args.data.secondaryStorageLimit;
+									}
+								});
+							}
+
               args.response.success({data: domainObj});
             }
           },
@@ -348,6 +392,42 @@
 											return false;
 									}
                 },
+                cpuLimit: {
+                  label: 'label.cpu.limits',
+                  isEditable: function(context) {
+                    if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits 												
+  										  return true;
+  										else
+  											return false;
+  									}
+                },
+                memoryLimit: {
+                  label: 'label.memory.limits',
+                  isEditable: function(context) {
+                    if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits 												
+										  return true;
+										else
+											return false;
+									}
+                },
+                primaryStorageLimit: {
+                  label: 'label.primary.storage.limits',
+                  isEditable: function(context) {
+                    if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits 												
+  										  return true;
+  										else
+  											return false;
+  									}
+                },
+                secondaryStorageLimit: {
+                  label: 'label.secondary.storage.limits',
+                  isEditable: function(context) {
+                    if(context.domains[0].level != 0) //ROOT domain (whose level is 0) is not allowed to updateResourceLimits 												
+  										  return true;
+  										else
+  											return false;
+  									}
+                },
                 accountTotal: { label: 'label.accounts' },
                 vmTotal: { label: 'label.instances' },
                 volumeTotal: { label: 'label.volumes' }
@@ -441,6 +521,18 @@
                       case "7":
                         domainObj["vpcLimit"] = limit.max;
                         break;
+                      case "8":
+                        domainObj["cpuLimit"] = limit.max;
+                        break;
+                      case "9":
+                        domainObj["memoryLimit"] = limit.max;
+                        break;
+                      case "10":
+                        domainObj["primaryStorageLimit"] = limit.max;
+                        break;
+                      case "7":
+                        domainObj["secondaryStorageLimit"] = limit.max;
+                        break;
                       }
                     }
                   }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2c176ab9/ui/scripts/projects.js
----------------------------------------------------------------------
diff --git a/ui/scripts/projects.js b/ui/scripts/projects.js
index b62dcb4..4004709 100644
--- a/ui/scripts/projects.js
+++ b/ui/scripts/projects.js
@@ -71,7 +71,7 @@
             var resourceLimits = $.grep(
               json.listresourcelimitsresponse.resourcelimit,
               function(resourceLimit) {
-                return resourceLimit.resourcetype != 5 && resourceLimit.resourcetype != 8;
+                return resourceLimit.resourcetype != 5 && resourceLimit.resourcetype != 12;
               }
             );
             
@@ -111,7 +111,23 @@
                     7: {
                       id: 'vpc',
                       label: 'label.max.vpcs'
-                    }                    
+                    },
+                    8: {
+                        id: 'cpu',
+                        label: 'label.max.cpus'
+                    },
+                    9: {
+                        id: 'memory',
+                        label: 'label.max.memory'
+                    },
+                    10: {
+                        id: 'primary_storage',
+                        label: 'label.max.primary.storage'
+                    },
+                    11: {
+                        id: 'secondary_storage',
+                        label: 'label.max.secondary.storage'
+                    }
                   };
 
                   return {


[12/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1844 - fix typo in agent pre-script to allow copy of old configs
to new config location

Reported-by: Sangeetha Hariharan (JIRA)
Signed-off-by: Marcus Sorensen <ma...@betterservers.com> 1364522608 -0600


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

Branch: refs/heads/bvt
Commit: d6e11f25ace4696ec39063f86342cd8a94bd96ee
Parents: 4534daf
Author: Marcus Sorensen <ma...@betterservers.com>
Authored: Thu Mar 28 20:03:28 2013 -0600
Committer: Marcus Sorensen <ma...@betterservers.com>
Committed: Thu Mar 28 20:03:28 2013 -0600

----------------------------------------------------------------------
 packaging/centos63/cloud.spec |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d6e11f25/packaging/centos63/cloud.spec
----------------------------------------------------------------------
diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec
index 3fd0dd4..f8e3133 100644
--- a/packaging/centos63/cloud.spec
+++ b/packaging/centos63/cloud.spec
@@ -397,7 +397,7 @@ fi
 # save old configs if they exist (for upgrade). Otherwise we may lose them
 # when the old packages are erased. There are a lot of properties files here.
 if [ -d "%{_sysconfdir}/cloud" ] ; then
-    mv %{_sysconfdir}/cloud %{_sysconfdir}/cloudr.rpmsave
+    mv %{_sysconfdir}/cloud %{_sysconfdir}/cloud.rpmsave
 fi
 
 %post agent


[09/25] git commit: updated refs/heads/bvt to 5727bd0

Posted by ts...@apache.org.
CLOUDSTACK-1838: cloudstack UI - volume page - listView, detailView - hide hypervisor field when log in as regular-user/domain-admin.


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

Branch: refs/heads/bvt
Commit: 86a153c595d65049fcd1a93bca1bf3ef40364fd3
Parents: 34a59fc
Author: Jessica Wang <je...@citrix.com>
Authored: Thu Mar 28 14:38:17 2013 -0700
Committer: Jessica Wang <je...@citrix.com>
Committed: Thu Mar 28 14:38:52 2013 -0700

----------------------------------------------------------------------
 ui/scripts/storage.js |    8 +++++++-
 1 files changed, 7 insertions(+), 1 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/86a153c5/ui/scripts/storage.js
----------------------------------------------------------------------
diff --git a/ui/scripts/storage.js b/ui/scripts/storage.js
index 5c19bd0..54605e2 100644
--- a/ui/scripts/storage.js
+++ b/ui/scripts/storage.js
@@ -34,6 +34,12 @@
         listView: {
           id: 'volumes',
           label: 'label.volumes',
+					preFilter: function(args) {
+					  var hiddenFields = [];
+					  if(isAdmin() != true)
+					    hiddenFields.push('hypervisor');
+						return hiddenFields;
+					},
           fields: {
             name: { label: 'label.name' },
             type: { label: 'label.type' },
@@ -1113,7 +1119,7 @@
                     hiddenFields = [];
                   }
                   else {
-                    hiddenFields = ["storage"];
+                    hiddenFields = ['storage', 'hypervisor'];
                   }
                   return hiddenFields;
                 },