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:39 UTC

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

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/929fbaba/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/vm/UserVmManagerImpl.java
index d7d4e70,e9cccc4..e4ebed0
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@@ -99,6 -99,8 +100,7 @@@ import com.cloud.agent.manager.Commands
  import com.cloud.alert.AlertManager;
  import com.cloud.api.ApiDBUtils;
  import com.cloud.api.query.dao.UserVmJoinDao;
 -import com.cloud.api.query.vo.UserVmJoinVO;
+ import com.cloud.capacity.Capacity;
  import com.cloud.capacity.CapacityManager;
  import com.cloud.configuration.Config;
  import com.cloud.configuration.ConfigurationManager;
@@@ -1277,10 -1331,14 +1326,14 @@@ public class UserVmManagerImpl extends 
          if (vmInstance.getState().equals(State.Running)) {
              int retry = _scaleRetry;
              ExcludeList excludes = new ExcludeList();
+ 
+             // Check zone wide flag
              boolean enableDynamicallyScaleVm = EnableDynamicallyScaleVm.valueIn(vmInstance.getDataCenterId());
-             if(!enableDynamicallyScaleVm){
+             if (!enableDynamicallyScaleVm) {
 -                throw new PermissionDeniedException("Dynamically scaling virtual machines is disabled for this zone, please contact your admin");
 +               throw new PermissionDeniedException("Dynamically scaling virtual machines is disabled for this zone, please contact your admin");
              }
+ 
+             // Check vm flag
              if (!vmInstance.isDynamicallyScalable()) {
                  throw new CloudRuntimeException("Unable to Scale the vm: " + vmInstance.getUuid() + " as vm does not have tools to support dynamic scaling");
              }
@@@ -1426,61 -1523,50 +1518,50 @@@
  
                  Account account = _accountDao.lockRow(vm.getAccountId(), true);
  
 -                // if the account is deleted, throw error
 -                if (account.getRemoved() != null) {
 +        // if the account is deleted, throw error
 +        if (account.getRemoved() != null) {
-             throw new CloudRuntimeException(
-                     "Unable to recover VM as the account is deleted");
+                     throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
 -                }
 +        }
  
 -                // Get serviceOffering for Virtual Machine
 +        // Get serviceOffering for Virtual Machine
-         ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId());
+                 ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
  
 -                // First check that the maximum number of UserVMs, CPU and Memory limit for the given
 -                // accountId will not be exceeded
 +        // First check that the maximum number of UserVMs, CPU and Memory limit for the given
 +        // accountId will not be exceeded
-         resourceLimitCheck(account, new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
+                 resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
  
 -                _haMgr.cancelDestroy(vm, vm.getHostId());
 +        _haMgr.cancelDestroy(vm, vm.getHostId());
  
 -                try {
 +        try {
-             if (!_itMgr.stateTransitTo(vm,
-                     VirtualMachine.Event.RecoveryRequested, null)) {
-                 s_logger.debug("Unable to recover the vm because it is not in the correct state: "
-                         + vmId);
-                 throw new InvalidParameterValueException(
-                         "Unable to recover the vm because it is not in the correct state: "
-                                 + vmId);
+                     if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
+                         s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
+                         throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
 -                    }
 -                } catch (NoTransitionException e) {
 +            }
 +        } catch (NoTransitionException e) {
-             throw new InvalidParameterValueException(
-                     "Unable to recover the vm because it is not in the correct state: "
-                             + vmId);
+                     throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
 -                }
 +        }
  
 -                // Recover the VM's disks
 -                List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
 -                for (VolumeVO volume : volumes) {
 -                    if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
 -                        // Create an event
 -                        Long templateId = volume.getTemplateId();
 -                        Long diskOfferingId = volume.getDiskOfferingId();
 -                        Long offeringId = null;
 -                        if (diskOfferingId != null) {
 +        // Recover the VM's disks
 +        List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
 +        for (VolumeVO volume : volumes) {
 +            if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
 +                // Create an event
 +                Long templateId = volume.getTemplateId();
 +                Long diskOfferingId = volume.getDiskOfferingId();
 +                Long offeringId = null;
 +                if (diskOfferingId != null) {
-                     DiskOfferingVO offering = _diskOfferingDao
-                             .findById(diskOfferingId);
-                     if (offering != null
-                             && (offering.getType() == DiskOfferingVO.Type.Disk)) {
+                             DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
+                             if (offering != null && (offering.getType() == DiskOfferingVO.Type.Disk)) {
 -                                offeringId = offering.getId();
 -                            }
 -                        }
 -                        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
 -                                offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid());
 +                        offeringId = offering.getId();
                      }
                  }
-                 UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(),
-                         volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId,
-                         volume.getSize(), Volume.class.getName(), volume.getUuid());
++                        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(),
++                                offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid());
 +            }
 +        }
  
 -                //Update Resource Count for the given account
 +        //Update Resource Count for the given account
-         resourceCountIncrement(account.getId(), new Long(serviceOffering.getCpu()),
-                 new Long(serviceOffering.getRamSize()));
+                 resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
              }
          });
  
@@@ -1531,13 -1613,12 +1608,12 @@@
  
          _itMgr.registerGuru(VirtualMachine.Type.User, this);
  
-         VirtualMachine.State.getStateMachine().registerListener(
-                 new UserVmStateListener(_usageEventDao, _networkDao, _nicDao));
+         VirtualMachine.State.getStateMachine().registerListener(new UserVmStateListener(_usageEventDao, _networkDao, _nicDao, _offeringDao));
  
          String value = _configDao.getValue(Config.SetVmInternalNameUsingDisplayName.key());
