You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ed...@apache.org on 2013/01/15 03:04:55 UTC

[11/44] Revert "Merge remote-tracking branch 'origin/javelin' into javelin"

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/dc/dao/HostPodDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java
index a06bd3f..4844d02 100644
--- a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java
+++ b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java
@@ -24,6 +24,7 @@ import java.util.HashMap;
 import java.util.List;
 
 import javax.ejb.Local;
+import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
@@ -37,7 +38,6 @@ import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.SearchCriteria.Op;
 import com.cloud.utils.db.Transaction;
-import com.cloud.utils.component.ComponentLocator;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.dao.VMInstanceDaoImpl;
@@ -46,32 +46,32 @@ import com.cloud.vm.dao.VMInstanceDaoImpl;
 @Local(value={HostPodDao.class})
 public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements HostPodDao {
     private static final Logger s_logger = Logger.getLogger(HostPodDaoImpl.class);
-	
-	protected SearchBuilder<HostPodVO> DataCenterAndNameSearch;
-	protected SearchBuilder<HostPodVO> DataCenterIdSearch;
-	
-	protected HostPodDaoImpl() {
-	    DataCenterAndNameSearch = createSearchBuilder();
-	    DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
-	    DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ);
-	    DataCenterAndNameSearch.done();
-	    
-	    DataCenterIdSearch = createSearchBuilder();
-	    DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
-	    DataCenterIdSearch.done();
-	}
-	
-	@Override
+    @Inject VMInstanceDaoImpl _vmDao;
+
+    protected SearchBuilder<HostPodVO> DataCenterAndNameSearch;
+    protected SearchBuilder<HostPodVO> DataCenterIdSearch;
+
+    protected HostPodDaoImpl() {
+        DataCenterAndNameSearch = createSearchBuilder();
+        DataCenterAndNameSearch.and("dc", DataCenterAndNameSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        DataCenterAndNameSearch.and("name", DataCenterAndNameSearch.entity().getName(), SearchCriteria.Op.EQ);
+        DataCenterAndNameSearch.done();
+
+        DataCenterIdSearch = createSearchBuilder();
+        DataCenterIdSearch.and("dcId", DataCenterIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        DataCenterIdSearch.done();
+    }
+
+    @Override
     public List<HostPodVO> listByDataCenterId(long id) {
-		SearchCriteria<HostPodVO> sc = DataCenterIdSearch.create();
-		sc.setParameters("dcId", id);
-		
-	    return listBy(sc);
-	}
-	
-	@Override
+        SearchCriteria<HostPodVO> sc = DataCenterIdSearch.create();
+        sc.setParameters("dcId", id);
+
+        return listBy(sc);
+    }
+
+    @Override
     public List<HostPodVO> listByDataCenterIdVMTypeAndStates(long id, VirtualMachine.Type type, VirtualMachine.State... states) {
-        final VMInstanceDaoImpl _vmDao = ComponentLocator.inject(VMInstanceDaoImpl.class);
         SearchBuilder<VMInstanceVO> vmInstanceSearch = _vmDao.createSearchBuilder();
         vmInstanceSearch.and("type", vmInstanceSearch.entity().getType(), SearchCriteria.Op.EQ);
         vmInstanceSearch.and("states", vmInstanceSearch.entity().getState(), SearchCriteria.Op.IN);
@@ -90,51 +90,51 @@ public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements H
         return listBy(sc);
     }
 
-	@Override
+    @Override
     public HostPodVO findByName(String name, long dcId) {
-	    SearchCriteria<HostPodVO> sc = DataCenterAndNameSearch.create();
-	    sc.setParameters("dc", dcId);
-	    sc.setParameters("name", name);
-	    
-	    return findOneBy(sc);
-	}
-	
-	@Override
-	public HashMap<Long, List<Object>> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) {
-		HashMap<Long, List<Object>> currentPodCidrSubnets = new HashMap<Long, List<Object>>();
-		
-		String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL";
-		Transaction txn = Transaction.currentTxn();
-		try {
-        	PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
-        	ResultSet rs = stmt.executeQuery();
-        	while (rs.next()) {
-        		Long podId = rs.getLong("id");
-        		if (podId.longValue() == podIdToSkip) {
+        SearchCriteria<HostPodVO> sc = DataCenterAndNameSearch.create();
+        sc.setParameters("dc", dcId);
+        sc.setParameters("name", name);
+
+        return findOneBy(sc);
+    }
+
+    @Override
+    public HashMap<Long, List<Object>> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip) {
+        HashMap<Long, List<Object>> currentPodCidrSubnets = new HashMap<Long, List<Object>>();
+
+        String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + zoneId +" and removed IS NULL";
+        Transaction txn = Transaction.currentTxn();
+        try {
+            PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
+            ResultSet rs = stmt.executeQuery();
+            while (rs.next()) {
+                Long podId = rs.getLong("id");
+                if (podId.longValue() == podIdToSkip) {
                     continue;
                 }
-        		String cidrAddress = rs.getString("cidr_address");
-        		long cidrSize = rs.getLong("cidr_size");
-        		List<Object> cidrPair = new ArrayList<Object>();
-        		cidrPair.add(0, cidrAddress);
-        		cidrPair.add(1, new Long(cidrSize));
-        		currentPodCidrSubnets.put(podId, cidrPair);
-        	}
+                String cidrAddress = rs.getString("cidr_address");
+                long cidrSize = rs.getLong("cidr_size");
+                List<Object> cidrPair = new ArrayList<Object>();
+                cidrPair.add(0, cidrAddress);
+                cidrPair.add(1, new Long(cidrSize));
+                currentPodCidrSubnets.put(podId, cidrPair);
+            }
         } catch (SQLException ex) {
-        	s_logger.warn("DB exception " + ex.getMessage(), ex);
+            s_logger.warn("DB exception " + ex.getMessage(), ex);
             return null;
         }
-        
+
         return currentPodCidrSubnets;
-	}
-	
+    }
+
     @Override
     public boolean remove(Long id) {
         Transaction txn = Transaction.currentTxn();
         txn.start();
         HostPodVO pod = createForUpdate();
         pod.setName(null);
-        
+
         update(id, pod);
 
         boolean result = super.remove(id);
@@ -150,11 +150,11 @@ public class HostPodDaoImpl extends GenericDaoBase<HostPodVO, Long> implements H
         podIdSearch.and("allocationState", podIdSearch.entity().getAllocationState(), Op.EQ);
         podIdSearch.done();
 
-        
+
         SearchCriteria<Long> sc = podIdSearch.create();
         sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
         sc.addAnd("allocationState", SearchCriteria.Op.EQ, Grouping.AllocationState.Disabled);
         return customSearch(sc, null);
     }
-    
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/dc/dao/VlanDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/dc/dao/VlanDaoImpl.java b/server/src/com/cloud/dc/dao/VlanDaoImpl.java
index 8fc0580..c5a635f 100644
--- a/server/src/com/cloud/dc/dao/VlanDaoImpl.java
+++ b/server/src/com/cloud/dc/dao/VlanDaoImpl.java
@@ -36,7 +36,6 @@ import com.cloud.dc.Vlan.VlanType;
 import com.cloud.dc.VlanVO;
 import com.cloud.network.dao.IPAddressDao;
 import com.cloud.utils.Pair;
