You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2014/01/17 23:40:40 UTC

[38/50] [abbrv] Merge branch 'master' into rbac.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/server/ManagementServerImpl.java
index dbbafad,59767f3..33c5c0f
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@@ -879,10 -885,10 +887,10 @@@ public class ManagementServerImpl exten
      public boolean archiveEvents(ArchiveEventsCmd cmd) {
          Account caller = CallContext.current().getCallingAccount();
          List<Long> ids = cmd.getIds();
-         boolean result =true;
+         boolean result = true;
          List<Long> permittedAccountIds = new ArrayList<Long>();
  
 -        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_PROJECT) {
 +        if (_accountService.isNormalUser(caller.getId()) || caller.getType() == Account.ACCOUNT_TYPE_PROJECT) {
              permittedAccountIds.add(caller.getId());
          } else {
              DomainVO domain = _domainDao.findById(caller.getDomainId());
@@@ -906,10 -912,10 +914,10 @@@
      public boolean deleteEvents(DeleteEventsCmd cmd) {
          Account caller = CallContext.current().getCallingAccount();
          List<Long> ids = cmd.getIds();
-         boolean result =true;
+         boolean result = true;
          List<Long> permittedAccountIds = new ArrayList<Long>();
  
 -        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_PROJECT) {
 +        if (_accountMgr.isNormalUser(caller.getId()) || caller.getType() == Account.ACCOUNT_TYPE_PROJECT) {
              permittedAccountIds.add(caller.getId());
          } else {
              DomainVO domain = _domainDao.findById(caller.getDomainId());
@@@ -1038,11 -1033,10 +1035,10 @@@
      }
  
      @Override
-     public Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>>
-     listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) {
+     public Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) {
          // access check - only root admin can migrate VM
          Account caller = CallContext.current().getCallingAccount();
 -        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
 +        if (!_accountMgr.isRootAdmin(caller.getId())) {
              if (s_logger.isDebugEnabled()) {
                  s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
              }
@@@ -1173,13 -1160,11 +1162,11 @@@
              }
          }
  
-         for (HostAllocator allocator : _hostAllocators) {
+         for (HostAllocator allocator : hostAllocators) {
 -            if (canMigrateWithStorage) {
 +            if  (canMigrateWithStorage) {
-                 suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, allHosts,
-                         HostAllocator.RETURN_UPTO_ALL, false);
+                 suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, allHosts, HostAllocator.RETURN_UPTO_ALL, false);
              } else {
-                 suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes,
-                         HostAllocator.RETURN_UPTO_ALL, false);
+                 suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, HostAllocator.RETURN_UPTO_ALL, false);
              }
  
              if (suitableHosts != null && !suitableHosts.isEmpty()) {
@@@ -1698,11 -1656,30 +1658,30 @@@
          // hidden configurations are not displayed using the search API
          sc.addAnd("category", SearchCriteria.Op.NEQ, "Hidden");
  
+         if (scope != null && !scope.isEmpty()) {
+             // getting the list of parameters at requested scope
+             if (id == null) {
+                 throw new InvalidParameterValueException("Invalid id null, id is needed corresponding to the scope");
+             }
+             sc.addAnd("scope", SearchCriteria.Op.EQ, scope);
+         }
+ 
          Pair<List<ConfigurationVO>, Integer> result = _configDao.searchAndCount(sc, searchFilter);
-         return new Pair<List<? extends Configuration>, Integer>(result.first(), result.second());
+ 
+         if (scope != null && !scope.isEmpty()) {
+             // Populate values corresponding the resource id
+             List<ConfigurationVO> configVOList = new ArrayList<ConfigurationVO>();
+             for (ConfigurationVO param : result.first()) {
+                 ConfigurationVO configVo = _configDao.findByName(param.getName());
+                 configVo.setValue(_configDepot.get(param.getName()).valueIn(id).toString());
+                 configVOList.add(configVo);
 -            }
 +    }
  
+             return new Pair<List<? extends Configuration>, Integer>(configVOList, configVOList.size());
+         }
  
+         return new Pair<List<? extends Configuration>, Integer>(result.first(), result.second());
+     }
  
      /* TODO: this method should go away. Keep here just in case that our latest refactoring using template_store_ref missed anything
       * in handling Swift or S3.
@@@ -3684,24 -3548,23 +3552,23 @@@
              Transaction.execute(new TransactionCallbackNoReturn() {
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
 -                    for (HostVO h : hosts) {
 -                        if (s_logger.isDebugEnabled()) {
 -                            s_logger.debug("Changing password for host name = " + h.getName());
 -                        }
 -                        // update password for this host
 -                        DetailVO nv = _detailsDao.findDetail(h.getId(), ApiConstants.USERNAME);
 -                        if (nv.getValue().equals(cmd.getUsername())) {
 -                            DetailVO nvp = _detailsDao.findDetail(h.getId(), ApiConstants.PASSWORD);
 -                            nvp.setValue(DBEncryptionUtil.encrypt(cmd.getPassword()));
 -                            _detailsDao.persist(nvp);
 -                        } else {
 -                            // if one host in the cluster has diff username then
 -                            // rollback to maintain consistency
 +                for (HostVO h : hosts) {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Changing password for host name = " + h.getName());
 +                    }
 +                    // update password for this host
 +                    DetailVO nv = _detailsDao.findDetail(h.getId(), ApiConstants.USERNAME);
 +                    if (nv.getValue().equals(cmd.getUsername())) {
 +                        DetailVO nvp = _detailsDao.findDetail(h.getId(), ApiConstants.PASSWORD);
 +                        nvp.setValue(DBEncryptionUtil.encrypt(cmd.getPassword()));
 +                        _detailsDao.persist(nvp);
 +                    } else {
 +                        // if one host in the cluster has diff username then
 +                        // rollback to maintain consistency
-                         throw new InvalidParameterValueException(
-                                 "The username is not same for all hosts, please modify passwords for individual hosts.");
+                             throw new InvalidParameterValueException("The username is not same for all hosts, please modify passwords for individual hosts.");
 -                        }
                      }
                  }
 +            }
              });
          }
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/servlet/ConsoleProxyServlet.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/servlet/ConsoleProxyServlet.java
index 4756830,e0deaa2..f39dcb5
--- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java
+++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java
@@@ -466,39 -477,37 +477,38 @@@ public class ConsoleProxyServlet extend
          }
  
          // root admin can access anything
 -        if (accountObj.getType() == Account.ACCOUNT_TYPE_ADMIN)
 +        if (_accountMgr.isRootAdmin(accountObj.getId()))
              return true;
  
-         switch(vm.getType())
-         {
-         case User :
+         switch (vm.getType()) {
+             case User:
 -                try {
 -                    _accountMgr.checkAccess(accountObj, null, true, vm);
 -                } catch (PermissionDeniedException ex) {
 -                    if (accountObj.getType() == Account.ACCOUNT_TYPE_NORMAL) {
 -                        if (s_logger.isDebugEnabled()) {
 +            try {
 +                _accountMgr.checkAccess(accountObj, null, true, vm);
 +            } catch (PermissionDeniedException ex) {
 +                if (_accountMgr.isNormalUser(accountObj.getId())) {
 +                    if (s_logger.isDebugEnabled()) {
-                         s_logger.debug("VM access is denied. VM owner account " + vm.getAccountId()
-                                 + " does not match the account id in session " + accountObj.getId() + " and caller is a normal user");
+                             s_logger.debug("VM access is denied. VM owner account " + vm.getAccountId() + " does not match the account id in session " +
+                                 accountObj.getId() + " and caller is a normal user");
 -                        }
 -                    } else if (accountObj.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || accountObj.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN) {
 -                        if (s_logger.isDebugEnabled()) {
 -                            s_logger.debug("VM access is denied. VM owner account " + vm.getAccountId() + " does not match the account id in session " +
 -                                accountObj.getId() + " and the domain-admin caller does not manage the target domain");
 -                        }
                      }
 -                    return false;
 +                } else if (_accountMgr.isDomainAdmin(accountObj.getId())
 +                        || accountObj.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN) {
 +                    if(s_logger.isDebugEnabled()) {
 +                        s_logger.debug("VM access is denied. VM owner account " + vm.getAccountId()
 +                                + " does not match the account id in session " + accountObj.getId() + " and the domain-admin caller does not manage the target domain");
 +                    }
                  }
 -                break;
 +                return false;
 +            }
 +            break;
  
 -            case DomainRouter:
 +        case DomainRouter:
-         case ConsoleProxy :
+             case ConsoleProxy:
 -            case SecondaryStorageVm:
 -                return false;
 +        case SecondaryStorageVm:
 +            return false;
  
-         default :
+             default:
 -                s_logger.warn("Unrecoginized virtual machine type, deny access by default. type: " + vm.getType());
 -                return false;
 +            s_logger.warn("Unrecoginized virtual machine type, deny access by default. type: " + vm.getType());
 +            return false;
          }
  
          return true;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/storage/StorageManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/storage/VolumeApiServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/VolumeApiServiceImpl.java
index 80d358f,ac0c438..d80f238
--- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java
+++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java
@@@ -387,11 -414,13 +414,13 @@@ public class VolumeApiServiceImpl exten
          }
  
          if ((format.equalsIgnoreCase("vhd") && (!url.toLowerCase().endsWith(".vhd") && !url.toLowerCase().endsWith("vhd.zip") && !url.toLowerCase().endsWith("vhd.bz2") && !url
-                 .toLowerCase().endsWith("vhd.gz"))) ||
-             (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip") && !url.toLowerCase().endsWith("qcow2.bz2") && !url
-                     .toLowerCase().endsWith("qcow2.gz"))) ||
-             (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url
+                 .toLowerCase().endsWith("vhd.gz")))
+                 || (format.equalsIgnoreCase("vhdx") && (!url.toLowerCase().endsWith(".vhdx") && !url.toLowerCase().endsWith("vhdx.zip") && !url.toLowerCase().endsWith("vhdx.bz2") && !url
+                         .toLowerCase().endsWith("vhdx.gz")))
+                 || (format.equalsIgnoreCase("qcow2") && (!url.toLowerCase().endsWith(".qcow2") && !url.toLowerCase().endsWith("qcow2.zip")
+                         && !url.toLowerCase().endsWith("qcow2.bz2") && !url.toLowerCase().endsWith("qcow2.gz")))
+                 || (format.equalsIgnoreCase("ova") && (!url.toLowerCase().endsWith(".ova") && !url.toLowerCase().endsWith("ova.zip") && !url.toLowerCase().endsWith("ova.bz2") && !url
 -                        .toLowerCase().endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) {
 +                    .toLowerCase().endsWith("ova.gz"))) || (format.equalsIgnoreCase("raw") && (!url.toLowerCase().endsWith(".img") && !url.toLowerCase().endsWith("raw")))) {
              throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase());
          }
          UriUtils.validateUrl(url);
@@@ -562,7 -602,10 +602,10 @@@
  
              diskOfferingId = snapshotCheck.getDiskOfferingId();
              diskOffering = _diskOfferingDao.findById(diskOfferingId);
+             if (zoneId == null) {
+                 // if zoneId is not provided, we default to create volume in the same zone as the snapshot zone.
 -                zoneId = snapshotCheck.getDataCenterId();
 +            zoneId = snapshotCheck.getDataCenterId();
+             }
              size = snapshotCheck.getSize(); // ; disk offering is used for tags
              // purposes
  
@@@ -615,42 -669,43 +669,43 @@@
          return Transaction.execute(new TransactionCallback<VolumeVO>() {
              @Override
              public VolumeVO doInTransaction(TransactionStatus status) {
 -                VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
 -                volume.setPoolId(null);
 +        VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
 +        volume.setPoolId(null);
+                 volume.setUuid(uuid);
 -                volume.setDataCenterId(zoneId);
 -                volume.setPodId(null);
 -                volume.setAccountId(ownerId);
 -                volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId()));
 -                volume.setDiskOfferingId(diskOfferingId);
 -                volume.setSize(size);
 -                volume.setMinIops(minIops);
 -                volume.setMaxIops(maxIops);
 -                volume.setInstanceId(null);
 -                volume.setUpdated(new Date());
 -                volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId());
 -                volume.setDisplayVolume(displayVolumeEnabled);
 -                if (parentVolume != null) {
 -                    volume.setTemplateId(parentVolume.getTemplateId());
 -                    volume.setFormat(parentVolume.getFormat());
 -                } else {
 -                    volume.setTemplateId(null);
 -                }
 +        volume.setDataCenterId(zoneId);
 +        volume.setPodId(null);
 +        volume.setAccountId(ownerId);
 +        volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId()));
 +        volume.setDiskOfferingId(diskOfferingId);
 +        volume.setSize(size);
 +        volume.setMinIops(minIops);
 +        volume.setMaxIops(maxIops);
 +        volume.setInstanceId(null);
 +        volume.setUpdated(new Date());
 +        volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId());
 +        volume.setDisplayVolume(displayVolumeEnabled);
 +        if (parentVolume != null) {
 +            volume.setTemplateId(parentVolume.getTemplateId());
 +            volume.setFormat(parentVolume.getFormat());
 +        } else {
 +            volume.setTemplateId(null);
 +        }
  
 -                volume = _volsDao.persist(volume);
 -                if (cmd.getSnapshotId() == null) {
 -                    // for volume created from snapshot, create usage event after volume creation
 +        volume = _volsDao.persist(volume);
 +        if (cmd.getSnapshotId() == null) {
 +            // for volume created from snapshot, create usage event after volume creation
-             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId,
-                     null, size, Volume.class.getName(), volume.getUuid());
+                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
+                             diskOfferingId, null, size, Volume.class.getName(), volume.getUuid());
 -                }
 +        }
  
 -                CallContext.current().setEventDetails("Volume Id: " + volume.getId());
 +        CallContext.current().setEventDetails("Volume Id: " + volume.getId());
  
 -                // Increment resource count during allocation; if actual creation fails,
 -                // decrement it
 +        // Increment resource count during allocation; if actual creation fails,
 +        // decrement it
-         _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
-         _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
+                 _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume, displayVolumeEnabled);
+                 _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, displayVolumeEnabled, new Long(volume.getSize()));
 -                return volume;
 -            }
 +        return volume;
 +    }
          });
      }
  
@@@ -820,9 -902,47 +902,47 @@@
  
          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));
+             _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize
+                     - currentSize));
          }
  
+         if (userVm != null) {
+             // serialize VM operation
+             AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
+             if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
+                 // avoid re-entrance
+                 return orchestrateResizeVolume(volume.getId(), currentSize, newSize,
+                         newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
+             } else {
+                 Outcome<Volume> outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize,
+                         newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
+ 
+                 Volume vol = null;
+                 try {
+                     vol = outcome.get();
+                 } catch (InterruptedException e) {
+                     throw new RuntimeException("Operation is interrupted", e);
+                 } catch (java.util.concurrent.ExecutionException e) {
+                     throw new RuntimeException("Execution excetion", e);
+                 }
+ 
+                 Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+                 if (jobResult != null) {
+                     if (jobResult instanceof ConcurrentOperationException)
+                         throw (ConcurrentOperationException)jobResult;
+                     else if (jobResult instanceof Throwable)
+                         throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
+                 }
+                 return volume;
+             }
+         }
+         return orchestrateResizeVolume(volume.getId(), currentSize, newSize,
+                 newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
 -    }
++        }
+ 
+     private VolumeVO orchestrateResizeVolume(long volumeId, long currentSize, long newSize, Long newDiskOfferingId, boolean shrinkOk) {
+         VolumeVO volume = _volsDao.findById(volumeId);
+         UserVmVO userVm = _userVmDao.findById(volume.getInstanceId());
          /*
           * 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.
@@@ -1073,9 -1223,8 +1223,8 @@@
          // managed storage can be used for different types of hypervisors
          // only perform this check if the volume's storage pool is not null and not managed
          if (dataDiskStoragePool != null && !dataDiskStoragePool.isManaged()) {
 -            if (dataDiskHyperType != HypervisorType.None && rootDiskHyperType != dataDiskHyperType) {
 +        if (dataDiskHyperType != HypervisorType.None && rootDiskHyperType != dataDiskHyperType) {
-                 throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType +
-                     " to a " + rootDiskHyperType + " vm");
+                 throw new InvalidParameterValueException("Can't attach a volume created by: " + dataDiskHyperType + " to a " + rootDiskHyperType + " vm");
              }
          }
  
@@@ -1383,8 -1641,66 +1641,66 @@@
      }
  
      @Override
-     public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account) throws ResourceAllocationException {
+     public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm) throws ResourceAllocationException {
+ 
+         VolumeInfo volume = volFactory.getVolume(volumeId);
+         if (volume == null) {
+             throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
+         }
+ 
+         if (volume.getState() != Volume.State.Ready) {
+             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
+         }
+ 
+         VMInstanceVO vm = null;
+         if (volume.getInstanceId() != null)
+             vm = _vmInstanceDao.findById(volume.getInstanceId());
+ 
+         if (vm != null) {
+             // serialize VM operation
+             AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
+             if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
+                 // avoid re-entrance
+                 return orchestrateTakeVolumeSnapshot(volumeId, policyId, snapshotId, account, quiescevm);
+             } else {
+                 Outcome<Snapshot> outcome = takeVolumeSnapshotThroughJobQueue(vm.getId(), volumeId, policyId, snapshotId, account.getId(), quiescevm);
+ 
+                 try {
+                     outcome.get();
+                 } catch (InterruptedException e) {
+                     throw new RuntimeException("Operation is interrupted", e);
+                 } catch (java.util.concurrent.ExecutionException e) {
+                     throw new RuntimeException("Execution excetion", e);
+                 }
+ 
+                 Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
+                 if (jobResult != null) {
+                     if (jobResult instanceof ConcurrentOperationException)
+                         throw (ConcurrentOperationException)jobResult;
+                     else if (jobResult instanceof ResourceAllocationException)
+                         throw (ResourceAllocationException)jobResult;
+                     else if (jobResult instanceof Throwable)
+                         throw new RuntimeException("Unexpected exception", (Throwable)jobResult);
+                 }
+ 
+                 return _snapshotDao.findById(snapshotId);
+             }
+         } else {
 -            CreateSnapshotPayload payload = new CreateSnapshotPayload();
 -            payload.setSnapshotId(snapshotId);
 -            payload.setSnapshotPolicyId(policyId);
 -            payload.setAccount(account);
++        CreateSnapshotPayload payload = new CreateSnapshotPayload();
++        payload.setSnapshotId(snapshotId);
++        payload.setSnapshotPolicyId(policyId);
++        payload.setAccount(account);
+             payload.setQuiescevm(quiescevm);
+             volume.addPayload(payload);
+             return volService.takeSnapshot(volume);
+         }
+     }
+ 
+     private Snapshot orchestrateTakeVolumeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account, boolean quiescevm)
+             throws ResourceAllocationException {
+ 
          VolumeInfo volume = volFactory.getVolume(volumeId);
+ 
          if (volume == null) {
              throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
          }
@@@ -1595,9 -1914,9 +1914,9 @@@
                  }
                  if (storeForDataStoreScope.getScopeId().equals(vmClusterId)) {
                      return false;
 -                }
 +            }
-             } else if (storeForDataStoreScope.getScopeType() == ScopeType.HOST &&
-                     (storeForRootStoreScope.getScopeType() == ScopeType.CLUSTER || storeForRootStoreScope.getScopeType() == ScopeType.ZONE)) {
+             } else if (storeForDataStoreScope.getScopeType() == ScopeType.HOST
+                     && (storeForRootStoreScope.getScopeType() == ScopeType.CLUSTER || storeForRootStoreScope.getScopeType() == ScopeType.ZONE)) {
                  Long hostId = _vmInstanceDao.findById(rootVolumeOfVm.getInstanceId()).getHostId();
                  if (storeForDataStoreScope.getScopeId().equals(hostId)) {
                      return false;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
index f3d7997,a9eae7d..baf36bd
--- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
@@@ -337,24 -334,24 +334,24 @@@ public class SnapshotManagerImpl extend
  
      @Override
      public Snapshot backupSnapshot(Long snapshotId) {
-     	 SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
-     	 if (snapshot != null) {
-     		 throw new CloudRuntimeException("Already in the backup snapshot:" + snapshotId);
-     	 }
+         SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
+         if (snapshot != null) {
+             throw new CloudRuntimeException("Already in the backup snapshot:" + snapshotId);
+         }
  
 -        return snapshotSrv.backupSnapshot(snapshot);
 +         return snapshotSrv.backupSnapshot(snapshot);
      }
  
      @Override
      public SnapshotVO getParentSnapshot(VolumeInfo volume) {
-     	 long preId = _snapshotDao.getLastSnapshot(volume.getId(), DataStoreRole.Primary);
+         long preId = _snapshotDao.getLastSnapshot(volume.getId(), DataStoreRole.Primary);
  
 -        SnapshotVO preSnapshotVO = null;
 -        if (preId != 0 && !(volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId()))) {
 -            preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preId);
 -        }
 +         SnapshotVO preSnapshotVO = null;
 +         if (preId != 0 && !(volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId()))) {
 +             preSnapshotVO = _snapshotDao.findByIdIncludingRemoved(preId);
 +         }
  
 -        return preSnapshotVO;
 +         return preSnapshotVO;
      }
  
      private Long getSnapshotUserId() {
@@@ -395,11 -392,12 +392,12 @@@
              SnapshotVO oldestSnapshot = snaps.get(0);
              long oldSnapId = oldestSnapshot.getId();
              if (policy != null) {
 -                s_logger.debug("Max snaps: " + policy.getMaxSnaps() + " exceeded for snapshot policy with Id: " + policyId + ". Deleting oldest snapshot: " + oldSnapId);
 +            s_logger.debug("Max snaps: " + policy.getMaxSnaps() + " exceeded for snapshot policy with Id: " + policyId + ". Deleting oldest snapshot: " + oldSnapId);
              }
-             if(deleteSnapshot(oldSnapId)){
-             	//log Snapshot delete event
-                 ActionEventUtils.onCompletedActionEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE, "Successfully deleted oldest snapshot: " + oldSnapId, 0);
+             if (deleteSnapshot(oldSnapId)) {
+                 //log Snapshot delete event
+                 ActionEventUtils.onCompletedActionEvent(User.UID_SYSTEM, oldestSnapshot.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_SNAPSHOT_DELETE,
+                     "Successfully deleted oldest snapshot: " + oldSnapId, 0);
              }
              snaps.remove(oldestSnapshot);
          }
@@@ -420,26 -418,27 +418,27 @@@
          _accountMgr.checkAccess(caller, null, true, snapshotCheck);
          SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshotCheck, SnapshotOperation.DELETE);
          if (snapshotStrategy == null) {
-             s_logger.error("Unable to find snaphot strategy to handle snapshot with id '"+snapshotId+"'");
+             s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
              return false;
          }
+         SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image);
  
          try {
-         	boolean result = snapshotStrategy.deleteSnapshot(snapshotId);
-         	if (result) {
+             boolean result = snapshotStrategy.deleteSnapshot(snapshotId);
+             if (result) {
                  if (snapshotCheck.getState() == Snapshot.State.BackedUp) {
-         			UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_DELETE, snapshotCheck.getAccountId(),
-         					snapshotCheck.getDataCenterId(), snapshotId, snapshotCheck.getName(), null, null, 0L,
-         					snapshotCheck.getClass().getName(), snapshotCheck.getUuid());
-         		}
+                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_DELETE, snapshotCheck.getAccountId(), snapshotCheck.getDataCenterId(), snapshotId,
+                         snapshotCheck.getName(), null, null, 0L, snapshotCheck.getClass().getName(), snapshotCheck.getUuid());
+                 }
+                 if (snapshotCheck.getState() != Snapshot.State.Error && snapshotCheck.getState() != Snapshot.State.Destroyed)
 -                    _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;
+                 if (snapshotCheck.getState() == Snapshot.State.BackedUp)
+                     _resourceLimitMgr.decrementResourceCount(snapshotCheck.getAccountId(), ResourceType.secondary_storage, new Long(snapshotStoreRef.getSize()));
+             }
+             return result;
          } catch (Exception e) {
-         	s_logger.debug("Failed to delete snapshot: " + snapshotCheck.getId() + ":" + e.toString());
-         	throw new CloudRuntimeException("Failed to delete snapshot:" + e.toString());
+             s_logger.debug("Failed to delete snapshot: " + snapshotCheck.getId() + ":" + e.toString());
+             throw new CloudRuntimeException("Failed to delete snapshot:" + e.toString());
          }
      }
  
@@@ -653,12 -649,13 +651,13 @@@
          _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
  
          if (volume.getState() != Volume.State.Ready) {
-             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
+             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() +
+                 ". Cannot take snapshot.");
          }
  
-         if (volume.getTemplateId() != null ) {
+         if (volume.getTemplateId() != null) {
 -            VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
 +            VMTemplateVO  template = _templateDao.findById(volume.getTemplateId());
-             if( template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM ) {
+             if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
                  throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
              }
          }
@@@ -702,11 -699,11 +701,11 @@@
          long accountLimit = _resourceLimitMgr.findCorrectResourceLimitForAccount(owner, ResourceType.snapshot);
          long domainLimit = _resourceLimitMgr.findCorrectResourceLimitForDomain(_domainMgr.getDomain(owner.getDomainId()), ResourceType.snapshot);
          int max = cmd.getMaxSnaps().intValue();
 -        if (owner.getType() != Account.ACCOUNT_TYPE_ADMIN && ((accountLimit != -1 && max > accountLimit) || (domainLimit != -1 && max > domainLimit))) {
 +        if (!_accountMgr.isRootAdmin(owner.getId())&& ((accountLimit != -1 && max > accountLimit) || (domainLimit != -1 && max > domainLimit))) {
-         	String message = "domain/account";
-         	if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
-         		message = "domain/project";
-         	}
+             String message = "domain/account";
+             if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
+                 message = "domain/project";
+             }
  
              throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit");
          }
@@@ -954,12 -947,13 +949,13 @@@
              snapshotStrategy.takeSnapshot(snapshot);
  
              try {
 -                postCreateSnapshot(volume.getId(), snapshotId, payload.getSnapshotPolicyId());
 +            postCreateSnapshot(volume.getId(), snapshotId, payload.getSnapshotPolicyId());
  
-             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(),
-                     snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null,
-                     volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
-             _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
+                 UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(), snapshot.getDataCenterId(), snapshotId, snapshot.getName(),
+                     null, null, volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
+                 SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image);
+                 // Correct the resource count of snapshot in case of delta snapshots.
+                 _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize() - snapshotStoreRef.getSize()));
              } catch (Exception e) {
                  s_logger.debug("post process snapshot failed", e);
              }
@@@ -1075,19 -1063,16 +1065,16 @@@
          Type snapshotType = getSnapshotType(policyId);
          Account owner = _accountMgr.getAccount(volume.getAccountId());
  
-         try{
+         try {
              _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
-             if (backup) {
 -            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize()));
 +                _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){
+             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");
+                 _alertMgr.sendAlert(AlertManager.AlertType.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;
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/tags/TaggedResourceManagerImpl.java
index 83e108d,be896f0..1982af7
--- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
+++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
@@@ -176,61 -147,32 +147,32 @@@ public class TaggedResourceManagerImpl 
  
      @Override
      public long getResourceId(String resourceId, ResourceObjectType resourceType) {
-         GenericDao<?, Long> dao = _daoMap.get(resourceType);
-         if (dao == null) {
-             throw new CloudRuntimeException("Dao is not loaded for the resource type " + resourceType);
+         Class<?> clazz = s_typeMap.get(resourceType);
+         Object entity = _entityMgr.findByUuid(clazz, resourceId);
+         if (entity != null) {
+             return ((InternalIdentity)entity).getId();
          }
-         Class<?> claz = DbUtil.getEntityBeanType(dao);
-         
-         Long identityId = null;
-         
-         while (claz != null && claz != Object.class) {
-             try {
-                 String tableName = DbUtil.getTableName(claz);
-                 if (tableName == null) {
-                     throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database");
-                 }
-                 identityId = _identityDao.getIdentityId(tableName, resourceId);
-                 if (identityId != null) {
-                     break;
+         entity = _entityMgr.findById(clazz, resourceId);
+         if (entity != null) {
+             return ((InternalIdentity)entity).getId();
 +                }
-             } catch (Exception ex) {
-                 //do nothing here, it might mean uuid field is missing and we have to search further
-             }
-             claz = claz.getSuperclass();
-         }
-        
-         if (identityId == null) {
 +            throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType);
          }
-         return identityId;
-     }
-     
-     
 -        throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + " and type " + resourceType);
 -    }
+ 
      private Pair<Long, Long> getAccountDomain(long resourceId, ResourceObjectType resourceType) {
-        
-         Pair<Long, Long> pair = null;
-         GenericDao<?, Long> dao = _daoMap.get(resourceType);
-         Class<?> claz = DbUtil.getEntityBeanType(dao);
-         while (claz != null && claz != Object.class) {
-             try {
-                 String tableName = DbUtil.getTableName(claz);
-                 if (tableName == null) {
-                     throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database");
-                 }
-                 pair = _identityDao.getAccountDomainInfo(tableName, resourceId, resourceType);
-                 if (pair.first() != null || pair.second() != null) {
-                     break;
-                 }
-             } catch (Exception ex) {
-                 //do nothing here, it might mean uuid field is missing and we have to search further
-             }
-             claz = claz.getSuperclass();
+         Class<?> clazz = s_typeMap.get(resourceType);
+ 
+         Object entity = _entityMgr.findById(clazz, resourceId);
+         Long accountId = null;
+         Long domainId = null;
+         if (entity instanceof OwnedBy) {
+             accountId = ((OwnedBy)entity).getAccountId();
+         }
+ 
+         if (entity instanceof PartOf) {
+             domainId = ((PartOf)entity).getDomainId();
          }
  
-         Long accountId = pair.first();
-         Long domainId = pair.second();
-         
          if (accountId == null) {
              accountId = Account.ACCOUNT_ID_SYSTEM;
          }
@@@ -267,13 -208,13 +208,13 @@@
              public void doInTransactionWithoutResult(TransactionStatus status) {
                  for (String key : tags.keySet()) {
                      for (String resourceId : resourceIds) {
 -                        if (!resourceType.resourceTagsSupport()) {
 +                        if (!resourceType.resourceTagsSupport())  {
                              throw new InvalidParameterValueException("The resource type " + resourceType + " doesn't support resource tags");
                          }
-                         
+ 
                          long id = getResourceId(resourceId, resourceType);
                          String resourceUuid = getUuid(resourceId, resourceType);
-                         
+ 
                          Pair<Long, Long> accountDomainPair = getAccountDomain(id, resourceType);
                          Long domainId = accountDomainPair.second();
                          Long accountId = accountDomainPair.first();
@@@ -308,35 -246,16 +246,16 @@@
  
      @Override
      public String getUuid(String resourceId, ResourceObjectType resourceType) {
-         GenericDao<?, Long> dao = _daoMap.get(resourceType);
-         Class<?> claz = DbUtil.getEntityBeanType(dao);
- 
-        String identiyUUId = null;
- 
-        while (claz != null && claz != Object.class) {
-            try {
-                String tableName = DbUtil.getTableName(claz);
-                if (tableName == null) {
-                    throw new InvalidParameterValueException("Unable to find resource of type " + resourceType + " in the database");
-                }
- 
-                claz = claz.getSuperclass();
-                if (claz == Object.class) {
-                    identiyUUId = _identityDao.getIdentityUuid(tableName, resourceId);
-                }
-            } catch (Exception ex) {
-                //do nothing here, it might mean uuid field is missing and we have to search further
-            }
+         Class<?> clazz = s_typeMap.get(resourceType);
+ 
+         Object entity = _entityMgr.findById(clazz, resourceId);
+         if (entity != null && entity instanceof Identity) {
+             return ((Identity)entity).getUuid();
 -        }
 +       }
  
-        if (identiyUUId == null) {
 -        return resourceId;
 -    }
 +           return resourceId;
 +       }
  
-        return identiyUUId;
-     }
- 
      @Override
      @DB
      @ActionEvent(eventType = EventTypes.EVENT_TAGS_DELETE, eventDescription = "deleting resource tags")

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/template/TemplateAdapterBase.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/template/TemplateAdapterBase.java
index 18fbbe7,59aab3b..d111a5d
--- a/server/src/com/cloud/template/TemplateAdapterBase.java
+++ b/server/src/com/cloud/template/TemplateAdapterBase.java
@@@ -98,13 -116,17 +116,12 @@@ public abstract class TemplateAdapterBa
          return true;
      }
  
 -    private static boolean isAdmin(short accountType) {
 -        return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) ||
 -            (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
 -    }
 -
      @Override
-     public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits,
-             Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured,
-             Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
-             String accountName, Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException {
-         return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType,
-                 chksum, bootable, null, null, details, false, null, false, TemplateType.USER);
+     public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHVM, String url,
+         Boolean isPublic, Boolean featured, Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType, String accountName,
+         Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException {
+         return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId,
+             hypervisorType, chksum, bootable, null, null, details, false, null, false, TemplateType.USER);
      }
  
      @Override
@@@ -303,12 -320,10 +315,10 @@@
          return _tmpltDao.findById(template.getId());
      }
  
- 
-     private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg)
-             throws PermissionDeniedException {
+     private Long accountAndUserValidation(Account account, long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) throws PermissionDeniedException {
  
          if (account != null) {
 -            if (!isAdmin(account.getType())) {
 +            if (!_accountMgr.isAdmin(account.getType())) {
                  if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) {
                      throw new PermissionDeniedException(msg + ". Permission denied.");
                  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/template/TemplateManagerImpl.java
index 2fc0c66,ac641a2..55443fd
--- a/server/src/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/com/cloud/template/TemplateManagerImpl.java
@@@ -796,29 -802,28 +802,28 @@@ public class TemplateManagerImpl extend
          }
  
          try {
-         StoragePool pool = (StoragePool) _dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
+             StoragePool pool = (StoragePool)_dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
 -            VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
 +        VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
  
 -            if (s_logger.isDebugEnabled()) {
 -                s_logger.debug("Evicting " + templatePoolVO);
 -            }
 -            DestroyCommand cmd = new DestroyCommand(pool, templatePoolVO);
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Evicting " + templatePoolVO);
 +        }
 +        DestroyCommand cmd = new DestroyCommand(pool, templatePoolVO);
  
 -            try {
 -                Answer answer = _storageMgr.sendToPool(pool, cmd);
 +        try {
 +            Answer answer = _storageMgr.sendToPool(pool, cmd);
  
 -                if (answer != null && answer.getResult()) {
 -                    // Remove the templatePoolVO
 -                    if (_tmpltPoolDao.remove(templatePoolVO.getId())) {
 -                        s_logger.debug("Successfully evicted template: " + template.getName() + " from storage pool: " + pool.getName());
 -                    }
 -                } else {
 -                    s_logger.info("Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
 +            if (answer != null && answer.getResult()) {
 +                // Remove the templatePoolVO
 +                if (_tmpltPoolDao.remove(templatePoolVO.getId())) {
 +                    s_logger.debug("Successfully evicted template: " + template.getName() + " from storage pool: " + pool.getName());
                  }
 -            } catch (StorageUnavailableException e) {
 -                s_logger.info("Storage is unavailable currently.  Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
 +            } else {
 +                s_logger.info("Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
              }
 +        } catch (StorageUnavailableException e) {
-             s_logger.info("Storage is unavailable currently.  Will retry evicte template: " + template.getName() + " from storage pool: "
-                     + pool.getName());
++                s_logger.info("Storage is unavailable currently.  Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
 +        }
          } finally {
              _tmpltPoolDao.releaseFromLockTable(templatePoolRef.getId());
          }
@@@ -1274,18 -1276,14 +1276,14 @@@
              updatedTemplate.setFeatured(isFeatured.booleanValue());
          }
  
-         if (isExtractable != null && _accountMgr.isRootAdmin(caller.getId())) {// Only
-             // ROOT
-             // admins
-             // allowed
-             // to
-             // change
-             // this
-             // powerful
-             // attribute
-             updatedTemplate.setExtractable(isExtractable.booleanValue());
-         } else if (isExtractable != null && !_accountMgr.isRootAdmin(caller.getId())) {
-             throw new InvalidParameterValueException("Only ROOT admins are allowed to modify this attribute.");
+         if (isExtractable != null) {
+             // Only Root admins allowed to change it for templates
 -            if (!template.getFormat().equals(ImageFormat.ISO) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
 -                throw new InvalidParameterValueException("Only ROOT admins are allowed to modify this attribute.");
++            if (!template.getFormat().equals(ImageFormat.ISO) && _accountMgr.isRootAdmin(caller.getId())) {
++             throw new InvalidParameterValueException("Only ROOT admins are allowed to modify this attribute.");
+             } else {
+                 // For Isos normal user can change it, as their are no derivatives.
+                 updatedTemplate.setExtractable(isExtractable.booleanValue());
+             }
          }
  
          _tmpltDao.update(template.getId(), updatedTemplate);
@@@ -1304,22 -1302,22 +1302,22 @@@
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
                      for (String accountName : accountNamesFinal) {
 -                        Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
 -                        if (permittedAccount != null) {
 -                            if (permittedAccount.getId() == caller.getId()) {
 -                                continue; // don't grant permission to the template
 -                                // owner, they implicitly have permission
 -                            }
 -                            LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
 -                            if (existingPermission == null) {
 -                                LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
 -                                _launchPermissionDao.persist(launchPermission);
 -                            }
 -                        } else {
 +                Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
 +                if (permittedAccount != null) {
 +                    if (permittedAccount.getId() == caller.getId()) {
 +                        continue; // don't grant permission to the template
 +                        // owner, they implicitly have permission
 +                    }
 +                    LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
 +                    if (existingPermission == null) {
 +                        LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
 +                        _launchPermissionDao.persist(launchPermission);
 +                    }
 +                } else {
-                     throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" + domain.getUuid()
-                             + ", account not found.  " + "No permissions updated, please verify the account names and retry.");
+                             throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" +
+                                 domain.getUuid() + ", account not found.  " + "No permissions updated, please verify the account names and retry.");
 -                        }
 -                    }
 +                }
 +            }
                  }
              });
          } else if ("remove".equalsIgnoreCase(operation)) {
@@@ -1397,8 -1395,14 +1395,14 @@@
                      throw new CloudRuntimeException("Failed to create template" + result.getResult());
                  }
  
+                 // create entries in template_zone_ref table
+                 if (_dataStoreMgr.isRegionStore(store)) {
+                     // template created on region store
+                     _tmpltSvr.associateTemplateToZone(templateId, null);
+                 } else {
 -                    VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
 -                    _tmpltZoneDao.persist(templateZone);
 +                VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
 +                _tmpltZoneDao.persist(templateZone);
+                 }
  
                  privateTemplate = _tmpltDao.findById(templateId);
                  if (snapshotId != null) {
@@@ -1635,13 -1642,23 +1637,23 @@@
          VMTemplateVO template = _tmpltDao.persist(privateTemplate);
          // Increment the number of templates
          if (template != null) {
-             Map<String, String> detailsStr = cmd.getDetails();
-             if (detailsStr != null) {
-                 List<VMTemplateDetailVO> details = new ArrayList<VMTemplateDetailVO>();
-                 for (String key : detailsStr.keySet()) {
-                     details.add(new VMTemplateDetailVO(template.getId(), key, detailsStr.get(key)));
+             Map<String, String> details = new HashMap<String, String>();
+             if (volume != null) {
+                 Long vmId = volume.getInstanceId();
+                 if (vmId != null) {
+                     UserVmVO userVm = _userVmDao.findById(vmId);
+                     if (userVm != null) {
+                         _userVmDao.loadDetails(userVm);
+                         details.putAll(userVm.getDetails());
+                     }
+                 }
 -            }
 +                }
-                 _templateDetailsDao.saveDetails(details);
+             if (cmd.getDetails() != null) {
+                 details.putAll(cmd.getDetails());
+             }
+             if (!details.isEmpty()) {
+                 privateTemplate.setDetails(details);
+                 _tmpltDao.saveDetails(privateTemplate);
              }
  
              _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
@@@ -1694,11 -1721,15 +1716,15 @@@
  
      @Override
      public Long getTemplateSize(long templateId, long zoneId) {
-         TemplateDataStoreVO templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, zoneId,
+         TemplateDataStoreVO templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, zoneId, VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
+         if (templateStoreRef == null) {
+             // check if it is ready on image cache stores
+             templateStoreRef = _tmplStoreDao.findByTemplateZoneStagingDownloadStatus(templateId, zoneId,
 -                    VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
 -            if (templateStoreRef == null) {
 -                throw new CloudRuntimeException("Template " + templateId + " has not been completely downloaded to zone " + zoneId);
 -            }
 +                VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
 +        if (templateStoreRef == null) {
 +            throw new CloudRuntimeException("Template " + templateId + " has not been completely downloaded to zone " + zoneId);
 +        }
+         }
          return templateStoreRef.getSize();
  
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/usage/UsageServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/usage/UsageServiceImpl.java
index 226f721,aaf117d..d1f62aa
--- a/server/src/com/cloud/usage/UsageServiceImpl.java
+++ b/server/src/com/cloud/usage/UsageServiceImpl.java
@@@ -59,31 -59,35 +60,37 @@@ import com.cloud.utils.db.SearchCriteri
  import com.cloud.utils.db.TransactionLegacy;
  
  @Component
- @Local(value = { UsageService.class })
+ @Local(value = {UsageService.class})
  public class UsageServiceImpl extends ManagerBase implements UsageService, Manager {
      public static final Logger s_logger = Logger.getLogger(UsageServiceImpl.class);
-     
+ 
      //ToDo: Move implementation to ManagaerImpl
-     
-     @Inject private AccountDao _accountDao;
-     @Inject private DomainDao _domainDao;
-     @Inject private UsageDao _usageDao;
-     @Inject private UsageJobDao _usageJobDao;
-     @Inject private ConfigurationDao _configDao;
-     @Inject private ProjectManager _projectMgr;
+ 
+     @Inject
+     private AccountDao _accountDao;
+     @Inject
+     private DomainDao _domainDao;
+     @Inject
+     private UsageDao _usageDao;
+     @Inject
+     private UsageJobDao _usageJobDao;
+     @Inject
+     private ConfigurationDao _configDao;
+     @Inject
+     private ProjectManager _projectMgr;
      private TimeZone _usageTimezone;
 +    @Inject
 +    private AccountService _accountService;
  
      public UsageServiceImpl() {
      }
-     
+ 
      @Override
      public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-     	super.configure(name,  params);
+         super.configure(name, params);
          String timeZoneStr = _configDao.getValue(Config.UsageAggregationTimezone.toString());
          if (timeZoneStr == null) {
 -            timeZoneStr = "GMT";
 +           timeZoneStr = "GMT";
          }
          _usageTimezone = TimeZone.getTimeZone(timeZoneStr);
          return true;
@@@ -156,15 -160,15 +163,15 @@@
  
          boolean isAdmin = false;
          boolean isDomainAdmin = false;
-         
+ 
          //If accountId couldn't be found using accountName and domainId, get it from userContext
-         if(accountId == null){
+         if (accountId == null) {
              accountId = caller.getId();
-             //List records for all the accounts if the caller account is of type admin. 
+             //List records for all the accounts if the caller account is of type admin.
              //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
 -            if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) {
 +            if (_accountService.isRootAdmin(caller.getId())) {
                  isAdmin = true;
 -            } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
 +            } else if (_accountService.isDomainAdmin(caller.getId())) {
                  isDomainAdmin = true;
              }
              s_logger.debug("Account details not available. Using userContext accountId: " + accountId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/user/AccountManager.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/user/AccountManager.java
index 46829e7,1f191fc..03bf842
--- a/server/src/com/cloud/user/AccountManager.java
+++ b/server/src/com/cloud/user/AccountManager.java
@@@ -55,52 -56,49 +55,53 @@@ public interface AccountManager extend
       * @param userId
       */
      void logoutUser(long userId);
