cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dar...@apache.org
Subject [23/47] New Transaction API
Date Wed, 23 Oct 2013 19:43:40 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/guru/DirectNetworkGuru.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/guru/DirectNetworkGuru.java b/server/src/com/cloud/network/guru/DirectNetworkGuru.java
index 55da113..65bc699 100755
--- a/server/src/com/cloud/network/guru/DirectNetworkGuru.java
+++ b/server/src/com/cloud/network/guru/DirectNetworkGuru.java
@@ -22,7 +22,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 
 import com.cloud.dc.DataCenter;
@@ -33,6 +32,7 @@ import com.cloud.deploy.DeployDestination;
 import com.cloud.deploy.DeploymentPlan;
 import com.cloud.exception.ConcurrentOperationException;
 import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.InsufficientCapacityException;
 import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.network.IpAddressManager;
@@ -56,6 +56,10 @@ import com.cloud.user.Account;
 import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionCallbackWithException;
+import com.cloud.utils.db.TransactionStatus;
+import com.cloud.utils.exception.ExceptionUtil;
 import com.cloud.vm.Nic;
 import com.cloud.vm.Nic.ReservationStrategy;
 import com.cloud.vm.NicProfile;
@@ -228,22 +232,32 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru {
     }
 
     @DB
-    protected void allocateDirectIp(NicProfile nic, Network network, VirtualMachineProfile vm, DataCenter dc, String requestedIp4Addr, String requestedIp6Addr)
+    protected void allocateDirectIp(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final DataCenter dc, final String requestedIp4Addr, final String requestedIp6Addr)
             throws InsufficientVirtualNetworkCapcityException,
             InsufficientAddressCapacityException {
-        
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        _ipAddrMgr.allocateDirectIp(nic, dc, vm, network, requestedIp4Addr, requestedIp6Addr);
-        //save the placeholder nic if the vm is the Virtual router
-        if (vm.getType() == VirtualMachine.Type.DomainRouter) {
-            Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
-            if (placeholderNic == null) {
-                s_logger.debug("Saving placeholder nic with ip4 address " + nic.getIp4Address() + " and ipv6 address " + nic.getIp6Address() + " for the network " + network);
-                _networkMgr.savePlaceholderNic(network, nic.getIp4Address(), nic.getIp6Address(), VirtualMachine.Type.DomainRouter);
-            }
+
+        try {
+            Transaction.executeWithException(new TransactionCallbackWithException<Object>() {
+                @Override
+                public Object doInTransaction(TransactionStatus status) throws InsufficientCapacityException {
+                    _ipAddrMgr.allocateDirectIp(nic, dc, vm, network, requestedIp4Addr, requestedIp6Addr);
+                    //save the placeholder nic if the vm is the Virtual router
+                    if (vm.getType() == VirtualMachine.Type.DomainRouter) {
+                        Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
+                        if (placeholderNic == null) {
+                            s_logger.debug("Saving placeholder nic with ip4 address " + nic.getIp4Address() + " and ipv6 address " + nic.getIp6Address() + " for the network " + network);
+                            _networkMgr.savePlaceholderNic(network, nic.getIp4Address(), nic.getIp6Address(), VirtualMachine.Type.DomainRouter);
+                        }
+                    }
+                    
+                    return null;
+                }
+            }, InsufficientCapacityException.class);
+        } catch (InsufficientCapacityException e) {
+            ExceptionUtil.rethrow(e, InsufficientVirtualNetworkCapcityException.class);
+            ExceptionUtil.rethrow(e, InsufficientAddressCapacityException.class);
+            throw new IllegalStateException(e);
         }
-        txn.commit();
     }
 
     @Override
@@ -257,37 +271,37 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru {
     }
 
     @Override @DB
-    public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) {
+    public void deallocate(final Network network, final NicProfile nic, VirtualMachineProfile vm) {
     	if (s_logger.isDebugEnabled()) {
             s_logger.debug("Deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address());
         }
     	
     	if (nic.getIp4Address() != null) {
-            IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
+            final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
             if (ip != null) {
-                Transaction txn = Transaction.currentTxn();
-                txn.start();
-                
-                // if the ip address a part of placeholder, don't release it
-                Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
-                if (placeholderNic != null && placeholderNic.getIp4Address().equalsIgnoreCase(ip.getAddress().addr())) {
-                    s_logger.debug("Not releasing direct ip " + ip.getId() +" yet as its ip is saved in the placeholder");
-                } else {
-                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
-                    _ipAddressDao.unassignIpAddress(ip.getId());
-                }
-               
-                //unassign nic secondary ip address
-                s_logger.debug("remove nic " + nic.getId() + " secondary ip ");
-                List<String> nicSecIps = null;
-                nicSecIps = _nicSecondaryIpDao.getSecondaryIpAddressesForNic(nic.getId());
-                for (String secIp: nicSecIps) {
-                    IPAddressVO pubIp = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), secIp);
-                    _ipAddrMgr.markIpAsUnavailable(pubIp.getId());
-                    _ipAddressDao.unassignIpAddress(pubIp.getId());
-                }
-    
-                txn.commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        // if the ip address a part of placeholder, don't release it
+                        Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, null);
+                        if (placeholderNic != null && placeholderNic.getIp4Address().equalsIgnoreCase(ip.getAddress().addr())) {
+                            s_logger.debug("Not releasing direct ip " + ip.getId() +" yet as its ip is saved in the placeholder");
+                        } else {
+                            _ipAddrMgr.markIpAsUnavailable(ip.getId());
+                            _ipAddressDao.unassignIpAddress(ip.getId());
+                        }
+                       
+                        //unassign nic secondary ip address
+                        s_logger.debug("remove nic " + nic.getId() + " secondary ip ");
+                        List<String> nicSecIps = null;
+                        nicSecIps = _nicSecondaryIpDao.getSecondaryIpAddressesForNic(nic.getId());
+                        for (String secIp: nicSecIps) {
+                            IPAddressVO pubIp = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), secIp);
+                            _ipAddrMgr.markIpAsUnavailable(pubIp.getId());
+                            _ipAddressDao.unassignIpAddress(pubIp.getId());
+                        }
+                    }
+                });
             }
     	}
     	
@@ -305,21 +319,23 @@ public class DirectNetworkGuru extends AdapterBase implements NetworkGuru {
     @DB
     public boolean trash(Network network, NetworkOffering offering) {
         //Have to remove all placeholder nics
-        List<NicVO> nics = _nicDao.listPlaceholderNicsByNetworkId(network.getId());
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        for (Nic nic : nics) {
-            if (nic.getIp4Address() != null) {
-                s_logger.debug("Releasing ip " + nic.getIp4Address() + " of placeholder nic " + nic);
-                IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
-                _ipAddrMgr.markIpAsUnavailable(ip.getId());
-                _ipAddressDao.unassignIpAddress(ip.getId());
-                s_logger.debug("Removing placeholder nic " + nic);
-                _nicDao.remove(nic.getId());
+        final List<NicVO> nics = _nicDao.listPlaceholderNicsByNetworkId(network.getId());
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                for (Nic nic : nics) {
+                    if (nic.getIp4Address() != null) {
+                        s_logger.debug("Releasing ip " + nic.getIp4Address() + " of placeholder nic " + nic);
+                        IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
+                        _ipAddrMgr.markIpAsUnavailable(ip.getId());
+                        _ipAddressDao.unassignIpAddress(ip.getId());
+                        s_logger.debug("Removing placeholder nic " + nic);
+                        _nicDao.remove(nic.getId());
+                    }
+                }
             }
-        }
-        
-        txn.commit();
+        });
+
         return true;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java
