cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dar...@apache.org
Subject [02/20] New Transaction API
Date Wed, 16 Oct 2013 16:50:13 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/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 6e87916..5053a97 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -35,7 +35,6 @@ 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;
@@ -239,8 +238,12 @@ 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.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
 import com.cloud.utils.db.SearchCriteria.Func;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallbackWithException;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.exception.ExecutionException;
 import com.cloud.utils.fsm.NoTransitionException;
@@ -1375,11 +1378,11 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     public UserVm recoverVirtualMachine(RecoverVMCmd cmd)
             throws ResourceAllocationException, CloudRuntimeException {
 
-        Long vmId = cmd.getId();
+        final Long vmId = cmd.getId();
         Account caller = CallContext.current().getCallingAccount();
 
         // Verify input parameters
-        UserVmVO vm = _vmDao.findById(vmId.longValue());
+        final UserVmVO vm = _vmDao.findById(vmId.longValue());
 
         if (vm == null) {
             throw new InvalidParameterValueException(
@@ -1409,68 +1412,72 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             s_logger.debug("Recovering vm " + vmId);
         }
 
-        Transaction txn = Transaction.currentTxn();
-        AccountVO account = null;
-        txn.start();
-
-        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.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)) {
-                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: "
+        Transaction.executeWithException(new TransactionCallbackWithException<Object>() {
+            @Override
+            public Object doInTransaction(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.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)) {
+                        s_logger.debug("Unable to recover the vm because it is not in the correct state: "
                                 + vmId);
-            }
-        } catch (NoTransitionException e) {
-            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) {
-                    DiskOfferingVO offering = _diskOfferingDao
-                            .findById(diskOfferingId);
-                    if (offering != null
-                            && (offering.getType() == DiskOfferingVO.Type.Disk)) {
-                        offeringId = offering.getId();
+                        throw new InvalidParameterValueException(
+                                "Unable to recover the vm because it is not in the correct state: "
+                                        + vmId);
+                    }
+                } catch (NoTransitionException e) {
+                    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) {
+                            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());
                     }
                 }
-                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
+                resourceCountIncrement(account.getId(), new Long(serviceOffering.getCpu()),
+                        new Long(serviceOffering.getRamSize()));
+                
+                return null;
             }
-        }
+        }, ResourceAllocationException.class);
 
-        //Update Resource Count for the given account
-        resourceCountIncrement(account.getId(), new Long(serviceOffering.getCpu()),
-                new Long(serviceOffering.getRamSize()));
-        txn.commit();
 
         return _vmDao.findById(vmId);
     }
@@ -1965,8 +1972,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     @DB
     protected InstanceGroupVO createVmGroup(String groupName, long accountId) {
         Account account = null;
-        final Transaction txn = Transaction.currentTxn();
-        txn.start();
         try {
             account = _accountDao.acquireInLockTable(accountId); // to ensure
             // duplicate
@@ -1989,7 +1994,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             if (account != null) {
                 _accountDao.releaseFromLockTable(accountId);
             }
-            txn.commit();
         }
     }
 
@@ -2032,7 +2036,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
 
     @Override
     @DB
-    public boolean addInstanceToGroup(long userVmId, String groupName) {
+    public boolean addInstanceToGroup(final long userVmId, String groupName) {
         UserVmVO vm = _vmDao.findById(userVmId);
 
         InstanceGroupVO group = _vmGroupDao.findByAccountAndName(
@@ -2043,43 +2047,47 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         }
 
         if (group != null) {
-            final Transaction txn = Transaction.currentTxn();
-            txn.start();
             UserVm userVm = _vmDao.acquireInLockTable(userVmId);
             if (userVm == null) {
                 s_logger.warn("Failed to acquire lock on user vm id="
                         + userVmId);
             }
             try {
-                // don't let the group be deleted when we are assigning vm to
-                // it.
-                InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(group.getId(),
-                        false);
-                if (ngrpLock == null) {
-                    s_logger.warn("Failed to acquire lock on vm group id="
-                            + group.getId() + " name=" + group.getName());
-                    txn.rollback();
-                    return false;
-                }
+                final InstanceGroupVO groupFinal = group;
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        // don't let the group be deleted when we are assigning vm to
+                        // it.
+                        InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(),
+                                false);
+                        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());
+                        }
+        
+                        // 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);
+                            for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
+                                SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao
+                                        .createSearchCriteria();
+                                sc.addAnd("instanceId", SearchCriteria.Op.EQ,
+                                        groupMap.getInstanceId());
+                                _groupVMMapDao.expunge(sc);
+                            }
+                        }
+                        InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(
+                                groupFinal.getId(), userVmId);
+                        _groupVMMapDao.persist(groupVmMapVO);
 