-         _instanceNameFlag = (value == null)?false:Boolean.parseBoolean(value);
+         _instanceNameFlag = (value == null) ? false : Boolean.parseBoolean(value);
  
 -        _scaleRetry = NumbersUtil.parseInt(configs.get(Config.ScaleRetry.key()), 2);
 +       _scaleRetry = NumbersUtil.parseInt(configs.get(Config.ScaleRetry.key()), 2);
  
          s_logger.info("User VM Manager is configured.");
  
@@@ -1884,21 -1938,20 +1933,20 @@@
          }
  
          for (Nic nic : nics) {
 -            Network network = _networkDao.findById(nic.getNetworkId());
 +             Network network = _networkDao.findById(nic.getNetworkId());
-              NicProfile nicProfile = new NicProfile(nic, network, null, null, null,
-                  _networkModel.isSecurityGroupSupportedInNetwork(network),
-                  _networkModel.getNetworkTag(template.getHypervisorType(), network));
+             NicProfile nicProfile = new NicProfile(nic, network, null, null, null, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(
+                     template.getHypervisorType(), network));
  
 -            VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm);
 +             VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm);
  
 -            UserDataServiceProvider element = _networkModel.getUserDataUpdateProvider(network);
 -            if (element == null) {
 -                throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for UserData update");
 -            }
 -            boolean result = element.saveUserData(network, nicProfile, vmProfile);
 -            if (!result) {
 -                s_logger.error("Failed to update userdata for vm " + vm + " and nic " + nic);
 -            }
 +             UserDataServiceProvider element = _networkModel.getUserDataUpdateProvider(network);
 +             if (element == null) {
 +                 throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for UserData update");
 +             }
 +             boolean result = element.saveUserData(network, nicProfile, vmProfile);
 +             if (!result) {
 +                 s_logger.error("Failed to update userdata for vm " + vm + " and nic " + nic);
 +             }
          }
  
          return true;
@@@ -2086,33 -2122,26 +2117,26 @@@
                  Transaction.execute(new TransactionCallbackNoReturn() {
                      @Override
                      public void doInTransactionWithoutResult(TransactionStatus status) {
 -                        // don't let the group be deleted when we are assigning vm to
 -                        // it.
 +                // don't let the group be deleted when we are assigning vm to
 +                // it.
-                         InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(),
-                         false);
+                         InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(), false);
 -                        if (ngrpLock == null) {
 +                if (ngrpLock == null) {
-                     s_logger.warn("Failed to acquire lock on vm group id="
-                                     + groupFinal.getId() + " name=" + groupFinal.getName());
-                             throw new CloudRuntimeException("Failed to acquire lock on vm group id="
-                                     + groupFinal.getId() + " name=" + groupFinal.getName());
+                             s_logger.warn("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
+                             throw new CloudRuntimeException("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
 -                        }
 +                }
  
 -                        // Currently don't allow to assign a vm to more than one group
 -                        if (_groupVMMapDao.listByInstanceId(userVmId) != null) {
 -                            // Delete all mappings from group_vm_map table
 +                // Currently don't allow to assign a vm to more than one group
 +                if (_groupVMMapDao.listByInstanceId(userVmId) != null) {
 +                    // Delete all mappings from group_vm_map table
-                     List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao
-                             .listByInstanceId(userVmId);
+                             List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId);
 -                            for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
 +                    for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
-                         SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao
-                                 .createSearchCriteria();
-                         sc.addAnd("instanceId", SearchCriteria.Op.EQ,
-                                 groupMap.getInstanceId());
+                                 SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria();
+                                 sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId());
 -                                _groupVMMapDao.expunge(sc);
 -                            }
 -                        }
 +                        _groupVMMapDao.expunge(sc);
 +                    }
 +                }
-                 InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(
-                                 groupFinal.getId(), userVmId);
+                         InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(groupFinal.getId(), userVmId);
 -                        _groupVMMapDao.persist(groupVmMapVO);
 +                _groupVMMapDao.persist(groupVmMapVO);
  
                      }
                  });
@@@ -2382,13 -2386,10 +2381,10 @@@
              // found, throw an error
              // * if network is not found, create a new one and use it
  
-             List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao
-                     .listByAvailability(Availability.Required, false);
+             List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
              if (requiredOfferings.size() < 1) {
-                 throw new InvalidParameterValueException(
-                         "Unable to find network offering with availability="
-                                 + Availability.Required
+                 throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required
 -                        + " to automatically create the network as a part of vm creation");
 +                                + " to automatically create the network as a part of vm creation");
              }
  
              if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
@@@ -2529,15 -2509,27 +2507,27 @@@
          Long tmp = _templateDao.findById(template.getId()).getSize();
          long size = 0;
          if (tmp != null) {
-         	size = tmp;
+             size = tmp;
          }
          if (diskOfferingId != null) {
+             DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
+             if (diskOffering != null && diskOffering.isCustomized()) {
+                 if (diskSize == null) {
+                     throw new InvalidParameterValueException("This disk offering requires a custom size specified");
+                 }
 -                Long customDiskOfferingMaxSize = volumeMgr.CustomDiskOfferingMaxSize.value();
 -                Long customDiskOfferingMinSize = volumeMgr.CustomDiskOfferingMinSize.value();
++                Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
++                Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
+                 if ((diskSize < customDiskOfferingMinSize) || (diskSize > customDiskOfferingMaxSize)) {
+                     throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize
+                             + " Min:" + customDiskOfferingMinSize);
+                 }
+             }
              size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
          }