-     
+ 
      /**
--     * Authenticates a user when s/he logs in.
-      * 
-      * @param username
-      *            required username for authentication
-      * @param password
-      *            password to use for authentication, can be null for single sign-on case
-      * @param domainId
-      *            id of domain where user with username resides
-      * @param requestParameters
-      *            the request parameters of the login request, which should contain timestamp of when the request signature is
-      *            made, and the signature itself in the single sign-on case
-      * @return a user object, null if the user failed to authenticate
-      */
 -     *
 -     * @param username
 -     *            required username for authentication
 -     * @param password
 -     *            password to use for authentication, can be null for single sign-on case
 -     * @param domainId
 -     *            id of domain where user with username resides
 -     * @param requestParameters
 -     *            the request parameters of the login request, which should contain timestamp of when the request signature is
 -     *            made, and the signature itself in the single sign-on case
 -     * @return a user object, null if the user failed to authenticate
 -     */
++      * Authenticates a user when s/he logs in.
++      *
++      * @param username
++      *            required username for authentication
++      * @param password
++      *            password to use for authentication, can be null for single sign-on case
++      * @param domainId
++      *            id of domain where user with username resides
++      * @param requestParameters
++      *            the request parameters of the login request, which should contain timestamp of when the request signature is
++      *            made, and the signature itself in the single sign-on case
++      * @return a user object, null if the user failed to authenticate
++      */
      UserAccount authenticateUser(String username, String password, Long domainId, String loginIpAddress, Map<String, Object[]> requestParameters);