-                // 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);
-                    for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
-                        SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao
-                                .createSearchCriteria();
-                        sc.addAnd("instanceId", SearchCriteria.Op.EQ,
-                                groupMap.getInstanceId());
-                        _groupVMMapDao.expunge(sc);
                     }
-                }
-                InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(
-                        group.getId(), userVmId);
-                _groupVMMapDao.persist(groupVmMapVO);
+                });
 
-                txn.commit();
                 return true;
             } finally {
                 if (userVm != null) {
@@ -2744,98 +2752,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             hypervisorType = template.getHypervisorType();
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        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);
-        }
-
-        if (keyboard != null && !keyboard.isEmpty())
-            vm.setDetail(VmDetailConstants.KEYBOARD, keyboard);
-
-        if (isIso) {
-            vm.setIsoId(template.getId());
-        }
-
-        if(isDisplayVmEnabled != null){
-            if(!_accountMgr.isRootAdmin(caller.getType())){
-                throw new PermissionDeniedException( "Cannot update parameter displayvm, only admin permitted ");
-            }
-            vm.setDisplayVm(isDisplayVmEnabled);
-        }else {
-            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);
-        }
-
-        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 (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");
-            }
-       }
-
-        _vmDao.persist(vm);
-        _vmDao.saveDetails(vm);
-
-        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> rootDiskTags =	new ArrayList<String>();
-        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 (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());
-
-        //Update Resource Count for the given account
-        resourceCountIncrement(accountId, new Long(offering.getCpu()),
-                new Long(offering.getRamSize()));
-
-        txn.commit();
+        UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData,
+                hypervisor, caller, isDisplayVmEnabled, keyboard, accountId, offering, isIso, sshPublicKey,
+                networkNicMap, id, instanceName, uuidName, hypervisorType);
 
         // Assign instance to the group
         try {
@@ -2860,6 +2779,108 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         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.executeWithException(new TransactionCallbackWithException<UserVmVO>() {
+            @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);
+                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 (isIso) {
+                    vm.setIsoId(template.getId());
+                }
+        
+                if(isDisplayVmEnabled != null){
+                    if(!_accountMgr.isRootAdmin(caller.getType())){
+                        throw new PermissionDeniedException( "Cannot update parameter displayvm, only admin permitted ");
+                    }
+                    vm.setDisplayVm(isDisplayVmEnabled);
+                }else {
+                    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);
+                }
+        
+                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 (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");
+                    }
+               }
+        
+                _vmDao.persist(vm);
+                _vmDao.saveDetails(vm);
+        
+                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> rootDiskTags =	new ArrayList<String>();
+                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 (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());
+        
+                //Update Resource Count for the given account
+                resourceCountIncrement(accountId, new Long(offering.getCpu()),
+                        new Long(offering.getRamSize()));
+                return vm;
+            }
+        }, InsufficientCapacityException.class);
+    }
+
     private void validateUserData(String userData, HTTPMethod httpmethod) {
         byte[] decodedUserData = null;
         if (userData != null) {
@@ -3417,7 +3438,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     }
 
     @Override
-    public void collectVmDiskStatistics (UserVmVO userVm) {
+    public void collectVmDiskStatistics (final UserVmVO userVm) {
         // support KVM only util 2013.06.25
         if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
             return;
@@ -3425,7 +3446,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     	long hostId = userVm.getHostId();
     	List<String> vmNames = new ArrayList<String>();
     	vmNames.add(userVm.getInstanceName());
-    	HostVO host = _hostDao.findById(hostId);
+    	final HostVO host = _hostDao.findById(hostId);
 
     	GetVmDiskStatsAnswer diskStatsAnswer = null;
     	try {
@@ -3439,98 +3460,98 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 s_logger.warn("Error while collecting disk stats vm: " + userVm.getHostName() + " from host: " + host.getName() + "; details: " + diskStatsAnswer.getDetails());
                 return;
             }
-            Transaction txn = Transaction.open(Transaction.CLOUD_DB);
             try {
-                txn.start();
-                HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswer.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);
-	        	}
-	        	txn.commit();
+                final GetVmDiskStatsAnswer diskStatsAnswerFinal = diskStatsAnswer;
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @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);
+        	        	}
+                    }
+                });
             } catch (Exception e) {
-                txn.rollback();
                 s_logger.warn("Unable to update vm disk statistics for vm: " + userVm.getId() + " from host: " + hostId, e);
-            } finally {
-                txn.close();
             }
         }
     }
@@ -4271,7 +4292,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
     @DB
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false)
-    public UserVm moveVMToUser(AssignVMCmd cmd)
+    public UserVm moveVMToUser(final AssignVMCmd cmd)
             throws ResourceAllocationException, ConcurrentOperationException,
             ResourceUnavailableException, InsufficientCapacityException {
         // VERIFICATIONS and VALIDATIONS
@@ -4291,7 +4312,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         }
 
         // get and check the valid VM
-        UserVmVO vm = _vmDao.findById(cmd.getVmId());
+        final UserVmVO vm = _vmDao.findById(cmd.getVmId());
         if (vm == null) {
             throw new InvalidParameterValueException(
                     "There is no vm by that id " + cmd.getVmId());
@@ -4306,7 +4327,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             throw ex;
         }
 
-        Account oldAccount = _accountService.getActiveAccountById(vm
+        final Account oldAccount = _accountService.getActiveAccountById(vm
                 .getAccountId());
         if (oldAccount == null) {
             throw new InvalidParameterValueException("Invalid account for VM "
@@ -4319,7 +4340,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             ex.addProxyObject(vm.getUuid(), "vmId");
             throw ex;
         }
-        Account newAccount = _accountService.getActiveAccountByName(
+        final Account newAccount = _accountService.getActiveAccountByName(
                 cmd.getAccountName(), cmd.getDomainId());
         if (newAccount == null
                 || newAccount.getType() == Account.ACCOUNT_TYPE_PROJECT) {
@@ -4376,8 +4397,8 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         DataCenterVO zone = _dcDao.findById(vm.getDataCenterId());
 
         // Get serviceOffering and Volumes for Virtual Machine
-        ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId());
-        List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
+        final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getServiceOfferingId());
+        final List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
 
         //Remove vm from instance group
         removeInstanceFromInstanceGroup(cmd.getVmId());
@@ -4407,55 +4428,57 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         DomainVO domain = _domainDao.findById(cmd.getDomainId());
         _accountMgr.checkAccess(newAccount, domain);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        //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());
-
-        // 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);
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                //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());
+        
+                // 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(),
+                            volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid());
+                    _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
+                    _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage,
+                            new Long(volume.getSize()));
+                    volume.setAccountId(newAccount.getAccountId());
+                    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());
+                    //snapshots: mark these removed in db
+                    List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
+                    for (SnapshotVO snapshot: snapshots){
+                        _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(),
+                        VirtualMachine.class.getName(), vm.getUuid());
+            }
+        });
 
-        // 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());
-            _resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
-            _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);
-            _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());
-            for (SnapshotVO snapshot: snapshots){
-                _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(),
-                VirtualMachine.class.getName(), vm.getUuid());
-
-        txn.commit();
 
         VirtualMachine vmoi = _itMgr.findById(vm.getId());
         VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
index aa772fe..18f17b8 100644
--- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
+++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
@@ -29,7 +29,6 @@ import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
-
 import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd;
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
@@ -90,6 +89,10 @@ import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionCallbackWithException;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.fsm.NoTransitionException;
 import com.cloud.utils.fsm.StateMachine2;
@@ -482,31 +485,32 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
     }
     
     @DB
-    protected void processAnswer(VMSnapshotVO vmSnapshot, UserVmVO  userVm, Answer as, Long hostId) {
-        final Transaction txn = Transaction.currentTxn();
+    protected void processAnswer(final VMSnapshotVO vmSnapshot, UserVmVO  userVm, final Answer as, Long hostId) {
         try {
-            txn.start();
-            if (as instanceof CreateVMSnapshotAnswer) {
-                CreateVMSnapshotAnswer answer = (CreateVMSnapshotAnswer) as;
-                finalizeCreate(vmSnapshot, answer.getVolumeTOs());
-                vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
-            } else if (as instanceof RevertToVMSnapshotAnswer) {
-                RevertToVMSnapshotAnswer answer = (RevertToVMSnapshotAnswer) as;
-                finalizeRevert(vmSnapshot, answer.getVolumeTOs());
-                vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
-            } else if (as instanceof DeleteVMSnapshotAnswer) {
-                DeleteVMSnapshotAnswer answer = (DeleteVMSnapshotAnswer) as;
-                finalizeDelete(vmSnapshot, answer.getVolumeTOs());
-                _vmSnapshotDao.remove(vmSnapshot.getId());
-            }
-            txn.commit();
+            Transaction.executeWithException(new TransactionCallbackWithException<Object>() {
+                @Override
+                public Object doInTransaction(TransactionStatus status) throws NoTransitionException {
+                    if (as instanceof CreateVMSnapshotAnswer) {
+                        CreateVMSnapshotAnswer answer = (CreateVMSnapshotAnswer) as;
+                        finalizeCreate(vmSnapshot, answer.getVolumeTOs());
+                        vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
+                    } else if (as instanceof RevertToVMSnapshotAnswer) {
+                        RevertToVMSnapshotAnswer answer = (RevertToVMSnapshotAnswer) as;
+                        finalizeRevert(vmSnapshot, answer.getVolumeTOs());
+                        vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
+                    } else if (as instanceof DeleteVMSnapshotAnswer) {
+                        DeleteVMSnapshotAnswer answer = (DeleteVMSnapshotAnswer) as;
+                        finalizeDelete(vmSnapshot, answer.getVolumeTOs());
+                        _vmSnapshotDao.remove(vmSnapshot.getId());
+                    }
+                    
+                    return null;
+                }
+            }, NoTransitionException.class);
         } catch (Exception e) {
             String errMsg = "Error while process answer: " + as.getClass() + " due to " + e.getMessage();
             s_logger.error(errMsg, e);
-            txn.rollback();
             throw new CloudRuntimeException(errMsg);
-        } finally {
-            txn.close();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
index 8f2caad..b7b51c9 100644
--- a/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
+++ b/server/src/org/apache/cloudstack/affinity/AffinityGroupServiceImpl.java
@@ -34,12 +34,16 @@ import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupDomainMapDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
 import org.apache.cloudstack.context.CallContext;
-
 import org.apache.log4j.Logger;
 import org.springframework.context.annotation.Primary;
 
 
 
+
+
+
+
+
 import com.cloud.deploy.DeploymentPlanner;
 import com.cloud.domain.DomainVO;
 import com.cloud.domain.dao.DomainDao;
@@ -65,6 +69,9 @@ import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.fsm.StateListener;
 import com.cloud.vm.UserVmVO;
@@ -142,8 +149,8 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
 
     @DB
     @Override
-    public AffinityGroup createAffinityGroupInternal(String account, Long domainId, String affinityGroupName,
-            String affinityGroupType, String description) {
+    public AffinityGroup createAffinityGroupInternal(String account, final Long domainId, final String affinityGroupName,
+            final String affinityGroupType, final String description) {
 
         Account caller = CallContext.current().getCallingAccount();
 
@@ -159,7 +166,7 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
                     "Unable to create affinity group, no Affinity Group Types configured");
         }
 
-        AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
+        final AffinityGroupProcessor processor = typeProcessorMap.get(affinityGroupType);
 
         if (processor.isAdminControlledGroup() && !_accountMgr.isRootAdmin(caller.getType())) {
             throw new PermissionDeniedException("Cannot create the affinity group");
@@ -210,21 +217,26 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
                     + affinityGroupName + " already exisits under the domain.");
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        
-        AffinityGroupVO group = new AffinityGroupVO(affinityGroupName, affinityGroupType, description, owner.getDomainId(),
-                owner.getId(), aclType);
-        _affinityGroupDao.persist(group);
-
-        if (domainId != null && aclType == ACLType.Domain) {
-            boolean subDomainAccess = false;
-            subDomainAccess = processor.subDomainAccess();
-            AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId, subDomainAccess);
-            _affinityGroupDomainMapDao.persist(domainMap);
-        }
+        final Account ownerFinal = owner;
+        final ControlledEntity.ACLType aclTypeFinal = aclType;
+        AffinityGroupVO group = Transaction.execute(new TransactionCallback<AffinityGroupVO>() {
+            @Override
+            public AffinityGroupVO doInTransaction(TransactionStatus status) {
+                AffinityGroupVO group = new AffinityGroupVO(affinityGroupName, affinityGroupType, description, ownerFinal.getDomainId(),
+                        ownerFinal.getId(), aclTypeFinal);
+                _affinityGroupDao.persist(group);
+
+                if (domainId != null && aclTypeFinal == ACLType.Domain) {
+                    boolean subDomainAccess = false;
+                    subDomainAccess = processor.subDomainAccess();
+                    AffinityGroupDomainMapVO domainMap = new AffinityGroupDomainMapVO(group.getId(), domainId, subDomainAccess);
+                    _affinityGroupDomainMapDao.persist(domainMap);
+                }
 
-        txn.commit();
+                return group;
+            }
+        });
+        
 
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Created affinity group =" + affinityGroupName);
@@ -265,35 +277,38 @@ public class AffinityGroupServiceImpl extends ManagerBase implements AffinityGro
         // check permissions
         _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, group);
 
-        final Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        group = _affinityGroupDao.lockRow(affinityGroupId, true);
-        if (group == null) {
-            throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
-        }
-
-        List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupId);
-        if (!affinityGroupVmMap.isEmpty()) {
-            SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
-            listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(),
-                    SearchCriteria.Op.EQ);
-            listByAffinityGroup.done();
-            SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
-            sc.setParameters("affinityGroupId", affinityGroupId);
-
-            _affinityGroupVMMapDao.lockRows(sc, null, true);
-            _affinityGroupVMMapDao.remove(sc);
-        }
+        final Long affinityGroupIdFinal = affinityGroupId;
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
 
-        // call processor to handle the group delete
-        AffinityGroupProcessor processor = getAffinityGroupProcessorForType(group.getType());
-        if (processor != null) {
-            processor.handleDeleteGroup(group);
-        }
-
-        _affinityGroupDao.expunge(affinityGroupId);
-        txn.commit();
+                AffinityGroupVO group = _affinityGroupDao.lockRow(affinityGroupIdFinal, true);
+                if (group == null) {
+                    throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupIdFinal);
+                }
+        
+                List<AffinityGroupVMMapVO> affinityGroupVmMap = _affinityGroupVMMapDao.listByAffinityGroup(affinityGroupIdFinal);
+                if (!affinityGroupVmMap.isEmpty()) {
+                    SearchBuilder<AffinityGroupVMMapVO> listByAffinityGroup = _affinityGroupVMMapDao.createSearchBuilder();
+                    listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(),
+                            SearchCriteria.Op.EQ);
+                    listByAffinityGroup.done();
+                    SearchCriteria<AffinityGroupVMMapVO> sc = listByAffinityGroup.create();
+                    sc.setParameters("affinityGroupId", affinityGroupIdFinal);
+        
+                    _affinityGroupVMMapDao.lockRows(sc, null, true);
+                    _affinityGroupVMMapDao.remove(sc);
+                }
+        
+                // call processor to handle the group delete
+                AffinityGroupProcessor processor = getAffinityGroupProcessorForType(group.getType());
+                if (processor != null) {
+                    processor.handleDeleteGroup(group);
+                }
+        
+                _affinityGroupDao.expunge(affinityGroupIdFinal);
+            }
+        });
 
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Deleted affinity group id=" + affinityGroupId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
index 2385edc..c9db371 100644
--- a/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
+++ b/server/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerManagerImpl.java
@@ -26,7 +26,6 @@ import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
-
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.command.user.loadbalancer.ListApplicationLoadBalancersCmd;
 import org.apache.cloudstack.context.CallContext;
@@ -72,6 +71,9 @@ import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackWithException;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.Ip;
 import com.cloud.utils.net.NetUtils;
@@ -156,30 +158,33 @@ public class ApplicationLoadBalancerManagerImpl extends ManagerBase implements A
 
     
     @DB
-    protected ApplicationLoadBalancerRule persistLbRule(ApplicationLoadBalancerRuleVO newRule) throws NetworkRuleConflictException {
-        
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        
-        //1) Persist the rule
-        newRule = _lbDao.persist(newRule);
+    protected ApplicationLoadBalancerRule persistLbRule(final ApplicationLoadBalancerRuleVO newRuleFinal) throws NetworkRuleConflictException {
         boolean success = true;
-
+        ApplicationLoadBalancerRuleVO newRule = null;
         try {
-            //2) Detect conflicts
-            detectLbRulesConflicts(newRule);
-            if (!_firewallDao.setStateToAdd(newRule)) {
-                throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
-            }
-            s_logger.debug("Load balancer " + newRule.getId() + " for Ip address " + newRule.getSourceIp().addr() + ", source port "
-                    + newRule.getSourcePortStart() + ", instance port " + newRule.getDefaultPortStart() + " is added successfully.");
-            CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
-            Network ntwk = _networkModel.getNetwork(newRule.getNetworkId());
-            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, newRule.getAccountId(),
-                    ntwk.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(),
-                    newRule.getUuid());
-            txn.commit();
-
+            newRule = Transaction.executeWithException(new TransactionCallbackWithException<ApplicationLoadBalancerRuleVO>() {
+                @Override
+                public ApplicationLoadBalancerRuleVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
+                    //1) Persist the rule
+                    ApplicationLoadBalancerRuleVO newRule = _lbDao.persist(newRuleFinal);
+
+                    //2) Detect conflicts
+                    detectLbRulesConflicts(newRule);
+                    if (!_firewallDao.setStateToAdd(newRule)) {
+                        throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
+                    }
+                    s_logger.debug("Load balancer " + newRule.getId() + " for Ip address " + newRule.getSourceIp().addr() + ", source port "
+                            + newRule.getSourcePortStart() + ", instance port " + newRule.getDefaultPortStart() + " is added successfully.");
+                    CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
+                    Network ntwk = _networkModel.getNetwork(newRule.getNetworkId());
+                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, newRule.getAccountId(),
+                            ntwk.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(),
+                            newRule.getUuid());
+                    
+                    return newRule;
+                }
+            }, NetworkRuleConflictException.class);
+            
             return newRule;
         } catch (Exception e) {
             success = false;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
index 25a40ee..62b9748 100644
--- a/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
+++ b/server/src/org/apache/cloudstack/region/gslb/GlobalLoadBalancingRulesServiceImpl.java
@@ -37,6 +37,9 @@ import com.cloud.user.AccountManager;
 import com.cloud.utils.Pair;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
 
@@ -46,7 +49,6 @@ import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.region.dao.RegionDao;
-
 import org.apache.log4j.Logger;
 
 import javax.ejb.Local;
@@ -94,15 +96,15 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             "balancer rule", create = true)
     public GlobalLoadBalancerRule createGlobalLoadBalancerRule(CreateGlobalLoadBalancerRuleCmd newRule) {
 
-        Integer regionId = newRule.getRegionId();
-        String algorithm = newRule.getAlgorithm();
-        String stickyMethod = newRule.getStickyMethod();
-        String name = newRule.getName();
-        String description = newRule.getDescription();
-        String domainName = newRule.getServiceDomainName();
-        String serviceType = newRule.getServiceType();
+        final Integer regionId = newRule.getRegionId();
+        final String algorithm = newRule.getAlgorithm();
+        final String stickyMethod = newRule.getStickyMethod();
+        final String name = newRule.getName();
+        final String description = newRule.getDescription();
+        final String domainName = newRule.getServiceDomainName();
+        final String serviceType = newRule.getServiceType();
 
-        Account gslbOwner = _accountMgr.getAccount(newRule.getEntityOwnerId());
+        final Account gslbOwner = _accountMgr.getAccount(newRule.getEntityOwnerId());
 
         if (!GlobalLoadBalancerRule.Algorithm.isValidAlgorithm(algorithm)) {
             throw new InvalidParameterValueException("Invalid Algorithm: " + algorithm);
@@ -135,18 +137,21 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             throw new CloudRuntimeException("GSLB service is not enabled in region : " + region.getName());
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        GlobalLoadBalancerRuleVO newGslbRule = new GlobalLoadBalancerRuleVO(name, description, domainName, algorithm,
-                stickyMethod, serviceType, regionId, gslbOwner.getId(), gslbOwner.getDomainId(),
-                GlobalLoadBalancerRule.State.Staged);
-        _gslbRuleDao.persist(newGslbRule);
+        GlobalLoadBalancerRuleVO newGslbRule = Transaction.execute(new TransactionCallback<GlobalLoadBalancerRuleVO>() {
+            @Override
+            public GlobalLoadBalancerRuleVO doInTransaction(TransactionStatus status) {
+                GlobalLoadBalancerRuleVO newGslbRule = new GlobalLoadBalancerRuleVO(name, description, domainName, algorithm,
+                        stickyMethod, serviceType, regionId, gslbOwner.getId(), gslbOwner.getDomainId(),
+                        GlobalLoadBalancerRule.State.Staged);
+                _gslbRuleDao.persist(newGslbRule);
 
-        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_GLOBAL_LOAD_BALANCER_CREATE, newGslbRule.getAccountId(),
-                0, newGslbRule.getId(), name, GlobalLoadBalancerRule.class.getName(),
-                newGslbRule.getUuid());
+                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_GLOBAL_LOAD_BALANCER_CREATE, newGslbRule.getAccountId(),
+                        0, newGslbRule.getId(), name, GlobalLoadBalancerRule.class.getName(),
+                        newGslbRule.getUuid());
 
-        txn.commit();
+                return newGslbRule;
+            }
+        });
 
         s_logger.debug("successfully created new global load balancer rule for the account " + gslbOwner.getId());
 
@@ -162,8 +167,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
         CallContext ctx = CallContext.current();
         Account caller = ctx.getCallingAccount();
 
-        long gslbRuleId =  assignToGslbCmd.getGlobalLoadBalancerRuleId();
-        GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
+        final long gslbRuleId =  assignToGslbCmd.getGlobalLoadBalancerRuleId();
+        final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
         if (gslbRule == null) {
             throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
         }
@@ -175,7 +180,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
                     + " is in revoked state");
         }
 
-        List<Long> newLbRuleIds = assignToGslbCmd.getLoadBalancerRulesIds();
+        final List<Long> newLbRuleIds = assignToGslbCmd.getLoadBalancerRulesIds();
         if (newLbRuleIds == null || newLbRuleIds.isEmpty()) {
             throw new InvalidParameterValueException("empty list of load balancer rule Ids specified to be assigned"
             + " global load balancer rule");
@@ -244,30 +249,31 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             }
         }
 
-        Map<Long, Long> lbRuleWeightMap = assignToGslbCmd.getLoadBalancerRuleWeightMap();
-
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        // persist the mapping for the new Lb rule that needs to assigned to a gslb rule
-        for (Long lbRuleId : newLbRuleIds) {
-            GlobalLoadBalancerLbRuleMapVO newGslbLbMap = new GlobalLoadBalancerLbRuleMapVO();
-            newGslbLbMap.setGslbLoadBalancerId(gslbRuleId);
-            newGslbLbMap.setLoadBalancerId(lbRuleId);
-            if (lbRuleWeightMap != null && lbRuleWeightMap.get(lbRuleId) != null) {
-                newGslbLbMap.setWeight(lbRuleWeightMap.get(lbRuleId));
+        final Map<Long, Long> lbRuleWeightMap = assignToGslbCmd.getLoadBalancerRuleWeightMap();
+
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                // persist the mapping for the new Lb rule that needs to assigned to a gslb rule
+                for (Long lbRuleId : newLbRuleIds) {
+                    GlobalLoadBalancerLbRuleMapVO newGslbLbMap = new GlobalLoadBalancerLbRuleMapVO();
+                    newGslbLbMap.setGslbLoadBalancerId(gslbRuleId);
+                    newGslbLbMap.setLoadBalancerId(lbRuleId);
+                    if (lbRuleWeightMap != null && lbRuleWeightMap.get(lbRuleId) != null) {
+                        newGslbLbMap.setWeight(lbRuleWeightMap.get(lbRuleId));
+                    }
+                    _gslbLbMapDao.persist(newGslbLbMap);
+                }
+        
+                // mark the gslb rule state as add
+                if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged || gslbRule.getState() ==
+                        GlobalLoadBalancerRule.State.Active ) {
+                    gslbRule.setState(GlobalLoadBalancerRule.State.Add);
+                    _gslbRuleDao.update(gslbRule.getId(), gslbRule);
+                }
             }
-            _gslbLbMapDao.persist(newGslbLbMap);
-        }
-
-        // mark the gslb rule state as add
-        if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged || gslbRule.getState() ==
-                GlobalLoadBalancerRule.State.Active ) {
-            gslbRule.setState(GlobalLoadBalancerRule.State.Add);
-            _gslbRuleDao.update(gslbRule.getId(), gslbRule);
-        }
+        });
 
-        txn.commit();
 
         boolean success = false;
         try {
@@ -304,8 +310,8 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
         CallContext ctx = CallContext.current();
         Account caller = ctx.getCallingAccount();
 
-        long gslbRuleId =  removeFromGslbCmd.getGlobalLoadBalancerRuleId();
-        GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
+        final long gslbRuleId =  removeFromGslbCmd.getGlobalLoadBalancerRuleId();
+        final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
         if (gslbRule == null) {
             throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
         }
@@ -316,7 +322,7 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             throw new InvalidParameterValueException("global load balancer rule id: " + gslbRuleId + " is already in revoked state");
         }
 
-        List<Long> lbRuleIdsToremove = removeFromGslbCmd.getLoadBalancerRulesIds();
+        final List<Long> lbRuleIdsToremove = removeFromGslbCmd.getLoadBalancerRulesIds();
         if (lbRuleIdsToremove == null || lbRuleIdsToremove.isEmpty()) {
             throw new InvalidParameterValueException("empty list of load balancer rule Ids specified to be un-assigned"
                     + " to global load balancer rule");
@@ -356,23 +362,24 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             }
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        // update the mapping of gslb rule to Lb rule, to revoke state
-        for (Long lbRuleId : lbRuleIdsToremove) {
-            GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
-            removeGslbLbMap.setRevoke(true);
-            _gslbLbMapDao.update(removeGslbLbMap.getId(), removeGslbLbMap);
-        }
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                // update the mapping of gslb rule to Lb rule, to revoke state
+                for (Long lbRuleId : lbRuleIdsToremove) {
+                    GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
+                    removeGslbLbMap.setRevoke(true);
+                    _gslbLbMapDao.update(removeGslbLbMap.getId(), removeGslbLbMap);
+                }
 
-        // mark the gslb rule state as add
-        if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged) {
-            gslbRule.setState(GlobalLoadBalancerRule.State.Add);
-            _gslbRuleDao.update(gslbRule.getId(), gslbRule);
-        }
+                // mark the gslb rule state as add
+                if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged) {
+                    gslbRule.setState(GlobalLoadBalancerRule.State.Add);
+                    _gslbRuleDao.update(gslbRule.getId(), gslbRule);
+                }
 
-        txn.commit();
+            }
+        });
 
         boolean success = false;
         try {
@@ -387,19 +394,21 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
                 throw ex;
             }
 
