You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by hu...@apache.org on 2013/11/07 13:35:32 UTC

[2/2] git commit: updated refs/heads/master to 9631df8

Fix CID 1127027 Dereference before null check

template can't be null at this point as it has already been dereferenced


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

Branch: refs/heads/master
Commit: f611c24dd509ddea69656813435800e03ecbbb5b
Parents: 4162065
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 13:11:54 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 13:34:48 2013 +0100

----------------------------------------------------------------------
 server/src/com/cloud/vm/UserVmManagerImpl.java | 445 ++++++++++----------
 1 file changed, 223 insertions(+), 222 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f611c24d/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 52fda38..3eaf33a 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -35,6 +35,7 @@ import javax.naming.ConfigurationException;
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.log4j.Logger;
+
 import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.affinity.AffinityGroupService;
@@ -68,15 +69,15 @@ import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationSer
 import org.apache.cloudstack.engine.service.api.OrchestrationService;
 import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
 import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
+import org.apache.cloudstack.framework.async.AsyncCallFuture;
 import org.apache.cloudstack.framework.config.ConfigKey;
 import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
-import org.apache.cloudstack.framework.async.AsyncCallFuture;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.storage.to.TemplateObjectTO;
@@ -243,9 +244,9 @@ import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.GlobalLock;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.TransactionCallbackNoReturn;
 import com.cloud.utils.db.SearchCriteria.Func;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
 import com.cloud.utils.db.TransactionCallbackWithException;
 import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn;
 import com.cloud.utils.db.TransactionStatus;
@@ -726,7 +727,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             return true;
         }
 
-        User user = _userDao.findById(userId);
+        _userDao.findById(userId);
         try {
             VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
             status = vmEntity.stop(Long.toString(userId));
@@ -1148,11 +1149,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vmInstance.getAccountId(), vmInstance.getDataCenterId(),
                     vmInstance.getId(), oldNicIdString, oldNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid());
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmInstance.getAccountId(), vmInstance.getDataCenterId(),
-                     vmInstance.getId(), nicIdString, newNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid());
+                    vmInstance.getId(), nicIdString, newNetworkOfferingId, null, 1L, VirtualMachine.class.getName(), vmInstance.getUuid());
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vmInstance.getAccountId(), vmInstance.getDataCenterId(),
                     vmInstance.getId(), nicIdString, newNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid());
             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmInstance.getAccountId(), vmInstance.getDataCenterId(),
-                     vmInstance.getId(), oldNicIdString, oldNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid());
+                    vmInstance.getId(), oldNicIdString, oldNetworkOfferingId, null, 0L, VirtualMachine.class.getName(), vmInstance.getUuid());
             return _vmDao.findById(vmInstance.getId());
         }
 
@@ -1286,7 +1287,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             ExcludeList excludes = new ExcludeList();
             boolean enableDynamicallyScaleVm = EnableDynamicallyScaleVm.valueIn(vmInstance.getDataCenterId());
             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");
             }
             if (!vmInstance.isDynamicallyScalable()) {
                 throw new CloudRuntimeException("Unable to Scale the vm: " + vmInstance.getUuid() + " as vm does not have tools to support dynamic scaling");
@@ -1430,24 +1431,24 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
             @Override
             public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
-        
+
                 Account account = _accountDao.lockRow(vm.getAccountId(), true);
-        
+
                 // if the account is deleted, throw error
                 if (account.getRemoved() != null) {
                     throw new CloudRuntimeException(
                             "Unable to recover VM as the account is deleted");
                 }
-        
+
                 // Get serviceOffering for Virtual Machine
                 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
                 resourceLimitCheck(account, new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
-        
+
                 _haMgr.cancelDestroy(vm, vm.getHostId());
-        
+
                 try {
                     if (!_itMgr.stateTransitTo(vm,
                             VirtualMachine.Event.RecoveryRequested, null)) {
@@ -1462,7 +1463,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                             "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) {
@@ -1484,7 +1485,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                                 volume.getSize(), Volume.class.getName(), volume.getUuid());
                     }
                 }
-        
+
                 //Update Resource Count for the given account
                 resourceCountIncrement(account.getId(), new Long(serviceOffering.getCpu()),
                         new Long(serviceOffering.getRamSize()));
@@ -1544,7 +1545,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         String value = _configDao.getValue(Config.SetVmInternalNameUsingDisplayName.key());
         _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.");
 
@@ -1795,7 +1796,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true,
                 vmInstance);