-         resourceLimitCheck(owner, new Long(offering.getCpu()), new Long(offering.getRamSize()));
-         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso
-                 || diskOfferingId == null ? 1 : 2));
-         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long (size));
+         resourceLimitCheck(owner, isDisplayVmEnabled, new Long(offering.getCpu()), new Long(offering.getRamSize()));
+ 
+         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso || diskOfferingId == null ? 1 : 2));
+         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
  
          // verify security group ids
          if (securityGroupIdList != null) {
@@@ -2570,10 -2560,9 +2558,9 @@@
                          // Root admin has access to both VM and AG by default,
                          // but
                          // make sure the owner of these entities is same
 -                        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) {
 +                        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                              if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
-                                 throw new PermissionDeniedException("Affinity Group " + ag
-                                         + " does not belong to the VM's domain");
+                                 throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                              }
                          }
                      } else {
@@@ -2581,10 -2570,9 +2568,9 @@@
                          // Root admin has access to both VM and AG by default,
                          // but
                          // make sure the owner of these entities is same
 -                        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getType())) {
 +                        if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                              if (ag.getAccountId() != owner.getAccountId()) {
-                                 throw new PermissionDeniedException("Affinity Group " + ag
-                                         + " does not belong to the VM's account");
+                                 throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
                              }
                          }
                      }
@@@ -2773,9 -2749,8 +2747,8 @@@
                  List<String> hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId);
                  // * verify that there are no duplicates
                  if (hostNames.contains(hostName)) {
-                     throw new InvalidParameterValueException("The vm with hostName " + hostName
-                         + " already exists in the network domain: " + ntwkDomain + "; network="
+                     throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + ntwkDomain.getKey() + "; network="
 -                            + _networkModel.getNetwork(ntwkId));
 +                        + _networkModel.getNetwork(ntwkId));
                  }
              }
          }
@@@ -2815,110 -2786,126 +2784,126 @@@
          return vm;
      }
  
