You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by mc...@apache.org on 2013/11/01 01:21:58 UTC

[47/50] [abbrv] Merge branch 'master' into rbac.

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2ef4d520/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 0c7374e,e3aa4fa..b7ffbfc
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@@ -477,15 -473,8 +473,8 @@@ public class ConfigurationManagerImpl e
                  if (pool == null) {
                      throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
                  }
-                 StoragePoolDetailVO storagePoolDetailVO = _storagePoolDetailsDao.findDetail(resourceId, name);
-                 if (storagePoolDetailVO == null) {
-                     storagePoolDetailVO = new StoragePoolDetailVO(resourceId, name, value);
-                     _storagePoolDetailsDao.persist(storagePoolDetailVO);
+                 _storagePoolDetailsDao.addDetail(resourceId, name, value);
 -                
 +
-                 } else {
-                     storagePoolDetailVO.setValue(value);
-                     _storagePoolDetailsDao.update(storagePoolDetailVO.getId(), storagePoolDetailVO);
-                 }
                  break;
  
              case Account:
@@@ -1004,50 -991,52 +991,52 @@@
  
          checkIfPodIsDeletable(podId);
  
-         HostPodVO pod = _podDao.findById(podId);
- 
-         txn.start();
+         final HostPodVO pod = _podDao.findById(podId);
  
+         Transaction.execute(new TransactionCallbackNoReturn() {
+             @Override
+             public void doInTransactionWithoutResult(TransactionStatus status) {
 -                // Delete private ip addresses for the pod if there are any
 -                List<DataCenterIpAddressVO> privateIps = _privateIpAddressDao.listByPodIdDcId(Long.valueOf(podId),
 -                        pod.getDataCenterId());
 -                if (!privateIps.isEmpty()) {
 -                    if (!(_privateIpAddressDao.deleteIpAddressByPod(podId))) {
 -                        throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
 -                    }
 -                }
 +        // Delete private ip addresses for the pod if there are any
 +        List<DataCenterIpAddressVO> privateIps = _privateIpAddressDao.listByPodIdDcId(Long.valueOf(podId),
 +                pod.getDataCenterId());
 +        if (!privateIps.isEmpty()) {
 +            if (!(_privateIpAddressDao.deleteIpAddressByPod(podId))) {
 +                throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
 +            }
 +        }
  
 -                // Delete link local ip addresses for the pod
 -                List<DataCenterLinkLocalIpAddressVO> localIps = _LinkLocalIpAllocDao.listByPodIdDcId(podId,
 -                        pod.getDataCenterId());
 -                if (!localIps.isEmpty()) {
 -                    if (!(_LinkLocalIpAllocDao.deleteIpAddressByPod(podId))) {
 -                        throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
 -                    }
 -                }
 +        // Delete link local ip addresses for the pod
 +        List<DataCenterLinkLocalIpAddressVO> localIps = _LinkLocalIpAllocDao.listByPodIdDcId(podId,
 +                pod.getDataCenterId());
 +        if (!localIps.isEmpty()) {
 +            if (!(_LinkLocalIpAllocDao.deleteIpAddressByPod(podId))) {
 +                throw new CloudRuntimeException("Failed to cleanup private ip addresses for pod " + podId);
 +            }
 +        }
  
 -                // Delete vlans associated with the pod
 -                List<? extends Vlan> vlans = _networkModel.listPodVlans(podId);
 -                if (vlans != null && !vlans.isEmpty()) {
 -                    for (Vlan vlan : vlans) {
 -                        _vlanDao.remove(vlan.getId());
 -                    }
 -                }
 +        // Delete vlans associated with the pod
 +        List<? extends Vlan> vlans = _networkModel.listPodVlans(podId);
 +        if (vlans != null && !vlans.isEmpty()) {
 +            for (Vlan vlan : vlans) {
 +                _vlanDao.remove(vlan.getId());
 +            }
 +        }
  
 -                // Delete corresponding capacity records
 -                _capacityDao.removeBy(null, null, podId, null, null);
 +        // Delete corresponding capacity records
 +        _capacityDao.removeBy(null, null, podId, null, null);
  
 -                // Delete the pod
 -                if (!(_podDao.remove(podId))) {
 -                    throw new CloudRuntimeException("Failed to delete pod " + podId);
 -                }
 +        // Delete the pod
 +        if (!(_podDao.remove(podId))) {
 +            throw new CloudRuntimeException("Failed to delete pod " + podId);
 +        }
  
 -                // remove from dedicated resources
 -                DedicatedResourceVO dr = _dedicatedDao.findByPodId(podId);
 -                if (dr != null) {
 -                    _dedicatedDao.remove(dr.getId());
 -                }
 +        // remove from dedicated resources
 +        DedicatedResourceVO dr = _dedicatedDao.findByPodId(podId);
 +        if (dr != null) {
 +            _dedicatedDao.remove(dr.getId());
 +        }
-         txn.commit();
+             }
+         });
  
          return true;
      }
@@@ -1152,54 -1141,68 +1141,68 @@@
          checkPodAttributes(id, name, pod.getDataCenterId(), gateway, cidr, startIp, endIp, allocationStateStr,
                  checkForDuplicates, false);
  
-         Transaction txn = Transaction.currentTxn();
          try {
-             txn.start();
+ 
+             final String[] existingPodIpRangeFinal = existingPodIpRange;
+             final String[] leftRangeToAddFinal = leftRangeToAdd;
+             final String[] rightRangeToAddFinal = rightRangeToAdd;
+             final boolean allowToDownsizeFinal = allowToDownsize;
+             final String allocationStateStrFinal = allocationStateStr;
+             final String startIpFinal = startIp;
+             final String endIpFinal = endIp;
+             final String nameFinal = name;
+             final String gatewayFinal = gateway;
+             Transaction.execute(new TransactionCallbackNoReturn() {
+                 @Override
+                 public void doInTransactionWithoutResult(TransactionStatus status) {
 -                    long zoneId = pod.getDataCenterId();
 +            long zoneId = pod.getDataCenterId();
  
-             if (!allowToDownsize) {
-                 if (leftRangeToAdd != null) {
-                     _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), leftRangeToAdd[0], leftRangeToAdd[1]);
+                     String startIp = startIpFinal;
+                     String endIp = endIpFinal;
+ 
+                     if (!allowToDownsizeFinal) {
+                         if (leftRangeToAddFinal != null) {
+                             _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), leftRangeToAddFinal[0], leftRangeToAddFinal[1]);
 -                        }
 +                }
  
-                 if (rightRangeToAdd != null) {
-                     _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), rightRangeToAdd[0], rightRangeToAdd[1]);
+                         if (rightRangeToAddFinal != null) {
+                             _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), rightRangeToAddFinal[0], rightRangeToAddFinal[1]);
 -                        }
 +                }
  
 -                    } else {
 -                        // delete the old range
 -                        _zoneDao.deletePrivateIpAddressByPod(pod.getId());
 +            } else {
 +                // delete the old range
 +                _zoneDao.deletePrivateIpAddressByPod(pod.getId());
  
 -                        // add the new one
 -                        if (startIp == null) {
 +                // add the new one
 +                if (startIp == null) {
-                     startIp = existingPodIpRange[0];
+                             startIp = existingPodIpRangeFinal[0];
 -                        }
 +                }
  
 -                        if (endIp == null) {
 +                if (endIp == null) {
-                     endIp = existingPodIpRange[1];
+                             endIp = existingPodIpRangeFinal[1];
 -                        }
 +                }
  
 -                        _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
 -                    }
 +                _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
 +            }
  