-        
+
         if (isDisplayVmEnabled != null) {
             if(!_accountMgr.isRootAdmin(caller.getType())){
                 throw new PermissionDeniedException( "Cannot update parameter displayvm, only admin permitted ");
@@ -1808,7 +1809,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     @Override
     public UserVm updateVirtualMachine(long id, String displayName, String group, Boolean ha,
             Boolean isDisplayVmEnabled, Long osTypeId, String userData, Boolean isDynamicallyScalable, HTTPMethod httpMethod)
-            throws ResourceUnavailableException, InsufficientCapacityException {
+                    throws ResourceUnavailableException, InsufficientCapacityException {
         UserVmVO vm = _vmDao.findById(id);
         if (vm == null) {
             throw new CloudRuntimeException(
@@ -1820,7 +1821,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             throw new InvalidParameterValueException("Vm with id " + id
                     + " is not in the right state");
         }
-        
+
         if (displayName == null) {
             displayName = vm.getDisplayName();
         }
@@ -1834,7 +1835,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             throw new InvalidParameterValueException(
                     "Can't enable ha for the vm as it's created from the Service offering having HA disabled");
         }
-        
+
         if (isDisplayVmEnabled == null) {
             isDisplayVmEnabled = vm.isDisplayVm();
         }
@@ -1853,7 +1854,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         if (isDynamicallyScalable == null) {
             isDynamicallyScalable = vm.isDynamicallyScalable();
         }
-        
+
         if (osTypeId == null) {
             osTypeId = vm.getGuestOSId();
         }
@@ -1886,26 +1887,26 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
         if (nics == null || nics.isEmpty()) {
-           s_logger.error("unable to find any nics for vm " + vm.getUuid());
-           return false;
+            s_logger.error("unable to find any nics for vm " + vm.getUuid());
+            return false;
         }
 
         for (Nic nic : nics) {
-             Network network = _networkDao.findById(nic.getNetworkId());
-             NicProfile nicProfile = new NicProfile(nic, network, null, null, null,
-                 _networkModel.isSecurityGroupSupportedInNetwork(network),
-                 _networkModel.getNetworkTag(template.getHypervisorType(), network));
+            Network network = _networkDao.findById(nic.getNetworkId());
+            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;
@@ -1957,11 +1958,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         CallContext ctx = CallContext.current();
         long vmId = cmd.getId();
         boolean expunge = cmd.getExpunge();
-        
+
         if (!_accountMgr.isAdmin(ctx.getCallingAccount().getType()) && expunge) {
             throw new PermissionDeniedException("Parameter " + ApiConstants.EXPUNGE + " can be passed by Admin only");
         }
-        
+
         UserVm destroyedVm = destroyVm(vmId);
         if (expunge) {
             UserVmVO vm = _vmDao.findById(vmId);
@@ -1969,7 +1970,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 throw new CloudRuntimeException("Failed to expunge vm " + destroyedVm);
             }
         }
-        
+
         return destroyedVm;
     }
 
@@ -2103,7 +2104,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                             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
@@ -2187,11 +2188,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true)
     public UserVm createBasicSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> securityGroupIdList, Account owner,
-                                                         String hostName, String displayName, Long diskOfferingId, Long diskSize, String group,
-                                                         HypervisorType hypervisor, HTTPMethod httpmethod, String userData, String sshKeyPair,
-                                                         Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard,
-                                                         List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
-        throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
+            String hostName, String displayName, Long diskOfferingId, Long diskSize, String group,
+            HypervisorType hypervisor, HTTPMethod httpmethod, String userData, String sshKeyPair,
+            Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard,
+            List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
+                    throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
         Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
@@ -2241,18 +2242,18 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId,
                 diskSize, networkList, securityGroupIdList, group, httpmethod, userData, sshKeyPair, hypervisor,
-		caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, cpuSpeed , memory, cpuNumber, rootDiskSize);
+                caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, cpuSpeed , memory, cpuNumber, rootDiskSize);
 
     }
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true)
     public UserVm createAdvancedSecurityGroupVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList,
