cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From dar...@apache.org
Subject [18/47] New Transaction API
Date Wed, 23 Oct 2013 19:43:35 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/storage/VolumeApiServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java
index 079f90c..8bdb8ee 100644
--- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java
+++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java
@@ -139,6 +139,8 @@ import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.EntityManager;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.fsm.NoTransitionException;
 import com.cloud.utils.fsm.StateMachine2;
@@ -403,34 +405,34 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
     }
 
     @DB
-    protected VolumeVO persistVolume(Account owner, Long zoneId, String volumeName, String url, String format) {
-
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        VolumeVO volume = new VolumeVO(volumeName, zoneId, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
-        volume.setPoolId(null);
-        volume.setDataCenterId(zoneId);
-        volume.setPodId(null);
-        volume.setAccountId(owner.getAccountId());
-        volume.setDomainId(owner.getDomainId());
-        long diskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId();
-        volume.setDiskOfferingId(diskOfferingId);
-        // volume.setSize(size);
-        volume.setInstanceId(null);
-        volume.setUpdated(new Date());
-        volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
-        volume.setFormat(ImageFormat.valueOf(format));
-        volume = _volsDao.persist(volume);
-        CallContext.current().setEventDetails("Volume Id: " + volume.getId());
-
-        // Increment resource count during allocation; if actual creation fails,
-        // decrement it
-        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
-        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
-
-        txn.commit();
-        return volume;
+    protected VolumeVO persistVolume(final Account owner, final Long zoneId, final String volumeName, final String url, final String format) {
+        return Transaction.execute(new TransactionCallback<VolumeVO>() {
+            @Override
+            public VolumeVO doInTransaction(TransactionStatus status) {
+                VolumeVO volume = new VolumeVO(volumeName, zoneId, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
+                volume.setPoolId(null);
+                volume.setDataCenterId(zoneId);
+                volume.setPodId(null);
+                volume.setAccountId(owner.getAccountId());
+                volume.setDomainId(owner.getDomainId());
+                long diskOfferingId = _diskOfferingDao.findByUniqueName("Cloud.com-Custom").getId();
+                volume.setDiskOfferingId(diskOfferingId);
+                // volume.setSize(size);
+                volume.setInstanceId(null);
+                volume.setUpdated(new Date());
+                volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner.getDomainId());
+                volume.setFormat(ImageFormat.valueOf(format));
+                volume = _volsDao.persist(volume);
+                CallContext.current().setEventDetails("Volume Id: " + volume.getId());
+        
+                // Increment resource count during allocation; if actual creation fails,
+                // decrement it
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
+                
+                return volume;
+            }
+        });
     }
 
     /*
@@ -599,49 +601,57 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic
             userSpecifiedName = getRandomVolumeName();
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
-        volume.setPoolId(null);
-        volume.setDataCenterId(zoneId);
-        volume.setPodId(null);
-        volume.setAccountId(ownerId);
-        volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId()));
-        volume.setDiskOfferingId(diskOfferingId);
-        volume.setSize(size);
-        volume.setMinIops(minIops);
-        volume.setMaxIops(maxIops);
-        volume.setInstanceId(null);
-        volume.setUpdated(new Date());
-        volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId());
-        volume.setDisplayVolume(displayVolumeEnabled);
-        if (parentVolume != null) {
-            volume.setTemplateId(parentVolume.getTemplateId());
-            volume.setFormat(parentVolume.getFormat());
-        } else {
-            volume.setTemplateId(null);
-        }
-
-        volume = _volsDao.persist(volume);
-        if (cmd.getSnapshotId() == null) {
-            // for volume created from snapshot, create usage event after volume creation
-            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId,
-                    null, size, Volume.class.getName(), volume.getUuid());
-        }
-
-        CallContext.current().setEventDetails("Volume Id: " + volume.getId());
-
-        // Increment resource count during allocation; if actual creation fails,
-        // decrement it
-        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
-        _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
-
-        txn.commit();
+        VolumeVO volume = commitVolume(cmd, caller, ownerId, displayVolumeEnabled, zoneId, diskOfferingId, size,
+                minIops, maxIops, parentVolume, userSpecifiedName);
 
         return volume;
     }
 
+    private VolumeVO commitVolume(final CreateVolumeCmd cmd, final Account caller, final long ownerId, final Boolean displayVolumeEnabled,
+            final Long zoneId, final Long diskOfferingId, final Long size, final Long minIops, final Long maxIops, final VolumeVO parentVolume,
+            final String userSpecifiedName) {
+        return Transaction.execute(new TransactionCallback<VolumeVO>() {
+            @Override
+            public VolumeVO doInTransaction(TransactionStatus status) {
+                VolumeVO volume = new VolumeVO(userSpecifiedName, -1, -1, -1, -1, new Long(-1), null, null, 0, Volume.Type.DATADISK);
+                volume.setPoolId(null);
+                volume.setDataCenterId(zoneId);
+                volume.setPodId(null);
+                volume.setAccountId(ownerId);
+                volume.setDomainId(((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId()));
+                volume.setDiskOfferingId(diskOfferingId);
+                volume.setSize(size);
+                volume.setMinIops(minIops);
+                volume.setMaxIops(maxIops);
+                volume.setInstanceId(null);
+                volume.setUpdated(new Date());
+                volume.setDomainId((caller == null) ? Domain.ROOT_DOMAIN : caller.getDomainId());
+                volume.setDisplayVolume(displayVolumeEnabled);
+                if (parentVolume != null) {
+                    volume.setTemplateId(parentVolume.getTemplateId());
+                    volume.setFormat(parentVolume.getFormat());
+                } else {
+                    volume.setTemplateId(null);
+                }
+        
+                volume = _volsDao.persist(volume);
+                if (cmd.getSnapshotId() == null) {
+                    // for volume created from snapshot, create usage event after volume creation
+                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), diskOfferingId,
+                            null, size, Volume.class.getName(), volume.getUuid());
+                }
+        
+                CallContext.current().setEventDetails("Volume Id: " + volume.getId());
+        
+                // Increment resource count during allocation; if actual creation fails,
+                // decrement it
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.volume);
+                _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
+                return volume;
+            }
+        });
+    }
+
     public boolean validateVolumeSizeRange(long size) {
         if (size < 0 || (size > 0 && size < (1024 * 1024 * 1024))) {
             throw new InvalidParameterValueException("Please specify a size of at least 1 Gb.");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
index 79aba63..9269dce 100644
--- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
+++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java
@@ -66,6 +66,8 @@ import com.cloud.utils.db.GenericDao;
 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.uuididentity.dao.IdentityDao;
 import com.cloud.vm.dao.NicDao;
@@ -254,55 +256,55 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_TAGS_CREATE, eventDescription = "creating resource tags")
-    public List<ResourceTag> createTags(List<String> resourceIds, TaggedResourceType resourceType, 
-            Map<String, String> tags, String customer) {
-        Account caller = CallContext.current().getCallingAccount();
-        
-        List<ResourceTag> resourceTags = new ArrayList<ResourceTag>(tags.size());
+    public List<ResourceTag> createTags(final List<String> resourceIds, final TaggedResourceType resourceType, 
+            final Map<String, String> tags, final String customer) {
+        final Account caller = CallContext.current().getCallingAccount();
         
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
+        final List<ResourceTag> resourceTags = new ArrayList<ResourceTag>(tags.size());
         
-        for (String key : tags.keySet()) {
-            for (String resourceId : resourceIds) {
-                Long id = getResourceId(resourceId, resourceType);
-                String resourceUuid = getUuid(resourceId, resourceType);
-                
-                //check if object exists
-                if (_daoMap.get(resourceType).findById(id) == null) {
-                    throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + 
-                            " and type " + resourceType);
-                }
-                
-                Pair<Long, Long> accountDomainPair = getAccountDomain(id, resourceType);
-                Long domainId = accountDomainPair.second();
-                Long accountId = accountDomainPair.first();
-                if (accountId != null) {
-                    _accountMgr.checkAccess(caller, null, false, _accountMgr.getAccount(accountId));
-                } else if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_NORMAL) {
-                    //check permissions;
-                    _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId));
-                } else {
-                    throw new PermissionDeniedException("Account " + caller + " doesn't have permissions to create tags" +
-                    		" for resource " + key);
-                }
-                
-                String value = tags.get(key);
-                
-                if (value == null || value.isEmpty()) {
-                    throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty");
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                for (String key : tags.keySet()) {
+                    for (String resourceId : resourceIds) {
+                        Long id = getResourceId(resourceId, resourceType);
+                        String resourceUuid = getUuid(resourceId, resourceType);
+                        
+                        //check if object exists
+                        if (_daoMap.get(resourceType).findById(id) == null) {
+                            throw new InvalidParameterValueException("Unable to find resource by id " + resourceId + 
+                                    " and type " + resourceType);
+                        }
+                        
+                        Pair<Long, Long> accountDomainPair = getAccountDomain(id, resourceType);
+                        Long domainId = accountDomainPair.second();
+                        Long accountId = accountDomainPair.first();
+                        if (accountId != null) {
+                            _accountMgr.checkAccess(caller, null, false, _accountMgr.getAccount(accountId));
+                        } else if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_NORMAL) {
+                            //check permissions;
+                            _accountMgr.checkAccess(caller, _domainMgr.getDomain(domainId));
+                        } else {
+                            throw new PermissionDeniedException("Account " + caller + " doesn't have permissions to create tags" +
+                            		" for resource " + key);
+                        }
+                        
+                        String value = tags.get(key);
+                        
+                        if (value == null || value.isEmpty()) {
+                            throw new InvalidParameterValueException("Value for the key " + key + " is either null or empty");
+                        }
+                       
+                        ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(),
+                                accountDomainPair.second(), 
+                                id, resourceType, customer, resourceUuid);
+                        resourceTag = _resourceTagDao.persist(resourceTag);
+                        resourceTags.add(resourceTag);
+                    }
                 }
-               
-                ResourceTagVO resourceTag = new ResourceTagVO(key, value, accountDomainPair.first(),
-                        accountDomainPair.second(), 
-                        id, resourceType, customer, resourceUuid);
-                resourceTag = _resourceTagDao.persist(resourceTag);
-                resourceTags.add(resourceTag);
             }
-        }
-        
-        txn.commit();
-        
+        });
+
         return resourceTags;
     }
 
@@ -354,7 +356,7 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso
         sc.setParameters("resourceType", resourceType);
         
         List<? extends ResourceTag> resourceTags = _resourceTagDao.search(sc, null);;
-        List<ResourceTag> tagsToRemove = new ArrayList<ResourceTag>();
+        final List<ResourceTag> tagsToRemove = new ArrayList<ResourceTag>();
         
         // Finalize which tags should be removed
         for (ResourceTag resourceTag : resourceTags) {
@@ -390,13 +392,15 @@ public class TaggedResourceManagerImpl extends ManagerBase implements TaggedReso
         }
         
         //Remove the tags
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        for (ResourceTag tagToRemove : tagsToRemove) {
-            _resourceTagDao.remove(tagToRemove.getId());
-            s_logger.debug("Removed the tag " + tagToRemove);
-        }
-        txn.commit();
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                for (ResourceTag tagToRemove : tagsToRemove) {
+                    _resourceTagDao.remove(tagToRemove.getId());
+                    s_logger.debug("Removed the tag " + tagToRemove);
+                }
+            }
+        });
 
         return true;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java
index c1ce892..fb1bb27 100755
--- a/server/src/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/com/cloud/template/TemplateManagerImpl.java
@@ -31,7 +31,6 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd;
 import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd;
@@ -177,6 +176,9 @@ import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.concurrency.NamedThreadFactory;
 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.UserVmManager;
 import com.cloud.vm.UserVmVO;
@@ -1163,11 +1165,9 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
     @DB
     @Override
     public boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd) {
-        Transaction txn = Transaction.currentTxn();
-
         // Input validation
-        Long id = cmd.getId();
-        Account caller = CallContext.current().getCallingAccount();
+        final Long id = cmd.getId();
+        final Account caller = CallContext.current().getCallingAccount();
         List<String> accountNames = cmd.getAccountNames();
         List<Long> projectIds = cmd.getProjectIds();
         Boolean isFeatured = cmd.isFeatured();
@@ -1284,28 +1284,31 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
 
         //Derive the domain id from the template owner as updateTemplatePermissions is not cross domain operation
         Account owner = _accountMgr.getAccount(ownerId);
-        Domain domain = _domainDao.findById(owner.getDomainId());
+        final Domain domain = _domainDao.findById(owner.getDomainId());
         if ("add".equalsIgnoreCase(operation)) {
-            txn.start();
-            for (String accountName : accountNames) {
-                Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
-                if (permittedAccount != null) {
-                    if (permittedAccount.getId() == caller.getId()) {
-                        continue; // don't grant permission to the template
-                        // owner, they implicitly have permission
-                    }
-                    LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
-                    if (existingPermission == null) {
-                        LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
-                        _launchPermissionDao.persist(launchPermission);
+            final List<String> accountNamesFinal = accountNames; 
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    for (String accountName : accountNamesFinal) {
+                        Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
+                        if (permittedAccount != null) {
+                            if (permittedAccount.getId() == caller.getId()) {
+                                continue; // don't grant permission to the template
+                                // owner, they implicitly have permission
+                            }
+                            LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
+                            if (existingPermission == null) {
+                                LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
+                                _launchPermissionDao.persist(launchPermission);
+                            }
+                        } else {
+                            throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" + domain.getUuid()
+                                    + ", account not found.  " + "No permissions updated, please verify the account names and retry.");
+                        }
                     }
-                } else {
-                    txn.rollback();
-                    throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" + domain.getUuid()
-                            + ", account not found.  " + "No permissions updated, please verify the account names and retry.");
                 }
-            }
-            txn.commit();
+            });
         } else if ("remove".equalsIgnoreCase(operation)) {
             List<Long> accountIds = new ArrayList<Long>();
             for (String accountName : accountNames) {
@@ -1335,11 +1338,11 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
         if (userId == null) {
             userId = User.UID_SYSTEM;
         }
-        long templateId = command.getEntityId();
+        final long templateId = command.getEntityId();
         Long volumeId = command.getVolumeId();
         Long snapshotId = command.getSnapshotId();
         VMTemplateVO privateTemplate = null;
-        Long accountId = null;
+        final Long accountId = null;
         SnapshotVO snapshot = null;
         VolumeVO volume = null;
 
@@ -1428,26 +1431,31 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager,
                         zoneId, accountId, volumeId);
             }*/
             if (privateTemplate == null) {
-                Transaction txn = Transaction.currentTxn();
-                txn.start();
-                // template_store_ref entries should have been removed using our
-                // DataObject.processEvent command in case of failure, but clean
-                // it up here to avoid
-                // some leftovers which will cause removing template from
-                // vm_template table fail.
-                _tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
-                // Remove the template_zone_ref record
-                _tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
-                // Remove the template record
-                _tmpltDao.expunge(templateId);
-
-                // decrement resource count
-                if (accountId != null) {
-                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
-                    _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volume != null ? volume.getSize()
-                            : snapshot.getSize()));
-                }
-                txn.commit();
+                final VolumeVO volumeFinal = volume;
+                final SnapshotVO snapshotFinal = snapshot;
+                Transaction.execute(new TransactionCallbackNoReturn() {
+                    @Override
+                    public void doInTransactionWithoutResult(TransactionStatus status) {
+                        // template_store_ref entries should have been removed using our
+                        // DataObject.processEvent command in case of failure, but clean
+                        // it up here to avoid
+                        // some leftovers which will cause removing template from
+                        // vm_template table fail.
+                        _tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
+                        // Remove the template_zone_ref record
+                        _tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
+                        // Remove the template record
+                        _tmpltDao.expunge(templateId);
+        
+                        // decrement resource count
+                        if (accountId != null) {
+                            _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
+                            _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volumeFinal != null ? volumeFinal.getSize()
+                                    : snapshotFinal.getSize()));
+                        }
+                    }
+                });
+
             }
         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/test/DatabaseConfig.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/test/DatabaseConfig.java b/server/src/com/cloud/test/DatabaseConfig.java
index 38a1abf..6f76a3a 100755
--- a/server/src/com/cloud/test/DatabaseConfig.java
+++ b/server/src/com/cloud/test/DatabaseConfig.java
@@ -57,6 +57,10 @@ import com.cloud.utils.PropertiesUtil;
 import com.cloud.utils.component.ComponentContext;
 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.TransactionLegacy;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.net.NfsUtils;
 
 public class DatabaseConfig {
@@ -407,34 +411,34 @@ public class DatabaseConfig {
 
     @DB
     protected void doConfig() {
-        Transaction txn = Transaction.currentTxn();
         try {
-
-            File configFile = new File(_configFileName);
+            final File configFile = new File(_configFileName);
 
             SAXParserFactory spfactory = SAXParserFactory.newInstance();
-            SAXParser saxParser = spfactory.newSAXParser();
-            DbConfigXMLHandler handler = new DbConfigXMLHandler();
+            final SAXParser saxParser = spfactory.newSAXParser();
+            final DbConfigXMLHandler handler = new DbConfigXMLHandler();
             handler.setParent(this);
 
-            txn.start();
-
-            // Save user configured values for all fields
-            saxParser.parse(configFile, handler);
-
-            // Save default values for configuration fields
-            saveVMTemplate();
-            saveRootDomain();
-            saveDefaultConfiguations();
+            Transaction.executeWithException(new TransactionCallbackWithException<Object>() {
+                @Override
+                public Object doInTransaction(TransactionStatus status) throws Exception {
+                    // Save user configured values for all fields
+                    saxParser.parse(configFile, handler);
+        
+                    // Save default values for configuration fields
+                    saveVMTemplate();
+                    saveRootDomain();
+                    saveDefaultConfiguations();
+
+                    return null;
+                }
+            }, Exception.class);
 
-            txn.commit();
             // Check pod CIDRs against each other, and against the guest ip network/netmask
             pzc.checkAllPodCidrSubnets();
-
         } catch (Exception ex) {
             System.out.print("ERROR IS"+ex);
             s_logger.error("error", ex);
-            txn.rollback();
         }
     }
 
@@ -486,7 +490,7 @@ public class DatabaseConfig {
         String insertSql1 = "INSERT INTO `host` (`id`, `name`, `status` , `type` , `private_ip_address`, `private_netmask` ,`private_mac_address` , `storage_ip_address` ,`storage_netmask`, `storage_mac_address`, `data_center_id`, `version`, `dom0_memory`, `last_ping`, `resource`, `guid`, `hypervisor_type`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
         String insertSqlHostDetails = "INSERT INTO `host_details` (`id`, `host_id`, `name`, `value`) VALUES(?,?,?,?)";
         String insertSql2 = "INSERT INTO `op_host` (`id`, `sequence`) VALUES(?, ?)";
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
             stmt.setLong(1, 0);
@@ -563,7 +567,7 @@ public class DatabaseConfig {
         String hypervisor = _currentObjectParams.get("hypervisorType");
         String insertSql1 = "INSERT INTO `cluster` (`id`, `name`, `data_center_id` , `pod_id`, `hypervisor_type` , `cluster_type`, `allocation_state`) VALUES (?,?,?,?,?,?,?)";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
             stmt.setLong(1, id);
@@ -599,7 +603,7 @@ public class DatabaseConfig {
         String insertSql1 = "INSERT INTO `storage_pool` (`id`, `name`, `uuid` , `pool_type` , `port`, `data_center_id` ,`available_bytes` , `capacity_bytes` ,`host_address`, `path`, `created`, `pod_id`,`status` , `cluster_id`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
         // String insertSql2 = "INSERT INTO `netfs_storage_pool` VALUES (?,?,?)";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
             stmt.setLong(1, id);
@@ -704,7 +708,7 @@ public class DatabaseConfig {
                 "`firewall_service_provided`, `source_nat_service_provided`, `load_balance_service_provided`, `static_nat_service_provided`," +
                 "`port_forwarding_service_provided`, `user_data_service_provided`, `security_group_service_provided`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
             stmt.setLong(1, id);
@@ -742,7 +746,7 @@ public class DatabaseConfig {
         String insertSql1 = "INSERT INTO `virtual_router_providers` (`id`, `nsp_id`, `uuid` , `type` , `enabled`) " +
                 "VALUES (?,?,?,?,?)";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql1);
             stmt.setLong(1, id);
@@ -1030,7 +1034,7 @@ public class DatabaseConfig {
         String insertNWRateSql = "UPDATE `cloud`.`service_offering` SET `nw_rate` = ?";
         String insertMCRateSql = "UPDATE `cloud`.`service_offering` SET `mc_rate` = ?";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt;
 
@@ -1109,7 +1113,7 @@ public class DatabaseConfig {
     protected void saveUser() {
         // insert system account
         String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')";
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
             stmt.executeUpdate();
@@ -1120,7 +1124,7 @@ public class DatabaseConfig {
         // insert system user
         insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created)" +
                 " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())";
-        txn = Transaction.currentTxn();
+        txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
             stmt.executeUpdate();
@@ -1159,7 +1163,7 @@ public class DatabaseConfig {
 
         // create an account for the admin user first
         insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')";
-        txn = Transaction.currentTxn();
+        txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
             stmt.executeUpdate();
@@ -1171,7 +1175,7 @@ public class DatabaseConfig {
         insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, email, created) " +
                 "VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "','" + email + "',now())";
 
-        txn = Transaction.currentTxn();
+        txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
             stmt.executeUpdate();
@@ -1227,7 +1231,7 @@ public class DatabaseConfig {
 
         String selectSql = "SELECT name FROM cloud.configuration WHERE name = '" + name + "'";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
             ResultSet result = stmt.executeQuery();
@@ -1270,7 +1274,7 @@ public class DatabaseConfig {
     @DB
     protected void saveRootDomain() {
         String insertSql = "insert into `cloud`.`domain` (id, name, parent, owner, path, level) values (1, 'ROOT', NULL, 2, '/', 0)";
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
             stmt.executeUpdate();
@@ -1377,7 +1381,7 @@ public class DatabaseConfig {
     }
 
     public static String getDatabaseValueString(String selectSql, String name, String errorMsg) {
-        Transaction txn = Transaction.open("getDatabaseValueString");
+        TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueString");
         PreparedStatement stmt = null;
 
         try {
@@ -1399,7 +1403,7 @@ public class DatabaseConfig {
     }
 
     public static long getDatabaseValueLong(String selectSql, String name, String errorMsg) {
-        Transaction txn = Transaction.open("getDatabaseValueLong");
+        TransactionLegacy txn = TransactionLegacy.open("getDatabaseValueLong");
         PreparedStatement stmt = null;
 
         try {
@@ -1420,7 +1424,7 @@ public class DatabaseConfig {
     }
 
     public static void saveSQL(String sql, String errorMsg) {
-        Transaction txn = Transaction.open("saveSQL");
+        TransactionLegacy txn = TransactionLegacy.open("saveSQL");
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(sql);
             stmt.executeUpdate();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/test/IPRangeConfig.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/test/IPRangeConfig.java b/server/src/com/cloud/test/IPRangeConfig.java
index 4b884f8..23ca1bb 100755
--- a/server/src/com/cloud/test/IPRangeConfig.java
+++ b/server/src/com/cloud/test/IPRangeConfig.java
@@ -29,6 +29,7 @@ import java.util.Vector;
 import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionLegacy;
 import com.cloud.utils.net.NetUtils;
 
 
@@ -303,7 +304,7 @@ public class IPRangeConfig {
             endIPLong = NetUtils.ip2Long(endIP);
         }
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         Vector<String> problemIPs = null;
         if (type.equals("public")) {
             problemIPs = deletePublicIPRange(txn, startIPLong, endIPLong, vlanDbId);
@@ -314,7 +315,7 @@ public class IPRangeConfig {
         return problemIPs;
     }
 
-    private Vector<String> deletePublicIPRange(Transaction txn, long startIP, long endIP, long vlanDbId) {
+    private Vector<String> deletePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long vlanDbId) {
         String deleteSql = "DELETE FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_id = ?";
         String isPublicIPAllocatedSelectSql = "SELECT * FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_id = ?";
 
@@ -349,7 +350,7 @@ public class IPRangeConfig {
         return problemIPs;
     }
 
-    private Vector<String> deletePrivateIPRange(Transaction txn, long startIP, long endIP, long podId, long zoneId) {
+    private Vector<String> deletePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
         String deleteSql = "DELETE FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND pod_id = ? AND data_center_id = ?";
         String isPrivateIPAllocatedSelectSql = "SELECT * FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND data_center_id = ? AND pod_id = ?";
 
@@ -429,7 +430,7 @@ public class IPRangeConfig {
             endIPLong = NetUtils.ip2Long(endIP);
         }
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         List<String> problemIPs = null;
 
         if (type.equals("public")) {
@@ -447,7 +448,7 @@ public class IPRangeConfig {
         return problemIPs;
     }
 
-    public Vector<String> savePublicIPRange(Transaction txn, long startIP, long endIP, long zoneId, long vlanDbId, Long sourceNetworkId, long physicalNetworkId) {
+    public Vector<String> savePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long zoneId, long vlanDbId, Long sourceNetworkId, long physicalNetworkId) {
         String insertSql = "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id, uuid) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?, ?)";
         String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
         Vector<String> problemIPs = new Vector<String>();
@@ -485,7 +486,7 @@ public class IPRangeConfig {
         return problemIPs;
     }
 
-    public List<String> savePrivateIPRange(Transaction txn, long startIP, long endIP, long podId, long zoneId) {
+    public List<String> savePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
         String insertSql = "INSERT INTO `cloud`.`op_dc_ip_address_alloc` (ip_address, data_center_id, pod_id, mac_address) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?))";
         String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
         Vector<String> problemIPs = new Vector<String>();
@@ -519,7 +520,7 @@ public class IPRangeConfig {
         return problemIPs;
     }
 
-    private Vector<String> saveLinkLocalPrivateIPRange(Transaction txn, long startIP, long endIP, long podId, long zoneId) {
+    private Vector<String> saveLinkLocalPrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
         String insertSql = "INSERT INTO `cloud`.`op_dc_link_local_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES (?, ?, ?)";
         Vector<String> problemIPs = new Vector<String>();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/test/PodZoneConfig.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/test/PodZoneConfig.java b/server/src/com/cloud/test/PodZoneConfig.java
index 59f8b6c..628c746 100644
--- a/server/src/com/cloud/test/PodZoneConfig.java
+++ b/server/src/com/cloud/test/PodZoneConfig.java
@@ -28,6 +28,7 @@ import com.cloud.network.Networks.TrafficType;
 import com.cloud.utils.component.ComponentContext;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionLegacy;
 import com.cloud.utils.net.NetUtils;
 
 public class PodZoneConfig {
@@ -148,7 +149,7 @@ public class PodZoneConfig {
         HashMap<Long, Vector<Object>> currentPodCidrSubnets = new HashMap<Long, Vector<Object>>();
 
         String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + dcId;
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
             ResultSet rs = stmt.executeQuery();
@@ -363,7 +364,7 @@ public class PodZoneConfig {
 
         String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id, physical_network_id) VALUES ( ?, ?, ?)";
 
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(insertVnet);
             for (int i = begin; i <= end; i++) {
@@ -483,7 +484,7 @@ public class PodZoneConfig {
         Vector<Long> allZoneIDs = new Vector<Long>();
 
         String selectSql = "SELECT id FROM data_center";
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         try {
             PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
             ResultSet rs = stmt.executeQuery();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/usage/UsageServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/usage/UsageServiceImpl.java b/server/src/com/cloud/usage/UsageServiceImpl.java
index 2ffb01d..e54a5b2 100755
--- a/server/src/com/cloud/usage/UsageServiceImpl.java
+++ b/server/src/com/cloud/usage/UsageServiceImpl.java
@@ -34,7 +34,6 @@ import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.usage.UsageService;
 import org.apache.cloudstack.usage.UsageTypes;
-
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -54,6 +53,7 @@ import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionLegacy;
 
 @Component
 @Local(value = { UsageService.class })
@@ -86,7 +86,7 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag
 
     @Override
     public boolean generateUsageRecords(GenerateUsageRecordsCmd cmd) {
-        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
         try {
             UsageJobVO immediateJob = _usageJobDao.getNextImmediateJob();
             if (immediateJob == null) {
@@ -104,7 +104,7 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag
             txn.close();
 
             // switch back to VMOPS_DB
-            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
+            TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
             swap.close();
         }
         return true;
@@ -199,14 +199,14 @@ public class UsageServiceImpl extends ManagerBase implements UsageService, Manag
         }
 
         List<UsageVO> usageRecords = null;
-        Transaction txn = Transaction.open(Transaction.USAGE_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
         try {
             usageRecords = _usageDao.searchAllRecords(sc, usageFilter);
         } finally {
             txn.close();
 
             // switch back to VMOPS_DB
-            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
+            TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
             swap.close();
         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java
index ae93548..c8007af 100755
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -136,6 +136,9 @@ import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.InstanceGroupVO;
@@ -480,22 +483,23 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     }
 
     @DB
-    public void updateLoginAttempts(Long id, int attempts, boolean toDisable) {
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
+    public void updateLoginAttempts(final Long id, final int attempts, final boolean toDisable) {
         try {
-            UserAccountVO user = null;
-            user = _userAccountDao.lockRow(id, true);
-            user.setLoginAttempts(attempts);
-            if(toDisable) {
-                user.setState(State.disabled.toString());
-            }
-            _userAccountDao.update(id, user);
-             txn.commit();
+            Transaction.execute(new TransactionCallbackNoReturn() {
+                @Override
+                public void doInTransactionWithoutResult(TransactionStatus status) {
+                    UserAccountVO user = null;
+                    user = _userAccountDao.lockRow(id, true);
+                    user.setLoginAttempts(attempts);
+                    if(toDisable) {
+                        user.setState(State.disabled.toString());
+                    }
+                    _userAccountDao.update(id, user);
+                }
+            });
         } catch (Exception e) {
             s_logger.error("Failed to update login attempts for user with id " + id );
         }
-        txn.close();
     }
 
     private boolean doSetUserStatus(long userId, State state) {
@@ -859,8 +863,8 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"),
         @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User")
     })
-    public UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType,
-                                         Long domainId, String networkDomain, Map<String, String> details, String accountUUID, String userUUID) {
+    public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, final short accountType,
+                                         Long domainId, final String networkDomain, final Map<String, String> details, String accountUUID, final String userUUID) {
 
         if (accountName == null) {
             accountName = userName;
@@ -902,31 +906,40 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             }
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        // create account
-        if(accountUUID == null){
-            accountUUID = UUID.randomUUID().toString();
-        }
-        AccountVO account = createAccount(accountName, accountType, domainId, networkDomain, details, accountUUID);
-        long accountId = account.getId();
-
-        // create the first user for the account
-        UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID);
+        final String accountNameFinal = accountName;
+        final Long domainIdFinal = domainId;
+        final String accountUUIDFinal = accountUUID;
+        Pair<Long, Account> pair = Transaction.execute(new TransactionCallback<Pair<Long, Account>>() {
+            @Override
+            public Pair<Long, Account> doInTransaction(TransactionStatus status) {
+                // create account
+                String accountUUID = accountUUIDFinal;
+                if(accountUUID == null){
+                    accountUUID = UUID.randomUUID().toString();
+                }
+                AccountVO account = createAccount(accountNameFinal, accountType, domainIdFinal, networkDomain, details, accountUUID);
+                long accountId = account.getId();
+        
+                // create the first user for the account
+                UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID);
+        
+                if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
+                    // set registration token
+                    byte[] bytes = (domainIdFinal + accountNameFinal + userName + System.currentTimeMillis()).getBytes();
+                    String registrationToken = UUID.nameUUIDFromBytes(bytes).toString();
+                    user.setRegistrationToken(registrationToken);
+                }
+                return new Pair<Long, Account>(user.getId(), account);
+            }
+        });
 
-        if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
-            // set registration token
-            byte[] bytes = (domainId + accountName + userName + System.currentTimeMillis()).getBytes();
-            String registrationToken = UUID.nameUUIDFromBytes(bytes).toString();
-            user.setRegistrationToken(registrationToken);
-        }
-        txn.commit();
+        long userId = pair.first();
+        Account account = pair.second();
 
         CallContext.current().putContextParameter(Account.class, account.getUuid());
 
         //check success
-        return _userAccountDao.findById(user.getId());
+        return _userAccountDao.findById(userId);
     }
 
     @Override
@@ -1132,12 +1145,12 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User")
-    public UserAccount enableUser(long userId) {
+    public UserAccount enableUser(final long userId) {
 
         Account caller = CallContext.current().getCallingAccount();
 
         // Check if user exists in the system
-        User user = _userDao.findById(userId);
+        final User user = _userDao.findById(userId);
         if (user == null || user.getRemoved() != null) {
             throw new InvalidParameterValueException("Unable to find active user by id " + userId);
         }
@@ -1155,15 +1168,18 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
         checkAccess(caller, null, true, account);
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        boolean success = doSetUserStatus(userId, State.enabled);
-
-        // make sure the account is enabled too
-        success = success && enableAccount(user.getAccountId());
+        boolean success = Transaction.execute(new TransactionCallback<Boolean>() {
+            @Override
+            public Boolean doInTransaction(TransactionStatus status) {
+                boolean success = doSetUserStatus(userId, State.enabled);
+        
+                // make sure the account is enabled too
+                success = success && enableAccount(user.getAccountId());
+                
+                return success;
+            }
+        });
 
-        txn.commit();
 
         if (success) {
             // whenever the user is successfully enabled, reset the login attempts to zero
@@ -1390,7 +1406,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         String accountName = cmd.getAccountName();
         String newAccountName = cmd.getNewName();
         String networkDomain = cmd.getNetworkDomain();
-        Map<String, String> details = cmd.getDetails();
+        final Map<String, String> details = cmd.getDetails();
 
         boolean success = false;
         Account account = null;
@@ -1434,7 +1450,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             }
         }
 
-        AccountVO acctForUpdate = _accountDao.findById(account.getId());
+        final AccountVO acctForUpdate = _accountDao.findById(account.getId());
         acctForUpdate.setAccountName(newAccountName);
 
         if (networkDomain != null) {
@@ -1445,16 +1461,19 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             }
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        success = _accountDao.update(account.getId(), acctForUpdate);
+        final Account accountFinal = account;
+        success = Transaction.execute(new TransactionCallback<Boolean>() {
+            @Override
+            public Boolean doInTransaction(TransactionStatus status) {
+                boolean success = _accountDao.update(accountFinal.getId(), acctForUpdate);
 
-        if (details != null && success) {
-            _accountDetailsDao.update(account.getId(), details);
-        }
+                if (details != null && success) {
+                    _accountDetailsDao.update(accountFinal.getId(), details);
+                }
 
-        txn.commit();
+                return success;
+            }
+        });
 
         if (success) {
             CallContext.current().putContextParameter(Account.class, account.getUuid());
@@ -1706,7 +1725,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 
     @Override
     @DB
-    public AccountVO createAccount(String accountName, short accountType, Long domainId, String networkDomain, Map<String, String> details, String uuid) {
+    public AccountVO createAccount(final String accountName, final short accountType, final Long domainId, final String networkDomain, final Map<String, String> details, final String uuid) {
         // Validate domain
         Domain domain = _domainMgr.getDomain(domainId);
         if (domain == null) {
@@ -1747,29 +1766,30 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
 
         // Create the account
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-
-        AccountVO account = _accountDao.persist(new AccountVO(accountName, domainId, networkDomain, accountType, uuid));
-
-        if (account == null) {
-            throw new CloudRuntimeException("Failed to create account name " + accountName + " in domain id=" + domainId);
-        }
-
-        Long accountId = account.getId();
-
-        if (details != null) {
-            _accountDetailsDao.persist(accountId, details);
-        }
-
-        // Create resource count records for the account
-        _resourceCountDao.createResourceCounts(accountId, ResourceLimit.ResourceOwnerType.Account);
-
-        // Create default security group
-        _networkGroupMgr.createDefaultSecurityGroup(accountId);
-        txn.commit();
+        return Transaction.execute(new TransactionCallback<AccountVO>() {
+            @Override
+            public AccountVO doInTransaction(TransactionStatus status) {
+                AccountVO account = _accountDao.persist(new AccountVO(accountName, domainId, networkDomain, accountType, uuid));
+        
+                if (account == null) {
+                    throw new CloudRuntimeException("Failed to create account name " + accountName + " in domain id=" + domainId);
+                }
+        
+                Long accountId = account.getId();
+        
+                if (details != null) {
+                    _accountDetailsDao.persist(accountId, details);
+                }
+        
+                // Create resource count records for the account
+                _resourceCountDao.createResourceCounts(accountId, ResourceLimit.ResourceOwnerType.Account);
+        
+                // Create default security group
+                _networkGroupMgr.createDefaultSecurityGroup(accountId);
 
-        return account;
+                return account;
+            }
+        });
     }
 
     protected UserVO createUser(long accountId, String userName, String password, String firstName, String lastName, String email, String timezone, String userUUID) {
@@ -2006,7 +2026,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
     @Override @DB
     @ActionEvent(eventType = EventTypes.EVENT_REGISTER_FOR_SECRET_API_KEY, eventDescription = "register for the developer API keys")
     public String[] createApiKeyAndSecretKey(RegisterCmd cmd) {
-        Long userId = cmd.getId();
+        final Long userId = cmd.getId();
 
         User user = getUserIncludingRemoved(userId);
         if (user == null) {
@@ -2019,12 +2039,14 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
         }
 
         // generate both an api key and a secret key, update the user table with the keys, return the keys to the user
-        String[] keys = new String[2];
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        keys[0] = createUserApiKey(userId);
-        keys[1] = createUserSecretKey(userId);
-        txn.commit();
+        final String[] keys = new String[2];
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                keys[0] = createUserApiKey(userId);
+                keys[1] = createUserSecretKey(userId);
+            }
+        });
 
         return keys;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/user/DomainManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java
index b885c48..2942148 100644
--- a/server/src/com/cloud/user/DomainManagerImpl.java
+++ b/server/src/com/cloud/user/DomainManagerImpl.java
@@ -26,7 +26,6 @@ import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
-
 import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd;
 import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd;
 import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd;
@@ -65,6 +64,9 @@ import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionCallback;
+import com.cloud.utils.db.TransactionCallbackNoReturn;
+import com.cloud.utils.db.TransactionStatus;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.ReservationContext;
@@ -158,7 +160,7 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
 
     @Override
     @DB
-    public Domain createDomain(String name, Long parentId, Long ownerId, String networkDomain, String domainUUID) {
+    public Domain createDomain(final String name, final Long parentId, final Long ownerId, final String networkDomain, String domainUUID) {
         // Verify network domain
         if (networkDomain != null) {
             if (!NetUtils.verifyDomainName(networkDomain)) {
@@ -181,11 +183,16 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
             domainUUID = UUID.randomUUID().toString();
         }
 
-        Transaction txn = Transaction.currentTxn();
-        txn.start();
-        DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUID));
-        _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
-        txn.commit();
+        final String domainUUIDFinal = domainUUID;
+        DomainVO domain = Transaction.execute(new TransactionCallback<DomainVO>() {
+            @Override
+            public DomainVO doInTransaction(TransactionStatus status) {
+                DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUIDFinal));
+                _resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
+                return domain;
+            }
+        });
+
         CallContext.current().putContextParameter(Domain.class, domain.getUuid());
         return domain;
     }
@@ -544,12 +551,12 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
     @ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
     @DB
     public DomainVO updateDomain(UpdateDomainCmd cmd) {
-        Long domainId = cmd.getId();
-        String domainName = cmd.getDomainName();
-        String networkDomain = cmd.getNetworkDomain();
+        final Long domainId = cmd.getId();
+        final String domainName = cmd.getDomainName();
+        final String networkDomain = cmd.getNetworkDomain();
 
         // check if domain exists in the system
-        DomainVO domain = _domainDao.findById(domainId);
+        final DomainVO domain = _domainDao.findById(domainId);
         if (domain == null) {
             InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
             ex.addProxyObject(domainId.toString(), "domainId");
@@ -587,27 +594,28 @@ public class DomainManagerImpl extends ManagerBase implements DomainManager, Dom
             }
         }
 
-        Transaction txn = Transaction.currentTxn();
-
-        txn.start();
-
-        if (domainName != null) {
-            String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
-            updateDomainChildren(domain, updatedDomainPath);
-            domain.setName(domainName);
-            domain.setPath(updatedDomainPath);
-        }
-
-        if (networkDomain != null) {
-            if (networkDomain.isEmpty()) {
-                domain.setNetworkDomain(null);
-            } else {
-                domain.setNetworkDomain(networkDomain);
+        Transaction.execute(new TransactionCallbackNoReturn() {
+            @Override
+            public void doInTransactionWithoutResult(TransactionStatus status) {
+                if (domainName != null) {
+                    String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
+                    updateDomainChildren(domain, updatedDomainPath);
+                    domain.setName(domainName);
+                    domain.setPath(updatedDomainPath);
+                }
+        
+                if (networkDomain != null) {
+                    if (networkDomain.isEmpty()) {
+                        domain.setNetworkDomain(null);
+                    } else {
+                        domain.setNetworkDomain(networkDomain);
+                    }
+                }
+                _domainDao.update(domainId, domain);
+                CallContext.current().putContextParameter(Domain.class, domain.getUuid());
             }
-        }
-        _domainDao.update(domainId, domain);
-        CallContext.current().putContextParameter(Domain.class, domain.getUuid());
-        txn.commit();
+        });
+
 
         return _domainDao.findById(domainId);
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f62e28c1/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java
index 18b7d8b..7e14c69 100644
--- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java
+++ b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java
@@ -33,6 +33,7 @@ import com.cloud.utils.Pair;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.TransactionLegacy;
 
 @Component
 @Local(value={IdentityDao.class})
@@ -48,7 +49,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
 		assert(identityString != null);
 
         PreparedStatement pstmt = null;
-		Transaction txn = Transaction.open(Transaction.CLOUD_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
 		try {
 	        try {
 	            try {
@@ -100,7 +101,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
         assert(tableName != null);
         
         PreparedStatement pstmt = null;
-        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
         try {
             Long domainId = null;
             Long accountId = null;
@@ -146,7 +147,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
 		assert(identityString != null);
 		
         PreparedStatement pstmt = null;
-		Transaction txn = Transaction.open(Transaction.CLOUD_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
 		try {
 	        try {
 	            pstmt = txn.prepareAutoCloseStatement(
@@ -187,7 +188,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
         assert(tableName != null);
         List<Long> l = getNullUuidRecords(tableName);
         
-        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
         try {
             try {
                 txn.start();
@@ -209,7 +210,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
         List<Long> l = new ArrayList<Long>();
         
         PreparedStatement pstmt = null;
-        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
+        TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
         try {
             try {
                 pstmt = txn.prepareAutoCloseStatement(
@@ -231,7 +232,7 @@ public class IdentityDaoImpl extends GenericDaoBase<IdentityVO, Long> implements
     
     @DB
     void setInitialUuid(String tableName, long id) throws SQLException {
-        Transaction txn = Transaction.currentTxn();
+        TransactionLegacy txn = TransactionLegacy.currentTxn();
         
         PreparedStatement pstmtUpdate = null;
         pstmtUpdate = txn.prepareAutoCloseStatement(


Mime
View raw message