-             pod.setName(name);
+                     pod.setName(nameFinal);
 -                    pod.setDataCenterId(zoneId);
 +            pod.setDataCenterId(zoneId);
-             pod.setGateway(gateway);
+                     pod.setGateway(gatewayFinal);
 -                    pod.setCidrAddress(getCidrAddress(cidr));
 -                    pod.setCidrSize(getCidrSize(cidr));
 +            pod.setCidrAddress(getCidrAddress(cidr));
 +            pod.setCidrSize(getCidrSize(cidr));
  
 -                    String ipRange = startIp + "-" + endIp;
 -                    pod.setDescription(ipRange);
 -                    Grouping.AllocationState allocationState = null;
 +            String ipRange = startIp + "-" + endIp;
 +            pod.setDescription(ipRange);
 +            Grouping.AllocationState allocationState = null;
-             if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
-                 allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
-                 _capacityDao.updateCapacityState(null, pod.getId(), null, null, allocationStateStr);
+                     if (allocationStateStrFinal != null && !allocationStateStrFinal.isEmpty()) {
+                         allocationState = Grouping.AllocationState.valueOf(allocationStateStrFinal);
+                         _capacityDao.updateCapacityState(null, pod.getId(), null, null, allocationStateStrFinal);
 -                        pod.setAllocationState(allocationState);
 -                    }
 -        
 -                    _podDao.update(id, pod);
 +                pod.setAllocationState(allocationState);
 +            }
 +
 +            _podDao.update(id, pod);
- 
-             txn.commit();
+                 }
+             });
          } catch (Exception e) {
              s_logger.error("Unable to edit pod due to " + e.getMessage(), e);
              throw new CloudRuntimeException("Failed to edit pod. Please contact Cloud Support.");
@@@ -1266,27 -1269,29 +1269,29 @@@
          Grouping.AllocationState allocationState = null;
          if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
              allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
-             pod.setAllocationState(allocationState);
+             podFinal.setAllocationState(allocationState);
          }
  
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+         final String endIpFinal = endIp;
+         return Transaction.execute(new TransactionCallback<HostPodVO>() {
+             @Override
+             public HostPodVO doInTransaction(TransactionStatus status) {
  
-         pod = _podDao.persist(pod);
+                 HostPodVO pod = _podDao.persist(podFinal);
  
 -                if (startIp != null) {
 +        if (startIp != null) {
-             _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
+                     _zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIpFinal);
 -                }
 +        }
  
 -                String[] linkLocalIpRanges = getLinkLocalIPRange();
 -                if (linkLocalIpRanges != null) {
 -                    _zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
 -                }
 +        String[] linkLocalIpRanges = getLinkLocalIPRange();
 +        if (linkLocalIpRanges != null) {
 +            _zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
 +        }
  
-         txn.commit();
- 
 -                return pod;
 -            }
 +        return pod;
 +    }