-                                                            List<Long> securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId,
-                                                            Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData,
-                                                            String sshKeyPair, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard,
-                                                            List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize) throws InsufficientCapacityException, ConcurrentOperationException,
-	        ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
+            List<Long> securityGroupIdList, Account owner, String hostName, String displayName, Long diskOfferingId,
+            Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData,
+            String sshKeyPair, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayVm, String keyboard,
+            List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize) throws InsufficientCapacityException, ConcurrentOperationException,
+            ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
         Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
@@ -2359,16 +2360,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId,
                 diskSize, networkList, securityGroupIdList, group, httpmethod, userData, sshKeyPair, hypervisor,
-		        caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, cpuSpeed, memory, cpuNumber, rootDiskSize);
+                caller, requestedIps, defaultIps, displayVm, keyboard, affinityGroupIdList, cpuSpeed, memory, cpuNumber, rootDiskSize);
     }
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true)
     public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList, Account owner, String hostName,
-                                               String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor,
-                                               HTTPMethod httpmethod, String userData, String sshKeyPair, Map<Long, IpAddresses> requestedIps,
-                                               IpAddresses defaultIps, Boolean displayvm, String keyboard, List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
-        throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
+            String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor,
+            HTTPMethod httpmethod, String userData, String sshKeyPair, Map<Long, IpAddresses> requestedIps,
+            IpAddresses defaultIps, Boolean displayvm, String keyboard, List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
+                    throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
 
         Account caller = CallContext.current().getCallingAccount();
         List<NetworkVO> networkList = new ArrayList<NetworkVO>();
@@ -2473,8 +2474,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         }
 
         return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId,
-		diskSize, networkList, null, group, httpmethod, userData, sshKeyPair, hypervisor, caller, requestedIps,
-		defaultIps, displayvm, keyboard, affinityGroupIdList, cpuSpeed, memory, cpuNumber, rootDiskSize);
+                diskSize, networkList, null, group, httpmethod, userData, sshKeyPair, hypervisor, caller, requestedIps,
+                defaultIps, displayvm, keyboard, affinityGroupIdList, cpuSpeed, memory, cpuNumber, rootDiskSize);
     }
 
 
@@ -2487,9 +2488,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
     @DB
     protected UserVm createVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate tmplt, String hostName, String displayName, Account owner, Long diskOfferingId,
-        Long diskSize, List<NetworkVO> networkList, List<Long> securityGroupIdList, String group, HTTPMethod httpmethod,
-	    String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map<Long, IpAddresses> requestedIps,
-	    IpAddresses defaultIps, Boolean isDisplayVmEnabled, String keyboard, List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
+            Long diskSize, List<NetworkVO> networkList, List<Long> securityGroupIdList, String group, HTTPMethod httpmethod,
+            String userData, String sshKeyPair, HypervisorType hypervisor, Account caller, Map<Long, IpAddresses> requestedIps,
+            IpAddresses defaultIps, Boolean isDisplayVmEnabled, String keyboard, List<Long> affinityGroupIdList, Integer cpuSpeed, Integer memory, Integer cpuNumber, Long rootDiskSize)
                     throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
 
         _accountMgr.checkAccess(caller, null, true, owner);
@@ -2535,17 +2536,17 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         Long tmp = _templateDao.findById(template.getId()).getSize();
         long size = 0;
         if (tmp != null) {
-        	size = tmp;
+            size = tmp;
         }
         if (diskOfferingId != null) {
             size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
         }
-       if (!offering.isDynamic()) {
-           resourceLimitCheck(owner, new Long(offering.getCpu()), new Long(offering.getRamSize()));
-       }
-       else {
-           resourceLimitCheck(owner, new Long(cpuSpeed), new Long(memory));
-       }
+        if (!offering.isDynamic()) {
+            resourceLimitCheck(owner, new Long(offering.getCpu()), new Long(offering.getRamSize()));
+        }
+        else {
+            resourceLimitCheck(owner, new Long(cpuSpeed), new Long(memory));
+        }
         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso
                 || diskOfferingId == null ? 1 : 2));
         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long (size));
@@ -2782,7 +2783,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 hostName = generateHostName(uuidName);
             }
         }
-        
+
         if (hostName != null) {
             // Check is hostName is RFC compliant
             checkNameForRFCCompliance(hostName);
@@ -2817,14 +2818,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 // * 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="
-                        + _networkModel.getNetwork(ntwkId));
+                            + " already exists in the network domain: " + ntwkDomain + "; network="
+                            + _networkModel.getNetwork(ntwkId));
                 }
             }
         }
 
         HypervisorType hypervisorType = null;
-        if (template == null || template.getHypervisorType() == null
+        if (template.getHypervisorType() == null
                 || template.getHypervisorType() == HypervisorType.None) {
             hypervisorType = hypervisor;
         } else {
@@ -2925,7 +2926,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                         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() ) {
@@ -2950,33 +2951,33 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 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);
+                    _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, rootDiskSize);
+                    _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 (!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());
+                    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 {
-                      HashMap<String, String> vmdetailsMap = new HashMap<String, String>();
-                      for (UserVmDetailVO vmdetail :vmdetails) {
-                           vmdetailsMap.put(vmdetail.getName(), vmdetail.getValue());
-                      }
-                      UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(),
-                      vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(),
-                      VirtualMachine.class.getName(), vm.getUuid(), vmdetailsMap);
+                    HashMap<String, String> vmdetailsMap = new HashMap<String, String>();
+                    for (UserVmDetailVO vmdetail :vmdetails) {
+                        vmdetailsMap.put(vmdetail.getName(), vmdetail.getValue());
+                    }
+                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, accountId, zone.getId(), vm.getId(),
+                            vm.getHostName(), offering.getId(), template.getId(), hypervisorType.toString(),
+                            VirtualMachine.class.getName(), vm.getUuid(), vmdetailsMap);
                 }
-        
+
                 //Update Resource Count for the given account
                 resourceCountIncrement(accountId, new Long(offering.getCpu()),
                         new Long(offering.getRamSize()));
@@ -3001,7 +3002,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 decodedUserData = Base64.decodeBase64(userData.getBytes());
                 if (decodedUserData.length > MAX_HTTP_GET_LENGTH) {
                     throw new InvalidParameterValueException(
-                        "User data is too long for GET request");
+                            "User data is too long for GET request");
                 }
             } else if (httpmethod.equals(HTTPMethod.POST)) {
                 if (userData.length() >= MAX_HTTP_POST_LENGTH) {
@@ -3011,7 +3012,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 decodedUserData = Base64.decodeBase64(userData.getBytes());
                 if (decodedUserData.length > MAX_HTTP_POST_LENGTH) {
                     throw new InvalidParameterValueException(
-                        "User data is too long for POST request");
+                            "User data is too long for POST request");
                 }
             }
 
@@ -3099,17 +3100,17 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     @Override
     public boolean setupVmForPvlan(boolean add, Long hostId, NicProfile nic) {
         if (!nic.getBroadCastUri().getScheme().equals("pvlan")) {
-    		return false;
-    	}
+            return false;
+        }
         String op = "add";
         if (!add) {
-        	// "delete" would remove all the rules(if using ovs) related to this vm
-        	op = "delete";
+            // "delete" would remove all the rules(if using ovs) related to this vm
+            op = "delete";
         }
         Network network = _networkDao.findById(nic.getNetworkId());
         Host host = _hostDao.findById(hostId);
         String networkTag = _networkModel.getNetworkTag(host.getHypervisorType(), network);
-    	PvlanSetupCommand cmd = PvlanSetupCommand.createVmSetup(op, nic.getBroadCastUri(), networkTag, nic.getMacAddress());
+        PvlanSetupCommand cmd = PvlanSetupCommand.createVmSetup(op, nic.getBroadCastUri(), networkTag, nic.getMacAddress());
         Answer answer = null;
         try {
             answer = _agentMgr.send(hostId, cmd);
@@ -3123,7 +3124,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         boolean result = true;
         if (answer == null || !answer.getResult()) {
-        	result = false;
+            result = false;
         }
         return result;
     }
@@ -3146,10 +3147,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         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());
-               _vmDiskStatsDao.persist(diskstats);
+                diskstats = new VmDiskStatisticsVO(userVm.getAccountId(), userVm.getDataCenterId(),userVm.getId(), volume.getId());
+                _vmDiskStatsDao.persist(diskstats);
             }
         }
 
@@ -3202,15 +3203,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 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)) {
             if (returnedIp != null && guestNic != null) {
@@ -3225,7 +3226,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             }
         }
         if (ipChanged) {
-            DataCenterVO dc = _dcDao.findById(vm.getDataCenterId());
+            _dcDao.findById(vm.getDataCenterId());
             UserVmVO userVm = _vmDao.findById(profile.getId());
             // dc.getDhcpProvider().equalsIgnoreCase(Provider.ExternalDhcpServer.getName())
             if (_ntwkSrvcDao.canProviderSupportServiceInNetwork(
@@ -3279,15 +3280,15 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                     "unable to find a virtual machine with id " + vmId);
         }
 
-        UserVO user = _userDao.findById(userId);
+        _userDao.findById(userId);
         boolean status = false;
         try {
             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(
@@ -3327,8 +3328,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             NetworkVO network = _networkDao.findById(nic.getNetworkId());
             if (network.getTrafficType() == TrafficType.Guest) {
                 if (nic.getBroadcastUri() != null && nic.getBroadcastUri().getScheme().equals("pvlan")) {
-                	NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
-                	setupVmForPvlan(false, vm.getHostId(), nicProfile);
+                    NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
+                    setupVmForPvlan(false, vm.getHostId(), nicProfile);
                 }
             }
         }
@@ -3497,7 +3498,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         }
 
         _accountMgr.checkAccess(caller, null, true, vm);
-        User userCaller = _userDao.findById(userId);
+        _userDao.findById(userId);
 
         boolean status;
         State vmState = vm.getState();
@@ -3546,16 +3547,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         // support KVM only util 2013.06.25
         if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
             return;
-    	s_logger.debug("Collect vm disk statistics from host before stopping Vm");
-    	long hostId = userVm.getHostId();
-    	List<String> vmNames = new ArrayList<String>();
-    	vmNames.add(userVm.getInstanceName());
-    	final HostVO host = _hostDao.findById(hostId);
-
-    	GetVmDiskStatsAnswer diskStatsAnswer = null;
-    	try {
-    		diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
-    	} catch (Exception e) {
+        s_logger.debug("Collect vm disk statistics from host before stopping Vm");
+        long hostId = userVm.getHostId();
+        List<String> vmNames = new ArrayList<String>();
+        vmNames.add(userVm.getInstanceName());
+        final HostVO host = _hostDao.findById(hostId);
+
+        GetVmDiskStatsAnswer diskStatsAnswer = null;
+        try {
+            diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
+        } catch (Exception e) {
             s_logger.warn("Error while collecting disk stats for vm: " + userVm.getHostName() + " from host: " + host.getName(), e);
             return;
         }
@@ -3575,83 +3576,83 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                         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);
-        	        	}
+
+                        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);
+                        }
                     }
                 });
             } catch (Exception e) {
@@ -3691,7 +3692,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         boolean status;
 
-        status = expunge(vm, userId, caller);    
+        status = expunge(vm, userId, caller);
         if (status) {
             return  _vmDao.findByIdIncludingRemoved(vmId);
         } else {
@@ -4063,7 +4064,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         checkHostsDedication(vm, srcHostId, destinationHost.getId());
 
-         // call to core process
+        // call to core process
         DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId());
         HostPodVO pod = _podDao.findById(destinationHost.getPodId());
         Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
@@ -4205,7 +4206,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                         if (!((destPlanner.getDeploymentPlanner() != null && destPlanner.getDeploymentPlanner().equals("ImplicitDedicationPlanner")) &&
                                 vmsDest.getAccountId()==accountOfVm)) {
                             msg = "VM of account " + accountOfVm + " with preffered implicit deployment planner being migrated to host " + destHost.getName() +
-                            " not having all vms implicitly dedicated to account " + accountOfVm;
+                                    " not having all vms implicitly dedicated to account " + accountOfVm;
                         }
                     }
                 }