-     
+ 
      /**
       * Locate a user by their apiKey
-      * 
+      *
       * @param apiKey
       *            that was created for a particular user
       * @return the user/account pair if one exact match was found, null otherwise
       */
      Pair<User, Account> findUserByApiKey(String apiKey);
-     
- 	boolean enableAccount(long accountId);
  
- 	
+     boolean enableAccount(long accountId);
+ 
 -    void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria);
+ 
 -    void buildACLViewSearchBuilder(SearchBuilder<? extends ControlledViewEntity> sb, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria);
 +    // new ACL model routine for query api based on db views
 +    void buildACLSearchParameters(Account caller, Long id,
 +            String accountName, Long projectId, List<Long> permittedDomains, List<Long> permittedAccounts, List<Long> permittedResources,
 +            Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation, String action);
 +
 +    void buildACLSearchBuilder(SearchBuilder<? extends ControlledEntity> sb, boolean isRecursive,
 +            List<Long> permittedDomains,
 +            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);
  
 -    void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria);
 +    void buildACLSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, boolean isRecursive,
 +            List<Long> permittedDomains,
 +            List<Long> permittedAccounts, List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);
  
 -    void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledViewEntity> sc, Long domainId, boolean isRecursive, List<Long> permittedAccounts,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria);
 +    void buildACLViewSearchCriteria(SearchCriteria<? extends ControlledEntity> sc, SearchCriteria<? extends ControlledEntity> aclSc, boolean isRecursive,
 +            List<Long> permittedDomains, List<Long> permittedAccounts,
 +            List<Long> permittedResources, ListProjectResourcesCriteria listProjectResourcesCriteria);
  
 -    void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List<Long> permittedAccounts,
 -        Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation);