+         });
+     }
  
      @DB
      protected void checkIfZoneIsDeletable(long zoneId) {
@@@ -1522,38 -1524,38 +1524,38 @@@
  
          checkIfZoneIsDeletable(zoneId);
  
-         txn.start();
- 
+         return Transaction.execute(new TransactionCallback<Boolean>() {
+             @Override
+             public Boolean doInTransaction(TransactionStatus status) {
 -                // delete vlans for this zone
 -                List<VlanVO> vlans = _vlanDao.listByZone(zoneId);
 -                for (VlanVO vlan : vlans) {
 -                    _vlanDao.remove(vlan.getId());
 -                }
 +        // delete vlans for this zone
 +        List<VlanVO> vlans = _vlanDao.listByZone(zoneId);
 +        for (VlanVO vlan : vlans) {
 +            _vlanDao.remove(vlan.getId());
 +        }
  
-         success = _zoneDao.remove(zoneId);
+                 boolean success = _zoneDao.remove(zoneId);
  
 -                if (success) {
 -                    // delete all capacity records for the zone
 -                    _capacityDao.removeBy(null, zoneId, null, null, null);
 -                    // remove from dedicated resources
 -                    DedicatedResourceVO dr = _dedicatedDao.findByZoneId(zoneId);
 -                    if (dr != null) {
 -                        _dedicatedDao.remove(dr.getId());
 -                        // find the group associated and check if there are any more
 -                        // resources under that group
 -                        List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(dr
 -                                .getAffinityGroupId());
 -                        if (resourcesInGroup.isEmpty()) {
 -                            // delete the group
 -                            _affinityGroupService.deleteAffinityGroup(dr.getAffinityGroupId(), null, null, null);
 -                        }
 -                    }
 +        if (success) {
 +            // delete all capacity records for the zone
 +            _capacityDao.removeBy(null, zoneId, null, null, null);
 +            // remove from dedicated resources
 +            DedicatedResourceVO dr = _dedicatedDao.findByZoneId(zoneId);
 +            if (dr != null) {
 +                _dedicatedDao.remove(dr.getId());
 +                // find the group associated and check if there are any more
 +                // resources under that group
 +                List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(dr
 +                        .getAffinityGroupId());
 +                if (resourcesInGroup.isEmpty()) {
 +                    // delete the group
 +                    _affinityGroupService.deleteAffinityGroup(dr.getAffinityGroupId(), null, null, null);
                  }
 +            }
 +        }
  
-         txn.commit();
- 
 -                return success;
 +        return success;
- 
+             }
+         });
      }
  
      @Override
@@@ -1699,86 -1701,87 +1701,87 @@@
              }
          }
  
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
- 
+         Transaction.execute(new TransactionCallbackNoReturn() {
+             @Override
+             public void doInTransactionWithoutResult(TransactionStatus status) {
 -                Map<String, String> updatedDetails = new HashMap<String, String>();
 -                _zoneDao.loadDetails(zone);
 -                if (zone.getDetails() != null) {
 -                    updatedDetails.putAll(zone.getDetails());
 -                }
 -                updatedDetails.putAll(newDetails);
 -                zone.setDetails(updatedDetails);
 -        
 -                if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
 -                    Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
 -        
 -                    if (allocationState == Grouping.AllocationState.Enabled) {
 -                        // check if zone has necessary trafficTypes before enabling
 -                        try {
 -                            PhysicalNetwork mgmtPhyNetwork;
 -                            // zone should have a physical network with management
 -                            // traffiType
 -                            mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId,
 -                                    TrafficType.Management);
 -                            if (NetworkType.Advanced == zone.getNetworkType() && !zone.isSecurityGroupEnabled()) {
 -                                // advanced zone without SG should have a physical
 -                                // network with public Thpe
 -                                _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
 -                            }
 -        
 -                            try {
 -                                _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
 -                            } catch (InvalidParameterValueException noStorage) {
 -                                PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(),
 -                                        TrafficType.Management);
 -                                _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(),
 -                                        TrafficType.Storage.toString(), mgmtTraffic.getXenNetworkLabel(),
 -                                        mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(),
 -                                        mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan());
 -                                s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network "
 -                                        + mgmtPhyNetwork.getId() + " with same configure of management traffic type");
 -                            }
 -                        } catch (InvalidParameterValueException ex) {
 -                            throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage());
 -                        }
 -                    }
 -                    _capacityDao.updateCapacityState(zone.getId(), null, null, null, allocationStateStr);
 -                    zone.setAllocationState(allocationState);
 -                }
 +        Map<String, String> updatedDetails = new HashMap<String, String>();
 +        _zoneDao.loadDetails(zone);
 +        if (zone.getDetails() != null) {
 +            updatedDetails.putAll(zone.getDetails());
 +        }
 +        updatedDetails.putAll(newDetails);
 +        zone.setDetails(updatedDetails);
  
 -                if (dhcpProvider != null) {
 -                    zone.setDhcpProvider(dhcpProvider);
 -                }
 +        if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
 +            Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
  
 -                // update a private zone to public; not vice versa
 -                if (isPublic != null && isPublic) {
 -                    zone.setDomainId(null);
 -                    zone.setDomain(null);
 -
 -                    // release the dedication for this zone
 -                    DedicatedResourceVO resource = _dedicatedDao.findByZoneId(zoneId);
 -                    Long resourceId = null;
 -                    if (resource != null) {
 -                        resourceId = resource.getId();
 -                        if (!_dedicatedDao.remove(resourceId)) {
 -                            throw new CloudRuntimeException("Failed to delete dedicated Zone Resource " + resourceId);
 -                        }
 -                        // find the group associated and check if there are any more
 -                        // resources under that group
 -                        List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
 -                        if (resourcesInGroup.isEmpty()) {
 -                            // delete the group
 -                            _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null);
 -                        }
 +            if (allocationState == Grouping.AllocationState.Enabled) {
 +                // check if zone has necessary trafficTypes before enabling
 +                try {
 +                    PhysicalNetwork mgmtPhyNetwork;
 +                    // zone should have a physical network with management
 +                    // traffiType
 +                    mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId,
 +                            TrafficType.Management);
 +                    if (NetworkType.Advanced == zone.getNetworkType() && !zone.isSecurityGroupEnabled()) {
 +                        // advanced zone without SG should have a physical
 +                        // network with public Thpe
 +                        _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                      }
 +
 +                    try {
 +                        _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
 +                    } catch (InvalidParameterValueException noStorage) {
 +                        PhysicalNetworkTrafficTypeVO mgmtTraffic = _trafficTypeDao.findBy(mgmtPhyNetwork.getId(),
 +                                TrafficType.Management);
 +                        _networkSvc.addTrafficTypeToPhysicalNetwork(mgmtPhyNetwork.getId(),
 +                                TrafficType.Storage.toString(), mgmtTraffic.getXenNetworkLabel(),
 +                                mgmtTraffic.getKvmNetworkLabel(), mgmtTraffic.getVmwareNetworkLabel(),
 +                                mgmtTraffic.getSimulatorNetworkLabel(), mgmtTraffic.getVlan());
 +                        s_logger.info("No storage traffic type was specified by admin, create default storage traffic on physical network "
 +                                + mgmtPhyNetwork.getId() + " with same configure of management traffic type");
 +                    }
 +                } catch (InvalidParameterValueException ex) {
 +                    throw new InvalidParameterValueException("Cannot enable this Zone since: " + ex.getMessage());
                  }
 +            }
 +            _capacityDao.updateCapacityState(zone.getId(), null, null, null, allocationStateStr);
 +            zone.setAllocationState(allocationState);
 +        }
  
 -                if (!_zoneDao.update(zoneId, zone)) {
 -                    throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support.");
 +        if (dhcpProvider != null) {
 +            zone.setDhcpProvider(dhcpProvider);
 +        }
 +        
 +        // update a private zone to public; not vice versa
 +        if (isPublic != null && isPublic) {
 +            zone.setDomainId(null);
 +            zone.setDomain(null);
 +
 +            // release the dedication for this zone
 +            DedicatedResourceVO resource = _dedicatedDao.findByZoneId(zoneId);
 +            Long resourceId = null;
 +            if (resource != null) {
 +                resourceId = resource.getId();
 +                if (!_dedicatedDao.remove(resourceId)) {
 +                    throw new CloudRuntimeException("Failed to delete dedicated Zone Resource " + resourceId);
                  }
 +                // find the group associated and check if there are any more
 +                // resources under that group
 +                List<DedicatedResourceVO> resourcesInGroup = _dedicatedDao.listByAffinityGroupId(resource.getAffinityGroupId());
 +                if (resourcesInGroup.isEmpty()) {
 +                    // delete the group
 +                    _affinityGroupService.deleteAffinityGroup(resource.getAffinityGroupId(), null, null, null);
 +                }
 +            }
 +        }
 +
 +        if (!_zoneDao.update(zoneId, zone)) {
 +            throw new CloudRuntimeException("Failed to edit zone. Please contact Cloud Support.");
 +        }
+             }
+         });
  
-         txn.commit();
          return zone;
      }
  
@@@ -1810,43 -1813,40 +1813,40 @@@
  
          byte[] bytes = (zoneName + System.currentTimeMillis()).getBytes();
          String zoneToken = UUID.nameUUIDFromBytes(bytes).toString();