@@ -4358,11 +4359,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         // Check if the source and destination hosts are of the same type and support storage motion.
         if (!(srcHost.getHypervisorType().equals(destinationHost.getHypervisorType()) &&
-            srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion()))) {
+                srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion()))) {
             throw new CloudRuntimeException("The source and destination hosts are not of the same type and version. " +
-                "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " +
-                srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " +
-                destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
+                    "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " +
+                    srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " +
+                    destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
         }
 
         HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(
@@ -4432,7 +4433,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         _itMgr.migrateWithStorage(vm.getUuid(), srcHostId, destinationHost.getId(), volToPoolObjectMap);
         return _vmDao.findById(vm.getId());
-}
+    }
 
     @DB
     @Override
@@ -4580,16 +4581,16 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 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
                 resourceCountDecrement(oldAccount.getAccountId(), 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);
-        
+
                 // OS 2: update volume
                 for (VolumeVO volume : volumes) {
                     UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(),
@@ -4613,10 +4614,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                         _snapshotDao.remove(snapshot.getId());
                     }
                 }
-        
+
                 //update resource count of new account
                 resourceCountIncrement(newAccount.getAccountId(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
-        
+
                 //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(),
@@ -4867,7 +4868,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
         Long userId = caller.getId();
         Account owner = _accountDao.findById(vm.getAccountId());
-        UserVO user = _userDao.findById(userId);
+        _userDao.findById(userId);
         long vmId = vm.getId();
         boolean needRestart = false;
 
@@ -4908,7 +4909,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         Long templateId = root.getTemplateId();
         boolean isISO = false;
         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();
         }
@@ -4963,10 +4964,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 vm.setTemplateId(newTemplateId);
                 _vmDao.update(vmId, vm);
             } else {
-            newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
-            vm.setGuestOSId(template.getGuestOSId());
-            vm.setTemplateId(newTemplateId);
-            _vmDao.update(vmId, vm);
+                newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
+                vm.setGuestOSId(template.getGuestOSId());
+                vm.setTemplateId(newTemplateId);
+                _vmDao.update(vmId, vm);
             }
         } else {
             newVol = volumeMgr.allocateDuplicateVolume(root, null);
@@ -5032,7 +5033,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         if (vm != null && vm.getState() == State.Stopping)
             collectVmDiskStatistics(vm);
     }
-    
+
     private void encryptAndStorePassword(UserVmVO vm, String password) {
         String sshPublicKey = vm.getDetail("SSH.PublicKey");
         if (sshPublicKey != null && !sshPublicKey.equals("")