+ 
      /**
       * Deletes a user by userId
       *

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/user/AccountManagerImpl.java
index 62b496d,5204589..e02f339
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@@ -273,11 -264,11 +273,10 @@@ public class AccountManagerImpl extend
      AccountVO _systemAccount;
  
      List<SecurityChecker> _securityCheckers;
-     
- 	int _cleanupInterval;
 -
+     int _cleanupInterval;
  
      public List<UserAuthenticator> getUserAuthenticators() {
-     	return _userAuthenticators;
+         return _userAuthenticators;
      }
  
      public void setUserAuthenticators(List<UserAuthenticator> authenticators) {
@@@ -293,24 -284,16 +292,24 @@@
      }
  
      public List<SecurityChecker> getSecurityCheckers() {
- 		return _securityCheckers;
- 	}
+         return _securityCheckers;
+     }
+ 
+     public void setSecurityCheckers(List<SecurityChecker> securityCheckers) {
+         _securityCheckers = securityCheckers;
+     }
  
- 	public void setSecurityCheckers(List<SecurityChecker> securityCheckers) {
- 		_securityCheckers = securityCheckers;
- 	}
-     
 +    public List<QuerySelector> getQuerySelectors() {
 +        return _querySelectors;
 +    }
 +
 +    public void setQuerySelectors(List<QuerySelector> querySelectors) {
 +        _querySelectors = querySelectors;
 +    }
 +
      @Override
      public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
-         _systemAccount = _accountDao.findById(AccountVO.ACCOUNT_ID_SYSTEM);
+         _systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
          if (_systemAccount == null) {
              throw new ConfigurationException("Unable to find the system account using " + Account.ACCOUNT_ID_SYSTEM);
          }
@@@ -430,17 -379,25 +429,32 @@@
      }
  
      @Override
 -    public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) {
 +    public void checkAccess(Account account, AccessType accessType, boolean sameOwner, PartOf... entities) throws PermissionDeniedException {
 +        // TODO Auto-generated method stub
 +
 +        //TO BE IMPLEMENTED
 +
 +    }
  
 +    @Override
 +    public void checkAccess(Account caller, AccessType accessType, boolean sameOwner, ControlledEntity... entities) {
+         //check for the same owner
+         Long ownerId = null;
+         ControlledEntity prevEntity = null;
+         if (sameOwner) {
+             for (ControlledEntity entity : entities) {
+                 if (sameOwner) {
+                     if (ownerId == null) {
+                         ownerId = entity.getAccountId();
+                     } else if (ownerId.longValue() != entity.getAccountId()) {
+                         throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts");
+                     }
+                     prevEntity = entity;
+                 }
+             }
+         }
  
 -        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getType())) {
 +        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getId())) {
              // no need to make permission checks if the system/root admin makes the call
              if (s_logger.isTraceEnabled()) {
                  s_logger.trace("No need to make permission check for System/RootAdmin account, returning true");
@@@ -548,13 -493,13 +550,13 @@@
              Transaction.execute(new TransactionCallbackNoReturn() {
                  @Override
                  public void doInTransactionWithoutResult(TransactionStatus status) {
 -                    UserAccountVO user = null;
 -                    user = _userAccountDao.lockRow(id, true);
 -                    user.setLoginAttempts(attempts);
 +            UserAccountVO user = null;
 +            user = _userAccountDao.lockRow(id, true);
 +            user.setLoginAttempts(attempts);
-             if(toDisable) {
+                     if (toDisable) {
 -                        user.setState(State.disabled.toString());
 -                    }
 -                    _userAccountDao.update(id, user);
 +                user.setState(State.disabled.toString());
 +            }
 +            _userAccountDao.update(id, user);
                  }
              });
          } catch (Exception e) {
@@@ -638,12 -581,9 +638,12 @@@
                  _gslbService.revokeAllGslbRulesForAccount(caller, accountId);
              }
  
-             //delete the account from project accounts
+             // delete the account from project accounts
              _projectAccountDao.removeAccountFromProjects(accountId);
  
 +            //delete the account from group
 +            _messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
 +
              // delete all vm groups belonging to accont
              List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
              for (InstanceGroupVO group : groups) {
@@@ -810,12 -750,15 +810,15 @@@
  
              // release account specific acquired portable IP's. Since all the portable IP's must have been already
              // disassociated with VPC/guest network (due to deletion), so just mark portable IP as free.
-             List<? extends IpAddress> portableIpsToRelease = _ipAddressDao.listByAccount(accountId);
-             for (IpAddress ip : portableIpsToRelease) {
+             List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
+             for (IpAddress ip : ipsToRelease) {
+                 if (ip.isPortable()) {
 -                    s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
 -                    _ipAddrMgr.releasePortableIpAddress(ip.getId());
 -                }
 +                s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
 +                _ipAddrMgr.releasePortableIpAddress(ip.getId());
 +            }
-             //release dedication if any
+             }
+ 
+             // release dedication if any
              List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
              if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
                  s_logger.debug("Releasing dedicated resources for account " + accountId);
@@@ -926,8 -869,10 +929,10 @@@
          @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"),
          @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User")
      })
-     public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, final short accountType,
+     public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email,
+         final String timezone, String accountName,
+         final short accountType,
 -        Long domainId, final String networkDomain, final Map<String, String> details, String accountUUID, final String userUUID) {
 +                                         Long domainId, final String networkDomain, final Map<String, String> details, String accountUUID, final String userUUID) {
  
          if (accountName == null) {
              accountName = userName;
@@@ -1879,8 -1818,8 +1886,8 @@@
              throw new CloudRuntimeException("Failed to encode password");
          }
  
-         if(userUUID == null){
+         if (userUUID == null) {
 -            userUUID = UUID.randomUUID().toString();
 +            userUUID =  UUID.randomUUID().toString();
          }
          UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone, userUUID));
          CallContext.current().putContextParameter(User.class, user.getUuid());
@@@ -2006,11 -1944,11 +2012,11 @@@
                  s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in");
              }
              if (NetUtils.isValidIp(loginIpAddress)) {
-                 ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN,
-                         "user has logged in from IP Address " + loginIpAddress);
+                 ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN, "user has logged in from IP Address " +
+                     loginIpAddress);
              } else {
                  ActionEventUtils.onActionEvent(user.getId(), user.getAccountId(), user.getDomainId(), EventTypes.EVENT_USER_LOGIN,
 -                    "user has logged in. The IP Address cannot be determined");
 +                        "user has logged in. The IP Address cannot be determined");
              }
              return user;
          } else {
@@@ -2250,49 -2242,32 +2257,48 @@@
                  }
              }
          } else {
 -            if (id == null) {
 -                domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources);
 -            }
 -            if (permittedAccounts.isEmpty() && domainId == null) {
 -                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
 -                    permittedAccounts.add(caller.getId());
 -                } else if (!listAll) {
 -                    if (id == null) {
 -                        permittedAccounts.add(caller.getId());
 -                    } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
 -                        domainIdRecursiveListProject.first(caller.getDomainId());
 -                        domainIdRecursiveListProject.second(true);
 -                    }
 -                } else if (domainId == null) {
 -                    if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
 -                        domainIdRecursiveListProject.first(caller.getDomainId());
 -                        domainIdRecursiveListProject.second(true);
 -                    }
 -                }
 -            } else if (domainId != null) {
 -                if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
 -                    permittedAccounts.add(caller.getId());
 +            domainIdRecursiveListProject.third(Project.ListProjectResourcesCriteria.SkipProjectResources);
 +
 +            // search for policy permissions associated with caller to get all his authorized domains, accounts, and resources
 +            // Assumption: if a domain is in grantedDomains, then all the accounts under this domain will not be returned in "grantedAccounts". Similarly, if an account
 +            // is in grantedAccounts, then all the resources owned by this account will not be returned in "grantedResources".
 +            // assume that there is only one query selector adapter
 +            if (_querySelectors == null || _querySelectors.size() == 0)
 +                return; // no futher filtering
 +
 +            QuerySelector qs = _querySelectors.get(0);
 +            boolean grantedAll = qs.isGrantedAll(caller, action);
 +            if ( grantedAll ){
 +                if ( domainId != null ){
 +                    permittedDomains.add(domainId);
                  }
              }
 +            else {
 +                List<Long> grantedDomains = qs.getAuthorizedDomains(caller, action);
 +                List<Long> grantedAccounts = qs.getAuthorizedAccounts(caller, action);
 +                List<Long> grantedResources = qs.getAuthorizedResources(caller, action);
  
 +                if (domainId != null) {
 +                    // specific domain is specified
 +                    if (grantedDomains.contains(domainId)) {
 +                        permittedDomains.add(domainId);
 +                    } else {
 +                        for (Long acctId : grantedAccounts) {
 +                            Account acct = _accountDao.findById(acctId);
 +                            if (acct != null && acct.getDomainId() == domainId) {
 +                                permittedAccounts.add(acctId);
 +                            }
 +                        }
 +                        permittedResources.addAll(grantedResources);
 +                    }
 +                } else if (permittedAccounts.isEmpty()) {
 +                    // neither domain nor account is not specified
 +                    permittedDomains.addAll(grantedDomains);
 +                    permittedAccounts.addAll(grantedAccounts);
 +                    permittedResources.addAll(grantedResources);
 +                }
 +            }
          }
- 
      }
  
      @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/user/DomainManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/vm/UserVmManager.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/vm/UserVmManager.java
index 0251754,950e7e3..fa90c18
--- a/server/src/com/cloud/vm/UserVmManager.java
+++ b/server/src/com/cloud/vm/UserVmManager.java
@@@ -30,6 -33,8 +30,8 @@@ import com.cloud.exception.Insufficient
  import com.cloud.exception.ManagementServerException;
  import com.cloud.exception.ResourceUnavailableException;
  import com.cloud.exception.VirtualMachineMigrationException;
 -import com.cloud.projects.Project.ListProjectResourcesCriteria;
 -import com.cloud.server.Criteria;
++import com.cloud.offering.ServiceOffering;
++import com.cloud.service.ServiceOfferingVO;
  import com.cloud.user.Account;
  import com.cloud.uservm.UserVm;
  import com.cloud.utils.Pair;
@@@ -81,14 -86,33 +83,17 @@@ public interface UserVmManager extends 
      boolean addInstanceToGroup(long userVmId, String group);
  
      InstanceGroupVO getGroupForVm(long vmId);
-     
+ 
      void removeInstanceFromInstanceGroup(long vmId);
  
- 	boolean expunge(UserVmVO vm, long callerUserId, Account caller);
- 	
-     Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
+     boolean expunge(UserVmVO vm, long callerUserId, Account caller);
+ 
 -    /**
 -     * Obtains a list of virtual machines by the specified search criteria.
 -     * Can search by: "userId", "name", "state", "dataCenterId", "podId", "hostId"
 -     * @param c
 -     * @param caller TODO
 -     * @param domainId TODO
 -     * @param isRecursive TODO
 -     * @param permittedAccounts TODO
 -     * @param listAll TODO
 -     * @param listProjectResourcesCriteria TODO
 -     * @param tags TODO
 -     * @return List of UserVMs + count
 -     */
 -    Pair<List<UserVmJoinVO>, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List<Long> permittedAccounts, boolean listAll,
 -        ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags);
 -
+     Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams)
+         throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
  
-     boolean upgradeVirtualMachine(Long id, Long serviceOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException;
+     boolean upgradeVirtualMachine(Long id, Long serviceOfferingId, Map<String, String> customParameters) throws ResourceUnavailableException,
+         ConcurrentOperationException, ManagementServerException,
+         VirtualMachineMigrationException;
  
      boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic);