cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dar...@apache.org
Subject [28/47] New Transaction API
Date Wed, 23 Oct 2013 19:43:45 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/SyncQueueManagerImpl.java
----------------------------------------------------------------------
diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/SyncQueueManagerImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/SyncQueueManagerImpl.java
index b9b5d6b..7fb0245 100644
--- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/SyncQueueManagerImpl.java
+++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/SyncQueueManagerImpl.java
@@ -21,8 +21,8 @@ import java.util.Date;
 import java.util.List;
 
 import javax.inject.Inject;
-import org.apache.log4j.Logger;
 
+import org.apache.log4j.Logger;
 import org.apache.cloudstack.framework.jobs.dao.SyncQueueDao;
 import org.apache.cloudstack.framework.jobs.dao.SyncQueueItemDao;
 
@@ -30,6 +30,9 @@ import com.cloud.utils.DateUtil;
 import com.cloud.utils.component.ManagerBase;
 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;
 
 public class SyncQueueManagerImpl extends ManagerBase implements SyncQueueManager {
@@ -40,84 +43,83 @@ public class SyncQueueManagerImpl extends ManagerBase implements SyncQueueManage
 
     @Override
     @DB
-    public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId, long queueSizeLimit) {
-        Transaction txn = Transaction.currentTxn();
+    public SyncQueueVO queue(final String syncObjType, final long syncObjId, final String itemType, final long itemId, final long queueSizeLimit) {
         try {
-            txn.start();
-
-            _syncQueueDao.ensureQueue(syncObjType, syncObjId);
-            SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId);
-            if(queueVO == null)
-                throw new CloudRuntimeException("Unable to queue item into DB, DB is full?");
-
-            queueVO.setQueueSizeLimit(queueSizeLimit);
-            _syncQueueDao.update(queueVO.getId(), queueVO);
-
-            Date dt = DateUtil.currentGMTTime();
-            SyncQueueItemVO item = new SyncQueueItemVO();
-            item.setQueueId(queueVO.getId());
-            item.setContentType(itemType);
-            item.setContentId(itemId);
-            item.setCreated(dt);
-
-            _syncQueueItemDao.persist(item);
-            txn.commit();
+            return Transaction.execute(new TransactionCallback<SyncQueueVO>() {
+                @Override
+                public SyncQueueVO doInTransaction(TransactionStatus status) {
+                    _syncQueueDao.ensureQueue(syncObjType, syncObjId);
+                    SyncQueueVO queueVO = _syncQueueDao.find(syncObjType, syncObjId);
+                    if(queueVO == null)
+                        throw new CloudRuntimeException("Unable to queue item into DB, DB is full?");
+
+                    queueVO.setQueueSizeLimit(queueSizeLimit);
+                    _syncQueueDao.update(queueVO.getId(), queueVO);
 
-            return queueVO;
+                    Date dt = DateUtil.currentGMTTime();
+                    SyncQueueItemVO item = new SyncQueueItemVO();
+                    item.setQueueId(queueVO.getId());
+                    item.setContentType(itemType);
+                    item.setContentId(itemId);
+                    item.setCreated(dt);
+
+                    _syncQueueItemDao.persist(item);
+                    return queueVO;
+                }
+            });
         } catch(Exception e) {
             s_logger.error("Unexpected exception: ", e);
-            txn.rollback();
         }
         return null;
     }
 
     @Override
     @DB
-    public SyncQueueItemVO dequeueFromOne(long queueId, Long msid) {
-        Transaction txt = Transaction.currentTxn();
+    public SyncQueueItemVO dequeueFromOne(final long queueId, final Long msid) {
         try {
-            txt.start();
-
-            SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true);
-            if(queueVO == null) {
-                s_logger.error("Sync queue(id: " + queueId + ") does not exist");
-                txt.commit();
-                return null;
-            }
-
-            if(queueReadyToProcess(queueVO)) {
-                SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId());
-                if(itemVO != null) {
-                    Long processNumber = queueVO.getLastProcessNumber();
-                    if(processNumber == null)
-                        processNumber = new Long(1);
-                    else
-                        processNumber = processNumber + 1;
-                    Date dt = DateUtil.currentGMTTime();
-                    queueVO.setLastProcessNumber(processNumber);
-                    queueVO.setLastUpdated(dt);
-                    queueVO.setQueueSize(queueVO.getQueueSize() + 1);
-                    _syncQueueDao.update(queueVO.getId(), queueVO);
+            return Transaction.execute(new TransactionCallback<SyncQueueItemVO>() {
+                @Override
+                public SyncQueueItemVO doInTransaction(TransactionStatus status) {
+                    SyncQueueVO queueVO = _syncQueueDao.lockRow(queueId, true);
+                    if(queueVO == null) {
+                        s_logger.error("Sync queue(id: " + queueId + ") does not exist");
+                        return null;
+                    }
 
-                    itemVO.setLastProcessMsid(msid);
-                    itemVO.setLastProcessNumber(processNumber);
-                    itemVO.setLastProcessTime(dt);
-                    _syncQueueItemDao.update(itemVO.getId(), itemVO);
+                    if(queueReadyToProcess(queueVO)) {
+                        SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId());
+                        if(itemVO != null) {
+                            Long processNumber = queueVO.getLastProcessNumber();
+                            if(processNumber == null)
+                                processNumber = new Long(1);
+                            else
+                                processNumber = processNumber + 1;
+                            Date dt = DateUtil.currentGMTTime();
+                            queueVO.setLastProcessNumber(processNumber);
+                            queueVO.setLastUpdated(dt);
+                            queueVO.setQueueSize(queueVO.getQueueSize() + 1);
+                            _syncQueueDao.update(queueVO.getId(), queueVO);
+
+                            itemVO.setLastProcessMsid(msid);
+                            itemVO.setLastProcessNumber(processNumber);
+                            itemVO.setLastProcessTime(dt);
+                            _syncQueueItemDao.update(itemVO.getId(), itemVO);
+
+                            return itemVO;
+                        } else {
+                            if(s_logger.isDebugEnabled())
+                                s_logger.debug("Sync queue (" + queueId + ") is currently empty");
+                        }
+                    } else {
+                        if(s_logger.isDebugEnabled())
+                            s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")");
+                    }
 
-                    txt.commit();
-                    return itemVO;
-                } else {
-                    if(s_logger.isDebugEnabled())
-                        s_logger.debug("Sync queue (" + queueId + ") is currently empty");
+                    return null;
                 }
-            } else {
-                if(s_logger.isDebugEnabled())
-                    s_logger.debug("There is a pending process in sync queue(id: " + queueId + ")");
-            }
-            txt.commit();
+            });
         } catch(Exception e) {
             s_logger.error("Unexpected exception: ", e);
-            txt.rollback();
         }
 
         return null;
@@ -125,101 +127,104 @@ public class SyncQueueManagerImpl extends ManagerBase implements SyncQueueManage
 
     @Override
     @DB
-    public List<SyncQueueItemVO> dequeueFromAny(Long msid, int maxItems) {
-
-        List<SyncQueueItemVO> resultList = new ArrayList<SyncQueueItemVO>();
-        Transaction txt = Transaction.currentTxn();
-        try {
-            txt.start();
+    public List<SyncQueueItemVO> dequeueFromAny(final Long msid, final int maxItems) {
 
-            List<SyncQueueItemVO> l = _syncQueueItemDao.getNextQueueItems(maxItems);
-            if(l != null && l.size() > 0) {
-                for(SyncQueueItemVO item : l) {
-                    SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true);
-                    SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true);
-                    if(queueReadyToProcess(queueVO) && itemVO.getLastProcessNumber() == null) {
-                        Long processNumber = queueVO.getLastProcessNumber();
-                        if(processNumber == null)
-                            processNumber = new Long(1);
-                        else
-                            processNumber = processNumber + 1;
+        final List<SyncQueueItemVO> resultList = new ArrayList<SyncQueueItemVO>();
 
-                        Date dt = DateUtil.currentGMTTime();
-                        queueVO.setLastProcessNumber(processNumber);
-                        queueVO.setLastUpdated(dt);
-                        queueVO.setQueueSize(queueVO.getQueueSize() + 1);
-                        _syncQueueDao.update(queueVO.getId(), queueVO);
-
-                        itemVO.setLastProcessMsid(msid);
-                        itemVO.setLastProcessNumber(processNumber);
-                        itemVO.setLastProcessTime(dt);
-                        _syncQueueItemDao.update(item.getId(), itemVO);
-
-                        resultList.add(item);
+        try {
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    List<SyncQueueItemVO> l = _syncQueueItemDao.getNextQueueItems(maxItems);
+                    if(l != null && l.size() > 0) {
+                        for(SyncQueueItemVO item : l) {
+                            SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true);
+                            SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true);
+                            if(queueReadyToProcess(queueVO) && itemVO.getLastProcessNumber() == null) {
+                                Long processNumber = queueVO.getLastProcessNumber();
+                                if(processNumber == null)
+                                    processNumber = new Long(1);
+                                else
+                                    processNumber = processNumber + 1;
+        
+                                Date dt = DateUtil.currentGMTTime();
+                                queueVO.setLastProcessNumber(processNumber);
+                                queueVO.setLastUpdated(dt);
+                                queueVO.setQueueSize(queueVO.getQueueSize() + 1);
+                                _syncQueueDao.update(queueVO.getId(), queueVO);
+        
+                                itemVO.setLastProcessMsid(msid);
+                                itemVO.setLastProcessNumber(processNumber);
+                                itemVO.setLastProcessTime(dt);
+                                _syncQueueItemDao.update(item.getId(), itemVO);
+        
+                                resultList.add(item);
+                            }
+                        }
                     }
                 }
-            }
-            txt.commit();
+            });
+
             return resultList;
         } catch(Exception e) {
             s_logger.error("Unexpected exception: ", e);
-            txt.rollback();
         }
+
         return null;
     }
 
     @Override
     @DB
-    public void purgeItem(long queueItemId) {
-        Transaction txt = Transaction.currentTxn();
+    public void purgeItem(final long queueItemId) {
         try {
-            txt.start();
-
-            SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
-            if(itemVO != null) {
-                SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
-
-                _syncQueueItemDao.expunge(itemVO.getId());
-
-                // if item is active, reset queue information
-                if (itemVO.getLastProcessMsid() != null) {
-                    queueVO.setLastUpdated(DateUtil.currentGMTTime());
-                    // decrement the count
-                    assert (queueVO.getQueueSize() > 0) : "Count reduce happens when it's already <= 0!";
-                    queueVO.setQueueSize(queueVO.getQueueSize() - 1);
-                    _syncQueueDao.update(queueVO.getId(), queueVO);
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
+                    if(itemVO != null) {
+                        SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
+        
+                        _syncQueueItemDao.expunge(itemVO.getId());
+        
+                        // if item is active, reset queue information
+                        if (itemVO.getLastProcessMsid() != null) {
+                            queueVO.setLastUpdated(DateUtil.currentGMTTime());
+                            // decrement the count
+                            assert (queueVO.getQueueSize() > 0) : "Count reduce happens when it's already <= 0!";
+                            queueVO.setQueueSize(queueVO.getQueueSize() - 1);
+                            _syncQueueDao.update(queueVO.getId(), queueVO);
+                        }
+                    }
                 }
-            }
-            txt.commit();
+            });
         } catch(Exception e) {
             s_logger.error("Unexpected exception: ", e);
-            txt.rollback();
         }
     }
 
     @Override
     @DB
-    public void returnItem(long queueItemId) {
-        Transaction txt = Transaction.currentTxn();
+    public void returnItem(final long queueItemId) {
         try {
-            txt.start();
-
-            SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
-            if(itemVO != null) {
-                SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
-
-                itemVO.setLastProcessMsid(null);
-                itemVO.setLastProcessNumber(null);
-                itemVO.setLastProcessTime(null);
-                _syncQueueItemDao.update(queueItemId, itemVO);
-
-                queueVO.setLastUpdated(DateUtil.currentGMTTime());
-                _syncQueueDao.update(queueVO.getId(), queueVO);
-            }
-            txt.commit();
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    SyncQueueItemVO itemVO = _syncQueueItemDao.findById(queueItemId);
+                    if(itemVO != null) {
+                        SyncQueueVO queueVO = _syncQueueDao.lockRow(itemVO.getQueueId(), true);
+
+                        itemVO.setLastProcessMsid(null);
+                        itemVO.setLastProcessNumber(null);
+                        itemVO.setLastProcessTime(null);
+                        _syncQueueItemDao.update(queueItemId, itemVO);
+
+                        queueVO.setLastUpdated(DateUtil.currentGMTTime());
+                        _syncQueueDao.update(queueVO.getId(), queueVO);
+                    }
+                }
+            });
         } catch(Exception e) {
             s_logger.error("Unexpected exception: ", e);
-            txt.rollback();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/affinity-group-processors/explicit-dedication/src/org/apache/cloudstack/affinity/ExplicitDedicationProcessor.java
----------------------------------------------------------------------
diff --git a/plugins/affinity-group-processors/explicit-dedication/src/org/apache/cloudstack/affinity/ExplicitDedicationProcessor.java b/plugins/affinity-group-processors/explicit-dedication/src/org/apache/cloudstack/affinity/ExplicitDedicationProcessor.java
index da23172..cc1d3f3 100644
--- a/plugins/affinity-group-processors/explicit-dedication/src/org/apache/cloudstack/affinity/ExplicitDedicationProcessor.java
+++ b/plugins/affinity-group-processors/explicit-dedication/src/org/apache/cloudstack/affinity/ExplicitDedicationProcessor.java
@@ -24,7 +24,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
 
@@ -48,6 +47,8 @@ import com.cloud.utils.db.DB;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachineProfile;
@@ -410,7 +411,7 @@ public class ExplicitDedicationProcessor extends AffinityProcessorBase implement
 
     @DB
     @Override
-    public void handleDeleteGroup(AffinityGroup group) {
+    public void handleDeleteGroup(final AffinityGroup group) {
         // When a group of the 'ExplicitDedication' type gets deleted, make sure
         // to remove the dedicated resources in the group as well.
         if (group != null) {
@@ -419,20 +420,21 @@ public class ExplicitDedicationProcessor extends AffinityProcessorBase implement
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("Releasing the dedicated resources under group: " + group);
                 }
-                Transaction txn = Transaction.currentTxn();
-                txn.start();
-
-                SearchBuilder<DedicatedResourceVO> listByAffinityGroup = _dedicatedDao.createSearchBuilder();
-                listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(),
-                        SearchCriteria.Op.EQ);
-                listByAffinityGroup.done();
-                SearchCriteria<DedicatedResourceVO> sc = listByAffinityGroup.create();
-                sc.setParameters("affinityGroupId", group.getId());
 
-                _dedicatedDao.lockRows(sc, null, true);
-                _dedicatedDao.remove(sc);
-
-                txn.commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        SearchBuilder<DedicatedResourceVO> listByAffinityGroup = _dedicatedDao.createSearchBuilder();
+                        listByAffinityGroup.and("affinityGroupId", listByAffinityGroup.entity().getAffinityGroupId(),
+                                SearchCriteria.Op.EQ);
+                        listByAffinityGroup.done();
+                        SearchCriteria<DedicatedResourceVO> sc = listByAffinityGroup.create();
+                        sc.setParameters("affinityGroupId", group.getId());
+        
+                        _dedicatedDao.lockRows(sc, null, true);
+                        _dedicatedDao.remove(sc);
+                    }
+                });
             } else {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("No dedicated resources to releease under group: " + group);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java b/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
index 6a6b47c..cda46ef 100755
--- a/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
+++ b/plugins/dedicated-resources/src/org/apache/cloudstack/dedicated/DedicatedResourceManagerImpl.java
@@ -48,7 +48,6 @@ import org.apache.cloudstack.api.response.DedicatePodResponse;
 import org.apache.cloudstack.api.response.DedicateZoneResponse;
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
-
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -79,6 +78,9 @@ import com.cloud.utils.NumbersUtil;
 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.vm.UserVmVO;
 import com.cloud.vm.dao.UserVmDao;
@@ -113,7 +115,7 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Zone")
-    public List<DedicatedResourceVO> dedicateZone(Long zoneId, Long domainId, String accountName) {
+    public List<DedicatedResourceVO> dedicateZone(final Long zoneId, final Long domainId, final String accountName) {
         Long accountId = null;
         List<HostVO> hosts = null;
         if(accountName != null){
@@ -124,7 +126,7 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
         List<Long> childDomainIds = getDomainChildIds(domainId);
         childDomainIds.add(domainId);
         checkAccountAndDomain(accountId, domainId);
-        DataCenterVO dc = _zoneDao.findById(zoneId);
+        final DataCenterVO dc = _zoneDao.findById(zoneId);
         if (dc == null) {
             throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
         } else {
@@ -220,46 +222,50 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
 
         checkHostsSuitabilityForExplicitDedication(accountId, childDomainIds, hosts);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        // find or create the affinity group by name under this account/domain
-        AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountId);
-        if (group == null) {
-            s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
-            throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
-        }
+        final Long accountIdFinal = accountId;
+        return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {
+            @Override
+            public List<DedicatedResourceVO> doInTransaction(TransactionStatus status) {
+                // find or create the affinity group by name under this account/domain
+                AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
+                if (group == null) {
+                    s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
+                    throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
+                }
 
-        DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zoneId, null, null, null, null, null,
-                group.getId());
-        try {
-            dedicatedResource.setDomainId(domainId);
-            if (accountId != null) {
-                dedicatedResource.setAccountId(accountId);
-            }
-            dedicatedResource = _dedicatedDao.persist(dedicatedResource);
+                DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zoneId, null, null, null, null, null,
+                        group.getId());
+                try {
+                    dedicatedResource.setDomainId(domainId);
+                    if (accountIdFinal != null) {
+                        dedicatedResource.setAccountId(accountIdFinal);
+                    }
+                    dedicatedResource = _dedicatedDao.persist(dedicatedResource);
 
-            // save the domainId in the zone
-            dc.setDomainId(domainId);
-            if (!_zoneDao.update(zoneId, dc)) {
-                throw new CloudRuntimeException(
-                        "Failed to dedicate zone, could not set domainId. Please contact Cloud Support.");
-            }
+                    // save the domainId in the zone
+                    dc.setDomainId(domainId);
+                    if (!_zoneDao.update(zoneId, dc)) {
+                        throw new CloudRuntimeException(
+                                "Failed to dedicate zone, could not set domainId. Please contact Cloud Support.");
+                    }
 
-        } catch (Exception e) {
-            s_logger.error("Unable to dedicate zone due to " + e.getMessage(), e);
-            throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
-        }
-        txn.commit();
+                } catch (Exception e) {
+                    s_logger.error("Unable to dedicate zone due to " + e.getMessage(), e);
+                    throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
+                }
+
+                List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
+                result.add(dedicatedResource);
+                return result;
 
-        List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
-        result.add(dedicatedResource);
-        return result;
+            }
+        });
     }
 
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Pod")
-    public List<DedicatedResourceVO> dedicatePod(Long podId, Long domainId, String accountName) {
+    public List<DedicatedResourceVO> dedicatePod(final Long podId, final Long domainId, final String accountName) {
         Long accountId = null;
         if(accountName != null){
             Account caller = CallContext.current().getCallingAccount();
@@ -353,37 +359,40 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
 
         checkHostsSuitabilityForExplicitDedication(accountId, childDomainIds, hosts);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        // find or create the affinity group by name under this account/domain
-        AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountId);
-        if (group == null) {
-            s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
-            throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
-        }
-        DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, podId, null, null, null, null,
-                group.getId());
-        try {
-            dedicatedResource.setDomainId(domainId);
-            if (accountId != null) {
-                dedicatedResource.setAccountId(accountId);
-            }
-            dedicatedResource = _dedicatedDao.persist(dedicatedResource);
-        } catch (Exception e) {
-            s_logger.error("Unable to dedicate pod due to " + e.getMessage(), e);
-            throw new CloudRuntimeException("Failed to dedicate pod. Please contact Cloud Support.");
-        }
-        txn.commit();
+        final Long accountIdFinal = accountId;
+        return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {
+            @Override
+            public List<DedicatedResourceVO> doInTransaction(TransactionStatus status) {
+                // find or create the affinity group by name under this account/domain
+                AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
+                if (group == null) {
+                    s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
+                    throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
+                }
+                DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, podId, null, null, null, null,
+                        group.getId());
+                try {
+                    dedicatedResource.setDomainId(domainId);
+                    if (accountIdFinal != null) {
+                        dedicatedResource.setAccountId(accountIdFinal);
+                    }
+                    dedicatedResource = _dedicatedDao.persist(dedicatedResource);
+                } catch (Exception e) {
+                    s_logger.error("Unable to dedicate pod due to " + e.getMessage(), e);
+                    throw new CloudRuntimeException("Failed to dedicate pod. Please contact Cloud Support.");
+                }
 
-        List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
-        result.add(dedicatedResource);
-        return result;
+                List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
+                result.add(dedicatedResource);
+                return result;
+            }
+        });
     }
 
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Cluster")
-    public List<DedicatedResourceVO> dedicateCluster(Long clusterId, Long domainId, String accountName) {
+    public List<DedicatedResourceVO> dedicateCluster(final Long clusterId, final Long domainId, final String accountName) {
         Long accountId = null;
         List<HostVO> hosts = null;
         if(accountName != null){
@@ -463,37 +472,40 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
 
         checkHostsSuitabilityForExplicitDedication(accountId, childDomainIds, hosts);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        // find or create the affinity group by name under this account/domain
-        AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountId);
-        if (group == null) {
-            s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
-            throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
-        }
-        DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, null, clusterId, null, null, null,
-                group.getId());
-        try {
-            dedicatedResource.setDomainId(domainId);
-            if (accountId != null) {
-                dedicatedResource.setAccountId(accountId);
-            }
-            dedicatedResource = _dedicatedDao.persist(dedicatedResource);
-        } catch (Exception e) {
-            s_logger.error("Unable to dedicate host due to " + e.getMessage(), e);
-            throw new CloudRuntimeException("Failed to dedicate cluster. Please contact Cloud Support.");
-        }
-        txn.commit();
+        final Long accountIdFinal = accountId;
+        return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {
+            @Override
+            public List<DedicatedResourceVO> doInTransaction(TransactionStatus status) {
+                // find or create the affinity group by name under this account/domain
+                AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
+                if (group == null) {
+                    s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
+                    throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
+                }
+                DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, null, clusterId, null, null, null,
+                        group.getId());
+                try {
+                    dedicatedResource.setDomainId(domainId);
+                    if (accountIdFinal != null) {
+                        dedicatedResource.setAccountId(accountIdFinal);
+                    }
+                    dedicatedResource = _dedicatedDao.persist(dedicatedResource);
+                } catch (Exception e) {
+                    s_logger.error("Unable to dedicate host due to " + e.getMessage(), e);
+                    throw new CloudRuntimeException("Failed to dedicate cluster. Please contact Cloud Support.");
+                }
 
-        List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
-        result.add(dedicatedResource);
-        return result;
+                List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
+                result.add(dedicatedResource);
+                return result;
+            }
+        });
     }
 
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Host")
-    public List<DedicatedResourceVO> dedicateHost(Long hostId, Long domainId, String accountName) {
+    public List<DedicatedResourceVO> dedicateHost(final Long hostId, final Long domainId, final String accountName) {
         Long accountId = null;
         if(accountName != null){
             Account caller = CallContext.current().getCallingAccount();
@@ -558,31 +570,35 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
         childDomainIds.add(domainId);
         checkHostSuitabilityForExplicitDedication(accountId, childDomainIds, hostId);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        // find or create the affinity group by name under this account/domain
-        AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountId);
-        if (group == null) {
-            s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
-            throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
-        }
-        DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, null, null, hostId, null, null,
-                group.getId());
-        try {
-            dedicatedResource.setDomainId(domainId);
-            if (accountId != null) {
-                dedicatedResource.setAccountId(accountId);
-            }
-            dedicatedResource = _dedicatedDao.persist(dedicatedResource);
-        } catch (Exception e) {
-            s_logger.error("Unable to dedicate host due to " + e.getMessage(), e);
-            throw new CloudRuntimeException("Failed to dedicate host. Please contact Cloud Support.");
-        }
-        txn.commit();
+        final Long accountIdFinal = accountId;
+        return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {
+            @Override
+            public List<DedicatedResourceVO> doInTransaction(TransactionStatus status) {
+                // find or create the affinity group by name under this account/domain
+                AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
+                if (group == null) {
+                    s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
+                    throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
+                }
+                DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(null, null, null, hostId, null, null,
+                        group.getId());
+                try {
+                    dedicatedResource.setDomainId(domainId);
+                    if (accountIdFinal != null) {
+                        dedicatedResource.setAccountId(accountIdFinal);
+                    }
+                    dedicatedResource = _dedicatedDao.persist(dedicatedResource);
+                } catch (Exception e) {
+                    s_logger.error("Unable to dedicate host due to " + e.getMessage(), e);
+                    throw new CloudRuntimeException("Failed to dedicate host. Please contact Cloud Support.");
+                }
+
+                List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
+                result.add(dedicatedResource);
+                return result;
+            }
+        });
 
-        List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
-        result.add(dedicatedResource);
-        return result;
     }
 
     private AffinityGroup findOrCreateDedicatedAffinityGroup(Long domainId, Long accountId) {
@@ -889,9 +905,8 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE_RELEASE, eventDescription = "Releasing dedicated resource")
-    public boolean releaseDedicatedResource(Long zoneId, Long podId, Long clusterId, Long hostId) throws InvalidParameterValueException{
+    public boolean releaseDedicatedResource(final Long zoneId, Long podId, Long clusterId, Long hostId) throws InvalidParameterValueException{
         DedicatedResourceVO resource = null;
-        Long resourceId = null;
         if (zoneId != null) {
             resource = _dedicatedDao.findByZoneId(zoneId);
         }
@@ -907,26 +922,28 @@ public class DedicatedResourceManagerImpl implements DedicatedService {
         if (resource == null){
             throw new InvalidParameterValueException("No Dedicated Resource available to release");
         } else {
-            Transaction txn = Transaction.currentTxn();
-            txn.start();
-            resourceId = resource.getId();
-            if (!_dedicatedDao.remove(resourceId)) {
-                throw new CloudRuntimeException("Failed to delete Resource " + resourceId);
-            }
-            if (zoneId != null) {
-                // remove the domainId set in zone
-                DataCenterVO dc = _zoneDao.findById(zoneId);
-                if (dc != null) {
-                    dc.setDomainId(null);
-                    dc.setDomain(null);
-                    if (!_zoneDao.update(zoneId, dc)) {
-                        throw new CloudRuntimeException(
-                                "Failed to release dedicated zone, could not clear domainId. Please contact Cloud Support.");
+            final DedicatedResourceVO resourceFinal = resource; 
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    Long resourceId = resourceFinal.getId();
+                    if (!_dedicatedDao.remove(resourceId)) {
+                        throw new CloudRuntimeException("Failed to delete Resource " + resourceId);
+                    }
+                    if (zoneId != null) {
+                        // remove the domainId set in zone
+                        DataCenterVO dc = _zoneDao.findById(zoneId);
+                        if (dc != null) {
+                            dc.setDomainId(null);
+                            dc.setDomain(null);
+                            if (!_zoneDao.update(zoneId, dc)) {
+                                throw new CloudRuntimeException(
+                                        "Failed to release dedicated zone, could not clear domainId. Please contact Cloud Support.");
+                            }
+                        }
                     }
                 }
-            }
-
-            txn.commit();
+            });
 
             // find the group associated and check if there are any more
             // resources under that group

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java
index 314c957..4c07dae 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java
@@ -255,15 +255,12 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements
         }
         
         BaremetalPxeVO vo = new BaremetalPxeVO();
-        Transaction txn = Transaction.currentTxn();
         vo.setHostId(pxeServer.getId());
         vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
         vo.setPodId(pod.getId());
         vo.setPhysicalNetworkId(pcmd.getPhysicalNetworkId());
         vo.setDeviceType(BaremetalPxeType.PING.toString());
-        txn.start();
         _pxeDao.persist(vo);
-        txn.commit();
         return vo;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java
index 7871377..29e180d 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetaNetworkGuru.java
@@ -22,7 +22,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 
@@ -53,6 +52,8 @@ import com.cloud.network.guru.DirectPodBasedNetworkGuru;
 import com.cloud.network.guru.NetworkGuru;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VirtualMachineProfile;
@@ -100,18 +101,18 @@ public class BaremetaNetworkGuru extends DirectPodBasedNetworkGuru {
         } else {
             // we need to get a new ip address if we try to deploy a vm in a
             // different pod
-            IPAddressVO ipVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), oldIp);
+            final IPAddressVO ipVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), oldIp);
             if (ipVO != null) {
                 PodVlanMapVO mapVO = _podVlanDao.listPodVlanMapsByVlan(ipVO.getVlanId());
                 if (mapVO.getPodId() != dest.getPod().getId()) {
-                    Transaction txn = Transaction.currentTxn();
-                    txn.start();
-
-                    // release the old ip here
-                    _ipAddrMgr.markIpAsUnavailable(ipVO.getId());
-                    _ipAddressDao.unassignIpAddress(ipVO.getId());
-
-                    txn.commit();
+                    Transaction.execute(new TransactionCallbackNoReturn() {
+                        @Override
+                        public void doInTransactionWithoutResult(TransactionStatus status) {
+                            // release the old ip here
+                            _ipAddrMgr.markIpAsUnavailable(ipVO.getId());
+                            _ipAddressDao.unassignIpAddress(ipVO.getId());
+                        }
+                    });
 
                     nic.setIp4Address(null);
                     getNewIp = true;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
index 6cf94f2..8057cd4 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
@@ -50,7 +50,6 @@ import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.QueryBuilder;
 import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.Transaction;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
 import com.cloud.vm.ReservationContext;
@@ -115,14 +114,11 @@ public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProv
             return false;
         }
         
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
         nic.setMacAddress(host.getPrivateMacAddress());
         NicVO vo = _nicDao.findById(nic.getId());
         assert vo != null : "Where ths nic " + nic.getId() + " going???";
         vo.setMacAddress(nic.getMacAddress());
         _nicDao.update(vo.getId(), vo);
-        txn.commit();
         return true;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
index 9e1fd65..82397f5 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
@@ -69,7 +69,6 @@ import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.QueryBuilder;
 import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.ReservationContext;
@@ -278,10 +277,7 @@ public class BaremetalDhcpManagerImpl extends ManagerBase implements BaremetalDh
         vo.setHostId(dhcpServer.getId());
         vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
         vo.setPhysicalNetworkId(cmd.getPhysicalNetworkId());
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
         _extDhcpDao.persist(vo);
-        txn.commit();
         return vo;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
index aa0ff1c..cb4babf 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
@@ -27,11 +27,10 @@ import java.util.Map;
 import javax.ejb.Local;
 import javax.inject.Inject;
 
-import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.api.AddBaremetalKickStartPxeCmd;
 import org.apache.cloudstack.api.AddBaremetalPxeCmd;
 import org.apache.cloudstack.api.ListBaremetalPxeServersCmd;
+import org.apache.log4j.Logger;
 
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.baremetal.IpmISetBootDevCommand;
@@ -58,7 +57,6 @@ import com.cloud.uservm.UserVm;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.QueryBuilder;
 import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.ReservationContext;
@@ -225,14 +223,11 @@ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase imple
         }
 
         BaremetalPxeVO vo = new BaremetalPxeVO();
-        Transaction txn = Transaction.currentTxn();
         vo.setHostId(pxeServer.getId());
         vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
         vo.setPhysicalNetworkId(kcmd.getPhysicalNetworkId());
         vo.setDeviceType(BaremetalPxeType.KICK_START.toString());
-        txn.start();
         _pxeDao.persist(vo);
-        txn.commit();
         return vo;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
index 244ce8c..b9dbc77 100755
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java
@@ -48,7 +48,6 @@ import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.QueryBuilder;
 import com.cloud.utils.db.SearchCriteria.Op;
-import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.NicProfile;
 import com.cloud.vm.NicVO;
@@ -117,14 +116,11 @@ public class BaremetalPxeElement extends AdapterBase implements NetworkElement {
         
         VMInstanceVO vo = _vmDao.findById(vm.getId());
         if (vo.getLastHostId() == null) {
-            Transaction txn = Transaction.currentTxn();
-            txn.start();
             nic.setMacAddress(dest.getHost().getPrivateMacAddress());
             NicVO nicVo = _nicDao.findById(nic.getId());
             assert vo != null : "Where ths nic " + nic.getId() + " going???";
             nicVo.setMacAddress(nic.getMacAddress());
             _nicDao.update(nicVo.getId(), nicVo);
-            txn.commit();
             
         	/*This vm is just being created */
         	if (!_pxeMgr.prepare(vm, nic, dest, context)) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java
index 9dfe91d..4239482 100755
--- a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java
+++ b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java
@@ -226,10 +226,7 @@ public class UcsManagerImpl implements UcsManager {
             vo.setZoneId(cmd.getZoneId());
             vo.setName(cmd.getName());
 
-            Transaction txn = Transaction.currentTxn();
-            txn.start();
             mgrvo = ucsDao.persist(vo);
-            txn.commit();
             UcsManagerResponse rsp = new UcsManagerResponse();
             rsp.setId(String.valueOf(vo.getId()));
             rsp.setName(vo.getName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
index 3f8fc5c..cf4c2f0 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
@@ -123,6 +123,10 @@ import com.cloud.utils.db.DB;
 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.net.Ip;
 import com.cloud.vm.DomainRouterVO;
@@ -582,19 +586,21 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast
     }
     
     @DB
-    public PublicIp allocDirectIp(Account account, long guestNetworkId) throws InsufficientAddressCapacityException {
-        Network frontEndNetwork = _networkModel.getNetwork(guestNetworkId);
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        
-        PublicIp ip = _ipAddrMgr.assignPublicIpAddress(frontEndNetwork.getDataCenterId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null, true);
-        IPAddressVO ipvo = _ipAddressDao.findById(ip.getId());
-        ipvo.setAssociatedWithNetworkId(frontEndNetwork.getId());
-        _ipAddressDao.update(ipvo.getId(), ipvo);
-        txn.commit();
-        s_logger.info("Acquired frontend IP for ELB " + ip);
-
-        return ip;
+    public PublicIp allocDirectIp(final Account account, final long guestNetworkId) throws InsufficientAddressCapacityException {
+        return Transaction.executeWithException(new TransactionCallbackWithException<PublicIp>() {
+            @Override
+            public PublicIp doInTransaction(TransactionStatus status) throws Exception {
+                Network frontEndNetwork = _networkModel.getNetwork(guestNetworkId);
+
+                PublicIp ip = _ipAddrMgr.assignPublicIpAddress(frontEndNetwork.getDataCenterId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null, true);
+                IPAddressVO ipvo = _ipAddressDao.findById(ip.getId());
+                ipvo.setAssociatedWithNetworkId(frontEndNetwork.getId());
+                _ipAddressDao.update(ipvo.getId(), ipvo);
+                s_logger.info("Acquired frontend IP for ELB " + ip);
+
+                return ip;
+            }
+        }, InsufficientAddressCapacityException.class);
     }
     
     public void releaseIp(long ipId, long userId, Account caller) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java
index 902f595..233b046 100644
--- a/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java
+++ b/plugins/storage/volume/solidfire/test/org/apache/cloudstack/storage/test/AopTestAdvice.java
@@ -18,11 +18,11 @@ package org.apache.cloudstack.storage.test;
 
 import org.aspectj.lang.ProceedingJoinPoint;
 
-import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionLegacy;
 
 public class AopTestAdvice {
     public Object AopTestMethod(ProceedingJoinPoint call) throws Throwable {
-        Transaction txn = Transaction.open(call.getSignature().getName());
+        TransactionLegacy txn = TransactionLegacy.open(call.getSignature().getName());
         Object ret = null;
         try {
             ret = call.proceed();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java
index b73045d..329b3d5 100755
--- a/server/src/com/cloud/api/ApiServer.java
+++ b/server/src/com/cloud/api/ApiServer.java
@@ -44,7 +44,6 @@ import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 
-import javax.annotation.PostConstruct;
 import javax.crypto.Mac;
 import javax.crypto.spec.SecretKeySpec;
 import javax.inject.Inject;
@@ -52,37 +51,6 @@ import javax.naming.ConfigurationException;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
-import org.apache.commons.codec.binary.Base64;
-import org.apache.http.ConnectionClosedException;
-import org.apache.http.HttpException;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpServerConnection;
-import org.apache.http.HttpStatus;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.utils.URLEncodedUtils;
-import org.apache.http.entity.BasicHttpEntity;
-import org.apache.http.impl.DefaultHttpResponseFactory;
-import org.apache.http.impl.DefaultHttpServerConnection;
-import org.apache.http.impl.NoConnectionReuseStrategy;
-import org.apache.http.impl.SocketHttpServerConnection;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.CoreConnectionPNames;
-import org.apache.http.params.CoreProtocolPNames;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.BasicHttpContext;
-import org.apache.http.protocol.BasicHttpProcessor;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.protocol.HttpRequestHandler;
-import org.apache.http.protocol.HttpRequestHandlerRegistry;
-import org.apache.http.protocol.HttpService;
-import org.apache.http.protocol.ResponseConnControl;
-import org.apache.http.protocol.ResponseContent;
-import org.apache.http.protocol.ResponseDate;
-import org.apache.http.protocol.ResponseServer;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
 import org.apache.cloudstack.acl.APIChecker;
 import org.apache.cloudstack.api.APICommand;
 import org.apache.cloudstack.api.ApiErrorCode;
@@ -120,6 +88,36 @@ import org.apache.cloudstack.framework.jobs.AsyncJob;
 import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
 import org.apache.cloudstack.managed.context.ManagedContextRunnable;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.ConnectionClosedException;
+import org.apache.http.HttpException;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpServerConnection;
+import org.apache.http.HttpStatus;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.utils.URLEncodedUtils;
+import org.apache.http.entity.BasicHttpEntity;
+import org.apache.http.impl.DefaultHttpResponseFactory;
+import org.apache.http.impl.DefaultHttpServerConnection;
+import org.apache.http.impl.NoConnectionReuseStrategy;
+import org.apache.http.impl.SocketHttpServerConnection;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.CoreConnectionPNames;
+import org.apache.http.params.CoreProtocolPNames;
+import org.apache.http.params.HttpParams;
+import org.apache.http.protocol.BasicHttpContext;
+import org.apache.http.protocol.BasicHttpProcessor;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpRequestHandler;
+import org.apache.http.protocol.HttpRequestHandlerRegistry;
+import org.apache.http.protocol.HttpService;
+import org.apache.http.protocol.ResponseConnControl;
+import org.apache.http.protocol.ResponseContent;
+import org.apache.http.protocol.ResponseDate;
+import org.apache.http.protocol.ResponseServer;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
 
 import com.cloud.api.response.ApiResponseSerializer;
 import com.cloud.configuration.Config;
@@ -149,7 +147,6 @@ import com.cloud.utils.component.PluggableService;
 import com.cloud.utils.concurrency.NamedThreadFactory;
 import com.cloud.utils.db.EntityManager;
 import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.exception.ExceptionProxyObject;
 
@@ -708,8 +705,6 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer
                 }
             }
 
-            Transaction txn = Transaction.open(Transaction.CLOUD_DB);
-            txn.close();
             User user = null;
             // verify there is a user with this api key
             Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/capacity/CapacityManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/capacity/CapacityManagerImpl.java b/server/src/com/cloud/capacity/CapacityManagerImpl.java
index b28fe20..72905a7 100755
--- a/server/src/com/cloud/capacity/CapacityManagerImpl.java
+++ b/server/src/com/cloud/capacity/CapacityManagerImpl.java
@@ -28,7 +28,6 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.framework.config.ConfigDepot;
 import org.apache.cloudstack.framework.config.ConfigKey;
 import org.apache.cloudstack.framework.config.Configurable;
@@ -61,6 +60,7 @@ import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
 import com.cloud.offering.ServiceOffering;
+import com.cloud.org.Cluster;
 import com.cloud.org.Grouping.AllocationState;
 import com.cloud.resource.ResourceListener;
 import com.cloud.resource.ResourceManager;
@@ -81,6 +81,9 @@ import com.cloud.utils.concurrency.NamedThreadFactory;
 import com.cloud.utils.db.DB;
 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.fsm.StateListener;
 import com.cloud.vm.UserVmDetailVO;
 import com.cloud.vm.UserVmVO;
@@ -170,100 +173,104 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
 
     @DB
     @Override
-    public boolean releaseVmCapacity(VirtualMachine vm, boolean moveFromReserved, boolean moveToReservered, Long hostId) {
-        ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
+    public boolean releaseVmCapacity(VirtualMachine vm, final boolean moveFromReserved, final boolean moveToReservered, final Long hostId) {
+        final ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
         CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_CPU);
         CapacityVO capacityMemory = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_MEMORY);
         Long clusterId = null;
         if (hostId != null) {
-        HostVO host = _hostDao.findById(hostId);
+            HostVO host = _hostDao.findById(hostId);
             clusterId = host.getClusterId();
         }
         if (capacityCpu == null || capacityMemory == null || svo == null) {
             return false;
         }
 
-        Transaction txn = Transaction.currentTxn();
         try {
-            txn.start();
-
-            capacityCpu = _capacityDao.lockRow(capacityCpu.getId(), true);
-            capacityMemory = _capacityDao.lockRow(capacityMemory.getId(), true);
-
-            long usedCpu = capacityCpu.getUsedCapacity();
-            long usedMem = capacityMemory.getUsedCapacity();
-            long reservedCpu = capacityCpu.getReservedCapacity();
-            long reservedMem = capacityMemory.getReservedCapacity();
-            long actualTotalCpu = capacityCpu.getTotalCapacity();
-            float cpuOvercommitRatio =Float.parseFloat(_clusterDetailsDao.findDetail(clusterId,"cpuOvercommitRatio").getValue());
-            float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId,"memoryOvercommitRatio").getValue());
-            int vmCPU = svo.getCpu() * svo.getSpeed();
-            long vmMem = svo.getRamSize() * 1024L * 1024L;
-            long actualTotalMem = capacityMemory.getTotalCapacity();
-            long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
-            long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
-                s_logger.debug("Hosts's actual total RAM: " + actualTotalMem + " and RAM after applying overprovisioning: " + totalMem);
-            }
-
+            final Long clusterIdFinal = clusterId;
+            final long capacityCpuId = capacityCpu.getId();
+            final long capacityMemoryId = capacityMemory.getId();
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    CapacityVO capacityCpu = _capacityDao.lockRow(capacityCpuId, true);
+                    CapacityVO capacityMemory = _capacityDao.lockRow(capacityMemoryId, true);
+        
+                    long usedCpu = capacityCpu.getUsedCapacity();
+                    long usedMem = capacityMemory.getUsedCapacity();
+                    long reservedCpu = capacityCpu.getReservedCapacity();
+                    long reservedMem = capacityMemory.getReservedCapacity();
+                    long actualTotalCpu = capacityCpu.getTotalCapacity();
+                    float cpuOvercommitRatio =Float.parseFloat(_clusterDetailsDao.findDetail(clusterIdFinal,"cpuOvercommitRatio").getValue());
+                    float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterIdFinal,"memoryOvercommitRatio").getValue());
+                    int vmCPU = svo.getCpu() * svo.getSpeed();
+                    long vmMem = svo.getRamSize() * 1024L * 1024L;
+                    long actualTotalMem = capacityMemory.getTotalCapacity();
+                    long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
+                    long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
+                        s_logger.debug("Hosts's actual total RAM: " + actualTotalMem + " and RAM after applying overprovisioning: " + totalMem);
+                    }
 
-            if (!moveFromReserved) {
-                /* move resource from used */
-                if (usedCpu >= vmCPU) {
-                    capacityCpu.setUsedCapacity(usedCpu - vmCPU);
-                }
-                if (usedMem >= vmMem) {
-                    capacityMemory.setUsedCapacity(usedMem - vmMem);
-                }
 
-                if (moveToReservered) {
-                    if (reservedCpu + vmCPU <= totalCpu) {
-                        capacityCpu.setReservedCapacity(reservedCpu + vmCPU);
+                    if (!moveFromReserved) {
+                        /* move resource from used */
+                        if (usedCpu >= vmCPU) {
+                            capacityCpu.setUsedCapacity(usedCpu - vmCPU);
+                        }
+                        if (usedMem >= vmMem) {
+                            capacityMemory.setUsedCapacity(usedMem - vmMem);
+                        }
+
+                        if (moveToReservered) {
+                            if (reservedCpu + vmCPU <= totalCpu) {
+                                capacityCpu.setReservedCapacity(reservedCpu + vmCPU);
+                            }
+                            if (reservedMem + vmMem <= totalMem) {
+                                capacityMemory.setReservedCapacity(reservedMem + vmMem);
+                            }
+                        }
+                    } else {
+                        if (reservedCpu >= vmCPU) {
+                            capacityCpu.setReservedCapacity(reservedCpu - vmCPU);
+                        }
+                        if (reservedMem >= vmMem) {
+                            capacityMemory.setReservedCapacity(reservedMem - vmMem);
+                        }
                     }
-                    if (reservedMem + vmMem <= totalMem) {
-                        capacityMemory.setReservedCapacity(reservedMem + vmMem);
-                    }
-                }
-            } else {
-                if (reservedCpu >= vmCPU) {
-                    capacityCpu.setReservedCapacity(reservedCpu - vmCPU);
-                }
-                if (reservedMem >= vmMem) {
-                    capacityMemory.setReservedCapacity(reservedMem - vmMem);
-                }
-            }
 
-            s_logger.debug("release cpu from host: " + hostId + ", old used: " + usedCpu + ",reserved: " + reservedCpu + ", actual total: "
-                    + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used: " + capacityCpu.getUsedCapacity() + ",reserved:"
-                    + capacityCpu.getReservedCapacity() + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
+                    s_logger.debug("release cpu from host: " + hostId + ", old used: " + usedCpu + ",reserved: " + reservedCpu + ", actual total: "
+                            + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used: " + capacityCpu.getUsedCapacity() + ",reserved:"
+                            + capacityCpu.getReservedCapacity() + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
+
+                    s_logger.debug("release mem from host: " + hostId + ", old used: " + usedMem + ",reserved: " + reservedMem + ", total: " + totalMem
+                            + "; new used: " + capacityMemory.getUsedCapacity() + ",reserved:" + capacityMemory.getReservedCapacity()
+                            + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
 
-            s_logger.debug("release mem from host: " + hostId + ", old used: " + usedMem + ",reserved: " + reservedMem + ", total: " + totalMem
-                    + "; new used: " + capacityMemory.getUsedCapacity() + ",reserved:" + capacityMemory.getReservedCapacity()
-                    + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
+                    _capacityDao.update(capacityCpu.getId(), capacityCpu);
+                    _capacityDao.update(capacityMemory.getId(), capacityMemory);
+                }
+            });
 
-            _capacityDao.update(capacityCpu.getId(), capacityCpu);
-            _capacityDao.update(capacityMemory.getId(), capacityMemory);
-            txn.commit();
             return true;
         } catch (Exception e) {
             s_logger.debug("Failed to transit vm's state, due to " + e.getMessage());
-            txn.rollback();
             return false;
         }
     }
 
     @DB
     @Override
-    public void allocateVmCapacity(VirtualMachine vm, boolean fromLastHost) {
+    public void allocateVmCapacity(VirtualMachine vm, final boolean fromLastHost) {
 
-        long hostId = vm.getHostId();
+        final long hostId = vm.getHostId();
         HostVO host = _hostDao.findById(hostId);
-        long clusterId = host.getClusterId();
-        float cpuOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio").getValue());
-        float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "memoryOvercommitRatio").getValue());
+        final long clusterId = host.getClusterId();
+        final float cpuOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio").getValue());
+        final float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterId, "memoryOvercommitRatio").getValue());
 
-        ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
+        final ServiceOfferingVO svo = _offeringsDao.findById(vm.getServiceOfferingId());
 
         CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_CPU);
         CapacityVO capacityMem = _capacityDao.findByHostIdType(hostId, CapacityVO.CAPACITY_TYPE_MEMORY);
@@ -272,74 +279,78 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
             return;
         }
 
-        int cpu = svo.getCpu() * svo.getSpeed();
-        long ram = svo.getRamSize() * 1024L * 1024L;
-
+        final int cpu = svo.getCpu() * svo.getSpeed();
+        final long ram = svo.getRamSize() * 1024L * 1024L;
 
-        Transaction txn = Transaction.currentTxn();
 
         try {
-            txn.start();
-            capacityCpu = _capacityDao.lockRow(capacityCpu.getId(), true);
-            capacityMem = _capacityDao.lockRow(capacityMem.getId(), true);
-
-            long usedCpu = capacityCpu.getUsedCapacity();
-            long usedMem = capacityMem.getUsedCapacity();
-            long reservedCpu = capacityCpu.getReservedCapacity();
-            long reservedMem = capacityMem.getReservedCapacity();
-            long actualTotalCpu = capacityCpu.getTotalCapacity();
-            long actualTotalMem = capacityMem.getTotalCapacity();
-            long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
-            long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
-            }
+            final long capacityCpuId = capacityCpu.getId();
+            final long capacityMemId = capacityMem.getId();
+
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    CapacityVO capacityCpu = _capacityDao.lockRow(capacityCpuId, true);
+                    CapacityVO capacityMem = _capacityDao.lockRow(capacityMemId, true);
+
+                    long usedCpu = capacityCpu.getUsedCapacity();
+                    long usedMem = capacityMem.getUsedCapacity();
+                    long reservedCpu = capacityCpu.getReservedCapacity();
+                    long reservedMem = capacityMem.getReservedCapacity();
+                    long actualTotalCpu = capacityCpu.getTotalCapacity();
+                    long actualTotalMem = capacityMem.getTotalCapacity();
+                    long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
+                    long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
+                    }
 
-            long freeCpu = totalCpu - (reservedCpu + usedCpu);
-            long freeMem = totalMem - (reservedMem + usedMem);
+                    long freeCpu = totalCpu - (reservedCpu + usedCpu);
+                    long freeMem = totalMem - (reservedMem + usedMem);
 
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("We are allocating VM, increasing the used capacity of this host:" + hostId);
-                s_logger.debug("Current Used CPU: " + usedCpu + " , Free CPU:" + freeCpu + " ,Requested CPU: " + cpu);
-                s_logger.debug("Current Used RAM: " + usedMem + " , Free RAM:" + freeMem + " ,Requested RAM: " + ram);
-            }
-            capacityCpu.setUsedCapacity(usedCpu + cpu);
-            capacityMem.setUsedCapacity(usedMem + ram);
-
-            if (fromLastHost) {
-                /* alloc from reserved */
-                if (s_logger.isDebugEnabled()) {
-                    s_logger.debug("We are allocating VM to the last host again, so adjusting the reserved capacity if it is not less than required");
-                    s_logger.debug("Reserved CPU: " + reservedCpu + " , Requested CPU: " + cpu);
-                    s_logger.debug("Reserved RAM: " + reservedMem + " , Requested RAM: " + ram);
-                }
-                if (reservedCpu >= cpu && reservedMem >= ram) {
-                    capacityCpu.setReservedCapacity(reservedCpu - cpu);
-                    capacityMem.setReservedCapacity(reservedMem - ram);
-                }
-            } else {
-                /* alloc from free resource */
-                if (!((reservedCpu + usedCpu + cpu <= totalCpu) && (reservedMem + usedMem + ram <= totalMem))) {
                     if (s_logger.isDebugEnabled()) {
-                        s_logger.debug("Host doesnt seem to have enough free capacity, but increasing the used capacity anyways, since the VM is already starting on this host ");
+                        s_logger.debug("We are allocating VM, increasing the used capacity of this host:" + hostId);
+                        s_logger.debug("Current Used CPU: " + usedCpu + " , Free CPU:" + freeCpu + " ,Requested CPU: " + cpu);
+                        s_logger.debug("Current Used RAM: " + usedMem + " , Free RAM:" + freeMem + " ,Requested RAM: " + ram);
+                    }
+                    capacityCpu.setUsedCapacity(usedCpu + cpu);
+                    capacityMem.setUsedCapacity(usedMem + ram);
+
+                    if (fromLastHost) {
+                        /* alloc from reserved */
+                        if (s_logger.isDebugEnabled()) {
+                            s_logger.debug("We are allocating VM to the last host again, so adjusting the reserved capacity if it is not less than required");
+                            s_logger.debug("Reserved CPU: " + reservedCpu + " , Requested CPU: " + cpu);
+                            s_logger.debug("Reserved RAM: " + reservedMem + " , Requested RAM: " + ram);
+                        }
+                        if (reservedCpu >= cpu && reservedMem >= ram) {
+                            capacityCpu.setReservedCapacity(reservedCpu - cpu);
+                            capacityMem.setReservedCapacity(reservedMem - ram);
+                        }
+                    } else {
+                        /* alloc from free resource */
+                        if (!((reservedCpu + usedCpu + cpu <= totalCpu) && (reservedMem + usedMem + ram <= totalMem))) {
+                            if (s_logger.isDebugEnabled()) {
+                                s_logger.debug("Host doesnt seem to have enough free capacity, but increasing the used capacity anyways, since the VM is already starting on this host ");
+                            }
+                        }
                     }
-                }
-            }
 
-            s_logger.debug("CPU STATS after allocation: for host: " + hostId + ", old used: " + usedCpu + ", old reserved: " + reservedCpu
-                    + ", actual total: " + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used:"
-                    + capacityCpu.getUsedCapacity() + ", reserved:" + capacityCpu.getReservedCapacity() + "; requested cpu:" + cpu
-                    + ",alloc_from_last:" + fromLastHost);
+                    s_logger.debug("CPU STATS after allocation: for host: " + hostId + ", old used: " + usedCpu + ", old reserved: " + reservedCpu
+                            + ", actual total: " + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used:"
+                            + capacityCpu.getUsedCapacity() + ", reserved:" + capacityCpu.getReservedCapacity() + "; requested cpu:" + cpu
+                            + ",alloc_from_last:" + fromLastHost);
 
-            s_logger.debug("RAM STATS after allocation: for host: " + hostId + ", old used: " + usedMem + ", old reserved: " + reservedMem
-                    + ", total: " + totalMem + "; new used: " + capacityMem.getUsedCapacity() + ", reserved: " + capacityMem.getReservedCapacity()
-                    + "; requested mem: " + ram + ",alloc_from_last:" + fromLastHost);
+                    s_logger.debug("RAM STATS after allocation: for host: " + hostId + ", old used: " + usedMem + ", old reserved: " + reservedMem
+                            + ", total: " + totalMem + "; new used: " + capacityMem.getUsedCapacity() + ", reserved: " + capacityMem.getReservedCapacity()
+                            + "; requested mem: " + ram + ",alloc_from_last:" + fromLastHost);
 
-            _capacityDao.update(capacityCpu.getId(), capacityCpu);
-            _capacityDao.update(capacityMem.getId(), capacityMem);
-            txn.commit();
+                    _capacityDao.update(capacityCpu.getId(), capacityCpu);
+                    _capacityDao.update(capacityMem.getId(), capacityMem);
+                }
+            });
         } catch (Exception e) {
-            txn.rollback();
+            s_logger.error("Exception allocating VM capacity", e);
             return;
         }
     }
@@ -512,7 +523,7 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
 
     @DB
     @Override
-	public void updateCapacityForHost(Host host){
+	public void updateCapacityForHost(final Host host){
     	// prepare the service offerings
         List<ServiceOfferingVO> offerings = _offeringsDao.listAllIncludingRemoved();
         Map<Long, ServiceOfferingVO> offeringsMap = new HashMap<Long, ServiceOfferingVO>();
@@ -625,36 +636,42 @@ public class CapacityManagerImpl extends ManagerBase implements CapacityManager,
 	        	s_logger.error("Caught exception while updating cpu/memory capacity for the host " +host.getId(), e);
 	        }
         }else {
-        	Transaction txn = Transaction.currentTxn();
-        	txn.start();
-        	CapacityVO capacity = new CapacityVO(host.getId(),
-                    host.getDataCenterId(), host.getPodId(), host.getClusterId(), usedMemory,
-                    host.getTotalMemory(),
-                    CapacityVO.CAPACITY_TYPE_MEMORY);
-            capacity.setReservedCapacity(reservedMemory);
-            CapacityState capacityState = CapacityState.Enabled;
-            if (host.getClusterId() != null) {
-                cluster = ApiDBUtils.findClusterById(host.getClusterId());
-                if (cluster != null) {
-                    capacityState = _configMgr.findClusterAllocationState(cluster) == AllocationState.Disabled ? CapacityState.Disabled
-                            : CapacityState.Enabled;
+            final long usedMemoryFinal = usedMemory;
+            final long reservedMemoryFinal = reservedMemory;
+            final long usedCpuFinal = usedCpu;
+            final long reservedCpuFinal = reservedCpu;
+        	Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                	CapacityVO capacity = new CapacityVO(host.getId(),
+                            host.getDataCenterId(), host.getPodId(), host.getClusterId(), usedMemoryFinal,
+                            host.getTotalMemory(),
+                            CapacityVO.CAPACITY_TYPE_MEMORY);
+                    capacity.setReservedCapacity(reservedMemoryFinal);
+                    CapacityState capacityState = CapacityState.Enabled;
+                    if (host.getClusterId() != null) {
+                        ClusterVO cluster = ApiDBUtils.findClusterById(host.getClusterId());
+                        if (cluster != null) {
+                            capacityState = _configMgr.findClusterAllocationState(cluster) == AllocationState.Disabled ? CapacityState.Disabled
+                                    : CapacityState.Enabled;
+                            capacity.setCapacityState(capacityState);
+                        }
+                    }
+                    _capacityDao.persist(capacity);
+        
+                    capacity = new CapacityVO(
+                            host.getId(),
+                            host.getDataCenterId(),
+                            host.getPodId(),
+                            host.getClusterId(),
+                            usedCpuFinal,
+                            host.getCpus().longValue() * host.getSpeed().longValue(),
+                            CapacityVO.CAPACITY_TYPE_CPU);
+                    capacity.setReservedCapacity(reservedCpuFinal);
                     capacity.setCapacityState(capacityState);
+                    _capacityDao.persist(capacity);
                 }
-            }
-            _capacityDao.persist(capacity);
-
-            capacity = new CapacityVO(
-                    host.getId(),
-                    host.getDataCenterId(),
-                    host.getPodId(),
-                    host.getClusterId(),
-                    usedCpu,
-                    host.getCpus().longValue() * host.getSpeed().longValue(),
-                    CapacityVO.CAPACITY_TYPE_CPU);
-            capacity.setReservedCapacity(reservedCpu);
-            capacity.setCapacityState(capacityState);
-            _capacityDao.persist(capacity);
-            txn.commit();
+            });
 
         }
 


Mime
View raw message