-         Transaction txn = Transaction.currentTxn();
-         try {
-             txn.start();
+ 
 -        // Create the new zone in the database
 +            // Create the new zone in the database
-             DataCenterVO zone = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr,
+         final DataCenterVO zoneFinal = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr,
 -                domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled,
 -                isLocalStorageEnabled,
 -                ip6Dns1, ip6Dns2);
 -        if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
 -            Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
 +                    domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled,
 +                    isLocalStorageEnabled,
 +                    ip6Dns1, ip6Dns2);
 +            if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
 +                Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
-                 zone.setAllocationState(allocationState);
+             zoneFinal.setAllocationState(allocationState);
 -        } else {
 -            // Zone will be disabled since 3.0. Admin should enable it after
 -            // physical network and providers setup.
 +            } else {
 +                // Zone will be disabled since 3.0. Admin should enable it after
 +                // physical network and providers setup.
-                 zone.setAllocationState(Grouping.AllocationState.Disabled);
+             zoneFinal.setAllocationState(Grouping.AllocationState.Disabled);
 -        }
 +            }
-             zone = _zoneDao.persist(zone);
+ 
+         return Transaction.execute(new TransactionCallback<DataCenterVO>() {
+             @Override
+             public DataCenterVO doInTransaction(TransactionStatus status) {
+                 DataCenterVO zone = _zoneDao.persist(zoneFinal);
 -                if (domainId != null) {
 -                    // zone is explicitly dedicated to this domain
 -                    // create affinity group associated and dedicate the zone.
 -                    AffinityGroup group = createDedicatedAffinityGroup(null, domainId, null);
 -                    DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zone.getId(), null, null, null,
 -                            domainId, null, group.getId());
 -                    _dedicatedDao.persist(dedicatedResource);
 -                }
 +            if (domainId != null) {
 +                // zone is explicitly dedicated to this domain
 +                // create affinity group associated and dedicate the zone.
 +                AffinityGroup group = createDedicatedAffinityGroup(null, domainId, null);
 +                DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zone.getId(), null, null, null,
 +                        domainId, null, group.getId());
 +                _dedicatedDao.persist(dedicatedResource);
 +            }
  
 -                // Create default system networks
 -                createDefaultSystemNetworks(zone.getId());
 +            // Create default system networks
 +            createDefaultSystemNetworks(zone.getId());
-             txn.commit();
+ 
 -                return zone;
 -            }
 +            return zone;
-         } catch (Exception ex) {
-             txn.rollback();
-             s_logger.warn("Exception: ", ex);
-             throw new CloudRuntimeException("Fail to create a network");
-         } finally {
-             txn.close();
 +        }
+         });
      }
  
      private AffinityGroup createDedicatedAffinityGroup(String affinityGroupName, Long domainId, Long accountId) {
@@@ -2658,32 -2668,44 +2668,44 @@@
          if (ipv4) {
              checkOverlapPrivateIpRange(zoneId, startIP, endIP);
          }
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+ 
+         return commitVlan(zoneId, podId, startIP, endIP, newVlanGateway, newVlanNetmask, vlanId,
+                 forVirtualNetwork, networkId, physicalNetworkId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, vlanOwner,
+                 network, sameSubnet);
+     }
+ 
+     private Vlan commitVlan(final Long zoneId, final Long podId, final String startIP, final String endIP, final String newVlanGatewayFinal,
+             final String newVlanNetmaskFinal, final String vlanId, final Boolean forVirtualNetwork, final Long networkId, final Long physicalNetworkId,
+             final String startIPv6, final String endIPv6, final String ip6Gateway, final String ip6Cidr, final Account vlanOwner, final Network network,
+             final Pair<Boolean, Pair<String, String>> sameSubnet) {
+         return Transaction.execute(new TransactionCallback<Vlan>() {
+             @Override
+             public Vlan doInTransaction(TransactionStatus status) {
+                 String newVlanNetmask = newVlanNetmaskFinal;
+                 String newVlanGateway = newVlanGatewayFinal;
 -                
 -                if ((sameSubnet == null || sameSubnet.first() == false) && (network.getTrafficType()== TrafficType.Guest) && (network.getGuestType() == GuestType.Shared) && (_vlanDao.listVlansByNetworkId(networkId) != null)) {
 -                    Map<Capability, String> dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()), Service.Dhcp);
 -                    String supportsMultipleSubnets = dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets);
 -                    if (supportsMultipleSubnets == null || !Boolean.valueOf(supportsMultipleSubnets)) {
 -                               throw new  InvalidParameterValueException("The Dhcp serivice provider for this network dose not support the dhcp  across multiple subnets");
 -                    }
 -                    s_logger.info("adding a new subnet to the network " + network.getId());
 -                } else if (sameSubnet != null)  {
 -                    // if it is same subnet the user might not send the vlan and the
 -                    // netmask details. so we are
 -                    // figuring out while validation and setting them here.
 -                    newVlanGateway = sameSubnet.second().first();
 -                    newVlanNetmask = sameSubnet.second().second();
 -                }
 -                Vlan vlan = createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP,
 -                        endIP, newVlanGateway, newVlanNetmask, vlanId, vlanOwner, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
 -                // create an entry in the nic_secondary table. This will be the new
 -                // gateway that will be configured on the corresponding routervm.
 -                return vlan;
 -            }
 +
 +        if ((sameSubnet == null || sameSubnet.first() == false) && (network.getTrafficType()== TrafficType.Guest) && (network.getGuestType() == GuestType.Shared) && (_vlanDao.listVlansByNetworkId(networkId) != null)) {
 +            Map<Capability, String> dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()), Service.Dhcp);
 +            String supportsMultipleSubnets = dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets);
 +            if (supportsMultipleSubnets == null || !Boolean.valueOf(supportsMultipleSubnets)) {
 +                       throw new  InvalidParameterValueException("The Dhcp serivice provider for this network dose not support the dhcp  across multiple subnets");
 +            }
 +            s_logger.info("adding a new subnet to the network " + network.getId());
 +        } else if (sameSubnet != null)  {
 +            // if it is same subnet the user might not send the vlan and the
 +            // netmask details. so we are
 +            // figuring out while validation and setting them here.
 +            newVlanGateway = sameSubnet.second().first();
 +            newVlanNetmask = sameSubnet.second().second();
 +        }
 +        Vlan vlan = createVlanAndPublicIpRange(zoneId, networkId, physicalNetworkId, forVirtualNetwork, podId, startIP,
 +                endIP, newVlanGateway, newVlanNetmask, vlanId, vlanOwner, startIPv6, endIPv6, ip6Gateway, ip6Cidr);
 +        // create an entry in the nic_secondary table. This will be the new
 +        // gateway that will be configured on the corresponding routervm.