index 31bc021..691135f 100755
--- a/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java
+++ b/server/src/com/cloud/network/guru/DirectPodBasedNetworkGuru.java
@@ -23,7 +23,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 
 import com.cloud.configuration.ZoneConfig;
@@ -53,6 +52,10 @@ import com.cloud.offering.NetworkOffering;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 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.TransactionCallbackWithException;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.Nic;
 import com.cloud.vm.Nic.ReservationStrategy;
@@ -133,18 +136,18 @@ public class DirectPodBasedNetworkGuru extends DirectNetworkGuru {
             getNewIp = true;
         } 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;
@@ -163,54 +166,57 @@ public class DirectPodBasedNetworkGuru extends DirectNetworkGuru {
     }
 
     @DB
-    protected void getIp(NicProfile nic, Pod pod, VirtualMachineProfile vm, Network network) throws InsufficientVirtualNetworkCapcityException,
+    protected void getIp(final NicProfile nic, final Pod pod, final VirtualMachineProfile vm, final Network network) throws InsufficientVirtualNetworkCapcityException,
             InsufficientAddressCapacityException, ConcurrentOperationException {
-        DataCenter dc = _dcDao.findById(pod.getDataCenterId());
+        final DataCenter dc = _dcDao.findById(pod.getDataCenterId());
         if (nic.getIp4Address() == null) {
-            Transaction txn = Transaction.currentTxn();
-            txn.start();
-            
-            PublicIp ip = null;
-            List<PodVlanMapVO> podRefs = _podVlanDao.listPodVlanMapsByPod(pod.getId());
-            String podRangeGateway = null;
-            if (!podRefs.isEmpty()) {
-                podRangeGateway = _vlanDao.findById(podRefs.get(0).getVlanDbId()).getVlanGateway();
-            }
-            //Get ip address from the placeholder and don't allocate a new one
-            if (vm.getType() == VirtualMachine.Type.DomainRouter) {
-                Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
-                if (placeholderNic != null) {
-                    IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), placeholderNic.getIp4Address());
-                    ip = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
-                    s_logger.debug("Nic got an ip address " + placeholderNic.getIp4Address() + " stored in placeholder nic for the network " + network + " and gateway " + podRangeGateway);
+            Transaction.executeWithException(new TransactionCallbackWithException<Object>() {
+                @Override
+                public Object doInTransaction(TransactionStatus status) throws InsufficientAddressCapacityException {
+                    PublicIp ip = null;
+                    List<PodVlanMapVO> podRefs = _podVlanDao.listPodVlanMapsByPod(pod.getId());
+                    String podRangeGateway = null;
+                    if (!podRefs.isEmpty()) {
+                        podRangeGateway = _vlanDao.findById(podRefs.get(0).getVlanDbId()).getVlanGateway();
+                    }
+                    //Get ip address from the placeholder and don't allocate a new one
+                    if (vm.getType() == VirtualMachine.Type.DomainRouter) {
+                        Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
+                        if (placeholderNic != null) {
+                            IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), placeholderNic.getIp4Address());
+                            ip = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
+                            s_logger.debug("Nic got an ip address " + placeholderNic.getIp4Address() + " stored in placeholder nic for the network " + network + " and gateway " + podRangeGateway);
+                        }
+                    }
+                    
+                    if (ip == null) {
+                        ip = _ipAddrMgr.assignPublicIpAddress(dc.getId(), pod.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId(), null, false);
+                    }
+                    
+                    nic.setIp4Address(ip.getAddress().toString());
+                    nic.setFormat(AddressFormat.Ip4);
+                    nic.setGateway(ip.getGateway());
+                    nic.setNetmask(ip.getNetmask());
+                    if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase(Vlan.UNTAGGED)) {
+                        nic.setIsolationUri(IsolationType.Ec2.toUri(Vlan.UNTAGGED));
+                        nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED));
+                        nic.setBroadcastType(BroadcastDomainType.Native);
+                    }
+                    nic.setReservationId(String.valueOf(ip.getVlanTag()));
+                    nic.setMacAddress(ip.getMacAddress());
+                    
+                    //save the placeholder nic if the vm is the Virtual router
+                    if (vm.getType() == VirtualMachine.Type.DomainRouter) {
+                        Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
+                        if (placeholderNic == null) {
+                            s_logger.debug("Saving placeholder nic with ip4 address " + nic.getIp4Address() + " for the network " + network);
+                            _networkMgr.savePlaceholderNic(network, nic.getIp4Address(), null, VirtualMachine.Type.DomainRouter);
+                        }
+                    }
+                    
+                    return null;
                 }
-            }
-            
-            if (ip == null) {
-                ip = _ipAddrMgr.assignPublicIpAddress(dc.getId(), pod.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId(), null, false);
-            }
-            
-            nic.setIp4Address(ip.getAddress().toString());
-            nic.setFormat(AddressFormat.Ip4);
-            nic.setGateway(ip.getGateway());
-            nic.setNetmask(ip.getNetmask());
-            if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase(Vlan.UNTAGGED)) {
-                nic.setIsolationUri(IsolationType.Ec2.toUri(Vlan.UNTAGGED));
-                nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED));
-                nic.setBroadcastType(BroadcastDomainType.Native);
-            }
-            nic.setReservationId(String.valueOf(ip.getVlanTag()));
-            nic.setMacAddress(ip.getMacAddress());
-            
-            //save the placeholder nic if the vm is the Virtual router
-            if (vm.getType() == VirtualMachine.Type.DomainRouter) {
-                Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
-                if (placeholderNic == null) {
-                    s_logger.debug("Saving placeholder nic with ip4 address " + nic.getIp4Address() + " for the network " + network);
-                    _networkMgr.savePlaceholderNic(network, nic.getIp4Address(), null, VirtualMachine.Type.DomainRouter);
-                }
-            }
-            txn.commit();
+            }, InsufficientAddressCapacityException.class);
         }
         nic.setDns1(dc.getDns1());
         nic.setDns2(dc.getDns2());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/guru/GuestNetworkGuru.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java
index 20b0ce5..85728c2 100755
--- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java
+++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java
@@ -24,7 +24,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 import org.apache.cloudstack.framework.config.ConfigKey;
@@ -70,6 +69,8 @@ import com.cloud.utils.Pair;
 import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.DB;
 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.utils.net.NetUtils;
 import com.cloud.vm.Nic.ReservationStrategy;