-     private UserVmVO commitUserVm(final DataCenter zone, final VirtualMachineTemplate template, final String hostName,
-             final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final String userData,
-             final HypervisorType hypervisor, final Account caller, final Boolean isDisplayVmEnabled, final String keyboard, final long accountId,
-             final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKey,
-             final LinkedHashMap<String, NicProfile> networkNicMap, final long id, final String instanceName, final String uuidName,
-             final HypervisorType hypervisorType) throws InsufficientCapacityException {
-         return Transaction.execute(new TransactionCallbackWithException<UserVmVO,InsufficientCapacityException>() {
+     private String generateHostName(String uuidName) {
+         return _instance + "-" + uuidName;
+     }
+ 
+     private UserVmVO commitUserVm(final DataCenter zone, final VirtualMachineTemplate template, final String hostName, final String displayName, final Account owner,
+             final Long diskOfferingId, final Long diskSize, final String userData, final HypervisorType hypervisor, final Account caller, final Boolean isDisplayVmEnabled,
+             final String keyboard, final long accountId, final ServiceOfferingVO offering, final boolean isIso, final String sshPublicKey,
+             final LinkedHashMap<String, NicProfile> networkNicMap, final long id, final String instanceName, final String uuidName, final HypervisorType hypervisorType,
+             final Map<String, String> customParameters) throws InsufficientCapacityException {
+         return Transaction.execute(new TransactionCallbackWithException<UserVmVO, InsufficientCapacityException>() {
              @Override
              public UserVmVO doInTransaction(TransactionStatus status) throws InsufficientCapacityException {
-         UserVmVO vm = new UserVmVO(id, instanceName, displayName,
-                 template.getId(), hypervisorType, template.getGuestOSId(),
-                 offering.getOfferHA(), offering.getLimitCpuUse(),
-                 owner.getDomainId(), owner.getId(), offering.getId(), userData,
-                 hostName, diskOfferingId);
+                 UserVmVO vm = new UserVmVO(id, instanceName, displayName, template.getId(), hypervisorType, template.getGuestOSId(), offering.getOfferHA(), offering
+                         .getLimitCpuUse(), owner.getDomainId(), owner.getId(), offering.getId(), userData, hostName, diskOfferingId);
 -                vm.setUuid(uuidName);
 -                vm.setDynamicallyScalable(template.isDynamicallyScalable());
 -                if (sshPublicKey != null) {
 -                    vm.setDetail("SSH.PublicKey", sshPublicKey);
 -                }
 +        vm.setUuid(uuidName);
 +        vm.setDynamicallyScalable(template.isDynamicallyScalable());
 +        if (sshPublicKey != null) {
 +            vm.setDetail("SSH.PublicKey", sshPublicKey);
 +        }
  
 -                if (keyboard != null && !keyboard.isEmpty())
 -                    vm.setDetail(VmDetailConstants.KEYBOARD, keyboard);
 +        if (keyboard != null && !keyboard.isEmpty())
 +            vm.setDetail(VmDetailConstants.KEYBOARD, keyboard);
  
 -                if (isIso) {
 -                    vm.setIsoId(template.getId());
 -                }
 +        if (isIso) {
 +            vm.setIsoId(template.getId());
 +        }
+                 Long rootDiskSize = null;
+                 if (customParameters.containsKey("rootdisksize")) {
+                     if (NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1) <= 0) {
+                         throw new InvalidParameterValueException("rootdisk size should be a non zero number.");
+                     }
+                     rootDiskSize = Long.parseLong(customParameters.get("rootDisksize"));
+                     customParameters.remove("rootdisksize");
+                 }
  
 -                if (isDisplayVmEnabled != null) {
 -                    if (!_accountMgr.isRootAdmin(caller.getType())) {
 -                        throw new PermissionDeniedException("Cannot update parameter displayvm, only admin permitted ");
 -                    }
 -                    vm.setDisplayVm(isDisplayVmEnabled);
 +        if(isDisplayVmEnabled != null){
 +            if(!_accountMgr.isRootAdmin(caller.getId())){
 +                throw new PermissionDeniedException( "Cannot update parameter displayvm, only admin permitted ");
 +            }
 +            vm.setDisplayVm(isDisplayVmEnabled);
-         }else {
+                 } else {
 -                    vm.setDisplayVm(true);
 -                }
 +            vm.setDisplayVm(true);
 +        }
  
 -                // If hypervisor is vSphere, check for clone type setting.
 -                if (hypervisorType.equals(HypervisorType.VMware)) {
 -                    // retrieve clone flag.
 -                    UserVmCloneType cloneType = UserVmCloneType.linked;
 -                    String value = _configDao.getValue(Config.VmwareCreateFullClone.key());
 -                    if (value != null) {
 -                        if (Boolean.parseBoolean(value) == true)
 -                            cloneType = UserVmCloneType.full;
 -                    }
 -                    UserVmCloneSettingVO vmCloneSettingVO = new UserVmCloneSettingVO(id, cloneType.toString());
 -                    _vmCloneSettingDao.persist(vmCloneSettingVO);
 -                }
 +        // If hypervisor is vSphere, check for clone type setting.
 +        if (hypervisorType.equals(HypervisorType.VMware)) {
 +            // retrieve clone flag.
 +            UserVmCloneType cloneType = UserVmCloneType.linked;
 +            String value = _configDao.getValue(Config.VmwareCreateFullClone.key());
 +            if (value != null) {
 +                if (Boolean.parseBoolean(value) == true)
 +                    cloneType = UserVmCloneType.full;
 +            }
 +            UserVmCloneSettingVO vmCloneSettingVO = new UserVmCloneSettingVO(id, cloneType.toString());
 +            _vmCloneSettingDao.persist(vmCloneSettingVO);
 +        }
  
 -                long guestOSId = template.getGuestOSId();
 -                GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
 -                long guestOSCategoryId = guestOS.getCategoryId();
 -                GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
 +        long guestOSId = template.getGuestOSId();
 +        GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
 +        long guestOSCategoryId = guestOS.getCategoryId();
 +        GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
  
- 
 -                // If hypervisor is vSphere and OS is OS X, set special settings.
 -                if (hypervisorType.equals(HypervisorType.VMware)) {
 +        // If hypervisor is vSphere and OS is OS X, set special settings.
 +        if (hypervisorType.equals(HypervisorType.VMware)) {
-             if (guestOS.getDisplayName().toLowerCase().contains("apple mac os")){
+                     if (guestOS.getDisplayName().toLowerCase().contains("apple mac os")) {
 -                        vm.setDetail("smc.present", "TRUE");
 -                        vm.setDetail(VmDetailConstants.ROOK_DISK_CONTROLLER, "scsi");
 -                        vm.setDetail("firmware", "efi");
 -                        s_logger.info("guestOS is OSX : overwrite root disk controller to scsi, use smc and efi");
 -                    }
 -                }
 +                vm.setDetail("smc.present", "TRUE");
 +                vm.setDetail(VmDetailConstants.ROOK_DISK_CONTROLLER, "scsi");
 +                vm.setDetail("firmware", "efi");
 +                s_logger.info("guestOS is OSX : overwrite root disk controller to scsi, use smc and efi");
 +            }
 +       }
  
                  Map<String, String> details = template.getDetails();
-                 if ( details != null && !details.isEmpty() ) {
+                 if (details != null && !details.isEmpty()) {
                      vm.details.putAll(details);
                  }
  
 -                _vmDao.persist(vm);
 +        _vmDao.persist(vm);
+                 if (customParameters != null && customParameters.size() > 0) {
+                     for (String key : customParameters.keySet()) {
+                         vm.setDetail(key, customParameters.get(key));
+                     }
+                 }
 -                _vmDao.saveDetails(vm);
 +        _vmDao.saveDetails(vm);
  
 -                s_logger.debug("Allocating in the DB for vm");
 -                DataCenterDeployment plan = new DataCenterDeployment(zone.getId());
 +        s_logger.debug("Allocating in the DB for vm");
 +        DataCenterDeployment plan = new DataCenterDeployment(zone.getId());
  
 -                List<String> computeTags = new ArrayList<String>();
 -                computeTags.add(offering.getHostTag());
 +        List<String> computeTags = new ArrayList<String>();
 +        computeTags.add(offering.getHostTag());
  
-         List<String> rootDiskTags =	new ArrayList<String>();
+                 List<String> rootDiskTags = new ArrayList<String>();
 -                rootDiskTags.add(offering.getTags());
 +        rootDiskTags.add(offering.getTags());
  
-         if(isIso){
-                     VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachineFromScratch(vm.getUuid(), Long.toString(owner.getAccountId()), vm.getIsoId().toString(), hostName, displayName, hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize,  computeTags, rootDiskTags, networkNicMap, plan);
-         }else {
-                     VirtualMachineEntity vmEntity = _orchSrvc.createVirtualMachine(vm.getUuid(), Long.toString(owner.getAccountId()), Long.toString(template.getId()), hostName, displayName, hypervisor.name(), offering.getCpu(),  offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkNicMap, plan);
+                 if (isIso) {
+                     _orchSrvc.createVirtualMachineFromScratch(vm.getUuid(), Long.toString(owner.getAccountId()), vm.getIsoId().toString(), hostName, displayName,
+                             hypervisor.name(), guestOSCategory.getName(), offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags,
+                             networkNicMap, plan);
+                 } else {
+                     _orchSrvc.createVirtualMachine(vm.getUuid(), Long.toString(owner.getAccountId()), Long.toString(template.getId()), hostName, displayName, hypervisor.name(),
+                             offering.getCpu(), offering.getSpeed(), offering.getRamSize(), diskSize, computeTags, rootDiskTags, networkNicMap, plan, rootDiskSize);
 -                }
 +        }
  
- 
- 
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Successfully allocated DB entry for " + vm);
 -                }
 -                CallContext.current().setEventDetails("Vm Id: " + vm.getId());
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Successfully allocated DB entry for " + vm);
 +        }
 +        CallContext.current().setEventDetails("Vm Id: " + vm.getId());
  
-         UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(),
-                 vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(),
-                 VirtualMachine.class.getName(), vm.getUuid());
+                 if (!offering.isDynamic()) {
+                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(),
+                             hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid());
+                 } else {
+                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(), vm.getHostName(), offering.getId(), template.getId(),
+                             hypervisorType.toString(), VirtualMachine.class.getName(), vm.getUuid(), customParameters);
+                 }
  
 -                //Update Resource Count for the given account
 +        //Update Resource Count for the given account
-         resourceCountIncrement(accountId, new Long(offering.getCpu()),
-                 new Long(offering.getRamSize()));
+                 resourceCountIncrement(accountId, isDisplayVmEnabled, new Long(offering.getCpu()), new Long(offering.getRamSize()));
 -                return vm;
 -            }
 +        return vm;
 +    }
          });
      }
  