-import com.cloud.utils.component.ComponentLocator;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.JoinBuilder;
@@ -48,56 +47,56 @@ import com.cloud.utils.exception.CloudRuntimeException;
 @Component
 @Local(value={VlanDao.class})
 public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao {
-    
-	private final String FindZoneWideVlans = "SELECT * FROM vlan WHERE data_center_id=? and vlan_type=? and vlan_id!=? and id not in (select vlan_db_id from account_vlan_map)";
-	
-	protected SearchBuilder<VlanVO> ZoneVlanIdSearch;
-	protected SearchBuilder<VlanVO> ZoneSearch;
-	protected SearchBuilder<VlanVO> ZoneTypeSearch;
-	protected SearchBuilder<VlanVO> ZoneTypeAllPodsSearch;
-	protected SearchBuilder<VlanVO> ZoneTypePodSearch;
-	protected SearchBuilder<VlanVO> ZoneVlanSearch;
-	protected SearchBuilder<VlanVO> NetworkVlanSearch;
-	protected SearchBuilder<VlanVO> PhysicalNetworkVlanSearch;
-
-	@Inject protected PodVlanMapDao _podVlanMapDao;
-	@Inject protected AccountVlanMapDao _accountVlanMapDao;
-	@Inject protected IPAddressDao _ipAddressDao;
-	 	
+
+    private final String FindZoneWideVlans = "SELECT * FROM vlan WHERE data_center_id=? and vlan_type=? and vlan_id!=? and id not in (select vlan_db_id from account_vlan_map)";
+
+    protected SearchBuilder<VlanVO> ZoneVlanIdSearch;
+    protected SearchBuilder<VlanVO> ZoneSearch;
+    protected SearchBuilder<VlanVO> ZoneTypeSearch;
+    protected SearchBuilder<VlanVO> ZoneTypeAllPodsSearch;
+    protected SearchBuilder<VlanVO> ZoneTypePodSearch;
+    protected SearchBuilder<VlanVO> ZoneVlanSearch;
+    protected SearchBuilder<VlanVO> NetworkVlanSearch;
+    protected SearchBuilder<VlanVO> PhysicalNetworkVlanSearch;
+
+    @Inject protected PodVlanMapDao _podVlanMapDao;
+    @Inject protected AccountVlanMapDao _accountVlanMapDao;
+    @Inject protected IPAddressDao _ipAddressDao;
+
     @Override
     public VlanVO findByZoneAndVlanId(long zoneId, String vlanId) {
-    	SearchCriteria<VlanVO> sc = ZoneVlanIdSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	sc.setParameters("vlanId", vlanId);
+        SearchCriteria<VlanVO> sc = ZoneVlanIdSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        sc.setParameters("vlanId", vlanId);
         return findOneBy(sc);
     }
-    
+
     @Override
     public List<VlanVO> listByZone(long zoneId) {
-    	SearchCriteria<VlanVO> sc = ZoneSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	return listBy(sc);
+        SearchCriteria<VlanVO> sc = ZoneSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        return listBy(sc);
     }
-	
+
     public VlanDaoImpl() {
-    	ZoneVlanIdSearch = createSearchBuilder();
-    	ZoneVlanIdSearch.and("zoneId", ZoneVlanIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        ZoneVlanIdSearch = createSearchBuilder();
+        ZoneVlanIdSearch.and("zoneId", ZoneVlanIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         ZoneVlanIdSearch.and("vlanId", ZoneVlanIdSearch.entity().getVlanTag(), SearchCriteria.Op.EQ);
         ZoneVlanIdSearch.done();
-        
+
         ZoneSearch = createSearchBuilder();
         ZoneSearch.and("zoneId", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         ZoneSearch.done();
-        
+
         ZoneTypeSearch = createSearchBuilder();
         ZoneTypeSearch.and("zoneId", ZoneTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         ZoneTypeSearch.and("vlanType", ZoneTypeSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
         ZoneTypeSearch.done();
-        
+
         NetworkVlanSearch = createSearchBuilder();
         NetworkVlanSearch.and("networkOfferingId", NetworkVlanSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
         NetworkVlanSearch.done();
-        
+
         PhysicalNetworkVlanSearch = createSearchBuilder();
         PhysicalNetworkVlanSearch.and("physicalNetworkId", PhysicalNetworkVlanSearch.entity().getPhysicalNetworkId(), SearchCriteria.Op.EQ);
         PhysicalNetworkVlanSearch.done();
@@ -105,211 +104,211 @@ public class VlanDaoImpl extends GenericDaoBase<VlanVO, Long> implements VlanDao
 
     @Override
     public List<VlanVO> listZoneWideVlans(long zoneId, VlanType vlanType, String vlanId){
-    	SearchCriteria<VlanVO> sc = ZoneVlanSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	sc.setParameters("vlanId", vlanId);
-    	sc.setParameters("vlanType", vlanType);
-    	return listBy(sc);
+        SearchCriteria<VlanVO> sc = ZoneVlanSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        sc.setParameters("vlanId", vlanId);
+        sc.setParameters("vlanType", vlanType);
+        return listBy(sc);
     }
-    
-	@Override
-	public List<VlanVO> listByZoneAndType(long zoneId, VlanType vlanType) {
-		SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	sc.setParameters("vlanType", vlanType);
+
+    @Override
+    public List<VlanVO> listByZoneAndType(long zoneId, VlanType vlanType) {
+        SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        sc.setParameters("vlanType", vlanType);
         return listBy(sc);
-	}
-	
-	
-	@Override
+    }
+
+
+    @Override
     public List<VlanVO> listByType(VlanType vlanType) {
         SearchCriteria<VlanVO> sc = ZoneTypeSearch.create();
         sc.setParameters("vlanType", vlanType);
         return listBy(sc);
     }
 
-	@Override
-	public List<VlanVO> listVlansForPod(long podId) {
-		//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two
-		List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
-		List<VlanVO> result  = new ArrayList<VlanVO>();
-		for (PodVlanMapVO pvmvo: vlanMaps) {
-			result.add(findById(pvmvo.getVlanDbId()));
-		}
-		return result;
-	}
-
-	@Override
-	public List<VlanVO> listVlansForPodByType(long podId, VlanType vlanType) {
-		//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
-		List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
-		List<VlanVO> result  = new ArrayList<VlanVO>();
-		for (PodVlanMapVO pvmvo: vlanMaps) {
-			VlanVO vlan =findById(pvmvo.getVlanDbId());
-			if (vlan.getVlanType() == vlanType) {
-				result.add(vlan);
-			}
-		}
-		return result;
-	}
-	
-	@Override
-	public List<VlanVO> listVlansForAccountByType(Long zoneId, long accountId, VlanType vlanType) {
-		//FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
-		List<AccountVlanMapVO> vlanMaps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
-		List<VlanVO> result  = new ArrayList<VlanVO>();
-		for (AccountVlanMapVO acvmvo: vlanMaps) {
-			VlanVO vlan =findById(acvmvo.getVlanDbId());
-			if (vlan.getVlanType() == vlanType && (zoneId == null || vlan.getDataCenterId() == zoneId)) {
-				result.add(vlan);
-			}
-		}
-		return result;
-	}
-
-	@Override
-	public void addToPod(long podId, long vlanDbId) {
-		PodVlanMapVO pvmvo = new PodVlanMapVO(podId, vlanDbId);
-		_podVlanMapDao.persist(pvmvo);
-		
-	}
-
-	@Override
-	public boolean configure(String name, Map<String, Object> params)
-			throws ConfigurationException {
-		boolean result = super.configure(name, params);
+    @Override
+    public List<VlanVO> listVlansForPod(long podId) {
+        //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two
+        List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
+        List<VlanVO> result  = new ArrayList<VlanVO>();
+        for (PodVlanMapVO pvmvo: vlanMaps) {
+            result.add(findById(pvmvo.getVlanDbId()));
+        }
+        return result;
+    }
+
+    @Override
+    public List<VlanVO> listVlansForPodByType(long podId, VlanType vlanType) {
+        //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
+        List<PodVlanMapVO> vlanMaps = _podVlanMapDao.listPodVlanMapsByPod(podId);
+        List<VlanVO> result  = new ArrayList<VlanVO>();
+        for (PodVlanMapVO pvmvo: vlanMaps) {
+            VlanVO vlan =findById(pvmvo.getVlanDbId());
+            if (vlan.getVlanType() == vlanType) {
+                result.add(vlan);
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public List<VlanVO> listVlansForAccountByType(Long zoneId, long accountId, VlanType vlanType) {
+        //FIXME: use a join statement to improve the performance (should be minor since we expect only one or two)
+        List<AccountVlanMapVO> vlanMaps = _accountVlanMapDao.listAccountVlanMapsByAccount(accountId);
+        List<VlanVO> result  = new ArrayList<VlanVO>();
+        for (AccountVlanMapVO acvmvo: vlanMaps) {
+            VlanVO vlan =findById(acvmvo.getVlanDbId());
+            if (vlan.getVlanType() == vlanType && (zoneId == null || vlan.getDataCenterId() == zoneId)) {
+                result.add(vlan);
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public void addToPod(long podId, long vlanDbId) {
+        PodVlanMapVO pvmvo = new PodVlanMapVO(podId, vlanDbId);
+        _podVlanMapDao.persist(pvmvo);
+
+    }
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params)
+            throws ConfigurationException {
+        boolean result = super.configure(name, params);
         ZoneTypeAllPodsSearch = createSearchBuilder();
         ZoneTypeAllPodsSearch.and("zoneId", ZoneTypeAllPodsSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         ZoneTypeAllPodsSearch.and("vlanType", ZoneTypeAllPodsSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
-        
+
         SearchBuilder<PodVlanMapVO> PodVlanSearch = _podVlanMapDao.createSearchBuilder();
         PodVlanSearch.and("podId", PodVlanSearch.entity().getPodId(), SearchCriteria.Op.NNULL);
         ZoneTypeAllPodsSearch.join("vlan", PodVlanSearch, PodVlanSearch.entity().getVlanDbId(), ZoneTypeAllPodsSearch.entity().getId(), JoinBuilder.JoinType.INNER);
-        
+
         ZoneTypeAllPodsSearch.done();
         PodVlanSearch.done();
-        
+
         ZoneTypePodSearch = createSearchBuilder();
         ZoneTypePodSearch.and("zoneId", ZoneTypePodSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         ZoneTypePodSearch.and("vlanType", ZoneTypePodSearch.entity().getVlanType(), SearchCriteria.Op.EQ);
-        
+
         SearchBuilder<PodVlanMapVO> PodVlanSearch2 = _podVlanMapDao.createSearchBuilder();
         PodVlanSearch2.and("podId", PodVlanSearch2.entity().getPodId(), SearchCriteria.Op.EQ);
         ZoneTypePodSearch.join("vlan", PodVlanSearch2,  PodVlanSearch2.entity().getVlanDbId(), ZoneTypePodSearch.entity().getId(), JoinBuilder.JoinType.INNER);
         PodVlanSearch2.done();
         ZoneTypePodSearch.done();
 
-		return result;
-	}
-	
-	private VlanVO findNextVlan(long zoneId, Vlan.VlanType vlanType) {
-		List<VlanVO> allVlans = listByZoneAndType(zoneId, vlanType);
-		List<VlanVO> emptyVlans = new ArrayList<VlanVO>();
-		List<VlanVO> fullVlans = new ArrayList<VlanVO>();
-		
-		// Try to find a VLAN that is partially allocated
-		for (VlanVO vlan : allVlans) {
-			long vlanDbId = vlan.getId();
-			
-			int countOfAllocatedIps = _ipAddressDao.countIPs(zoneId, vlanDbId, true);
-			int countOfAllIps = _ipAddressDao.countIPs(zoneId, vlanDbId, false);
-			
-			if ((countOfAllocatedIps > 0) && (countOfAllocatedIps < countOfAllIps)) {
-				return vlan;
-			} else if (countOfAllocatedIps == 0) {
-				emptyVlans.add(vlan);
-			} else if (countOfAllocatedIps == countOfAllIps) {
-				fullVlans.add(vlan);
-			}
-		}
-		
-		if (emptyVlans.isEmpty()) {
-			return null;
-		}
-		
-		// Try to find an empty VLAN with the same tag/subnet as a VLAN that is full
-		for (VlanVO fullVlan : fullVlans) {
-			for (VlanVO emptyVlan : emptyVlans) {
-				if (fullVlan.getVlanTag().equals(emptyVlan.getVlanTag()) && 
-					fullVlan.getVlanGateway().equals(emptyVlan.getVlanGateway()) &&
-					fullVlan.getVlanNetmask().equals(emptyVlan.getVlanNetmask())) {
-					return emptyVlan;
-				}
-			}
-		}
-		
-		// Return a random empty VLAN
-		return emptyVlans.get(0);
-	}
-
-	@Override
-	public boolean zoneHasDirectAttachUntaggedVlans(long zoneId) {
-		SearchCriteria<VlanVO> sc = ZoneTypeAllPodsSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	sc.setParameters("vlanType", VlanType.DirectAttached);
-    	
+        return result;
+    }
+
+    private VlanVO findNextVlan(long zoneId, Vlan.VlanType vlanType) {
+        List<VlanVO> allVlans = listByZoneAndType(zoneId, vlanType);
+        List<VlanVO> emptyVlans = new ArrayList<VlanVO>();
+        List<VlanVO> fullVlans = new ArrayList<VlanVO>();
+
+        // Try to find a VLAN that is partially allocated
+        for (VlanVO vlan : allVlans) {
+            long vlanDbId = vlan.getId();
+
+            int countOfAllocatedIps = _ipAddressDao.countIPs(zoneId, vlanDbId, true);
+            int countOfAllIps = _ipAddressDao.countIPs(zoneId, vlanDbId, false);
+
+            if ((countOfAllocatedIps > 0) && (countOfAllocatedIps < countOfAllIps)) {
+                return vlan;
+            } else if (countOfAllocatedIps == 0) {
+                emptyVlans.add(vlan);
+            } else if (countOfAllocatedIps == countOfAllIps) {
+                fullVlans.add(vlan);
+            }
+        }
+
+        if (emptyVlans.isEmpty()) {
+            return null;
+        }
+
+        // Try to find an empty VLAN with the same tag/subnet as a VLAN that is full
+        for (VlanVO fullVlan : fullVlans) {
+            for (VlanVO emptyVlan : emptyVlans) {
+                if (fullVlan.getVlanTag().equals(emptyVlan.getVlanTag()) && 
+                        fullVlan.getVlanGateway().equals(emptyVlan.getVlanGateway()) &&
+                        fullVlan.getVlanNetmask().equals(emptyVlan.getVlanNetmask())) {
+                    return emptyVlan;
+                }
+            }
+        }
+
+        // Return a random empty VLAN
+        return emptyVlans.get(0);
+    }
+
+    @Override
+    public boolean zoneHasDirectAttachUntaggedVlans(long zoneId) {
+        SearchCriteria<VlanVO> sc = ZoneTypeAllPodsSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        sc.setParameters("vlanType", VlanType.DirectAttached);
+
         return listIncludingRemovedBy(sc).size() > 0;
-	}
-
-
-	public Pair<String, VlanVO> assignPodDirectAttachIpAddress(long zoneId,
-			long podId, long accountId, long domainId) {
-		SearchCriteria<VlanVO> sc = ZoneTypePodSearch.create();
-    	sc.setParameters("zoneId", zoneId);
-    	sc.setParameters("vlanType", VlanType.DirectAttached);
-    	sc.setJoinParameters("vlan", "podId", podId);
-    	
-    	VlanVO vlan = findOneIncludingRemovedBy(sc);
-    	if (vlan == null) {
-    		return null;
-    	}
-    	
-    	return null;
+    }
+
+
+    public Pair<String, VlanVO> assignPodDirectAttachIpAddress(long zoneId,
+            long podId, long accountId, long domainId) {
+        SearchCriteria<VlanVO> sc = ZoneTypePodSearch.create();
+        sc.setParameters("zoneId", zoneId);
+        sc.setParameters("vlanType", VlanType.DirectAttached);
+        sc.setJoinParameters("vlan", "podId", podId);
+
+        VlanVO vlan = findOneIncludingRemovedBy(sc);
+        if (vlan == null) {
+            return null;
+        }
+
+        return null;
 //    	String ipAddress = _ipAddressDao.assignIpAddress(accountId, domainId, vlan.getId(), false).getAddress();
 //    	if (ipAddress == null) {
 //    		return null;
 //    	}
 //		return new Pair<String, VlanVO>(ipAddress, vlan);
 
-	}
-	
-	@Override
-	@DB
-	public List<VlanVO> searchForZoneWideVlans(long dcId, String vlanType, String vlanId){
-		
-	    StringBuilder sql = new StringBuilder(FindZoneWideVlans);
-
-	    Transaction txn = Transaction.currentTxn();
-		PreparedStatement pstmt = null;
-	    try {
-	        pstmt = txn.prepareAutoCloseStatement(sql.toString());
-	        pstmt.setLong(1, dcId);
-	        pstmt.setString(2, vlanType);
-	        pstmt.setString(3, vlanId);
-	        
-	        ResultSet rs = pstmt.executeQuery();
-	        List<VlanVO> zoneWideVlans = new ArrayList<VlanVO>();
-
-	        while (rs.next()) {
-	        	zoneWideVlans.add(toEntityBean(rs, false));
-	        }
-	        
-	        return zoneWideVlans;
-	    } catch (SQLException e) {
-	        throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e);
-	    }
-	}
-    
-	@Override
+    }
+
+    @Override
+    @DB
+    public List<VlanVO> searchForZoneWideVlans(long dcId, String vlanType, String vlanId){
+
+        StringBuilder sql = new StringBuilder(FindZoneWideVlans);
+
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        try {
+            pstmt = txn.prepareAutoCloseStatement(sql.toString());
+            pstmt.setLong(1, dcId);
+            pstmt.setString(2, vlanType);
+            pstmt.setString(3, vlanId);
+
+            ResultSet rs = pstmt.executeQuery();
+            List<VlanVO> zoneWideVlans = new ArrayList<VlanVO>();
+
+            while (rs.next()) {
+                zoneWideVlans.add(toEntityBean(rs, false));
+            }
+
+            return zoneWideVlans;
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("Unable to execute " + pstmt.toString(), e);
+        }
+    }
+
+    @Override
     public List<VlanVO> listVlansByNetworkId(long networkOfferingId) {
-       SearchCriteria<VlanVO> sc = NetworkVlanSearch.create();
+        SearchCriteria<VlanVO> sc = NetworkVlanSearch.create();
         sc.setParameters("networkOfferingId", networkOfferingId);
         return listBy(sc);
     }
 
     @Override
     public List<VlanVO> listVlansByPhysicalNetworkId(long physicalNetworkId) {
-       SearchCriteria<VlanVO> sc = PhysicalNetworkVlanSearch.create();
+        SearchCriteria<VlanVO> sc = PhysicalNetworkVlanSearch.create();
         sc.setParameters("physicalNetworkId", physicalNetworkId);
         return listBy(sc);
     }	

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/deploy/FirstFitPlanner.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java
index bcc1d26..3517bf8 100755
--- a/server/src/com/cloud/deploy/FirstFitPlanner.java
+++ b/server/src/com/cloud/deploy/FirstFitPlanner.java
@@ -18,7 +18,6 @@ package com.cloud.deploy;
 
 import java.util.ArrayList;
 import java.util.Comparator;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -74,7 +73,6 @@ import com.cloud.storage.dao.VolumeDao;
 import com.cloud.user.AccountManager;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
-import com.cloud.utils.component.Adapters;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.ReservationContext;
 import com.cloud.vm.VirtualMachine;
@@ -106,7 +104,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
 
     //@com.cloud.utils.component.Inject(adapter=StoragePoolAllocator.class)
     @Inject protected List<StoragePoolAllocator> _storagePoolAllocators;
-    
+
     //@com.cloud.utils.component.Inject(adapter=HostAllocator.class)
     @Inject protected List<HostAllocator> _hostAllocators;
     protected String _allocationAlgorithm = "random";
@@ -115,7 +113,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
     @Override
     public DeployDestination plan(VirtualMachineProfile<? extends VirtualMachine> vmProfile,
             DeploymentPlan plan, ExcludeList avoid)
-    throws InsufficientServerCapacityException {
+                    throws InsufficientServerCapacityException {
         VirtualMachine vm = vmProfile.getVirtualMachine();
         DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
 
@@ -126,7 +124,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
             }
             return null;
         }
-        
+
         ServiceOffering offering = vmProfile.getServiceOffering();
         int cpu_requested = offering.getCpu() * offering.getSpeed();
         long ram_requested = offering.getRamSize() * 1024L * 1024L;
@@ -143,9 +141,9 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
 
             s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId()!=null ? "Yes": "No"));
         }
-        
+
         String haVmTag = (String)vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
-        
+
         if(plan.getHostId() != null && haVmTag == null){
             Long hostIdSpecified = plan.getHostId();
             if (s_logger.isDebugEnabled()){
@@ -238,7 +236,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
             }
             s_logger.debug("Cannot choose the last host to deploy this VM ");
         }
-        
+
 
         List<Long> clusterList = new ArrayList<Long>();
         if (plan.getClusterId() != null) {
@@ -272,7 +270,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
             }
         } else {
             s_logger.debug("Searching all possible resources under this Zone: "+ plan.getDataCenterId());
-            
+
             boolean applyAllocationAtPods = Boolean.parseBoolean(_configDao.getValue(Config.ApplyAllocationAlgorithmToPods.key()));
             if(applyAllocationAtPods){
                 //start scan at all pods under this zone.
@@ -284,15 +282,15 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         }
 
     }
-    
+
     private DeployDestination scanPodsForDestination(VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
-        
+
         ServiceOffering offering = vmProfile.getServiceOffering();
         int requiredCpu = offering.getCpu() * offering.getSpeed();
         long requiredRam = offering.getRamSize() * 1024L * 1024L;
         String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
         float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
-        
+
         //list pods under this zone by cpu and ram capacity
         List<Long> prioritizedPodIds = new ArrayList<Long>();
         Pair<List<Long>, Map<Long, Double>> podCapacityInfo = listPodsByCapacity(plan.getDataCenterId(), requiredCpu, requiredRam, cpuOverprovisioningFactor); 
@@ -313,16 +311,16 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                     }
                     podsWithCapacity.removeAll(disabledPods);
                 }
-           }
+            }
         }else{
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("No pods found having a host with enough capacity, returning.");
             }
             return null;
         }
-        
+
         if(!podsWithCapacity.isEmpty()){
-            
+
             prioritizedPodIds = reorderPods(podCapacityInfo, vmProfile, plan);
 
             //loop over pods
@@ -345,9 +343,9 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
             return null;
         }
     }
-    
+
     private DeployDestination scanClustersForDestinationInZoneOrPod(long id, boolean isZone, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid){
-        
+
         VirtualMachine vm = vmProfile.getVirtualMachine();
         ServiceOffering offering = vmProfile.getServiceOffering();
         DataCenter dc = _dcDao.findById(vm.getDataCenterIdToDeployIn());
@@ -355,7 +353,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         long requiredRam = offering.getRamSize() * 1024L * 1024L;
         String opFactor = _configDao.getValue(Config.CPUOverprovisioningFactor.key());
         float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1);
-        
+
         //list clusters under this zone by cpu and ram capacity
         Pair<List<Long>, Map<Long, Double>> clusterCapacityInfo = listClustersByCapacity(id, requiredCpu, requiredRam, avoid, isZone, cpuOverprovisioningFactor);
         List<Long> prioritizedClusterIds = clusterCapacityInfo.first();
@@ -366,7 +364,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                 }
                 prioritizedClusterIds.removeAll(avoid.getClustersToAvoid());
             }
-            
+
             if(!isRootAdmin(plan.getReservationContext())){
                 List<Long> disabledClusters = new ArrayList<Long>();
                 if(isZone){
@@ -397,7 +395,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
             return null;
         }
     }
-    
+
     /**
      * This method should reorder the given list of Cluster Ids by applying any necessary heuristic 
      * for this planner
@@ -409,7 +407,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         List<Long> reordersClusterIds = clusterCapacityInfo.first();
         return reordersClusterIds;
     }
-    
+
     /**
      * This method should reorder the given list of Pod Ids by applying any necessary heuristic 
      * for this planner
@@ -421,7 +419,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         List<Long> podIdsByCapacity = podCapacityInfo.first();
         return podIdsByCapacity;
     }
-    
+
     private List<Long> listDisabledClusters(long zoneId, Long podId){
         List<Long> disabledClusters = _clusterDao.listDisabledClusters(zoneId, podId);
         if(podId == null){
@@ -431,70 +429,70 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         }
         return disabledClusters;
     }
-    
+
     private List<Long> listDisabledPods(long zoneId){
         List<Long> disabledPods = _podDao.listDisabledPods(zoneId);
         return disabledPods;
     }    
-    
+
     private Map<Short,Float> getCapacityThresholdMap(){
-    	// Lets build this real time so that the admin wont have to restart MS if he changes these values
-    	Map<Short,Float> disableThresholdMap = new HashMap<Short, Float>();
-    	
-    	String cpuDisableThresholdString = _configDao.getValue(Config.CPUCapacityDisableThreshold.key());
+        // Lets build this real time so that the admin wont have to restart MS if he changes these values
+        Map<Short,Float> disableThresholdMap = new HashMap<Short, Float>();
+
+        String cpuDisableThresholdString = _configDao.getValue(Config.CPUCapacityDisableThreshold.key());
         float cpuDisableThreshold = NumbersUtil.parseFloat(cpuDisableThresholdString, 0.85F);
         disableThresholdMap.put(Capacity.CAPACITY_TYPE_CPU, cpuDisableThreshold);
-        
+
         String memoryDisableThresholdString = _configDao.getValue(Config.MemoryCapacityDisableThreshold.key());
         float memoryDisableThreshold = NumbersUtil.parseFloat(memoryDisableThresholdString, 0.85F);
         disableThresholdMap.put(Capacity.CAPACITY_TYPE_MEMORY, memoryDisableThreshold);
-        
-    	return disableThresholdMap;
+
+        return disableThresholdMap;
     }
 
     private List<Short> getCapacitiesForCheckingThreshold(){
-    	List<Short> capacityList = new ArrayList<Short>();    	
-    	capacityList.add(Capacity.CAPACITY_TYPE_CPU);
-    	capacityList.add(Capacity.CAPACITY_TYPE_MEMORY);    	
-    	return capacityList;
+        List<Short> capacityList = new ArrayList<Short>();    	
+        capacityList.add(Capacity.CAPACITY_TYPE_CPU);
+        capacityList.add(Capacity.CAPACITY_TYPE_MEMORY);    	
+        return capacityList;
     }
-    
+
     private void removeClustersCrossingThreshold(List<Long> clusterListForVmAllocation, ExcludeList avoid, VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan){
-    	        
-    	Map<Short,Float> capacityThresholdMap = getCapacityThresholdMap();
-    	List<Short> capacityList = getCapacitiesForCheckingThreshold();
-    	List<Long> clustersCrossingThreshold = new ArrayList<Long>();
-    	
+
+        Map<Short,Float> capacityThresholdMap = getCapacityThresholdMap();
+        List<Short> capacityList = getCapacitiesForCheckingThreshold();
+        List<Long> clustersCrossingThreshold = new ArrayList<Long>();
+
         ServiceOffering offering = vmProfile.getServiceOffering();
         int cpu_requested = offering.getCpu() * offering.getSpeed();
         long ram_requested = offering.getRamSize() * 1024L * 1024L;
-    	
+
         // 	For each capacity get the cluster list crossing the threshold and remove it from the clusterList that will be used for vm allocation.
         for(short capacity : capacityList){
-        	
-        	if (clusterListForVmAllocation == null || clusterListForVmAllocation.size() == 0){
-           		return;
-           	}
-           	
-           	if (capacity == Capacity.CAPACITY_TYPE_CPU){
-           		clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(Capacity.CAPACITY_TYPE_CPU, plan.getDataCenterId(),
-           				capacityThresholdMap.get(capacity), cpu_requested, ApiDBUtils.getCpuOverprovisioningFactor());
-           	}else{
-           		clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(capacity, plan.getDataCenterId(),
-           				capacityThresholdMap.get(capacity), ram_requested, 1.0f);//Mem overprov not supported yet
-           	}
-
-           	
-           	if (clustersCrossingThreshold != null && clustersCrossingThreshold.size() != 0){
-               	// addToAvoid Set
-           		avoid.addClusterList(clustersCrossingThreshold);
-           		// Remove clusters crossing disabled threshold
-               	clusterListForVmAllocation.removeAll(clustersCrossingThreshold);
-               	
-           		s_logger.debug("Cannot allocate cluster list " + clustersCrossingThreshold.toString() + " for vm creation since their allocated percentage" +
-           				" crosses the disable capacity threshold: " + capacityThresholdMap.get(capacity) + " for capacity Type : " + capacity + ", skipping these clusters");           		
-           	}
-           	           	           	
+
+            if (clusterListForVmAllocation == null || clusterListForVmAllocation.size() == 0){
+                return;
+            }
+
+            if (capacity == Capacity.CAPACITY_TYPE_CPU){
+                clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(Capacity.CAPACITY_TYPE_CPU, plan.getDataCenterId(),
+                        capacityThresholdMap.get(capacity), cpu_requested, ApiDBUtils.getCpuOverprovisioningFactor());
+            }else{
+                clustersCrossingThreshold = _capacityDao.listClustersCrossingThreshold(capacity, plan.getDataCenterId(),
+                        capacityThresholdMap.get(capacity), ram_requested, 1.0f);//Mem overprov not supported yet
+            }
+
+
+            if (clustersCrossingThreshold != null && clustersCrossingThreshold.size() != 0){
+                // addToAvoid Set
+                avoid.addClusterList(clustersCrossingThreshold);
+                // Remove clusters crossing disabled threshold
+                clusterListForVmAllocation.removeAll(clustersCrossingThreshold);
+
+                s_logger.debug("Cannot allocate cluster list " + clustersCrossingThreshold.toString() + " for vm creation since their allocated percentage" +
+                        " crosses the disable capacity threshold: " + capacityThresholdMap.get(capacity) + " for capacity Type : " + capacity + ", skipping these clusters");           		
+            }
+
         }
     }
 
@@ -506,7 +504,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         }
 
         removeClustersCrossingThreshold(clusterList, avoid, vmProfile, plan);
-        
+
         for(Long clusterId : clusterList){
             Cluster clusterVO = _clusterDao.findById(clusterId);
 
@@ -515,7 +513,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                 avoid.addCluster(clusterVO.getId());
                 continue;
             }
-            
+
             s_logger.debug("Checking resources in Cluster: "+clusterId + " under Pod: "+clusterVO.getPodId());
             //search for resources(hosts and storage) under this zone, pod, cluster.
             DataCenterDeployment potentialPlan = new DataCenterDeployment(plan.getDataCenterId(), clusterVO.getPodId(), clusterVO.getId(), null, plan.getPoolId(), null, plan.getReservationContext());
@@ -595,11 +593,11 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         if (s_logger.isTraceEnabled()) {
             s_logger.trace("ClusterId List having enough CPU and RAM capacity & in order of aggregate capacity: " + clusterIdsOrderedByAggregateCapacity);
         }
-        
+
         return result;
 
     }
-    
+
     protected Pair<List<Long>, Map<Long, Double>> listPodsByCapacity(long zoneId, int requiredCpu, long requiredRam, float cpuOverprovisioningFactor){
         //look at the aggregate available cpu and ram per pod
         //although an aggregate value may be false indicator that a pod can host a vm, it will at the least eliminate those pods which definitely cannot
@@ -632,7 +630,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         if (s_logger.isTraceEnabled()) {
             s_logger.trace("PodId List having enough CPU and RAM capacity & in order of aggregate capacity: " + podIdsOrderedByAggregateCapacity);
         }
-        
+
         return result;
 
     }
@@ -719,7 +717,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                 break;
             }
         }
-        
+
         if(suitableHosts.isEmpty()){
             s_logger.debug("No suitable hosts found");
         }
@@ -801,8 +799,8 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                 // when deploying VM based on ISO, we have a service offering and an additional disk offering, use-local storage flag is actually
                 // saved in service offering, overrde the flag from service offering when it is a ROOT disk
                 if(!useLocalStorage && vmProfile.getServiceOffering().getUseLocalStorage()) {
-                	if(toBeCreated.getVolumeType() == Volume.Type.ROOT)
-                		useLocalStorage = true;
+                    if(toBeCreated.getVolumeType() == Volume.Type.ROOT)
+                        useLocalStorage = true;
                 }
             }
             diskProfile.setUseLocalStorage(useLocalStorage);
@@ -816,7 +814,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
                     break;
                 }
             }
-            
+
             if(!foundPotentialPools){
                 s_logger.debug("No suitable pools found for volume: "+toBeCreated +" under cluster: "+plan.getClusterId());
                 //No suitable storage pools found under this cluster for this volume. - remove any suitable pools found for other volumes.
@@ -862,7 +860,7 @@ public class FirstFitPlanner extends PlannerBase implements DeploymentPlanner {
         }
         return false;
     }
-    
+
     @Override
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
         super.configure(name, params);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/event/EventUtils.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/event/EventUtils.java b/server/src/com/cloud/event/EventUtils.java
index 68317bf..53d224e 100755
--- a/server/src/com/cloud/event/EventUtils.java
+++ b/server/src/com/cloud/event/EventUtils.java
@@ -16,6 +16,7 @@
 // under the License.
 package com.cloud.event;
 
+import javax.annotation.PostConstruct;
 import javax.inject.Inject;
 
 import org.springframework.stereotype.Component;
@@ -33,6 +34,10 @@ public class EventUtils {
 	@Inject AccountDao _placeHoderAccountDao;
 	
 	public EventUtils() {
+	}
+	
+	@PostConstruct
+	void init() {
 		_eventDao = _placeHoderEventDao;
 		_accountDao = _placeHoderAccountDao;
 	}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/event/dao/EventJoinDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/event/dao/EventJoinDaoImpl.java b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java
index 764df99..873ee29 100644
--- a/server/src/com/cloud/event/dao/EventJoinDaoImpl.java
+++ b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java
@@ -27,6 +27,8 @@ import com.cloud.api.ApiResponseHelper;
 import com.cloud.api.query.vo.EventJoinVO;
 
 import org.apache.cloudstack.api.response.EventResponse;
+import org.springframework.stereotype.Component;
+
 import com.cloud.event.Event;
 import com.cloud.event.Event.State;
 import com.cloud.utils.db.Filter;
@@ -34,7 +36,7 @@ import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 
-
+@Component
 @Local(value={EventJoinDao.class})
 public class EventJoinDaoImpl extends GenericDaoBase<EventJoinVO, Long> implements EventJoinDao {
     public static final Logger s_logger = Logger.getLogger(EventJoinDaoImpl.class);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
index 6df0822..813728f 100755
--- a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
+++ b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
@@ -37,7 +37,6 @@ import com.cloud.agent.AgentManager;
 import com.cloud.alert.AlertManager;
 import com.cloud.cluster.ClusterManagerListener;
 import com.cloud.cluster.ManagementServerHostVO;
-import com.cloud.cluster.StackMaid;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.ClusterDetailsDao;
@@ -142,7 +141,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
     ManagementServer _msServer;
     @Inject
     ConfigurationDao _configDao;
-    
+
     String _instance;
     ScheduledExecutorService _executor;
     int _stopRetryInterval;
@@ -189,12 +188,12 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
         if (host.getType() != Host.Type.Routing) {
             return;
         }
-        
+
         if(host.getHypervisorType() == HypervisorType.VMware) {
             s_logger.info("Don't restart for VMs on host " + host.getId() + " as the host is VMware host");
-        	return;
+            return;
         }
-        
+
         s_logger.warn("Scheduling restart for VMs on host " + host.getId());
 
         final List<VMInstanceVO> vms = _instanceDao.listByHostId(host.getId());
@@ -268,29 +267,29 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
 
     @Override
     public void scheduleRestart(VMInstanceVO vm, boolean investigate) {
-    	Long hostId = vm.getHostId();
-    	if (hostId == null) {
-    	    try {
-    	        s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm);
+        Long hostId = vm.getHostId();
+        if (hostId == null) {
+            try {
+                s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm);
                 _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
             } catch (ResourceUnavailableException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             } catch (OperationTimedoutException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             } catch (ConcurrentOperationException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             }            
-    	    return;
-    	}
-
-    	if(vm.getHypervisorType() == HypervisorType.VMware) {
-    		s_logger.info("Skip HA for VMware VM " + vm.getInstanceName());
-    		return;
-    	}
-    	
+            return;
+        }
+
+        if(vm.getHypervisorType() == HypervisorType.VMware) {
+            s_logger.info("Skip HA for VMware VM " + vm.getInstanceName());
+            return;
+        }
+
         if (!investigate) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString());
@@ -319,13 +318,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                 _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
             } catch (ResourceUnavailableException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             } catch (OperationTimedoutException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             } catch (ConcurrentOperationException e) {
                 assert false : "How do we hit this when force is true?";
-                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+            throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
             }        
         }
 
@@ -360,7 +359,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
             s_logger.info(str.toString());
             return null;
         }
-        
+
         items = _haDao.listRunningHaWorkForVm(work.getInstanceId());
         if (items.size() > 0) {
             StringBuilder str = new StringBuilder("Waiting because there's HA work being executed on an item currently.  Work Ids =[");
@@ -371,7 +370,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
             s_logger.info(str.toString());
             return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
         }
-        
+
         long vmId = work.getInstanceId();
 
         VMInstanceVO vm = _itMgr.findByIdAndType(work.getType(), work.getInstanceId());
@@ -420,14 +419,14 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
 
                 Investigator investigator = null;
                 for(Investigator it : _investigators) {
-                	investigator = it;
+                    investigator = it;
                     alive = investigator.isVmAlive(vm, host);
                     s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive);
                     if (alive != null) {
                         break;
                     }
                 }
-                
+
                 boolean fenced = false;
                 if (alive == null) {
                     s_logger.debug("Fencing off VM that we don't know the state of");
@@ -439,7 +438,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                             break;
                         }
                     }
-                    
+
                 } else if (!alive) {
                     fenced = true;
                 } else {
@@ -464,13 +463,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                     _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
                 } catch (ResourceUnavailableException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 } catch (OperationTimedoutException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 } catch (ConcurrentOperationException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 }
 
                 work.setStep(Step.Scheduled);
@@ -481,13 +480,13 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                     _itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
                 } catch (ResourceUnavailableException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 } catch (OperationTimedoutException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 } catch (ConcurrentOperationException e) {
                     assert false : "How do we hit this when force is true?";
-                    throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
+                throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
                 }
             }
         }
@@ -519,7 +518,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                 params.put(VirtualMachineProfile.Param.HaTag, _haTag);
             }
             VMInstanceVO started = _itMgr.advanceStart(vm, params, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
-            
+
             if (started != null) {
                 s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId());
                 return null;
@@ -735,7 +734,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
         if (_instance == null) {
             _instance = "VMOPS";
         }
-        
+
         _haTag = params.get("ha.tag");
 
         _haDao.releaseWorkItems(_serverId);
@@ -785,8 +784,6 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                 _haDao.cleanup(System.currentTimeMillis() - _timeBetweenFailures);
             } catch (Exception e) {
                 s_logger.warn("Error while cleaning up", e);
-            } finally {
-                StackMaid.current().exitCleanup();
             }
         }
     }
@@ -832,7 +829,7 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                             nextTime = destroyVM(work);
                         } else {
                             assert false : "How did we get here with " + wt.toString();
-                            continue;
+                        continue;
                         }
 
                         if (nextTime == null) {
@@ -852,7 +849,6 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
                 } catch (final Throwable th) {
                     s_logger.error("Caught this throwable, ", th);
                 } finally {
-                    StackMaid.current().exitCleanup();
                     if (work != null) {
                         NDC.pop();
                     }
@@ -885,5 +881,5 @@ public class HighAvailabilityManagerImpl implements HighAvailabilityManager, Clu
     public String getHaTag() {
         return _haTag;
     }
-    
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/host/dao/HostDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/host/dao/HostDaoImpl.java b/server/src/com/cloud/host/dao/HostDaoImpl.java
index 0767bef..2a7139c 100755
--- a/server/src/com/cloud/host/dao/HostDaoImpl.java
+++ b/server/src/com/cloud/host/dao/HostDaoImpl.java
@@ -47,7 +47,6 @@ import com.cloud.info.RunningHostCountInfo;
 import com.cloud.org.Managed;
 import com.cloud.resource.ResourceState;
 import com.cloud.utils.DateUtil;
-import com.cloud.utils.component.ComponentLocator;
 import com.cloud.utils.db.Attribute;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Filter;
@@ -103,7 +102,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
     protected SearchBuilder<HostVO> ManagedDirectConnectSearch;
     protected SearchBuilder<HostVO> ManagedRoutingServersSearch;
     protected SearchBuilder<HostVO> SecondaryStorageVMSearch;
-    
+
 
     protected GenericSearchBuilder<HostVO, Long> HostsInStatusSearch;
     protected GenericSearchBuilder<HostVO, Long> CountRoutingByDc;
@@ -123,7 +122,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
 
     public HostDaoImpl() {
     }
-    
+
     @PostConstruct
     public void init() {
 
@@ -152,7 +151,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         TypeDcSearch.and("type", TypeDcSearch.entity().getType(), SearchCriteria.Op.EQ);
         TypeDcSearch.and("dc", TypeDcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         TypeDcSearch.done();
-        
+
         SecondaryStorageVMSearch = createSearchBuilder();
         SecondaryStorageVMSearch.and("type", SecondaryStorageVMSearch.entity().getType(), SearchCriteria.Op.EQ);
         SecondaryStorageVMSearch.and("dc", SecondaryStorageVMSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
@@ -165,14 +164,14 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         TypeDcStatusSearch.and("status", TypeDcStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
         TypeDcStatusSearch.and("resourceState", TypeDcStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
         TypeDcStatusSearch.done();
-        
+
         TypeClusterStatusSearch = createSearchBuilder();
         TypeClusterStatusSearch.and("type", TypeClusterStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
         TypeClusterStatusSearch.and("cluster", TypeClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
         TypeClusterStatusSearch.and("status", TypeClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
         TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
         TypeClusterStatusSearch.done();
-        
+
         IdStatusSearch = createSearchBuilder();
         IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ);
         IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
@@ -218,7 +217,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         StatusSearch = createSearchBuilder();
         StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
         StatusSearch.done();
-        
+
         ResourceStateSearch = createSearchBuilder();
         ResourceStateSearch.and("resourceState", ResourceStateSearch.entity().getResourceState(), SearchCriteria.Op.IN);
         ResourceStateSearch.done();
@@ -261,7 +260,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
         UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getClusterId(), JoinType.INNER);
         UnmanagedDirectConnectSearch.done();
-        
+
 
         DirectConnectSearch = createSearchBuilder();
         DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
@@ -311,7 +310,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         ManagedRoutingServersSearch.and("server", ManagedRoutingServersSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
         ManagedRoutingServersSearch.and("type", ManagedRoutingServersSearch.entity().getType(), SearchCriteria.Op.EQ);
         ManagedRoutingServersSearch.done();
-        
+
         RoutingSearch = createSearchBuilder();
         RoutingSearch.and("type", RoutingSearch.entity().getType(), SearchCriteria.Op.EQ);
         RoutingSearch.done();
@@ -334,52 +333,52 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         List<HostVO> hosts = listBy(sc);
         return hosts.size();
     }
-    
+
 
     @Override
     public HostVO findByGuid(String guid) {
         SearchCriteria<HostVO> sc = GuidSearch.create("guid", guid);
         return findOneBy(sc);
     }
-    
+
     @Override @DB
     public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) {
         Transaction txn = Transaction.currentTxn();
         txn.start();       
-    	SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
-    	sc.setParameters("lastPinged", lastPingSecondsAfter);
+        SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
+        sc.setParameters("lastPinged", lastPingSecondsAfter);
         //sc.setParameters("resourceStates", ResourceState.ErrorInMaintenance, ResourceState.Maintenance, ResourceState.PrepareForMaintenance, ResourceState.Disabled);
         sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
         List<HostVO> hosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true);
-        
+
         for (HostVO host : hosts) {
             host.setManagementServerId(managementServerId);
             update(host.getId(), host);
         }
-        
+
         txn.commit();
-        
+
         return hosts;
     }
-    
+
     @Override @DB
     public List<HostVO> findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) {
-    	Transaction txn = Transaction.currentTxn();
-    	
-    	txn.start();
-    	SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
-    	sc.setParameters("lastPinged", lastPingSecondsAfter);
+        Transaction txn = Transaction.currentTxn();
+
+        txn.start();
+        SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
+        sc.setParameters("lastPinged", lastPingSecondsAfter);
         sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.PxeServer, Type.TrafficMonitor, Type.L2Networking);
-    	List<HostVO> hosts = lockRows(sc, null, true);
-    	
-    	for (HostVO host : hosts) {
-    		host.setManagementServerId(managementServerId);
-    		update(host.getId(), host);
-    	}
-    	
-    	txn.commit();
-    	
-    	return hosts;
+        List<HostVO> hosts = lockRows(sc, null, true);
+
+        for (HostVO host : hosts) {
+            host.setManagementServerId(managementServerId);
+            update(host.getId(), host);
+        }
+
+        txn.commit();
+
+        return hosts;
     }
 
     @Override
@@ -405,7 +404,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         ub = getUpdateBuilder(host);
         update(ub, sc, null);
     }
- 
+
     @Override
     public List<HostVO> listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) {
 
@@ -438,8 +437,8 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
 
         return listBy(sc);
     }
-    
-    
+
+
     @Override
     public List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) {
         SearchBuilder<HostTagVO> hostTagSearch = null;
@@ -449,42 +448,42 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
             hostTagSearch.or("tagNull", hostTagSearch.entity().getTag(), SearchCriteria.Op.NULL);
             hostTagSearch.cp();
         }
-        
+
         SearchBuilder<HostVO> hostSearch = createSearchBuilder();
-     
+
         hostSearch.and("type", hostSearch.entity().getType(), SearchCriteria.Op.EQ);
         hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
         hostSearch.and("podId", hostSearch.entity().getPodId(), SearchCriteria.Op.EQ);
         hostSearch.and("zoneId", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         hostSearch.and("status", hostSearch.entity().getStatus(), SearchCriteria.Op.EQ);
         hostSearch.and("resourceState", hostSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
-        
+
         if (haTag != null && !haTag.isEmpty()) {
             hostSearch.join("hostTagSearch", hostTagSearch, hostSearch.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER);
         }
 
         SearchCriteria<HostVO> sc = hostSearch.create();
-        
+
         if (haTag != null && !haTag.isEmpty()) {
             sc.setJoinParameters("hostTagSearch", "tag", haTag);
         }
-        
+
         if (type != null) {
             sc.setParameters("type", type);
         }
-        
+
         if (clusterId != null) {
             sc.setParameters("clusterId", clusterId);
         }
-        
+
         if (podId != null) {
             sc.setParameters("podId", podId);
         }
-        
+
         sc.setParameters("zoneId", dcId);
         sc.setParameters("status", Status.Up);
         sc.setParameters("resourceState", ResourceState.Enabled);
-        
+
         return listBy(sc);
     }
 
@@ -531,7 +530,7 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         }
         return result;
     }
-   
+
     @Override
     public void saveDetails(HostVO host) {
         Map<String, String> details = host.getDetails();
@@ -653,81 +652,81 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
     }
 
 
-	@Override
-	public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) {
-		HostVO host = findById(vo.getId());
-		long oldPingTime = host.getLastPinged();
-
-		SearchBuilder<HostVO> sb = createSearchBuilder();
-		sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
-		sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
-		sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ);
-		if (newStatus.checkManagementServer()) {
-			sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ);
-			sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL);
-			sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ);
-			sb.closeParen();
-		}
-		sb.done();
-
-		SearchCriteria<HostVO> sc = sb.create();
-
-		sc.setParameters("status", oldStatus);
-		sc.setParameters("id", host.getId());
-		sc.setParameters("update", host.getUpdated());
-		long oldUpdateCount = host.getUpdated();
-		if (newStatus.checkManagementServer()) {
-			sc.setParameters("ping", oldPingTime);
-			sc.setParameters("msid", host.getManagementServerId());
-		}
-
-		long newUpdateCount = host.incrUpdated();
-		UpdateBuilder ub = getUpdateBuilder(host);
-		ub.set(host, _statusAttr, newStatus);
-		if (newStatus.updateManagementServer()) {
-			if (newStatus.lostConnection()) {
-				ub.set(host, _msIdAttr, null);
-			} else {
-				ub.set(host, _msIdAttr, host.getManagementServerId());
-			}
-			if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) {
-				ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10);
-			}
-		}
-		if (event.equals(Event.ManagementServerDown)) {
-			ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60)));
-		}
-		int result = update(ub, sc, null);
-		assert result <= 1 : "How can this update " + result + " rows? ";
-
-		if (status_logger.isDebugEnabled() && result == 0) {
-			HostVO ho = findById(host.getId());
-			assert ho != null : "How how how? : " + host.getId();
-
-			StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
-			str.append(". Name=").append(host.getName());
-			str.append("; New=[status=").append(newStatus.toString()).append(":msid=")
-			        .append(newStatus.lostConnection() ? "null" : host.getManagementServerId()).append(":lastpinged=").append(host.getLastPinged()).append("]");
-			str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=")
-			        .append(oldPingTime).append("]");
-			str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=")
-			        .append(vo.getLastPinged()).append(":old update count=").append(oldUpdateCount).append("]");
-			status_logger.debug(str.toString());
-		} else {
-			StringBuilder msg = new StringBuilder("Agent status update: [");
-			msg.append("id = " + host.getId());
-			msg.append("; name = " + host.getName());
-			msg.append("; old status = " + oldStatus);
-			msg.append("; event = " + event);
-			msg.append("; new status = " + newStatus);
-			msg.append("; old update count = " + oldUpdateCount);
-			msg.append("; new update count = " + newUpdateCount + "]");
-			status_logger.debug(msg.toString());
-		}
-		
-		return result > 0;
-	}
-	
+    @Override
+    public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) {
+        HostVO host = findById(vo.getId());
+        long oldPingTime = host.getLastPinged();
+
+        SearchBuilder<HostVO> sb = createSearchBuilder();
+        sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ);
+        if (newStatus.checkManagementServer()) {
+            sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ);
+            sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL);
+            sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ);
+            sb.closeParen();
+        }
+        sb.done();
+
+        SearchCriteria<HostVO> sc = sb.create();
+
+        sc.setParameters("status", oldStatus);
+        sc.setParameters("id", host.getId());
+        sc.setParameters("update", host.getUpdated());
+        long oldUpdateCount = host.getUpdated();
+        if (newStatus.checkManagementServer()) {
+            sc.setParameters("ping", oldPingTime);
+            sc.setParameters("msid", host.getManagementServerId());
+        }
+
+        long newUpdateCount = host.incrUpdated();
+        UpdateBuilder ub = getUpdateBuilder(host);
+        ub.set(host, _statusAttr, newStatus);
+        if (newStatus.updateManagementServer()) {
+            if (newStatus.lostConnection()) {
+                ub.set(host, _msIdAttr, null);
+            } else {
+                ub.set(host, _msIdAttr, host.getManagementServerId());
+            }
+            if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) {
+                ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10);
+            }
+        }
+        if (event.equals(Event.ManagementServerDown)) {
+            ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60)));
+        }
+        int result = update(ub, sc, null);
+        assert result <= 1 : "How can this update " + result + " rows? ";
+
+        if (status_logger.isDebugEnabled() && result == 0) {
+            HostVO ho = findById(host.getId());
+            assert ho != null : "How how how? : " + host.getId();
+
+            StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
+            str.append(". Name=").append(host.getName());
+            str.append("; New=[status=").append(newStatus.toString()).append(":msid=")
+            .append(newStatus.lostConnection() ? "null" : host.getManagementServerId()).append(":lastpinged=").append(host.getLastPinged()).append("]");
+            str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=")
+            .append(oldPingTime).append("]");
+            str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=")
+            .append(vo.getLastPinged()).append(":old update count=").append(oldUpdateCount).append("]");
+            status_logger.debug(str.toString());
+        } else {
+            StringBuilder msg = new StringBuilder("Agent status update: [");
+            msg.append("id = " + host.getId());
+            msg.append("; name = " + host.getName());
+            msg.append("; old status = " + oldStatus);
+            msg.append("; event = " + event);
+            msg.append("; new status = " + newStatus);
+            msg.append("; old update count = " + oldUpdateCount);
+            msg.append("; new update count = " + newUpdateCount + "]");
+            status_logger.debug(msg.toString());
+        }
+
+        return result > 0;
+    }
+
     @Override
     public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) {
         HostVO host = (HostVO)vo;
@@ -735,41 +734,41 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         sb.and("resource_state", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
         sb.done();
-        
+
         SearchCriteria<HostVO> sc = sb.create();
 
         sc.setParameters("resource_state", oldState);
         sc.setParameters("id", host.getId());
-        
+
         UpdateBuilder ub = getUpdateBuilder(host);
         ub.set(host, _resourceStateAttr, newState);
         int result = update(ub, sc, null);
         assert result <= 1 : "How can this update " + result + " rows? ";
-        
+
         if (state_logger.isDebugEnabled() && result == 0) {
             HostVO ho = findById(host.getId());
             assert ho != null : "How how how? : " + host.getId();
 
             StringBuilder str = new StringBuilder("Unable to update resource state: [");
-			str.append("m = " + host.getId());
-			str.append("; name = " + host.getName());
-			str.append("; old state = " + oldState);
-			str.append("; event = " + event);
-			str.append("; new state = " + newState + "]");
-			state_logger.debug(str.toString());
+            str.append("m = " + host.getId());
+            str.append("; name = " + host.getName());
+            str.append("; old state = " + oldState);
+            str.append("; event = " + event);
+            str.append("; new state = " + newState + "]");
+            state_logger.debug(str.toString());
         } else {
-			StringBuilder msg = new StringBuilder("Resource state update: [");
-			msg.append("id = " + host.getId());
-			msg.append("; name = " + host.getName());
-			msg.append("; old state = " + oldState);
-			msg.append("; event = " + event);
-			msg.append("; new state = " + newState + "]");
-			state_logger.debug(msg.toString());
+            StringBuilder msg = new StringBuilder("Resource state update: [");
+            msg.append("id = " + host.getId());
+            msg.append("; name = " + host.getName());
+            msg.append("; old state = " + oldState);
+            msg.append("; event = " + event);
+            msg.append("; new state = " + newState + "]");
+            state_logger.debug(msg.toString());
         }
-		
+
         return result > 0;
     }
-    
+
     @Override
     public HostVO findByTypeNameAndZoneId(long zoneId, String name, Host.Type type) {
         SearchCriteria<HostVO> sc = TypeNameZoneSearch.create();
@@ -779,15 +778,15 @@ public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao
         return findOneBy(sc);
     }
 
-	@Override
-	public List<HostVO> findHypervisorHostInCluster(long clusterId) {
-		 SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create();
-		 sc.setParameters("type", Host.Type.Routing);
-		 sc.setParameters("cluster", clusterId);
-		 sc.setParameters("status", Status.Up);
-		 sc.setParameters("resourceState", ResourceState.Enabled);
-		
-		return listBy(sc);
-	}
+    @Override
+    public List<HostVO> findHypervisorHostInCluster(long clusterId) {
+        SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create();
+        sc.setParameters("type", Host.Type.Routing);
+        sc.setParameters("cluster", clusterId);
+        sc.setParameters("status", Status.Up);
+        sc.setParameters("resourceState", ResourceState.Enabled);
+
+        return listBy(sc);
+    }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java b/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java
index 5a32de7..b0c25c7 100644
--- a/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java
+++ b/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java
@@ -33,8 +33,6 @@ import com.cloud.host.Host;
 import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
-import com.cloud.utils.component.Adapters;
-import com.cloud.utils.component.ComponentLocator;
 
 @Component
 @Local(value = { HypervisorGuruManager.class } )
@@ -42,54 +40,56 @@ public class HypervisorGuruManagerImpl implements HypervisorGuruManager {
     public static final Logger s_logger = Logger.getLogger(HypervisorGuruManagerImpl.class.getName());
 
     @Inject HostDao _hostDao;
-    
-	String _name;
-	
-	@Inject List<HypervisorGuru> _hvGuruList;
+
+    String _name;
+
+    @Inject List<HypervisorGuru> _hvGuruList;
     Map<HypervisorType, HypervisorGuru> _hvGurus = new HashMap<HypervisorType, HypervisorGuru>();
-	
-	@Override
-	public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
-		_name = name;
- 		return true;
-	}
-	
-	@PostConstruct
-	public void init() {
-		for(HypervisorGuru guru : _hvGuruList) {
-			_hvGurus.put(guru.getHypervisorType(), guru);
-		}
-	}
-
-	@Override
-	public boolean start() {
-		return true;
-	}
-
-	@Override
-	public boolean stop() {
-		return true;
-	}
-
-	@Override
-	public String getName() {
-		return _name;
-	}
-
-	public HypervisorGuru getGuru(HypervisorType hypervisorType) {
-		return _hvGurus.get(hypervisorType);
-	}
-	
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+        _name = name;
+        return true;
+    }
+
+    @PostConstruct
+    public void init() {
+        for(HypervisorGuru guru : _hvGuruList) {
+            _hvGurus.put(guru.getHypervisorType(), guru);
+        }
+    }
+
+    @Override
+    public boolean start() {
+        return true;
+    }
+
+    @Override
+    public boolean stop() {
+        return true;
+    }
+
+    @Override
+    public String getName() {
+        return _name;
+    }
+
+    @Override
+    public HypervisorGuru getGuru(HypervisorType hypervisorType) {
+        return _hvGurus.get(hypervisorType);
+    }
+
+    @Override
     public long getGuruProcessedCommandTargetHost(long hostId, Command cmd) {
-    	HostVO hostVo = _hostDao.findById(hostId);
-    	HypervisorGuru hvGuru = null;
-    	if(hostVo.getType() == Host.Type.Routing) {
-    		hvGuru = _hvGurus.get(hostVo.getHypervisorType());
-    	}
-    	
-    	if(hvGuru != null)
-    		return hvGuru.getCommandHostDelegation(hostId, cmd);
-    	
-    	return hostId;
+        HostVO hostVo = _hostDao.findById(hostId);
+        HypervisorGuru hvGuru = null;
+        if(hostVo.getType() == Host.Type.Routing) {
+            hvGuru = _hvGurus.get(hostVo.getHypervisorType());
+        }
+
+        if(hvGuru != null)
+            return hvGuru.getCommandHostDelegation(hostId, cmd);
+
+        return hostId;
     }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/110465b5/server/src/com/cloud/maint/UpgradeManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/maint/UpgradeManagerImpl.java b/server/src/com/cloud/maint/UpgradeManagerImpl.java
index 2f50dff..03c7d2f 100644
--- a/server/src/com/cloud/maint/UpgradeManagerImpl.java
+++ b/server/src/com/cloud/maint/UpgradeManagerImpl.java
@@ -36,15 +36,14 @@ import javax.naming.ConfigurationException;
 
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.maint.dao.AgentUpgradeDao;
 import com.cloud.utils.PropertiesUtil;
-import com.cloud.utils.component.ComponentLocator;
 
 /**
  *
@@ -57,7 +56,7 @@ import com.cloud.utils.component.ComponentLocator;
 @Component
 @Local(UpgradeManager.class)
 public class UpgradeManagerImpl implements UpgradeManager {
-	private final static Logger s_logger = Logger.getLogger(UpgradeManagerImpl.class);
+    private final static Logger s_logger = Logger.getLogger(UpgradeManagerImpl.class);
     private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager();
 
     String _name;
@@ -66,10 +65,10 @@ public class UpgradeManagerImpl implements UpgradeManager {
 //    String _upgradeUrl;
     String _agentPath;
     long _checkInterval;
-    
+
     @Inject AgentUpgradeDao _upgradeDao;
     @Inject ConfigurationDao _configDao;
-    
+
     @Override
     public State registerForUpgrade(long hostId, String version) {
         State state = State.UpToDate;
@@ -90,11 +89,11 @@ public class UpgradeManagerImpl implements UpgradeManager {
                 _upgradeDao.persist(vo);
             }
         }
-        */
-        
+         */
+
         return state;
     }
-    
+
     public String deployNewAgent(String url) {
         s_logger.info("Updating agent with binary from " + url);
 
@@ -132,18 +131,18 @@ public class UpgradeManagerImpl implements UpgradeManager {
 
             s_logger.debug("New Agent zip file is now retrieved");
         } catch (final HttpException e) {
-        	return "Unable to retrieve the file from " + url;
+            return "Unable to retrieve the file from " + url;
         } catch (final IOException e) {
-        	return "Unable to retrieve the file from " + url;
+            return "Unable to retrieve the file from " + url;
         } finally {
-               method.releaseConnection();
+            method.releaseConnection();
         }
-        
+
         file.delete();
-        
+
         return "File will be deployed.";
     }
-    
+
 //    @Override
 //    public String getAgentUrl() {
 //        return _upgradeUrl;
@@ -174,7 +173,7 @@ public class UpgradeManagerImpl implements UpgradeManager {
             }
 
             //_upgradeUrl = configs.get("upgrade.url");
-            
+
 //			if (_upgradeUrl == null) {
 //				s_logger.debug("There is no upgrade url found in configuration table");
 //                // _upgradeUrl = "http://updates.vmops.com/releases/rss.xml";