@@ -223,13 +224,15 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur
                 s_logger.debug("Deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address());
             }
 
-            IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
+            final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
             if (ip != null) {
-                Transaction txn = Transaction.currentTxn();
-                txn.start();
-                _ipAddrMgr.markIpAsUnavailable(ip.getId());
-                _ipAddressDao.unassignIpAddress(ip.getId());
-                txn.commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
+                    _ipAddressDao.unassignIpAddress(ip.getId());
+                    }
+                });
             }
             nic.deallocate();
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/guru/PublicNetworkGuru.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/guru/PublicNetworkGuru.java b/server/src/com/cloud/network/guru/PublicNetworkGuru.java
index f82e22e..6fed1a6 100755
--- a/server/src/com/cloud/network/guru/PublicNetworkGuru.java
+++ b/server/src/com/cloud/network/guru/PublicNetworkGuru.java
@@ -20,7 +20,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 
 import com.cloud.dc.DataCenter;
@@ -50,6 +49,8 @@ import com.cloud.user.Account;
 import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.DB;
 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.Nic.ReservationStrategy;
 import com.cloud.vm.NicProfile;
@@ -192,16 +193,15 @@ public class PublicNetworkGuru extends AdapterBase implements NetworkGuru {
             s_logger.debug("public network deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIp4Address());
         }
 
-        IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
+        final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIp4Address());
         if (ip != null && nic.getReservationStrategy() != ReservationStrategy.Managed) {
-
-            Transaction txn = Transaction.currentTxn();
-            txn.start();
-
-            _ipAddrMgr.markIpAsUnavailable(ip.getId());
-            _ipAddressDao.unassignIpAddress(ip.getId());
-
-            txn.commit();
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
+                    _ipAddressDao.unassignIpAddress(ip.getId());
+                }
+            });
         }
         nic.deallocate();
         

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
index c685ee3..60bb40b 100755
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
@@ -152,6 +152,10 @@ 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.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;
@@ -379,11 +383,11 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
 
     @Override
     @DB
-    public boolean configureLbAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException {
-        AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.findById(vmGroupid);
+    public boolean configureLbAutoScaleVmGroup(final long vmGroupid, String currentState) throws ResourceUnavailableException {
+        final AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.findById(vmGroupid);
         boolean success = false;
 
-        LoadBalancerVO loadBalancer = _lbDao.findById(vmGroup.getLoadBalancerId());
+        final LoadBalancerVO loadBalancer = _lbDao.findById(vmGroup.getLoadBalancerId());
 
         FirewallRule.State backupState = loadBalancer.getState();
 
@@ -416,14 +420,17 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
 
         if (success) {
             if (vmGroup.getState().equals(AutoScaleVmGroup.State_New)) {
-                Transaction.currentTxn().start();
-                loadBalancer.setState(FirewallRule.State.Active);
-                s_logger.debug("LB rule " + loadBalancer.getId() + " state is set to Active");
-                _lbDao.persist(loadBalancer);
-                vmGroup.setState(AutoScaleVmGroup.State_Enabled);
-                _autoScaleVmGroupDao.persist(vmGroup);
-                s_logger.debug("LB Auto Scale Vm Group with Id: " + vmGroupid + " is set to Enabled state.");
-                Transaction.currentTxn().commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        loadBalancer.setState(FirewallRule.State.Active);
+                        s_logger.debug("LB rule " + loadBalancer.getId() + " state is set to Active");
+                        _lbDao.persist(loadBalancer);
+                        vmGroup.setState(AutoScaleVmGroup.State_Enabled);
+                        _autoScaleVmGroupDao.persist(vmGroup);
+                        s_logger.debug("LB Auto Scale Vm Group with Id: " + vmGroupid + " is set to Enabled state.");
+                    }
+                });
             }
             s_logger.info("Successfully configured LB Autoscale Vm Group with Id: " + vmGroupid);
         }
@@ -813,7 +820,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
             throw new InvalidParameterException("Invalid Load balancer : " + healthCheckPolicy.getLoadBalancerId()
                     + " for HealthCheck policy id: " + healthCheckPolicyId);
         }
-        long loadBalancerId = loadBalancer.getId();
+        final long loadBalancerId = loadBalancer.getId();
         FirewallRule.State backupState = loadBalancer.getState();
         _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
 
@@ -830,17 +837,19 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
                     + ", healthCheckpolicyID " + healthCheckPolicyId);
 
             // removing the state of services set by the monitor.
-            List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
+            final List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
             if (maps != null) {
-                Transaction txn = Transaction.currentTxn();
-                txn.start();
-                s_logger.debug("Resetting health state policy for services in loadbalancing rule id : "
-                        + loadBalancerId);
-                for (LoadBalancerVMMapVO map : maps) {
-                    map.setState(null);
-                    _lb2VmMapDao.persist(map);
-                }
-                txn.commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        s_logger.debug("Resetting health state policy for services in loadbalancing rule id : "
+                                + loadBalancerId);
+                        for (LoadBalancerVMMapVO map : maps) {
+                            map.setState(null);
+                            _lb2VmMapDao.persist(map);
+                        }
+                    }
+                });
             }
 
             try {
@@ -957,7 +966,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         CallContext ctx = CallContext.current();
         Account caller = ctx.getCallingAccount();
 
-        LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
+        final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
         if (loadBalancer == null) {
             throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId
                     + ", the load balancer was not found.");
@@ -969,7 +978,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
             mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
         }
 
-        List<UserVm> vmsToAdd = new ArrayList<UserVm>();
+        final List<UserVm> vmsToAdd = new ArrayList<UserVm>();
         
         if (instanceIds == null || instanceIds.isEmpty()) {
             s_logger.warn("List of vms to assign to the lb, is empty");
@@ -1022,13 +1031,16 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
             vmsToAdd.add(vm);
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        for (UserVm vm : vmsToAdd) {
-            LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vm.getId(), false);
-            map = _lb2VmMapDao.persist(map);
-        }
-        txn.commit();
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                for (UserVm vm : vmsToAdd) {
+                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vm.getId(), false);
+                    map = _lb2VmMapDao.persist(map);
+                }
+            }
+        });
+
         if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
             // For autoscaled loadbalancer, the rules need not be applied,
             // meaning the call need not reach the resource layer.
@@ -1044,13 +1056,15 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
             success = true;
         } catch (ResourceUnavailableException e) {
             if (isRollBackAllowedForProvider(loadBalancer)) {
-                List<Long> vmInstanceIds = new ArrayList<Long>();
-                txn = Transaction.currentTxn();
-                txn.start();
-                for (UserVm vm : vmsToAdd) {
-                    vmInstanceIds.add(vm.getId());
-                }
-                txn.commit();
+                final List<Long> vmInstanceIds = new ArrayList<Long>();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        for (UserVm vm : vmsToAdd) {
+                            vmInstanceIds.add(vm.getId());
+                        }
+                    }
+                });
                 if (!vmInstanceIds.isEmpty()) {
                     _lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
                     s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while attaching VM: "
@@ -1203,49 +1217,52 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     }
 
     @DB