@@@ -3083,10 -3066,10 +3064,10 @@@
          List<VolumeVO> volumes = _volsDao.findByInstance(userVm.getId());
          VmDiskStatisticsVO diskstats = null;
          for (VolumeVO volume : volumes) {
-                diskstats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(),userVm.getId(), volume.getId());
+             diskstats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
              if (diskstats == null) {
-                diskstats = new VmDiskStatisticsVO(userVm.getAccountId(), userVm.getDataCenterId(),userVm.getId(), volume.getId());
+                 diskstats = new VmDiskStatisticsVO(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
 -                _vmDiskStatsDao.persist(diskstats);
 +               _vmDiskStatsDao.persist(diskstats);
              }
          }
  
@@@ -3139,14 -3119,14 +3117,14 @@@
                  guestNetwork = network;
                  // In vmware, we will be effecting pvlan settings in portgroups in StartCommand.
                  if (profile.getHypervisorType() != HypervisorType.VMware) {
-                 if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
-                 	NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
-                 	if (!setupVmForPvlan(true, hostId, nicProfile)) {
-                 		return false;
-                 	}
+                     if (nic.getBroadcastUri().getScheme().equals("pvlan")) {
+                         NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
+                         if (!setupVmForPvlan(true, hostId, nicProfile)) {
+                             return false;
+                         }
+                     }
                  }
--            }
 +        }
          }
          boolean ipChanged = false;
          if (originalIp != null && !originalIp.equalsIgnoreCase(returnedIp)) {
@@@ -3222,18 -3192,14 +3190,14 @@@
              VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
              status = vmEntity.stop(Long.toString(userId));
              if (status) {
 -                return _vmDao.findById(vmId);
 +               return _vmDao.findById(vmId);
              } else {
 -                return null;
 +               return null;
              }
          } catch (ResourceUnavailableException e) {
-             throw new CloudRuntimeException(
-                     "Unable to contact the agent to stop the virtual machine "
-                             + vm, e);
+             throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
          } catch (CloudException e) {
-             throw new CloudRuntimeException(
-                     "Unable to contact the agent to stop the virtual machine "
-                             + vm, e);
+             throw new CloudRuntimeException("Unable to contact the agent to stop the virtual machine " + vm, e);
          }
      }
  
@@@ -3507,88 -3446,87 +3445,88 @@@
                      @Override
                      public void doInTransactionWithoutResult(TransactionStatus status) {
                          HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswerFinal.getVmDiskStatsMap();
-                 if (vmDiskStatsByName == null)
-                     return;
-                 List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
-                 if (vmDiskStats == null)
- 		    return;
- 
- 	        for (VmDiskStatsEntry vmDiskStat:vmDiskStats) {
-                     SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
-                     sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
-                     VolumeVO volume = _volsDao.search(sc_volume, null).get(0);
- 	            VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
- 	            VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
- 
- 	                if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) {
- 	                    s_logger.debug("Read/Write of IO and Bytes are both 0. Not updating vm_disk_statistics");
- 	                    continue;
- 	                }
- 
- 	                if (vmDiskStat_lock == null) {
- 	                    s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId()+ " and volumeId:" + volume.getId());
- 	                    continue;
- 	                }
- 
- 	                if (previousVmDiskStats != null
- 	                        && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead())
- 	                        || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock.getCurrentIOWrite())
- 	                        || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead())
- 	    	                || (previousVmDiskStats.getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) {
- 	                    s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " +
- 	                            "Ignoring current answer. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() +
- 	                            " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() +
- 	                            " Bytes Read: " + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite());
- 	                    continue;
- 	                }
- 
- 	                if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) {
- 	                    if (s_logger.isDebugEnabled()) {
- 	                        s_logger.debug("Read # of IO that's less than the last one.  " +
- 	                                "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() +
- 	                                " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead());
- 	                    }
- 	                    vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
- 	                }
- 	                vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead());
- 	                if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) {
- 	                    if (s_logger.isDebugEnabled()) {
- 	                        s_logger.debug("Write # of IO that's less than the last one.  " +
- 	                                "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() +
- 	                                " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite());
- 	                    }
- 	                    vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
- 	                }
- 	                vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite());
- 	                if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) {
- 	                    if (s_logger.isDebugEnabled()) {
- 	                        s_logger.debug("Read # of Bytes that's less than the last one.  " +
- 	                                "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() +
- 	                                " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead());
- 	                    }
- 	                    vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
- 	                }
- 	                vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead());
- 	                if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) {
- 	                    if (s_logger.isDebugEnabled()) {
- 	                        s_logger.debug("Write # of Bytes that's less than the last one.  " +
- 	                                "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() +
- 	                                " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + vmDiskStat_lock.getCurrentBytesWrite());
- 	                    }
- 	                    vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
- 	                }
- 	                vmDiskStat_lock.setCurrentBytesWrite(vmDiskStat.getBytesWrite());
- 
- 	                if (! _dailyOrHourly) {
- 	                    //update agg bytes
- 	                	vmDiskStat_lock.setAggIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
- 	                	vmDiskStat_lock.setAggIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
- 	                	vmDiskStat_lock.setAggBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
- 	                	vmDiskStat_lock.setAggBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
- 	                }
- 
- 	                _vmDiskStatsDao.update(vmDiskStat_lock.getId(), vmDiskStat_lock);
- 	        	}
+                         if (vmDiskStatsByName == null)
+                             return;
+                         List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
+                         if (vmDiskStats == null)
+                             return;
+ 
+                         for (VmDiskStatsEntry vmDiskStat : vmDiskStats) {
+                             SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
+                             sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
+                             List<VolumeVO> volumes = _volsDao.search(sc_volume, null);
+                             if ((volumes == null) || (volumes.size() == 0))
+                                 break;
+                             VolumeVO volume = volumes.get(0);
+                             VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
+                             VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
+ 
+                             if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) {
+                                 s_logger.debug("Read/Write of IO and Bytes are both 0. Not updating vm_disk_statistics");
+                                 continue;
+                             }
+ 
+                             if (vmDiskStat_lock == null) {
+                                 s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + " and volumeId:"
+                                         + volume.getId());
+                                 continue;
+                             }
+ 
+                             if (previousVmDiskStats != null
+                                     && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock
 -                                            .getCurrentIOWrite()) || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats
++                                            .getCurrentIOWrite())
++                                            || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats
+                                             .getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) {
+                                 s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + host.getName()
+                                         + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() + " Bytes Read: "
+                                         + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite());
+                                 continue;
+                             }
+ 
+                             if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) {
+                                 if (s_logger.isDebugEnabled()) {
+                                     s_logger.debug("Read # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName()
+                                             + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead());
+                                 }
+                                 vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
+                             }
+                             vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead());
+                             if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) {
+                                 if (s_logger.isDebugEnabled()) {
+                                     s_logger.debug("Write # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName()
+                                             + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite());
+                                 }
+                                 vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
+                             }
+                             vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite());
+                             if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) {
+                                 if (s_logger.isDebugEnabled()) {
+                                     s_logger.debug("Read # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName()
+                                             + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead());
+                                 }
+                                 vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
+                             }
+                             vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead());
+                             if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) {
+                                 if (s_logger.isDebugEnabled()) {
+                                     s_logger.debug("Write # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName()
+                                             + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: "
+                                             + vmDiskStat_lock.getCurrentBytesWrite());
+                                 }
+                                 vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
+                             }
+                             vmDiskStat_lock.setCurrentBytesWrite(vmDiskStat.getBytesWrite());
+ 
+                             if (!_dailyOrHourly) {
+                                 //update agg bytes
+                                 vmDiskStat_lock.setAggIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
+                                 vmDiskStat_lock.setAggIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
+                                 vmDiskStat_lock.setAggBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
+                                 vmDiskStat_lock.setAggBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
+                             }
+ 
+                             _vmDiskStatsDao.update(vmDiskStat_lock.getId(), vmDiskStat_lock);
+                         }
                      }
                  });
              } catch (Exception e) {
@@@ -3640,8 -3574,185 +3574,7 @@@
  
      }
  