-            txn.start();
-
-            // remove the mappings of gslb rule to Lb rule that are in revoked state
-            for (Long lbRuleId : lbRuleIdsToremove) {
-                GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
-                _gslbLbMapDao.remove(removeGslbLbMap.getId());
-            }
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    // remove the mappings of gslb rule to Lb rule that are in revoked state
+                    for (Long lbRuleId : lbRuleIdsToremove) {
+                        GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
+                        _gslbLbMapDao.remove(removeGslbLbMap.getId());
+                    }
 
-            // on success set state back to Active
-            gslbRule.setState(GlobalLoadBalancerRule.State.Active);
-            _gslbRuleDao.update(gslbRule.getId(), gslbRule);
+                    // on success set state back to Active
+                    gslbRule.setState(GlobalLoadBalancerRule.State.Active);
+                    _gslbRuleDao.update(gslbRule.getId(), gslbRule);
 
-            txn.commit();
+                }
+            });
 
             success = true;
         } catch (ResourceUnavailableException e) {
@@ -429,9 +438,9 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
     }
 
     @DB
-    private void revokeGslbRule(long gslbRuleId, Account caller) {
+    private void revokeGslbRule(final long gslbRuleId, Account caller) {
 
-        GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
+        final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
 
         if (gslbRule == null) {
             throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
@@ -454,19 +463,21 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             _gslbRuleDao.update(gslbRuleId, gslbRule);
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
-        if (gslbLbMapVos != null) {
-            //mark all the GSLB-LB mapping to be in revoke state
-            for (GlobalLoadBalancerLbRuleMapVO gslbLbMap : gslbLbMapVos) {
-                gslbLbMap.setRevoke(true);
-                _gslbLbMapDao.update(gslbLbMap.getId(), gslbLbMap);
+        final List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = Transaction.execute(new TransactionCallback<List<GlobalLoadBalancerLbRuleMapVO>>() {
+            @Override
+            public List<GlobalLoadBalancerLbRuleMapVO> doInTransaction(TransactionStatus status) {
+                List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
+                if (gslbLbMapVos != null) {
+                    //mark all the GSLB-LB mapping to be in revoke state
+                    for (GlobalLoadBalancerLbRuleMapVO gslbLbMap : gslbLbMapVos) {
+                        gslbLbMap.setRevoke(true);
+                        _gslbLbMapDao.update(gslbLbMap.getId(), gslbLbMap);
+                    }
+                }
+                
+                return gslbLbMapVos;
             }
-        }
-
-        txn.commit();
+        });
 
         boolean success = false;
         try {
@@ -478,22 +489,25 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             throw new CloudRuntimeException("Failed to update the gloabal load balancer");
         }
 
-        txn.start();
-        //remove all mappings between GSLB rule and load balancer rules
-        if (gslbLbMapVos != null) {
-            for (GlobalLoadBalancerLbRuleMapVO gslbLbMap : gslbLbMapVos) {
-                _gslbLbMapDao.remove(gslbLbMap.getId());
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                //remove all mappings between GSLB rule and load balancer rules
+                if (gslbLbMapVos != null) {
+                    for (GlobalLoadBalancerLbRuleMapVO gslbLbMap : gslbLbMapVos) {
+                        _gslbLbMapDao.remove(gslbLbMap.getId());
+                    }
+                }
+        
+                //remove the GSLB rule itself
+                _gslbRuleDao.remove(gslbRuleId);
+        
+                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_GLOBAL_LOAD_BALANCER_DELETE, gslbRule.getAccountId(),
+                        0, gslbRule.getId(), gslbRule.getName(), GlobalLoadBalancerRule.class.getName(),
+                        gslbRule.getUuid());
             }
-        }
-
-        //remove the GSLB rule itself
-        _gslbRuleDao.remove(gslbRuleId);
-
-        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_GLOBAL_LOAD_BALANCER_DELETE, gslbRule.getAccountId(),
-                0, gslbRule.getId(), gslbRule.getName(), GlobalLoadBalancerRule.class.getName(),
-                gslbRule.getUuid());
+        });
 
-        txn.commit();
     }
 
     @Override
@@ -523,8 +537,6 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
             throw new InvalidParameterValueException("Invalid persistence: " + stickyMethod);
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
         if (algorithm != null) {
             gslbRule.setAlgorithm(algorithm);
         }
@@ -536,7 +548,6 @@ public class GlobalLoadBalancingRulesServiceImpl implements GlobalLoadBalancingR
         }
         gslbRule.setState(GlobalLoadBalancerRule.State.Add);
         _gslbRuleDao.update(gslbRule.getId(), gslbRule);
-        txn.commit();
 
         try {
             s_logger.debug("Updating global load balancer with id " + gslbRule.getUuid());


Mime
View raw message