-    public boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply, Account caller, long callerUserId,
+    public boolean deleteLoadBalancerRule(final long loadBalancerId, boolean apply, Account caller, long callerUserId,
             boolean rollBack) {
-        LoadBalancerVO lb = _lbDao.findById(loadBalancerId);
-        Transaction txn = Transaction.currentTxn();
-        boolean generateUsageEvent = false;
-        boolean success = true;
+        final LoadBalancerVO lb = _lbDao.findById(loadBalancerId);
         FirewallRule.State backupState = lb.getState();
 
-        txn.start();
-        if (lb.getState() == FirewallRule.State.Staged) {
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Found a rule that is still in stage state so just removing it: " + lb);
-            }
-            generateUsageEvent = true;
-        } else if (lb.getState() == FirewallRule.State.Add || lb.getState() == FirewallRule.State.Active) {
-            lb.setState(FirewallRule.State.Revoke);
-            _lbDao.persist(lb);
-            generateUsageEvent = true;
-        }
-        List<LoadBalancerVMMapVO> backupMaps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
-        List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
-        if (maps != null) {
-            for (LoadBalancerVMMapVO map : maps) {
-                map.setRevoke(true);
-                _lb2VmMapDao.persist(map);
-                s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId "
-                        + map.getInstanceId());
+        List<LoadBalancerVMMapVO> backupMaps = Transaction.execute(new TransactionCallback<List<LoadBalancerVMMapVO>>() {
+            @Override
+            public List<LoadBalancerVMMapVO> doInTransaction(TransactionStatus status) {
+                boolean generateUsageEvent = false;
+        
+                if (lb.getState() == FirewallRule.State.Staged) {
+                    if (s_logger.isDebugEnabled()) {
+                        s_logger.debug("Found a rule that is still in stage state so just removing it: " + lb);
+                    }
+                    generateUsageEvent = true;
+                } else if (lb.getState() == FirewallRule.State.Add || lb.getState() == FirewallRule.State.Active) {
+                    lb.setState(FirewallRule.State.Revoke);
+                    _lbDao.persist(lb);
+                    generateUsageEvent = true;
+                }
+                List<LoadBalancerVMMapVO> backupMaps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
+                List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
+                if (maps != null) {
+                    for (LoadBalancerVMMapVO map : maps) {
+                        map.setRevoke(true);
+                        _lb2VmMapDao.persist(map);
+                        s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId "
+                                + map.getInstanceId());
+                    }
+                }
+        
+                List<LBHealthCheckPolicyVO> hcPolicies = _lb2healthcheckDao.listByLoadBalancerId(loadBalancerId);
+                for (LBHealthCheckPolicyVO lbHealthCheck : hcPolicies) {
+                    lbHealthCheck.setRevoke(true);
+                    _lb2healthcheckDao.persist(lbHealthCheck);
+                }
+        
+                if (generateUsageEvent) {
+                    // Generate usage event right after all rules were marked for revoke
+                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(),
+                            null, LoadBalancingRule.class.getName(), lb.getUuid());
+                }
+                
+                return backupMaps;
             }
-        }
-
-        List<LBHealthCheckPolicyVO> hcPolicies = _lb2healthcheckDao.listByLoadBalancerId(loadBalancerId);
-        for (LBHealthCheckPolicyVO lbHealthCheck : hcPolicies) {
-            lbHealthCheck.setRevoke(true);
-            _lb2healthcheckDao.persist(lbHealthCheck);
-        }
-
-        if (generateUsageEvent) {
-            // Generate usage event right after all rules were marked for revoke
-            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), 0, lb.getId(),
-                    null, LoadBalancingRule.class.getName(), lb.getUuid());
-        }
-
-        txn.commit();
+        });
 
         // gather external network usage stats for this lb rule
         NetworkVO network = _networkDao.findById(lb.getNetworkId());
@@ -1283,7 +1300,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         if (relatedRule != null) {
             s_logger.warn("Unable to remove firewall rule id=" + lb.getId() + " as it has related firewall rule id="
                     + relatedRule.getId() + "; leaving it in Revoke state");
-            success = false;
+            return false;
         } else {
             _firewallMgr.removeRule(lb);
         }
@@ -1293,11 +1310,9 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         // Bug CS-15411 opened to document this
         // _elbMgr.handleDeleteLoadBalancerRule(lb, callerUserId, caller);
 
-        if (success) {
-            s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
-        }
-
-        return success;
+        s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
+        
+        return true;
     }
 
     @Override
@@ -1392,8 +1407,8 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
 
     @DB
     @Override
-    public LoadBalancer createPublicLoadBalancer(String xId, String name, String description,
-            int srcPort, int destPort, long sourceIpId, String protocol, String algorithm, boolean openFirewall, CallContext caller)
+    public LoadBalancer createPublicLoadBalancer(final String xId, final String name, final String description,
+            final int srcPort, final int destPort, final long sourceIpId, final String protocol, final String algorithm, final boolean openFirewall, final CallContext caller)
             throws NetworkRuleConflictException {
         
         if (!NetUtils.isValidPort(destPort)) {
@@ -1404,7 +1419,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
             throw new InvalidParameterValueException("Invalid algorithm: " + algorithm);
         }
 
-        IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId);
+        final IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId);
         // make sure ip address exists
         if (ipAddr == null || !ipAddr.readyToUse()) {
             InvalidParameterValueException ex = new InvalidParameterValueException(
@@ -1426,7 +1441,7 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         _accountMgr.checkAccess(caller.getCallingAccount(), null, true, ipAddr);
 
 
-        Long networkId = ipAddr.getAssociatedWithNetworkId();
+        final Long networkId = ipAddr.getAssociatedWithNetworkId();
         if (networkId == null) {
             InvalidParameterValueException ex = new InvalidParameterValueException(
                     "Unable to create load balancer rule ; specified sourceip id is not associated with any network");
@@ -1440,61 +1455,60 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         _firewallMgr.validateFirewallRule(caller.getCallingAccount(), ipAddr, srcPort, srcPort, protocol,
                 Purpose.LoadBalancing, FirewallRuleType.User, networkId, null);
 
-        LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description,
-                sourceIpId, srcPort, destPort, algorithm,
-                networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId());
 
-        // verify rule is supported by Lb provider of the network
-        Ip sourceIp = getSourceIp(newRule);
-        LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(),
-                new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp);
-        if (!validateLbRule(loadBalancing)) {
-            throw new InvalidParameterValueException("LB service provider cannot support this rule");
-        }
+        return Transaction.executeWithException(new TransactionCallbackWithException<LoadBalancerVO>() {
+            @Override
+            public LoadBalancerVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
+                LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description,
+                        sourceIpId, srcPort, destPort, algorithm,
+                        networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId());
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        
-        newRule = _lbDao.persist(newRule);
-
-        //create rule for all CIDRs
-        if (openFirewall) {
-            _firewallMgr.createRuleForAllCidrs(sourceIpId, caller.getCallingAccount(), srcPort,
-                    srcPort, protocol, null, null, newRule.getId(), networkId);
-        }
-
-        boolean success = true;
+                // verify rule is supported by Lb provider of the network
+                Ip sourceIp = getSourceIp(newRule);
+                LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(),
+                        new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp);
+                if (!validateLbRule(loadBalancing)) {
+                    throw new InvalidParameterValueException("LB service provider cannot support this rule");
+                }
 
-        try {
-            _firewallMgr.detectRulesConflict(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 id=" + sourceIpId + ", public port "
-                    + srcPort + ", private port " + destPort + " is added successfully.");
-            CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
-            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(),
-                    ipAddr.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(),
-                    newRule.getUuid());
-            txn.commit();
-
-            return newRule;
-        } catch (Exception e) {
-            success = false;
-            if (e instanceof NetworkRuleConflictException) {
-                throw (NetworkRuleConflictException) e;
+                newRule = _lbDao.persist(newRule);
+        
+                //create rule for all CIDRs
+                if (openFirewall) {
+                    _firewallMgr.createRuleForAllCidrs(sourceIpId, caller.getCallingAccount(), srcPort,
+                            srcPort, protocol, null, null, newRule.getId(), networkId);
+                }
+        
+                boolean success = true;
+        
+                try {
+                    _firewallMgr.detectRulesConflict(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 id=" + sourceIpId + ", public port "
+                            + srcPort + ", private port " + destPort + " is added successfully.");
+                    CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
+                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(),
+                            ipAddr.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(),
+                            newRule.getUuid());
+        
+                    return newRule;
+                } catch (Exception e) {
+                    success = false;
+                    if (e instanceof NetworkRuleConflictException) {
+                        throw (NetworkRuleConflictException) e;
+                    }
+                    throw new CloudRuntimeException("Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e);
+                } finally {
+                    if (!success && newRule != null) {
+                        _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
+                        removeLBRule(newRule);
+                    }
+                }
             }
-            throw new CloudRuntimeException("Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e);
-        } finally {
-            if (!success && newRule != null) {
+        }, NetworkRuleConflictException.class);
 
-                txn.start();
-                _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
-                removeLBRule(newRule);
-
-                txn.commit();
-            }
-        }
     }
 
     @Override
@@ -1583,7 +1597,6 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
     @DB
     protected boolean applyLoadBalancerRules(List<LoadBalancerVO> lbs, boolean updateRulesInDB)
             throws ResourceUnavailableException {
-        Transaction txn = Transaction.currentTxn();
         List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
         for (LoadBalancerVO lb : lbs) {
             rules.add(getLoadBalancerRuleToApply(lb));
@@ -1595,57 +1608,63 @@ public class LoadBalancingRulesManagerImpl<Type> extends ManagerBase implements
         }
 
         if (updateRulesInDB) {
-            for (LoadBalancerVO lb : lbs) {
-                boolean checkForReleaseElasticIp = false;
-                txn.start();
-                if (lb.getState() == FirewallRule.State.Revoke) {
-                    removeLBRule(lb);
-                    s_logger.debug("LB " + lb.getId() + " is successfully removed");
-                    checkForReleaseElasticIp = true;
-                } else if (lb.getState() == FirewallRule.State.Add) {
-                    lb.setState(FirewallRule.State.Active);
-                    s_logger.debug("LB rule " + lb.getId() + " state is set to Active");
-                    _lbDao.persist(lb);
-                }
-
-                // remove LB-Vm mappings that were state to revoke
-                List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true);
-                List<Long> instanceIds = new ArrayList<Long>();
-
-                for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
-                    instanceIds.add(lbVmMap.getInstanceId());
-                }
-
-                if (!instanceIds.isEmpty()) {
-                    _lb2VmMapDao.remove(lb.getId(), instanceIds, null);
-                    s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds);
-                }
-
-                if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) {
-                    lb.setState(FirewallRule.State.Add);
-                    _lbDao.persist(lb);
-                    s_logger.debug("LB rule " + lb.getId()
-                            + " state is set to Add as there are no more active LB-VM mappings");
-                }
-
-                // remove LB-Stickiness policy mapping that were state to revoke
-                List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(
-                        lb.getId(), true);
-                if (!stickinesspolicies.isEmpty()) {
-                    _lb2stickinesspoliciesDao.remove(lb.getId(), true);
-                    s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
-                }
-
-                // remove LB-HealthCheck policy mapping that were state to
-                // revoke
-                List<LBHealthCheckPolicyVO> healthCheckpolicies = _lb2healthcheckDao.listByLoadBalancerId(lb.getId(),
-                        true);
-                if (!healthCheckpolicies.isEmpty()) {
-                    _lb2healthcheckDao.remove(lb.getId(), true);
-                    s_logger.debug("Load balancer rule id " + lb.getId() + " is removed health check monitors policies");
-                }
+            for (final LoadBalancerVO lb : lbs) {
+                boolean checkForReleaseElasticIp = Transaction.execute(new TransactionCallback<Boolean>() {
+                    @Override
+                    public Boolean doInTransaction(TransactionStatus status) {
+                        boolean checkForReleaseElasticIp = false;
+
+                        if (lb.getState() == FirewallRule.State.Revoke) {
+                            removeLBRule(lb);
+                            s_logger.debug("LB " + lb.getId() + " is successfully removed");
+                            checkForReleaseElasticIp = true;
+                        } else if (lb.getState() == FirewallRule.State.Add) {
+                            lb.setState(FirewallRule.State.Active);
+                            s_logger.debug("LB rule " + lb.getId() + " state is set to Active");
+                            _lbDao.persist(lb);
+                        }
+        
+                        // remove LB-Vm mappings that were state to revoke
+                        List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true);
+                        List<Long> instanceIds = new ArrayList<Long>();
+        
+                        for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
+                            instanceIds.add(lbVmMap.getInstanceId());
+                        }
+        
+                        if (!instanceIds.isEmpty()) {
+                            _lb2VmMapDao.remove(lb.getId(), instanceIds, null);
+                            s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vms " + instanceIds);
+                        }
+        
+                        if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) {
+                            lb.setState(FirewallRule.State.Add);
+                            _lbDao.persist(lb);
+                            s_logger.debug("LB rule " + lb.getId()
+                                    + " state is set to Add as there are no more active LB-VM mappings");
+                        }
+        
+                        // remove LB-Stickiness policy mapping that were state to revoke
+                        List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(
+                                lb.getId(), true);
+                        if (!stickinesspolicies.isEmpty()) {
+                            _lb2stickinesspoliciesDao.remove(lb.getId(), true);
+                            s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
+                        }
+        
+                        // remove LB-HealthCheck policy mapping that were state to
+                        // revoke
+                        List<LBHealthCheckPolicyVO> healthCheckpolicies = _lb2healthcheckDao.listByLoadBalancerId(lb.getId(),
+                                true);
+                        if (!healthCheckpolicies.isEmpty()) {
+                            _lb2healthcheckDao.remove(lb.getId(), true);
+                            s_logger.debug("Load balancer rule id " + lb.getId() + " is removed health check monitors policies");
+                        }
+                        
+                        return checkForReleaseElasticIp;
+                    }
+                });
 
-                txn.commit();
                 if (checkForReleaseElasticIp && lb.getSourceIpAddressId() != null) {
                     boolean success = true;
                     long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index 5ea7560..56e0e5d 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -230,6 +230,8 @@ 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.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.Ip;
 import com.cloud.utils.net.MacAddress;
@@ -578,34 +580,30 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
 
     @DB
     public void processStopOrRebootAnswer(final DomainRouterVO router, Answer answer) {
-        final Transaction txn = Transaction.currentTxn();
-        try {
-            txn.start();
-            //FIXME!!! - UserStats command should grab bytesSent/Received for all guest interfaces of the VR
-            List<Long> routerGuestNtwkIds = _routerDao.getRouterNetworks(router.getId());
-            for (Long guestNtwkId : routerGuestNtwkIds) {
-                final UserStatisticsVO userStats = _userStatsDao.lock(router.getAccountId(), router.getDataCenterId(),
-                        guestNtwkId, null, router.getId(), router.getType().toString());
-            if (userStats != null) {
-                final long currentBytesRcvd = userStats.getCurrentBytesReceived();
-                userStats.setCurrentBytesReceived(0);
-                userStats.setNetBytesReceived(userStats.getNetBytesReceived() + currentBytesRcvd);
-
-                final long currentBytesSent = userStats.getCurrentBytesSent();
-                userStats.setCurrentBytesSent(0);
-                userStats.setNetBytesSent(userStats.getNetBytesSent() + currentBytesSent);
-                _userStatsDao.update(userStats.getId(), userStats);
-                s_logger.debug("Successfully updated user statistics as a part of domR " + router + " reboot/stop");
-            } else {
-                s_logger.warn("User stats were not created for account " + router.getAccountId() + " and dc " + router.getDataCenterId());
-            }
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                //FIXME!!! - UserStats command should grab bytesSent/Received for all guest interfaces of the VR
+                List<Long> routerGuestNtwkIds = _routerDao.getRouterNetworks(router.getId());
+                for (Long guestNtwkId : routerGuestNtwkIds) {
+                    final UserStatisticsVO userStats = _userStatsDao.lock(router.getAccountId(), router.getDataCenterId(),
+                            guestNtwkId, null, router.getId(), router.getType().toString());
+                    if (userStats != null) {
+                        final long currentBytesRcvd = userStats.getCurrentBytesReceived();
+                        userStats.setCurrentBytesReceived(0);
+                        userStats.setNetBytesReceived(userStats.getNetBytesReceived() + currentBytesRcvd);
+        
+                        final long currentBytesSent = userStats.getCurrentBytesSent();
+                        userStats.setCurrentBytesSent(0);
+                        userStats.setNetBytesSent(userStats.getNetBytesSent() + currentBytesSent);
+                        _userStatsDao.update(userStats.getId(), userStats);
+                        s_logger.debug("Successfully updated user statistics as a part of domR " + router + " reboot/stop");
+                    } else {
+                        s_logger.warn("User stats were not created for account " + router.getAccountId() + " and dc " + router.getDataCenterId());
+                    }
+                }
             }
-            
-            txn.commit();
-        } catch (final Exception e) {
-            txn.rollback();
-            throw new CloudRuntimeException("Problem updating stats after reboot/stop ", e);
-        }
+        });
     }
 
     @Override @ActionEvent(eventType = EventTypes.EVENT_ROUTER_REBOOT, eventDescription = "rebooting router Vm", async = true)
@@ -862,21 +860,21 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                 final List<DomainRouterVO> routers = _routerDao.listByStateAndNetworkType(State.Running, GuestType.Isolated, mgmtSrvrId);
                 s_logger.debug("Found " + routers.size() + " running routers. ");
 
-                for (DomainRouterVO router : routers) {
+                for (final DomainRouterVO router : routers) {
                     String privateIP = router.getPrivateIpAddress();
 
                     if (privateIP != null) {
-                        boolean forVpc = router.getVpcId() != null;
+                        final boolean forVpc = router.getVpcId() != null;
                         List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId());
-                        for (Nic routerNic : routerNics) {
-                            Network network = _networkModel.getNetwork(routerNic.getNetworkId());
+                        for (final Nic routerNic : routerNics) {
+                            final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
                             //Send network usage command for public nic in VPC VR
                             //Send network usage command for isolated guest nic of non VPC VR
                             if ((forVpc && network.getTrafficType() == TrafficType.Public) || (!forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated)) {
                                 final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(),
                                         forVpc, routerNic.getIp4Address());
-                                String routerType = router.getType().toString();
-                                UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(),
+                                final String routerType = router.getType().toString();
+                                final UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(),
                                         router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
                                 NetworkUsageAnswer answer = null;
                                 try {
@@ -891,62 +889,63 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                                         s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
                                         continue;
                                     }
-                                    Transaction txn = Transaction.open(Transaction.CLOUD_DB);
                                     try {
                                         if ((answer.getBytesReceived() == 0) && (answer.getBytesSent() == 0)) {
                                             s_logger.debug("Recieved and Sent bytes are both 0. Not updating user_statistics");
                                             continue;
                                         }
-                                        txn.start();
-                                        UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(),
-                                                router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
-                                        if (stats == null) {
-                                            s_logger.warn("unable to find stats for account: " + router.getAccountId());
-                                            continue;
-                                        }
-
-                                        if (previousStats != null
-                                                && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived())
-                                                || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))) {
-                                            s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " +
-                                                    "Ignoring current answer. Router: " + answer.getRouterName() + " Rcvd: " +
-                                                    answer.getBytesReceived() + "Sent: " + answer.getBytesSent());
-                                            continue;
-                                        }
-
-                                        if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) {
-                                            if (s_logger.isDebugEnabled()) {
-                                                s_logger.debug("Received # of bytes that's less than the last one.  " +
-                                                        "Assuming something went wrong and persisting it. Router: " +
-                                                        answer.getRouterName() + " Reported: " + answer.getBytesReceived()
-                                                        + " Stored: " + stats.getCurrentBytesReceived());
-                                            }
-                                            stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
-                                        }
-                                        stats.setCurrentBytesReceived(answer.getBytesReceived());
-                                        if (stats.getCurrentBytesSent() > answer.getBytesSent()) {
-                                            if (s_logger.isDebugEnabled()) {
-                                                s_logger.debug("Received # of bytes that's less than the last one.  " +
-                                                        "Assuming something went wrong and persisting it. Router: " +
-                                                        answer.getRouterName() + " Reported: " + answer.getBytesSent()
-                                                        + " Stored: " + stats.getCurrentBytesSent());
+                                        final NetworkUsageAnswer answerFinal = answer;
+                                        Transaction.execute(new TransactionCallbackNoReturn() {
+                                            @Override
+                                            public void doInTransactionWithoutResult(TransactionStatus status) {
+                                                UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(),
+                                                        router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
+                                                if (stats == null) {
+                                                    s_logger.warn("unable to find stats for account: " + router.getAccountId());
+                                                    return;
+                                                }
+        
+                                                if (previousStats != null
+                                                        && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived())
+                                                        || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))) {
+                                                    s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " +
+                                                            "Ignoring current answer. Router: " + answerFinal.getRouterName() + " Rcvd: " +
+                                                            answerFinal.getBytesReceived() + "Sent: " + answerFinal.getBytesSent());
+                                                    return;
+                                                }
+        
+                                                if (stats.getCurrentBytesReceived() > answerFinal.getBytesReceived()) {
+                                                    if (s_logger.isDebugEnabled()) {
+                                                        s_logger.debug("Received # of bytes that's less than the last one.  " +
+                                                                "Assuming something went wrong and persisting it. Router: " +
+                                                                answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesReceived()
+                                                                + " Stored: " + stats.getCurrentBytesReceived());
+                                                    }
+                                                    stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
+                                                }
+                                                stats.setCurrentBytesReceived(answerFinal.getBytesReceived());
+                                                if (stats.getCurrentBytesSent() > answerFinal.getBytesSent()) {
+                                                    if (s_logger.isDebugEnabled()) {
+                                                        s_logger.debug("Received # of bytes that's less than the last one.  " +
+                                                                "Assuming something went wrong and persisting it. Router: " +
+                                                                answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesSent()
+                                                                + " Stored: " + stats.getCurrentBytesSent());
+                                                    }
+                                                    stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
+                                                }
+                                                stats.setCurrentBytesSent(answerFinal.getBytesSent());
+                                                if (! _dailyOrHourly) {
+                                                    //update agg bytes
+                                                    stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
+                                                    stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
+                                                }
+                                                _userStatsDao.update(stats.getId(), stats);
                                             }
-                                            stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
-                                        }
-                                        stats.setCurrentBytesSent(answer.getBytesSent());
-                                        if (! _dailyOrHourly) {
-                                            //update agg bytes
-                                            stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
-                                            stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
-                                        }
-                                        _userStatsDao.update(stats.getId(), stats);
-                                        txn.commit();
+                                        });
+
                                     } catch (Exception e) {
-                                        txn.rollback();
                                         s_logger.warn("Unable to update user statistics for account: " + router.getAccountId()
                                                 + " Rx: " + answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
-                                    } finally {
-                                        txn.close();
                                     }
                                 }
                             }
@@ -977,30 +976,30 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                         scanLock.unlock();
                         return;
                     }
-                    Transaction txn = Transaction.open(Transaction.CLOUD_DB);
                     try {
-                        txn.start();
-                        //get all stats with delta > 0
-                        List<UserStatisticsVO> updatedStats = _userStatsDao.listUpdatedStats();
-                        Date updatedTime = new Date();
-                        for(UserStatisticsVO stat : updatedStats){
-                            //update agg bytes
-                            stat.setAggBytesReceived(stat.getCurrentBytesReceived() + stat.getNetBytesReceived());
-                            stat.setAggBytesSent(stat.getCurrentBytesSent() + stat.getNetBytesSent());
-                            _userStatsDao.update(stat.getId(), stat);
-                            //insert into op_user_stats_log
-                            UserStatsLogVO statsLog = new UserStatsLogVO(stat.getId(), stat.getNetBytesReceived(), stat.getNetBytesSent(), stat.getCurrentBytesReceived(),
-                                                                         stat.getCurrentBytesSent(), stat.getAggBytesReceived(), stat.getAggBytesSent(), updatedTime);
-                            _userStatsLogDao.persist(statsLog);
-                        }
-                        s_logger.debug("Successfully updated aggregate network stats");
-                        txn.commit();
+                        Transaction.execute(new TransactionCallbackNoReturn() {
+                            @Override
+                            public void doInTransactionWithoutResult(TransactionStatus status) {
+                                //get all stats with delta > 0
+                                List<UserStatisticsVO> updatedStats = _userStatsDao.listUpdatedStats();
+                                Date updatedTime = new Date();
+                                for(UserStatisticsVO stat : updatedStats){
+                                    //update agg bytes
+                                    stat.setAggBytesReceived(stat.getCurrentBytesReceived() + stat.getNetBytesReceived());
+                                    stat.setAggBytesSent(stat.getCurrentBytesSent() + stat.getNetBytesSent());
+                                    _userStatsDao.update(stat.getId(), stat);
+                                    //insert into op_user_stats_log
+                                    UserStatsLogVO statsLog = new UserStatsLogVO(stat.getId(), stat.getNetBytesReceived(), stat.getNetBytesSent(), stat.getCurrentBytesReceived(),
+                                                                                 stat.getCurrentBytesSent(), stat.getAggBytesReceived(), stat.getAggBytesSent(), updatedTime);
+                                    _userStatsLogDao.persist(statsLog);
+                                }
+                                s_logger.debug("Successfully updated aggregate network stats");
+                            }
+                        });
                     } catch (Exception e){
-                        txn.rollback();
                         s_logger.debug("Failed to update aggregate network stats", e);
                     } finally {
                         scanLock.unlock();
-                        txn.close();
                     }
                 }
             } catch (Exception e){
@@ -1137,17 +1136,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                 }
             }
             if (updated) {
-                Transaction txn = Transaction.open(Transaction.CLOUD_DB);
-                try {
-                    txn.start();
-                    _routerDao.update(router.getId(), router);
-                    txn.commit();
-                } catch (Exception e) {
-                    txn.rollback();
-                    s_logger.warn("Unable to update router status for account: " + router.getAccountId());
-                } finally {
-                    txn.close();
-                }
+                _routerDao.update(router.getId(), router);
             }
             RedundantState currState = router.getRedundantState();
             if (prevState != currState) {
@@ -2847,12 +2836,15 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                 configDnsMasq(router, network, cmds);
                 boolean result = sendCommandsToRouter(router, cmds);
                 if (result == false) {
-                    NicIpAliasVO ipAliasVO = _nicIpAliasDao.findByInstanceIdAndNetworkId(network.getId(), router.getId());
-                    Transaction txn = Transaction.currentTxn();
-                    txn.start();
-                    _nicIpAliasDao.expunge(ipAliasVO.getId());
-                    _ipAddressDao.unassignIpAddress(routerPublicIP.getId());
-                    txn.commit();
+                    final NicIpAliasVO ipAliasVO = _nicIpAliasDao.findByInstanceIdAndNetworkId(network.getId(), router.getId());
+                    final PublicIp routerPublicIPFinal = routerPublicIP; 
+                    Transaction.execute(new TransactionCallbackNoReturn() {
+                        @Override
+                        public void doInTransactionWithoutResult(TransactionStatus status) {
+                            _nicIpAliasDao.expunge(ipAliasVO.getId());
+                            _ipAddressDao.unassignIpAddress(routerPublicIPFinal.getId());
+                        }
+                    });
                     throw new CloudRuntimeException("failed to configure ip alias on the router as a part of dhcp config");
                 }
             }
@@ -2877,7 +2869,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
             }
 
             Commands cmds = new Commands(Command.OnError.Continue);
-            List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.state.revoked);
+            final List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.state.revoked);
             s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to revoke on the router as a part of dhcp configuration");
             List<IpAliasTO> revokedIpAliasTOs = new ArrayList<IpAliasTO>();
             for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
@@ -2893,12 +2885,14 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
             configDnsMasq(router, network, cmds);
             boolean result = sendCommandsToRouter(router, cmds);
             if (result) {
-                Transaction txn= Transaction.currentTxn();
-                txn.start();
-                for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
-                    _nicIpAliasDao.expunge(revokedAliasVO.getId());
-                }
-                txn.commit();
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        for (NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
+                            _nicIpAliasDao.expunge(revokedAliasVO.getId());
+                        }
+                    }
+                });
                 return true;
             }
         }
@@ -3966,7 +3960,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
     public void prepareStop(VirtualMachineProfile profile){
         //Collect network usage before stopping Vm
 
-        DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
+        final DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
         if(router == null){
             return;
         }
@@ -3974,17 +3968,17 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
         String privateIP = router.getPrivateIpAddress();
 
         if (privateIP != null) {
-            boolean forVpc = router.getVpcId() != null;
+            final boolean forVpc = router.getVpcId() != null;
             List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId());
-            for (Nic routerNic : routerNics) {
-                Network network = _networkModel.getNetwork(routerNic.getNetworkId());
+            for (final Nic routerNic : routerNics) {
+                final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
                 //Send network usage command for public nic in VPC VR
                 //Send network usage command for isolated guest nic of non VPC VR
                 if ((forVpc && network.getTrafficType() == TrafficType.Public) || (!forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated)) {
                     final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(),
                             forVpc, routerNic.getIp4Address());
-                    String routerType = router.getType().toString();
-                    UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(),
+                    final String routerType = router.getType().toString();
+                    final UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(),
                             router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
                     NetworkUsageAnswer answer = null;
                     try {
@@ -3999,62 +3993,63 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
                             s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
                             continue;
                         }
-                        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
                         try {
                             if ((answer.getBytesReceived() == 0) && (answer.getBytesSent() == 0)) {
                                 s_logger.debug("Recieved and Sent bytes are both 0. Not updating user_statistics");
                                 continue;
                             }
-                            txn.start();
-                            UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(),
-                                    router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
-                            if (stats == null) {
-                                s_logger.warn("unable to find stats for account: " + router.getAccountId());
-                                continue;
-                            }
-
-                            if (previousStats != null
-                                    && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived())
-                                    || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))){
-                                s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " +
-                                        "Ignoring current answer. Router: " + answer.getRouterName() + " Rcvd: " +
-                                        answer.getBytesReceived() + "Sent: " + answer.getBytesSent());
-                                continue;
-                            }
-
-                            if (stats.getCurrentBytesReceived() > answer.getBytesReceived()) {
-                                if (s_logger.isDebugEnabled()) {
-                                    s_logger.debug("Received # of bytes that's less than the last one.  " +
-                                            "Assuming something went wrong and persisting it. Router: " +
-                                            answer.getRouterName() + " Reported: " + answer.getBytesReceived()
-                                            + " Stored: " + stats.getCurrentBytesReceived());
-                                }
-                                stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
-                            }
-                            stats.setCurrentBytesReceived(answer.getBytesReceived());
-                            if (stats.getCurrentBytesSent() > answer.getBytesSent()) {
-                                if (s_logger.isDebugEnabled()) {
-                                    s_logger.debug("Received # of bytes that's less than the last one.  " +
-                                            "Assuming something went wrong and persisting it. Router: " +
-                                            answer.getRouterName() + " Reported: " + answer.getBytesSent()
-                                            + " Stored: " + stats.getCurrentBytesSent());
+                            
+                            final NetworkUsageAnswer answerFinal = answer;
+                            Transaction.execute(new TransactionCallbackNoReturn() {
+                                @Override
+                                public void doInTransactionWithoutResult(TransactionStatus status) {
+                                    UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(),
+                                            router.getDataCenterId(), network.getId(), (forVpc ? routerNic.getIp4Address() : null), router.getId(), routerType);
+                                    if (stats == null) {
+                                        s_logger.warn("unable to find stats for account: " + router.getAccountId());
+                                        return;
+                                    }
+        
+                                    if (previousStats != null
+                                            && ((previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived())
+                                            || (previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent()))){
+                                        s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " +
+                                                "Ignoring current answer. Router: " + answerFinal.getRouterName() + " Rcvd: " +
+                                                answerFinal.getBytesReceived() + "Sent: " + answerFinal.getBytesSent());
+                                        return;
+                                    }
+        
+                                    if (stats.getCurrentBytesReceived() > answerFinal.getBytesReceived()) {
+                                        if (s_logger.isDebugEnabled()) {
+                                            s_logger.debug("Received # of bytes that's less than the last one.  " +
+                                                    "Assuming something went wrong and persisting it. Router: " +
+                                                    answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesReceived()
+                                                    + " Stored: " + stats.getCurrentBytesReceived());
+                                        }
+                                        stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
+                                    }
+                                    stats.setCurrentBytesReceived(answerFinal.getBytesReceived());
+                                    if (stats.getCurrentBytesSent() > answerFinal.getBytesSent()) {
+                                        if (s_logger.isDebugEnabled()) {
+                                            s_logger.debug("Received # of bytes that's less than the last one.  " +
+                                                    "Assuming something went wrong and persisting it. Router: " +
+                                                    answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesSent()
+                                                    + " Stored: " + stats.getCurrentBytesSent());
+                                        }
+                                        stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
+                                    }
+                                    stats.setCurrentBytesSent(answerFinal.getBytesSent());
+                                    if (! _dailyOrHourly) {
+                                        //update agg bytes
+                                        stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
+                                        stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
+                                    }
+                                    _userStatsDao.update(stats.getId(), stats);
                                 }
-                                stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
-                            }
-                            stats.setCurrentBytesSent(answer.getBytesSent());
-                            if (! _dailyOrHourly) {
-                                //update agg bytes
-                                stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
-                                stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
-                            }
-                            _userStatsDao.update(stats.getId(), stats);
-                            txn.commit();
+                            });
                         } catch (Exception e) {
-                            txn.rollback();
                             s_logger.warn("Unable to update user statistics for account: " + router.getAccountId()
                                     + " Rx: " + answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
-                        } finally {
-                            txn.close();
                         }
                     }
                 }


Mime
View raw message