- 
-         txn.commit();
- 
 +        return vlan;
 +    }
+         });
+     }
  
      public NetUtils.supersetOrSubset checkIfSubsetOrSuperset(String newVlanGateway, String newVlanNetmask, VlanVO vlan, String startIP,
              String endIP) {
@@@ -3010,48 -3039,58 +3039,58 @@@
          }
  
          // Everything was fine, so persist the VLAN
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+         VlanVO vlan = commitVlanAndIpRange(zoneId, networkId, physicalNetworkId, podId, startIP, endIP, vlanGateway,
+                 vlanNetmask, vlanId, vlanOwner, vlanIp6Gateway, vlanIp6Cidr, ipv4, zone, vlanType, ipv6Range, ipRange);
  
+         return vlan;
+     }
+ 
+     private VlanVO commitVlanAndIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final Long podId,
+             final String startIP, final String endIP, final String vlanGateway, final String vlanNetmask, final String vlanId, final Account vlanOwner,
+             final String vlanIp6Gateway, final String vlanIp6Cidr, final boolean ipv4, final DataCenterVO zone, final VlanType vlanType,
+             final String ipv6Range, final String ipRange) {
+         return Transaction.execute(new TransactionCallback<VlanVO>() {
+             @Override
+             public VlanVO doInTransaction(TransactionStatus status) {
 -                VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId,
 -                        physicalNetworkId, vlanIp6Gateway, vlanIp6Cidr, ipv6Range);
 -                s_logger.debug("Saving vlan range " + vlan);
 -                vlan = _vlanDao.persist(vlan);
 +        VlanVO vlan = new VlanVO(vlanType, vlanId, vlanGateway, vlanNetmask, zone.getId(), ipRange, networkId,
 +                physicalNetworkId, vlanIp6Gateway, vlanIp6Cidr, ipv6Range);
 +        s_logger.debug("Saving vlan range " + vlan);
 +        vlan = _vlanDao.persist(vlan);
  
 -                // IPv6 use a used ip map, is different from ipv4, no need to save
 -                // public ip range
 -                if (ipv4) {
 -                    if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) {
 -                        throw new CloudRuntimeException("Failed to save IPv4 range. Please contact Cloud Support.");
 -                    }
 -                }
 +        // IPv6 use a used ip map, is different from ipv4, no need to save
 +        // public ip range
 +        if (ipv4) {
 +            if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) {
 +                throw new CloudRuntimeException("Failed to save IPv4 range. Please contact Cloud Support.");
 +            }
 +        }
  
 -                if (vlanOwner != null) {
 -                    // This VLAN is account-specific, so create an AccountVlanMapVO
 -                    // entry
 -                    AccountVlanMapVO accountVlanMapVO = new AccountVlanMapVO(vlanOwner.getId(), vlan.getId());
 -                    _accountVlanMapDao.persist(accountVlanMapVO);
 +        if (vlanOwner != null) {
 +            // This VLAN is account-specific, so create an AccountVlanMapVO
 +            // entry
 +            AccountVlanMapVO accountVlanMapVO = new AccountVlanMapVO(vlanOwner.getId(), vlan.getId());
 +            _accountVlanMapDao.persist(accountVlanMapVO);
  
 -                    // generate usage event for dedication of every ip address in the
 -                    // range
 -                    List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlan.getId());
 -                    for (IPAddressVO ip : ips) {
 -                        UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip
 -                                .getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan
 -                                .getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid());
 -                    }
 -                    // increment resource count for dedicated public ip's
 -                    _resourceLimitMgr.incrementResourceCount(vlanOwner.getId(), ResourceType.public_ip, new Long(ips.size()));
 -                } else if (podId != null) {
 -                    // This VLAN is pod-wide, so create a PodVlanMapVO entry
 -                    PodVlanMapVO podVlanMapVO = new PodVlanMapVO(podId, vlan.getId());
 -                    _podVlanMapDao.persist(podVlanMapVO);
 -                }
 -                return vlan;
 +            // generate usage event for dedication of every ip address in the
 +            // range
 +            List<IPAddressVO> ips = _publicIpAddressDao.listByVlanId(vlan.getId());
 +            for (IPAddressVO ip : ips) {
 +                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_IP_ASSIGN, vlanOwner.getId(), ip
 +                        .getDataCenterId(), ip.getId(), ip.getAddress().toString(), ip.isSourceNat(), vlan
 +                        .getVlanType().toString(), ip.getSystem(), ip.getClass().getName(), ip.getUuid());
              }
 +            // increment resource count for dedicated public ip's
 +            _resourceLimitMgr.incrementResourceCount(vlanOwner.getId(), ResourceType.public_ip, new Long(ips.size()));
 +        } else if (podId != null) {
 +            // This VLAN is pod-wide, so create a PodVlanMapVO entry
 +            PodVlanMapVO podVlanMapVO = new PodVlanMapVO(podId, vlan.getId());
 +            _podVlanMapDao.persist(podVlanMapVO);
 +        }
- 
-         txn.commit();
- 
 +        return vlan;
 +    }
+         });
+ 
+     }
  
      @Override
      @DB
@@@ -3142,12 -3181,13 +3181,13 @@@
              }
          }
  
- 
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+         Transaction.execute(new TransactionCallbackNoReturn() {
+             @Override
+             public void doInTransactionWithoutResult(TransactionStatus status) {
 -                _publicIpAddressDao.deletePublicIPRange(vlanDbId);
 -                _vlanDao.expunge(vlanDbId);
 +        _publicIpAddressDao.deletePublicIPRange(vlanDbId);
 +        _vlanDao.expunge(vlanDbId);
-         txn.commit();
+             }
+         });
  
          return true;
      }
@@@ -3328,16 -3363,20 +3363,20 @@@
      }
  
      @DB
-     protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid,
-             long physicalNetworkId) {
-         long startIPLong = NetUtils.ip2Long(startIP);
-         long endIPLong = NetUtils.ip2Long(endIP);
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+     protected boolean savePublicIPRange(String startIP, String endIP, final long zoneId, final long vlanDbId, final long sourceNetworkid,
+             final long physicalNetworkId) {
+         final long startIPLong = NetUtils.ip2Long(startIP);
+         final long endIPLong = NetUtils.ip2Long(endIP);
+ 
+         List<String> problemIps = Transaction.execute(new TransactionCallback<List<String>>() {
+             @Override
+             public List<String> doInTransaction(TransactionStatus status) {
 -                IPRangeConfig config = new IPRangeConfig();
 +        IPRangeConfig config = new IPRangeConfig();
-         List<String> problemIps = config.savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId,
+                 return config.savePublicIPRange(TransactionLegacy.currentTxn(), startIPLong, endIPLong, zoneId, vlanDbId,
 -                        sourceNetworkid, physicalNetworkId);
 +                sourceNetworkid, physicalNetworkId);
-         txn.commit();
+             }
+         });
+ 
          return problemIps != null && problemIps.size() == 0;
      }
  
@@@ -3956,13 -4004,13 +4004,13 @@@
                              + Capability.AssociatePublicIP.getName()
                              + " capabilitiy can be sepcified for static nat service");
                  }
-                 if (eipDisabled && associatePublicIP) {
+             }
+             if ((! eipEnabled) && associatePublicIP) {
 -                throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName()
 -                        + " can only be set when capability " + Capability.ElasticIp.getName() + " is true");
 +                    throw new InvalidParameterValueException("Capability " + Capability.AssociatePublicIP.getName()
 +                            + " can only be set when capability " + Capability.ElasticIp.getName() + " is true");
 +                }
              }
          }
--    }
  
      @Override
      @DB
@@@ -4125,47 -4173,51 +4173,51 @@@
              validateNtwkOffDetails(details, serviceProviderMap);
          }
  
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
+         return Transaction.execute(new TransactionCallback<NetworkOfferingVO>() {
+             @Override
+             public NetworkOfferingVO doInTransaction(TransactionStatus status) {
+                 NetworkOfferingVO offering = offeringFinal;
+ 
 -                // 1) create network offering object
 -                s_logger.debug("Adding network offering " + offering);
 -                offering.setConcurrentConnections(maxconn);
 +        // 1) create network offering object
 +        s_logger.debug("Adding network offering " + offering);
 +        offering.setConcurrentConnections(maxconn);
+                 offering.setKeepAliveEnabled(enableKeepAlive);
 -                offering = _networkOfferingDao.persist(offering, details);
 -                // 2) populate services and providers
 -                if (serviceProviderMap != null) {
 -                    for (Network.Service service : serviceProviderMap.keySet()) {
 -                        Set<Provider> providers = serviceProviderMap.get(service);
 -                        if (providers != null && !providers.isEmpty()) {
 -                            boolean vpcOff = false;
 -                            for (Network.Provider provider : providers) {
 -                                if (provider == Provider.VPCVirtualRouter) {
 -                                    vpcOff = true;
 -                                }
 -                                NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(),
 -                                        service, provider);
 -                                _ntwkOffServiceMapDao.persist(offService);
 -                                s_logger.trace("Added service for the network offering: " + offService + " with provider "
 -                                        + provider.getName());
 -                            }
 -
 -                            if (vpcOff) {
 -                                List<Service> supportedSvcs = new ArrayList<Service>();
 -                                supportedSvcs.addAll(serviceProviderMap.keySet());
 -                                _vpcMgr.validateNtwkOffForVpc(offering, supportedSvcs);
 -                            }
 -                        } else {
 -                            NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service,
 -                                    null);
 -                            _ntwkOffServiceMapDao.persist(offService);
 -                            s_logger.trace("Added service for the network offering: " + offService + " with null provider");
 +        offering = _networkOfferingDao.persist(offering, details);
 +        // 2) populate services and providers
 +        if (serviceProviderMap != null) {
 +            for (Network.Service service : serviceProviderMap.keySet()) {
 +                Set<Provider> providers = serviceProviderMap.get(service);
 +                if (providers != null && !providers.isEmpty()) {
 +                    boolean vpcOff = false;
 +                    for (Network.Provider provider : providers) {
 +                        if (provider == Provider.VPCVirtualRouter) {
 +                            vpcOff = true;
                          }
 +                        NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(),
 +                                service, provider);
 +                        _ntwkOffServiceMapDao.persist(offService);
 +                        s_logger.trace("Added service for the network offering: " + offService + " with provider "
 +                                + provider.getName());
                      }
 -                }
  
 -                return offering;
 +                    if (vpcOff) {
 +                        List<Service> supportedSvcs = new ArrayList<Service>();
 +                        supportedSvcs.addAll(serviceProviderMap.keySet());
 +                        _vpcMgr.validateNtwkOffForVpc(offering, supportedSvcs);
 +                    }
 +                } else {
 +                    NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service,
 +                            null);
 +                    _ntwkOffServiceMapDao.persist(offService);
 +                    s_logger.trace("Added service for the network offering: " + offService + " with null provider");
 +                }
              }
 +        }
 +
-         txn.commit();
- 
 +        return offering;
 +    }
+         });
+     }
  
      protected void validateNtwkOffDetails(Map<Detail, String> details, Map<Service, Set<Provider>> serviceProviderMap) {
          for (Detail detail : details.keySet()) {
@@@ -4691,22 -4743,24 +4743,24 @@@
  
      @Override
      @DB
-     public boolean releaseAccountSpecificVirtualRanges(long accountId) {
-         List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
-         boolean result = true;
+     public boolean releaseAccountSpecificVirtualRanges(final long accountId) {
+         final List<AccountVlanMapVO> maps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
          if (maps != null && !maps.isEmpty()) {
-             Transaction txn = Transaction.currentTxn();
-             txn.start();
+             try {
+                 Transaction.execute(new TransactionCallbackNoReturn() {
+                     @Override
+                     public void doInTransactionWithoutResult(TransactionStatus status) {
 -                        for (AccountVlanMapVO map : maps) {
 -                            if (!releasePublicIpRange(map.getVlanDbId(), _accountMgr.getSystemUser().getId(),
 -                                    _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM))) {
 +            for (AccountVlanMapVO map : maps) {
 +                if (!releasePublicIpRange(map.getVlanDbId(), _accountMgr.getSystemUser().getId(),
 +                        _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM))) {
-                     result = false;
+                                 throw new CloudRuntimeException("Failed to release account specific virtual ip ranges for account id=" + accountId);
 -                            }
 -                        }
 +                }
 +            }
-             if (result) {
-                 txn.commit();
-             } else {
-                 s_logger.error("Failed to release account specific virtual ip ranges for account id=" + accountId);
+                     }
+                 });
+             } catch ( CloudRuntimeException e ) {
+                 s_logger.error(e);
+                 return false;
              }
          } else {
              s_logger.trace("Account id=" + accountId + " has no account specific virtual ip ranges, nothing to release");
@@@ -4833,29 -4889,34 +4889,34 @@@
          }
          GlobalLock portableIpLock = GlobalLock.getInternLock("PortablePublicIpRange");
          portableIpLock.lock(5);
-         Transaction txn = Transaction.currentTxn();
-         txn.start();
- 
-         PortableIpRangeVO portableIpRange = new PortableIpRangeVO(regionId, vlanId, gateway, netmask, startIP, endIP);
+         try {
+             final String vlanIdFinal = vlanId;
+             return Transaction.execute(new TransactionCallback<PortableIpRangeVO>() {
+                 @Override
+                 public PortableIpRangeVO doInTransaction(TransactionStatus status) {
+                     PortableIpRangeVO portableIpRange = new PortableIpRangeVO(regionId, vlanIdFinal, gateway, netmask, startIP, endIP);
 -                    portableIpRange = _portableIpRangeDao.persist(portableIpRange);
 +        portableIpRange = _portableIpRangeDao.persist(portableIpRange);
  
 -                    long startIpLong = NetUtils.ip2Long(startIP);
 -                    long endIpLong = NetUtils.ip2Long(endIP);
 -                    while (startIpLong <= endIpLong) {
 +        long startIpLong = NetUtils.ip2Long(startIP);
 +        long endIpLong = NetUtils.ip2Long(endIP);
 +        while (startIpLong <= endIpLong) {
-             PortableIpVO portableIP = new PortableIpVO(regionId, portableIpRange.getId(), vlanId, gateway, netmask,
+                         PortableIpVO portableIP = new PortableIpVO(regionId, portableIpRange.getId(), vlanIdFinal, gateway, netmask,
 -                                NetUtils.long2Ip(startIpLong));
 -                        _portableIpDao.persist(portableIP);
 -                        startIpLong++;
 -                    }
 +                    NetUtils.long2Ip(startIpLong));
 +            _portableIpDao.persist(portableIP);
 +            startIpLong++;
 +        }
  
 -                    // implicitly enable portable IP service for the region
 -                    region.setPortableipEnabled(true);
 -                    _regionDao.update(region.getId(), region);
 -                    
 -                    return portableIpRange;
 -                }
 +        // implicitly enable portable IP service for the region
 +        region.setPortableipEnabled(true);
 +        _regionDao.update(region.getId(), region);
 +
-         txn.commit();
-         portableIpLock.unlock();
 +        return portableIpRange;
 +    }
+             });
+         } finally {
+             portableIpLock.unlock();
+         }
+     }
  
      @Override
      @DB

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2ef4d520/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
index e1d5cb1,e79e8e3..719f209
--- a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
+++ b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
@@@ -562,36 -565,35 +565,35 @@@ public class DeploymentPlanningManagerI
                      return false;
                  }
              } else {
+                 final PlannerResourceUsage hostResourceTypeFinal = hostResourceType;
                  // reserve the host for required resourceType
                  // let us lock the reservation entry before updating.
-                 final Transaction txn = Transaction.currentTxn();
- 
-                 try {
-                     txn.start();
- 
+                 return Transaction.execute(new TransactionCallback<Boolean>() {
+                     @Override
+                     public Boolean doInTransaction(TransactionStatus status) {
 -                        final PlannerHostReservationVO lockedEntry = _plannerHostReserveDao.lockRow(id, true);
 -                        if (lockedEntry == null) {
 -                            s_logger.error("Unable to lock the host entry for reservation, host: " + hostId);
 -                            return false;
 -                        }
 -                        // check before updating
 -                        if (lockedEntry.getResourceUsage() == null) {
 -                            lockedEntry.setResourceUsage(resourceUsageRequired);
 -                            _plannerHostReserveDao.persist(lockedEntry);
 +                    final PlannerHostReservationVO lockedEntry = _plannerHostReserveDao.lockRow(id, true);
 +                    if (lockedEntry == null) {
 +                        s_logger.error("Unable to lock the host entry for reservation, host: " + hostId);
 +                        return false;
 +                    }
 +                    // check before updating
 +                    if (lockedEntry.getResourceUsage() == null) {
 +                        lockedEntry.setResourceUsage(resourceUsageRequired);
 +                        _plannerHostReserveDao.persist(lockedEntry);
 +                        return true;
 +                    } else {
 +                        // someone updated it earlier. check if we can still use it
 +                        if (lockedEntry.getResourceUsage() == resourceUsageRequired) {
                              return true;
                          } else {
 -                            // someone updated it earlier. check if we can still use it
 -                            if (lockedEntry.getResourceUsage() == resourceUsageRequired) {
 -                                return true;
 -                            } else {
 -                                s_logger.debug("Cannot use this host for usage: " + resourceUsageRequired
 +                            s_logger.debug("Cannot use this host for usage: " + resourceUsageRequired
-                                     + ", since this host has been reserved for planner usage : " + hostResourceType);
+                                         + ", since this host has been reserved for planner usage : " + hostResourceTypeFinal);
 -                                return false;
 -                            }
 +                            return false;
                          }
                      }
-                 } finally {
-                     txn.commit();
 +                }
+                 });
+ 
              }
  
          }
@@@ -662,26 -664,26 +664,26 @@@
                      s_logger.debug("Host has no VMs associated, releasing the planner reservation for host " + hostId);
                  }
  
-                 long id = reservationEntry.getId();
-                 final Transaction txn = Transaction.currentTxn();
- 
-                 try {
-                     txn.start();
+                 final long id = reservationEntry.getId();
  
+                 return Transaction.execute(new TransactionCallback<Boolean>() {
+                     @Override
+                     public Boolean doInTransaction(TransactionStatus status) {
 -                        final PlannerHostReservationVO lockedEntry = _plannerHostReserveDao.lockRow(id, true);
 -                        if (lockedEntry == null) {
 -                            s_logger.error("Unable to lock the host entry for reservation, host: " + hostId);
 -                            return false;
 -                        }
 -                        // check before updating
 -                        if (lockedEntry.getResourceUsage() != null) {
 -                            lockedEntry.setResourceUsage(null);
 -                            _plannerHostReserveDao.persist(lockedEntry);
 -                            return true;
 -                        }
 -
 +                    final PlannerHostReservationVO lockedEntry = _plannerHostReserveDao.lockRow(id, true);
 +                    if (lockedEntry == null) {
 +                        s_logger.error("Unable to lock the host entry for reservation, host: " + hostId);
                          return false;
                      }
 +                    // check before updating
 +                    if (lockedEntry.getResourceUsage() != null) {
 +                        lockedEntry.setResourceUsage(null);
 +                        _plannerHostReserveDao.persist(lockedEntry);
 +                        return true;
 +                    }
-                 } finally {
-                     txn.commit();
++
++                        return false;
 +                }
+                 });
              }
  
          }