- 
      @Override
 -    public Pair<List<UserVmJoinVO>, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List<Long> permittedAccounts, boolean listAll,
 -            ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
 -        Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit());
 -
 -        //first search distinct vm id by using query criteria and pagination
 -        SearchBuilder<UserVmJoinVO> sb = _vmJoinDao.createSearchBuilder();
 -        sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids
 -        _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 -
 -        Object id = c.getCriteria(Criteria.ID);
 -        Object name = c.getCriteria(Criteria.NAME);
 -        Object state = c.getCriteria(Criteria.STATE);
 -        Object notState = c.getCriteria(Criteria.NOTSTATE);
 -        Object zone = c.getCriteria(Criteria.DATACENTERID);
 -        Object pod = c.getCriteria(Criteria.PODID);
 -        Object hostId = c.getCriteria(Criteria.HOSTID);
 -        Object hostName = c.getCriteria(Criteria.HOSTNAME);
 -        Object keyword = c.getCriteria(Criteria.KEYWORD);
 -        Object isAdmin = c.getCriteria(Criteria.ISADMIN);
 -        assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more.  If you see this assert, it means we have to find a different way to search by the nic table.";
 -        Object groupId = c.getCriteria(Criteria.GROUPID);
 -        Object networkId = c.getCriteria(Criteria.NETWORKID);
 -        Object hypervisor = c.getCriteria(Criteria.HYPERVISOR);
 -        Object storageId = c.getCriteria(Criteria.STORAGE_ID);
 -        Object templateId = c.getCriteria(Criteria.TEMPLATE_ID);
 -        Object isoId = c.getCriteria(Criteria.ISO_ID);
 -        Object vpcId = c.getCriteria(Criteria.VPC_ID);
 -
 -        sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);
 -        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
 -        sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
 -        sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ);
 -        sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
 -        sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN);
 -        sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
 -        sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
 -        sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
 -        sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ);
 -        sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE);
 -        sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
 -        sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ);
 -        sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
 -
 -        if (groupId != null && (Long)groupId != -1) {
 -            sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
 -        }
 -
 -        if (tags != null && !tags.isEmpty()) {
 -            for (int count = 0; count < tags.size(); count++) {
 -                sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ);
 -                sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ);
 -                sb.cp();
 -            }
 -        }
 -
 -        if (networkId != null) {
 -            sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
 -        }
 -
 -        if (vpcId != null && networkId == null) {
 -            sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
 -        }
 -
 -        if (storageId != null) {
 -            sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ);
 -        }
 -
 -        // populate the search criteria with the values passed in
 -        SearchCriteria<UserVmJoinVO> sc = sb.create();
 -
 -        // building ACL condition
 -        _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
 -
 -        if (tags != null && !tags.isEmpty()) {
 -            int count = 0;
 -            for (String key : tags.keySet()) {
 -                sc.setParameters("key" + String.valueOf(count), key);
 -                sc.setParameters("value" + String.valueOf(count), tags.get(key));
 -                count++;
 -            }
 -        }
 -
 -        if (groupId != null && (Long)groupId != -1) {
 -            sc.setParameters("instanceGroupId", groupId);
 -        }
 -
 -        if (keyword != null) {
 -            SearchCriteria<UserVmJoinVO> ssc = _vmJoinDao.createSearchCriteria();
 -            ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
 -            ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
 -            ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
 -            ssc.addOr("state", SearchCriteria.Op.EQ, keyword);
 -
 -            sc.addAnd("displayName", SearchCriteria.Op.SC, ssc);
 -        }
 -
 -        if (id != null) {
 -            sc.setParameters("id", id);
 -        }
 -
 -        if (templateId != null) {
 -            sc.setParameters("templateId", templateId);
 -        }
 -
 -        if (isoId != null) {
 -            sc.setParameters("isoId", isoId);
 -        }
 -
 -        if (networkId != null) {
 -            sc.setParameters("networkId", networkId);
 -        }
 -
 -        if (vpcId != null && networkId == null) {
 -            sc.setParameters("vpcId", vpcId);
 -        }
 -
 -        if (name != null) {
 -            sc.setParameters("name", "%" + name + "%");
 -        }
 -
 -        if (state != null) {
 -            if (notState != null && (Boolean)notState == true) {
 -                sc.setParameters("stateNEQ", state);
 -            } else {
 -                sc.setParameters("stateEQ", state);
 -            }
 -        }
 -
 -        if (hypervisor != null) {
 -            sc.setParameters("hypervisorType", hypervisor);
 -        }
 -
 -        // Don't show Destroyed and Expunging vms to the end user
 -        if ((isAdmin != null) && ((Boolean)isAdmin != true)) {
 -            sc.setParameters("stateNIN", "Destroyed", "Expunging");
 -        }
 -
 -        if (zone != null) {
 -            sc.setParameters("dataCenterId", zone);
 -        }
 -        if (pod != null) {
 -            sc.setParameters("podId", pod);
 -
 -            if (state == null) {
 -                sc.setParameters("stateNEQ", "Destroyed");
 -            }
 -        }
 -
 -        if (hostId != null) {
 -            sc.setParameters("hostIdEQ", hostId);
 -        } else {
 -            if (hostName != null) {
 -                sc.setParameters("hostName", hostName);
 -            }
 -        }
 -
 -        if (storageId != null) {
 -            sc.setParameters("poolId", storageId);
 -        }
 -
 -        // search vm details by ids
 -        Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _vmJoinDao.searchAndCount(sc, searchFilter);
 -        Integer count = uniqueVmPair.second();
 -        if (count.intValue() == 0) {
 -            // handle empty result cases
 -            return uniqueVmPair;
 -        }
 -        List<UserVmJoinVO> uniqueVms = uniqueVmPair.first();
 -        Long[] vmIds = new Long[uniqueVms.size()];
 -        int i = 0;
 -        for (UserVmJoinVO v : uniqueVms) {
 -            vmIds[i++] = v.getId();
 -        }
 -        List<UserVmJoinVO> vms = _vmJoinDao.searchByIds(vmIds);
 -        return new Pair<List<UserVmJoinVO>, Integer>(vms, count);
 -    }
 -
 -    @Override
      public HypervisorType getHypervisorTypeOfUserVM(long vmId) {
          UserVmVO userVm = _vmDao.findById(vmId);
          if (userVm == null) {
@@@ -3740,12 -3836,11 +3658,11 @@@
  
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
-     public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost)
-             throws ResourceUnavailableException, ConcurrentOperationException,
-             ManagementServerException, VirtualMachineMigrationException {
+     public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
+             VirtualMachineMigrationException {
          // 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");
              }
@@@ -3799,12 -3883,9 +3705,9 @@@
          }
  
          // check if host is UP
-         if (destinationHost.getState() != com.cloud.host.Status.Up
-                 || destinationHost.getResourceState() != ResourceState.Enabled) {
-             throw new InvalidParameterValueException(
-                     "Cannot migrate VM, destination host is not in correct state, has status: "
-                             + destinationHost.getState() + ", state: "
+         if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
+             throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: "
 -                    + destinationHost.getResourceState());
 +                            + destinationHost.getResourceState());
          }
  
          if (vm.getType() != VirtualMachine.Type.User) {
@@@ -3832,16 -3911,11 +3733,11 @@@
          HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
          if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
              if (s_logger.isDebugEnabled()) {
-                 s_logger.debug("Host name: "
-                         + destinationHost.getName()
-                         + ", hostId: "
-                         + destinationHost.getId()
+                 s_logger.debug("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId()
                          + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
              }
-             throw new VirtualMachineMigrationException(
-                     "Destination host, hostId: "
-                             + destinationHost.getId()
+             throw new VirtualMachineMigrationException("Destination host, hostId: " + destinationHost.getId()
 -                    + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
 +                            + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
          }
  
          UserVmVO uservm = _vmDao.findById(vmId);
@@@ -4070,12 -4141,11 +3963,11 @@@
  
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
-     public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinationHost,
-             Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException,
-             ManagementServerException, VirtualMachineMigrationException {
+     public VirtualMachine migrateVirtualMachineWithVolume(Long vmId, Host destinationHost, Map<String, String> volumeToPool) throws ResourceUnavailableException,
+             ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
          // Access check - only root administrator 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");
              }
@@@ -4334,51 -4361,44 +4184,44 @@@
          Transaction.execute(new TransactionCallbackNoReturn() {
              @Override
              public void doInTransactionWithoutResult(TransactionStatus status) {
 -                //generate destroy vm event for usage
 +        //generate destroy vm event for usage
-         UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(),
-                 vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(),
-                 VirtualMachine.class.getName(), vm.getUuid());
+                 UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(),
+                         vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid());
  
 -                // update resource counts for old account
 +        // update resource counts for old account
-         resourceCountDecrement(oldAccount.getAccountId(), new Long(offering.getCpu()),
-                 new Long(offering.getRamSize()));
+                 resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
  
 -                // OWNERSHIP STEP 1: update the vm owner
 -                vm.setAccountId(newAccount.getAccountId());
 -                vm.setDomainId(cmd.getDomainId());
 -                _vmDao.persist(vm);
 +        // OWNERSHIP STEP 1: update the vm owner
 +        vm.setAccountId(newAccount.getAccountId());
 +        vm.setDomainId(cmd.getDomainId());
 +        _vmDao.persist(vm);
  
 -                // OS 2: update volume
 -                for (VolumeVO volume : volumes) {
 +        // OS 2: update volume
 +        for (VolumeVO volume : volumes) {
-             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(),
-                     volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid());
+                     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.volume);
-             _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage,
-                     new Long(volume.getSize()));
+                     _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
 -                    volume.setAccountId(newAccount.getAccountId());
 -                    volume.setDomainId(newAccount.getDomainId());
 -                    _volsDao.persist(volume);
 -                    _resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
 +            volume.setAccountId(newAccount.getAccountId());
 +            volume.setDomainId(newAccount.getDomainId());
 +            _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(),
-                     volume.getUuid());
+                     _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(), volume.getUuid());
 -                    //snapshots: mark these removed in db
 -                    List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
 +            //snapshots: mark these removed in db
 +            List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
-             for (SnapshotVO snapshot: snapshots){
+                     for (SnapshotVO snapshot : snapshots) {
 -                        _snapshotDao.remove(snapshot.getId());
 -                    }
 -                }
 +                _snapshotDao.remove(snapshot.getId());
 +            }
 +        }
  
 -                //update resource count of new account
 +        //update resource count of new account