@@@ -935,12 -938,32 +938,32 @@@
              }
          }
  
+         // Cluster can be put in avoid set in following scenarios:
+         // 1. If storage allocators haven't put any pools in avoid set means either no pools in cluster 
+         // or pools not suitable for the allocators to handle.
+         // 2. If all 'shared' or 'local' pools are in avoid set
+         if  (allocatorAvoidOutput.getPoolsToAvoid() != null && !allocatorAvoidOutput.getPoolsToAvoid().isEmpty()) {
+             // check shared pools
 -            List<StoragePoolVO> allPoolsInCluster = _storagePoolDao.findPoolsByTags(clusterVO.getDataCenterId(),
 -                    clusterVO.getPodId(), clusterVO.getId(), null);
 -            for (StoragePoolVO pool : allPoolsInCluster) {
 -                if (!allocatorAvoidOutput.shouldAvoid(pool)) {
 -                    // there's some pool in the cluster that is not yet in avoid set
 -                    avoidAllPools = false;
 +        List<StoragePoolVO> allPoolsInCluster = _storagePoolDao.findPoolsByTags(clusterVO.getDataCenterId(),
 +                clusterVO.getPodId(), clusterVO.getId(), null);
 +        for (StoragePoolVO pool : allPoolsInCluster) {
 +            if (!allocatorAvoidOutput.shouldAvoid(pool)) {
 +                // there's some pool in the cluster that is not yet in avoid set
 +                avoidAllPools = false;
+                     break;
+                 }
+             }
+             if (avoidAllPools) {
+                 // check local pools
+                 List<StoragePoolVO> allLocalPoolsInCluster = _storagePoolDao.findLocalStoragePoolsByTags(clusterVO.getDataCenterId(),
+                         clusterVO.getPodId(), clusterVO.getId(), null);
+                 for (StoragePoolVO pool : allLocalPoolsInCluster) {
+                     if (!allocatorAvoidOutput.shouldAvoid(pool)) {
+                         // there's some pool in the cluster that is not yet in avoid set
+                         avoidAllPools = false;
+                         break;
+                     }
+                 }
              }
          }
  
@@@ -1230,51 -1253,52 +1253,52 @@@
  
      @DB
      @Override
-     public String finalizeReservation(DeployDestination plannedDestination,
-             VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids)
+     public String finalizeReservation(final DeployDestination plannedDestination,
+             final VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids)
              throws InsufficientServerCapacityException, AffinityConflictException {
  
-         VirtualMachine vm = vmProfile.getVirtualMachine();
-         long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
+         final VirtualMachine vm = vmProfile.getVirtualMachine();
+         final long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
  
+         return Transaction.execute(new TransactionCallback<String>() {
+             @Override
+             public String doInTransaction(TransactionStatus status) {
 -                boolean saveReservation = true;
 -
 -                if (vmGroupCount > 0) {
 -                    List<Long> groupIds = _affinityGroupVMMapDao.listAffinityGroupIdsByVmId(vm.getId());
 -                    SearchCriteria<AffinityGroupVO> criteria = _affinityGroupDao.createSearchCriteria();
 -                    criteria.addAnd("id", SearchCriteria.Op.IN, groupIds.toArray(new Object[groupIds.size()]));
 -                    List<AffinityGroupVO> groups = _affinityGroupDao.lockRows(criteria, null, true);
 -
 -                    for (AffinityGroupProcessor processor : _affinityProcessors) {
 -                        if (!processor.check(vmProfile, plannedDestination)) {
 -                            saveReservation = false;
 -                            break;
 -                        }
 +        boolean saveReservation = true;
-         final Transaction txn = Transaction.currentTxn();
-         try {
-             txn.start();
++
 +            if (vmGroupCount > 0) {
 +                List<Long> groupIds = _affinityGroupVMMapDao.listAffinityGroupIdsByVmId(vm.getId());
 +                SearchCriteria<AffinityGroupVO> criteria = _affinityGroupDao.createSearchCriteria();
 +                criteria.addAnd("id", SearchCriteria.Op.IN, groupIds.toArray(new Object[groupIds.size()]));
 +                List<AffinityGroupVO> groups = _affinityGroupDao.lockRows(criteria, null, true);
 +
 +                for (AffinityGroupProcessor processor : _affinityProcessors) {
 +                    if (!processor.check(vmProfile, plannedDestination)) {
 +                        saveReservation = false;
 +                        break;
                      }
                  }
 +            }
  
 -                if (saveReservation) {
 -                    VMReservationVO vmReservation = new VMReservationVO(vm.getId(), plannedDestination.getDataCenter()
 -                            .getId(), plannedDestination.getPod().getId(), plannedDestination.getCluster().getId(),
 -                            plannedDestination.getHost().getId());
 -                    Map<Long, Long> volumeReservationMap = new HashMap<Long, Long>();
 +            if (saveReservation) {
 +                VMReservationVO vmReservation = new VMReservationVO(vm.getId(), plannedDestination.getDataCenter()
 +                        .getId(), plannedDestination.getPod().getId(), plannedDestination.getCluster().getId(),
 +                        plannedDestination.getHost().getId());
 +                Map<Long, Long> volumeReservationMap = new HashMap<Long, Long>();
  
 -                    if (vm.getHypervisorType() != HypervisorType.BareMetal) {
 -                        for (Volume vo : plannedDestination.getStorageForDisks().keySet()) {
 -                            volumeReservationMap.put(vo.getId(), plannedDestination.getStorageForDisks().get(vo).getId());
 -                        }
 -                        vmReservation.setVolumeReservation(volumeReservationMap);
 +                if (vm.getHypervisorType() != HypervisorType.BareMetal) {
 +                    for (Volume vo : plannedDestination.getStorageForDisks().keySet()) {
 +                        volumeReservationMap.put(vo.getId(), plannedDestination.getStorageForDisks().get(vo).getId());
                      }
 -                    _reservationDao.persist(vmReservation);
 -                    return vmReservation.getUuid();
 +                    vmReservation.setVolumeReservation(volumeReservationMap);
                  }
 -
 -                return null;
 +                _reservationDao.persist(vmReservation);
 +                return vmReservation.getUuid();
              }
-         } finally {
-             txn.commit();
-         }
++
 +        return null;
 +    }
+         });
+     }
  
      @Override
      public boolean preStateTransitionEvent(State oldState, Event event, State newState, VirtualMachine vo,