-         resourceCountIncrement(newAccount.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
+                 resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
  
 -                //generate usage events to account for this change
 +        //generate usage events to account for this change
-         UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(),
-                 vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(),
-                 VirtualMachine.class.getName(), vm.getUuid());
+                 UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(),
+                         vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid());
              }
          });
  
@@@ -4463,21 -4475,15 +4298,15 @@@
              VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
              _networkMgr.allocate(vmProfile, networks);
  
-             _securityGroupMgr.addInstanceToGroups(vm.getId(),
-                     securityGroupIdList);
+             _securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
  
-             s_logger.debug("AssignVM: Basic zone, adding security groups no "
-                     + securityGroupIdList.size() + " to "
-                     + vm.getInstanceName());
+             s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
          } else {
 -            if (zone.isSecurityGroupEnabled()) {
 +            if (zone.isSecurityGroupEnabled())  {
-                 throw new InvalidParameterValueException(
-                         "Not yet implemented for SecurityGroupEnabled advanced networks.");
+                 throw new InvalidParameterValueException("Not yet implemented for SecurityGroupEnabled advanced networks.");
              } else {
-                 if (securityGroupIdList != null
-                         && !securityGroupIdList.isEmpty()) {
-                     throw new InvalidParameterValueException(
-                             "Can't move vm with security groups; security group feature is not enabled in this zone");
+                 if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) {
+                     throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone");
                  }
                  // cleanup the network for the oldOwner
                  _networkMgr.cleanupNics(vmOldProfile);
@@@ -4510,13 -4514,10 +4337,10 @@@
                      }
                  } else {
                      NetworkVO defaultNetwork = null;
-                     List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao
-                             .listByAvailability(Availability.Required, false);
+                     List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
                      if (requiredOfferings.size() < 1) {
-                         throw new InvalidParameterValueException(
-                                 "Unable to find network offering with availability="
-                                         + Availability.Required
+                         throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required
 -                                + " to automatically create the network as a part of vm creation");
 +                                        + " to automatically create the network as a part of vm creation");
                      }
                      if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
                          // get Virtual networks
@@@ -4560,10 -4560,8 +4383,8 @@@
                              }
                              defaultNetwork = _networkDao.findById(newNetwork.getId());
                          } else if (virtualNetworks.size() > 1) {
-                             throw new InvalidParameterValueException(
-                                     "More than 1 default Isolated networks are found "
-                                             + "for account " + newAccount
+                             throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount
 -                                    + "; please specify networkIds");
 +                                            + "; please specify networkIds");
                          } else {
                              defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
                          }
@@@ -4665,8 -4648,8 +4471,8 @@@
          VolumeVO root = rootVols.get(0);
          Long templateId = root.getTemplateId();
          boolean isISO = false;
-         if(templateId == null) {
+         if (templateId == null) {
 -            // Assuming that for a vm deployed using ISO, template ID is set to NULL
 +        // Assuming that for a vm deployed using ISO, template ID is set to NULL
              isISO = true;
              templateId = vm.getIsoId();
          }

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