incubator-cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From edi...@apache.org
Subject [21/45] squash changes into one giant patch
Date Thu, 21 Feb 2013 19:15:16 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java b/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java
index 61b5e1f..d747d25 100755
--- a/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java
+++ b/server/src/com/cloud/storage/allocator/AbstractStoragePoolAllocator.java
@@ -26,6 +26,8 @@ import java.util.Set;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.log4j.Logger;
 
 import com.cloud.capacity.CapacityManager;
@@ -41,7 +43,6 @@ import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageManager;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.StoragePoolStatus;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.storage.VMTemplateStoragePoolVO;
 import com.cloud.storage.VMTemplateStorageResourceAssoc;
 import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
@@ -76,6 +77,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement
     @Inject ClusterDao _clusterDao;
     @Inject SwiftManager _swiftMgr;
     @Inject CapacityManager _capacityMgr;
+    @Inject DataStoreManager dataStoreMgr;
     protected BigDecimal _storageOverprovisioningFactor = new BigDecimal(1);    
     long _extraBytesPerVolume = 0;
     Random _rand;
@@ -121,7 +123,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement
 		boolean localStorageAllocationNeeded = localStorageAllocationNeeded(dskCh);
 		if (s_logger.isDebugEnabled()) {
             s_logger.debug("Is localStorageAllocationNeeded? "+ localStorageAllocationNeeded);
-            s_logger.debug("Is storage pool shared? "+ pool.getPoolType().isShared());
+            s_logger.debug("Is storage pool shared? "+ pool.isShared());
         }
 		
 		return ((!localStorageAllocationNeeded && pool.getPoolType().isShared()) || (localStorageAllocationNeeded && !pool.getPoolType().isShared()));
@@ -133,8 +135,8 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement
 		if (s_logger.isDebugEnabled()) {
             s_logger.debug("Checking if storage pool is suitable, name: " + pool.getName()+ " ,poolId: "+ pool.getId());
         }
-		
-		if (avoid.shouldAvoid(pool)) {
+		StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
+		if (avoid.shouldAvoid(pol)) {
 			if (s_logger.isDebugEnabled()) {
                 s_logger.debug("StoragePool is in avoid set, skipping this pool");
             }			
@@ -157,7 +159,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement
         }
         
 		// Check that the pool type is correct
-		if (!poolIsCorrectType(dskCh, pool)) {
+		if (!poolIsCorrectType(dskCh, pol)) {
     		if (s_logger.isDebugEnabled()) {
                 s_logger.debug("StoragePool is not of correct type, skipping this pool");
             }
@@ -181,7 +183,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement
         Volume volume =  _volumeDao.findById(dskCh.getVolumeId());
         List<Volume> requestVolumes = new ArrayList<Volume>();
         requestVolumes.add(volume);
-        return _storageMgr.storagePoolHasEnoughSpace(requestVolumes, pool);
+        return _storageMgr.storagePoolHasEnoughSpace(requestVolumes, pol);
 	}
 
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/allocator/FirstFitStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/allocator/FirstFitStoragePoolAllocator.java b/server/src/com/cloud/storage/allocator/FirstFitStoragePoolAllocator.java
index 13a0107..f0df3a6 100644
--- a/server/src/com/cloud/storage/allocator/FirstFitStoragePoolAllocator.java
+++ b/server/src/com/cloud/storage/allocator/FirstFitStoragePoolAllocator.java
@@ -27,6 +27,7 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.log4j.Logger;
 
 import com.cloud.deploy.DeploymentPlan;
@@ -34,11 +35,10 @@ import com.cloud.deploy.DeploymentPlanner.ExcludeList;
 import com.cloud.offering.ServiceOffering;
 import com.cloud.server.StatsCollector;
 import com.cloud.storage.DiskOfferingVO;
-import com.cloud.storage.dao.DiskOfferingDao;
-import com.cloud.storage.StoragePool;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.dao.DiskOfferingDao;
 import com.cloud.user.Account;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
@@ -117,7 +117,8 @@ public class FirstFitStoragePoolAllocator extends AbstractStoragePoolAllocator {
             }
 
         	if (checkPool(avoid, pool, dskCh, template, null, sc, plan)) {
-        		suitablePools.add(pool);
+        	    StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
+        		suitablePools.add(pol);
         	}
         }
         

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java b/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java
index b6b8e8e..24b4dab 100644
--- a/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java
+++ b/server/src/com/cloud/storage/allocator/LocalStoragePoolAllocator.java
@@ -25,6 +25,7 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.log4j.Logger;
 
 import com.cloud.capacity.CapacityVO;
@@ -36,7 +37,6 @@ import com.cloud.offering.ServiceOffering;
 import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.StoragePoolHostVO;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.storage.Volume;
 import com.cloud.storage.VolumeVO;
 import com.cloud.storage.dao.StoragePoolHostDao;
@@ -110,7 +110,8 @@ public class LocalStoragePoolAllocator extends FirstFitStoragePoolAllocator {
                 StoragePoolVO pool = _storagePoolDao.findById(hostPool.getPoolId());
                 if (pool != null && pool.isLocal()) {
                     s_logger.debug("Found suitable local storage pool " + pool.getId() + ", adding to list");
-                    suitablePools.add(pool);
+                    StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
+                    suitablePools.add(pol);
                 }
 
                 if (suitablePools.size() == returnUpTo) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/LaunchPermissionDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/LaunchPermissionDao.java b/server/src/com/cloud/storage/dao/LaunchPermissionDao.java
index 86e5a9b..0ad60b5 100644
--- a/server/src/com/cloud/storage/dao/LaunchPermissionDao.java
+++ b/server/src/com/cloud/storage/dao/LaunchPermissionDao.java
@@ -18,6 +18,7 @@ package com.cloud.storage.dao;
 
 import java.util.List;
 
+
 import com.cloud.storage.LaunchPermissionVO;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.utils.db.GenericDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/StoragePoolDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/StoragePoolDao.java b/server/src/com/cloud/storage/dao/StoragePoolDao.java
index ff8292e..64bbd5f 100644
--- a/server/src/com/cloud/storage/dao/StoragePoolDao.java
+++ b/server/src/com/cloud/storage/dao/StoragePoolDao.java
@@ -20,8 +20,9 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+
 import com.cloud.storage.StoragePoolStatus;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.utils.db.GenericDao;
 /**
  * Data Access Object for storage_pool table

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/StoragePoolDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/StoragePoolDaoImpl.java b/server/src/com/cloud/storage/dao/StoragePoolDaoImpl.java
index 4019dff..ebf2943 100644
--- a/server/src/com/cloud/storage/dao/StoragePoolDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/StoragePoolDaoImpl.java
@@ -28,13 +28,13 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.springframework.stereotype.Component;
 
 import com.cloud.host.Status;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StoragePoolDetailVO;
 import com.cloud.storage.StoragePoolStatus;
-import com.cloud.storage.StoragePoolVO;
 
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplateDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplateDao.java b/server/src/com/cloud/storage/dao/VMTemplateDao.java
index a043a2c..c39626f 100755
--- a/server/src/com/cloud/storage/dao/VMTemplateDao.java
+++ b/server/src/com/cloud/storage/dao/VMTemplateDao.java
@@ -20,6 +20,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
+
 import com.cloud.domain.DomainVO;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
@@ -28,11 +31,12 @@ import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
 import com.cloud.user.Account;
 import com.cloud.utils.Pair;
 import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
 
 /*
  * Data Access Object for vm_templates table
  */
-public interface VMTemplateDao extends GenericDao<VMTemplateVO, Long> {
+public interface VMTemplateDao extends GenericDao<VMTemplateVO, Long>, StateDao<TemplateState, TemplateEvent, VMTemplateVO> {
 	
 	
 	public List<VMTemplateVO> listByPublic();

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java
index 42f10d3..c4928be 100755
--- a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java
@@ -16,8 +16,8 @@
 // under the License.
 package com.cloud.storage.dao;
 
-import static com.cloud.utils.StringUtils.*;
-import static com.cloud.utils.db.DbUtil.*;
+import static com.cloud.utils.StringUtils.join;
+import static com.cloud.utils.db.DbUtil.closeResources;
 
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
@@ -34,10 +34,12 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.api.BaseCmd;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
-import org.apache.cloudstack.api.BaseCmd;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.domain.DomainVO;
@@ -55,11 +57,10 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.VMTemplateZoneVO;
 import com.cloud.tags.ResourceTagVO;
-import com.cloud.tags.dao.ResourceTagsDaoImpl;
+import com.cloud.tags.dao.ResourceTagDao;
 import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
 import com.cloud.user.Account;
 import com.cloud.utils.Pair;
-
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.GenericDaoBase;
@@ -68,7 +69,9 @@ import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.SearchCriteria.Func;
+import com.cloud.utils.db.SearchCriteria.Op;
 import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.UpdateBuilder;
 import com.cloud.utils.exception.CloudRuntimeException;
 
 @Component
@@ -122,14 +125,15 @@ public class VMTemplateDaoImpl extends GenericDaoBase<VMTemplateVO, Long> implem
     private SearchBuilder<VMTemplateVO> PublicIsoSearch;
     private SearchBuilder<VMTemplateVO> UserIsoSearch;
     private GenericSearchBuilder<VMTemplateVO, Long> CountTemplatesByAccount;
+    private SearchBuilder<VMTemplateVO> updateStateSearch;
 
-    @Inject ResourceTagsDaoImpl _tagsDao;
+    @Inject ResourceTagDao _tagsDao;
 
 
     private String routerTmpltName;
     private String consoleProxyTmpltName;
     
-    protected VMTemplateDaoImpl() {
+    public VMTemplateDaoImpl() {
     }
     
     @Override
@@ -378,6 +382,12 @@ public class VMTemplateDaoImpl extends GenericDaoBase<VMTemplateVO, Long> implem
 		CountTemplatesByAccount.and("account", CountTemplatesByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
 		CountTemplatesByAccount.and("removed", CountTemplatesByAccount.entity().getRemoved(), SearchCriteria.Op.NULL);
 		CountTemplatesByAccount.done();
+		
+        updateStateSearch = this.createSearchBuilder();
+        updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
+        updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
+        updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
+        updateStateSearch.done();
 
 		return result;
 	}
@@ -1073,4 +1083,39 @@ public class VMTemplateDaoImpl extends GenericDaoBase<VMTemplateVO, Long> implem
         return templateZonePairList;
     }
 
+    @Override
+    public boolean updateState(TemplateState currentState, TemplateEvent event,
+            TemplateState nextState, VMTemplateVO vo, Object data) {
+        Long oldUpdated = vo.getUpdatedCount();
+        Date oldUpdatedTime = vo.getUpdated();
+    
+        
+        SearchCriteria<VMTemplateVO> sc = updateStateSearch.create();
+        sc.setParameters("id", vo.getId());
+        sc.setParameters("state", currentState);
+        sc.setParameters("updatedCount", vo.getUpdatedCount());
+
+        vo.incrUpdatedCount();
+
+        UpdateBuilder builder = getUpdateBuilder(vo);
+        builder.set(vo, "state", nextState);
+        builder.set(vo, "updated", new Date());
+
+        int rows = update((VMTemplateVO) vo, sc);
+        if (rows == 0 && s_logger.isDebugEnabled()) {
+            VMTemplateVO dbVol = findByIdIncludingRemoved(vo.getId());
+            if (dbVol != null) {
+                StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
+                str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
+                        .append(dbVol.getUpdated());
+                str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount())
+                        .append("; updatedTime=").append(vo.getUpdated());
+                str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated)
+                        .append("; updatedTime=").append(oldUpdatedTime);
+            } else {
+                s_logger.debug("Unable to update objectIndatastore: id=" + vo.getId() + ", as there is no such object exists in the database anymore");
+            }
+        }
+        return rows > 0;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplateHostDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplateHostDao.java b/server/src/com/cloud/storage/dao/VMTemplateHostDao.java
index 5625e56..23241cd 100755
--- a/server/src/com/cloud/storage/dao/VMTemplateHostDao.java
+++ b/server/src/com/cloud/storage/dao/VMTemplateHostDao.java
@@ -18,11 +18,15 @@ package com.cloud.storage.dao;
 
 import java.util.List;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+
 import com.cloud.storage.VMTemplateHostVO;
 import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
 
-public interface VMTemplateHostDao extends GenericDao<VMTemplateHostVO, Long> {
+public interface VMTemplateHostDao extends GenericDao<VMTemplateHostVO, Long>, StateDao<ObjectInDataStoreStateMachine.State, ObjectInDataStoreStateMachine.Event, DataObjectInStore> {
     List<VMTemplateHostVO> listByHostId(long id);
 
     List<VMTemplateHostVO> listByTemplateId(long templateId);
@@ -30,6 +34,8 @@ public interface VMTemplateHostDao extends GenericDao<VMTemplateHostVO, Long> {
     List<VMTemplateHostVO> listByOnlyTemplateId(long templateId);
 
     VMTemplateHostVO findByHostTemplate(long hostId, long templateId);
+    
+    VMTemplateHostVO findByTemplateId(long templateId);
 
     VMTemplateHostVO findByHostTemplate(long hostId, long templateId, boolean lock);
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java
index 4d1ac02..4d19bfc 100755
--- a/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VMTemplateHostDaoImpl.java
@@ -29,6 +29,9 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -42,7 +45,9 @@ import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.JoinBuilder;
 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.db.UpdateBuilder;
 
 @Component
 @Local(value={VMTemplateHostDao.class})
@@ -57,6 +62,7 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase<VMTemplateHostVO, Long
 	protected final SearchBuilder<VMTemplateHostVO> HostDestroyedSearch;
 	protected final SearchBuilder<VMTemplateHostVO> TemplateStatusSearch;
 	protected final SearchBuilder<VMTemplateHostVO> TemplateStatesSearch;
+	protected final SearchBuilder<VMTemplateHostVO> updateStateSearch;
 	protected SearchBuilder<VMTemplateHostVO> ZONE_TEMPLATE_SEARCH;
 	protected SearchBuilder<VMTemplateHostVO> LOCAL_SECONDARY_STORAGE_SEARCH;
 
@@ -120,6 +126,12 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase<VMTemplateHostVO, Long
         HostTemplateStateSearch.and("states", HostTemplateStateSearch.entity().getDownloadState(), SearchCriteria.Op.IN);
         HostTemplateStateSearch.and("destroyed", HostTemplateStateSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
         HostTemplateStateSearch.done();
+        
+        updateStateSearch = this.createSearchBuilder();
+        updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
+        updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
+        updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
+        updateStateSearch.done();
 
     }
 	
@@ -201,6 +213,14 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase<VMTemplateHostVO, Long
         sc.setParameters("destroyed", false);
         return findOneIncludingRemovedBy(sc);
 	}
+
+	@Override
+	public VMTemplateHostVO findByTemplateId(long templateId) {
+	    SearchCriteria<VMTemplateHostVO> sc = HostTemplateSearch.create();
+	    sc.setParameters("template_id", templateId);
+	    sc.setParameters("destroyed", false);
+	    return findOneIncludingRemovedBy(sc);
+	}
 	
 	@Override
 	public List<VMTemplateHostVO> listByTemplateStatus(long templateId, VMTemplateHostVO.Status downloadState) {
@@ -367,5 +387,42 @@ public class VMTemplateHostDaoImpl extends GenericDaoBase<VMTemplateHostVO, Long
             remove(tmpltHost.getId());
         }
     }
+    
+    @Override
+    public boolean updateState(State currentState, Event event,
+            State nextState, DataObjectInStore vo, Object data) {
+        VMTemplateHostVO templateHost = (VMTemplateHostVO)vo;
+        Long oldUpdated = templateHost.getUpdatedCount();
+        Date oldUpdatedTime = templateHost.getUpdated();
+    
+        
+        SearchCriteria<VMTemplateHostVO> sc = updateStateSearch.create();
+        sc.setParameters("id", templateHost.getId());
+        sc.setParameters("state", currentState);
+        sc.setParameters("updatedCount", templateHost.getUpdatedCount());
+
+        templateHost.incrUpdatedCount();
+
+        UpdateBuilder builder = getUpdateBuilder(vo);
+        builder.set(vo, "state", nextState);
+        builder.set(vo, "updated", new Date());
+
+        int rows = update((VMTemplateHostVO) vo, sc);
+        if (rows == 0 && s_logger.isDebugEnabled()) {
+            VMTemplateHostVO dbVol = findByIdIncludingRemoved(templateHost.getId());
+            if (dbVol != null) {
+                StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
+                str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
+                        .append(dbVol.getUpdated());
+                str.append(": New Data={id=").append(templateHost.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(templateHost.getUpdatedCount())
+                        .append("; updatedTime=").append(templateHost.getUpdated());
+                str.append(": stale Data={id=").append(templateHost.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated)
+                        .append("; updatedTime=").append(oldUpdatedTime);
+            } else {
+                s_logger.debug("Unable to update objectIndatastore: id=" + templateHost.getId() + ", as there is no such object exists in the database anymore");
+            }
+        }
+        return rows > 0;
+    }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplatePoolDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplatePoolDao.java b/server/src/com/cloud/storage/dao/VMTemplatePoolDao.java
index f485be7..501c3ca 100644
--- a/server/src/com/cloud/storage/dao/VMTemplatePoolDao.java
+++ b/server/src/com/cloud/storage/dao/VMTemplatePoolDao.java
@@ -18,10 +18,14 @@ package com.cloud.storage.dao;
 
 import java.util.List;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+
 import com.cloud.storage.VMTemplateStoragePoolVO;
 import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
 
-public interface VMTemplatePoolDao extends GenericDao<VMTemplateStoragePoolVO, Long> {
+public interface VMTemplatePoolDao extends GenericDao<VMTemplateStoragePoolVO, Long>, StateDao<ObjectInDataStoreStateMachine.State, ObjectInDataStoreStateMachine.Event, DataObjectInStore> {
 	public List<VMTemplateStoragePoolVO> listByPoolId(long id);
 	
 	public List<VMTemplateStoragePoolVO> listByTemplateId(long templateId);
@@ -42,5 +46,4 @@ public interface VMTemplatePoolDao extends GenericDao<VMTemplateStoragePoolVO, L
 	boolean templateAvailable(long templateId, long poolId);
 
 	public VMTemplateStoragePoolVO findByHostTemplate(Long hostId, Long templateId);
-
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java b/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java
index 292bd5b..5f212eb 100644
--- a/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java
@@ -20,10 +20,14 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.util.ArrayList;
+import java.util.Date;
 import java.util.List;
 
 import javax.ejb.Local;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -33,7 +37,9 @@ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.utils.db.GenericDaoBase;
 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.db.UpdateBuilder;
 
 @Component
 @Local(value={VMTemplatePoolDao.class})
@@ -46,6 +52,7 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase<VMTemplateStoragePoolV
 	protected final SearchBuilder<VMTemplateStoragePoolVO> TemplateStatusSearch;
     protected final SearchBuilder<VMTemplateStoragePoolVO> TemplatePoolStatusSearch;
 	protected final SearchBuilder<VMTemplateStoragePoolVO> TemplateStatesSearch;
+	protected final SearchBuilder<VMTemplateStoragePoolVO> updateStateSearch;
 	
 	protected static final String UPDATE_TEMPLATE_HOST_REF =
 		"UPDATE template_spool_ref SET download_state = ?, download_pct= ?, last_updated = ? "
@@ -94,6 +101,12 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase<VMTemplateStoragePoolV
 		TemplateStatesSearch.and("template_id", TemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ);
 		TemplateStatesSearch.and("states", TemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.IN);
 		TemplateStatesSearch.done();
+
+		updateStateSearch = this.createSearchBuilder();
+		updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
+		updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
+		updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
+		updateStateSearch.done();
 	}
 
 	@Override
@@ -252,4 +265,40 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase<VMTemplateStoragePoolV
 		return (result.size() == 0)?null:result.get(1);
 	}
 
+    @Override
+    public boolean updateState(State currentState, Event event,
+            State nextState, DataObjectInStore vo, Object data) {
+        VMTemplateStoragePoolVO templatePool = (VMTemplateStoragePoolVO)vo;
+        Long oldUpdated = templatePool.getUpdatedCount();
+        Date oldUpdatedTime = templatePool.getUpdated();
+    
+        SearchCriteria<VMTemplateStoragePoolVO> sc = updateStateSearch.create();
+        sc.setParameters("id", templatePool.getId());
+        sc.setParameters("state", currentState);
+        sc.setParameters("updatedCount", templatePool.getUpdatedCount());
+
+        templatePool.incrUpdatedCount();
+
+        UpdateBuilder builder = getUpdateBuilder(vo);
+        builder.set(vo, "state", nextState);
+        builder.set(vo, "updated", new Date());
+
+        int rows = update((VMTemplateStoragePoolVO) vo, sc);
+        if (rows == 0 && s_logger.isDebugEnabled()) {
+            VMTemplateStoragePoolVO dbVol = findByIdIncludingRemoved(templatePool.getId());
+            if (dbVol != null) {
+                StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
+                str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
+                        .append(dbVol.getUpdated());
+                str.append(": New Data={id=").append(templatePool.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(templatePool.getUpdatedCount())
+                        .append("; updatedTime=").append(templatePool.getUpdated());
+                str.append(": stale Data={id=").append(templatePool.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated)
+                        .append("; updatedTime=").append(oldUpdatedTime);
+            } else {
+                s_logger.debug("Unable to update objectIndatastore: id=" + templatePool.getId() + ", as there is no such object exists in the database anymore");
+            }
+        }
+        return rows > 0;
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
index a189d00..ca3b82a 100755
--- a/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VolumeDaoImpl.java
@@ -39,7 +39,6 @@ import com.cloud.storage.Volume.Type;
 import com.cloud.storage.VolumeVO;
 import com.cloud.tags.dao.ResourceTagsDaoImpl;
 import com.cloud.utils.Pair;
-
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.GenericSearchBuilder;
@@ -250,7 +249,7 @@ public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements Vol
         }
     }
     
-	protected VolumeDaoImpl() {
+	public VolumeDaoImpl() {
 	    AllFieldsSearch = createSearchBuilder();
 	    AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
         AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), Op.EQ);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VolumeHostDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VolumeHostDao.java b/server/src/com/cloud/storage/dao/VolumeHostDao.java
index 6ba8237..39dda12 100755
--- a/server/src/com/cloud/storage/dao/VolumeHostDao.java
+++ b/server/src/com/cloud/storage/dao/VolumeHostDao.java
@@ -18,10 +18,14 @@ package com.cloud.storage.dao;
 
 import java.util.List;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+
 import com.cloud.storage.VolumeHostVO;
 import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
 
-public interface VolumeHostDao extends GenericDao<VolumeHostVO, Long> {
+public interface VolumeHostDao extends GenericDao<VolumeHostVO, Long>, StateDao<ObjectInDataStoreStateMachine.State, ObjectInDataStoreStateMachine.Event, DataObjectInStore>{
 
 	VolumeHostVO findByHostVolume(long hostId, long volumeId);
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java
index 57f2153..2fd39e6 100755
--- a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java
+++ b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java
@@ -16,28 +16,35 @@
 // under the License.
 package com.cloud.storage.dao;
 
+import java.util.Date;
 import java.util.List;
 
 import javax.ejb.Local;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State;
+import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
 import com.cloud.storage.VolumeHostVO;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.UpdateBuilder;
 
 @Component
 @Local(value={VolumeHostDao.class})
 public class VolumeHostDaoImpl extends GenericDaoBase<VolumeHostVO, Long> implements VolumeHostDao {
-
+    private static final Logger s_logger = Logger.getLogger(VolumeHostDaoImpl.class);
     protected final SearchBuilder<VolumeHostVO> HostVolumeSearch;
     protected final SearchBuilder<VolumeHostVO> ZoneVolumeSearch;
     protected final SearchBuilder<VolumeHostVO> VolumeSearch;
     protected final SearchBuilder<VolumeHostVO> HostSearch;
     protected final SearchBuilder<VolumeHostVO> HostDestroyedSearch;
-
-    VolumeHostDaoImpl(){
+    protected final SearchBuilder<VolumeHostVO> updateStateSearch;
+    public VolumeHostDaoImpl(){
         HostVolumeSearch = createSearchBuilder();
         HostVolumeSearch.and("host_id", HostVolumeSearch.entity().getHostId(), SearchCriteria.Op.EQ);
         HostVolumeSearch.and("volume_id", HostVolumeSearch.entity().getVolumeId(), SearchCriteria.Op.EQ);
@@ -64,6 +71,12 @@ public class VolumeHostDaoImpl extends GenericDaoBase<VolumeHostVO, Long> implem
         HostDestroyedSearch.and("host_id", HostDestroyedSearch.entity().getHostId(), SearchCriteria.Op.EQ);
         HostDestroyedSearch.and("destroyed", HostDestroyedSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
         HostDestroyedSearch.done();	
+        
+        updateStateSearch = this.createSearchBuilder();
+        updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
+        updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
+        updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
+        updateStateSearch.done();
     }
 
 
@@ -112,4 +125,41 @@ public class VolumeHostDaoImpl extends GenericDaoBase<VolumeHostVO, Long> implem
         return listIncludingRemovedBy(sc);
     }
 
+    @Override
+    public boolean updateState(State currentState, Event event,
+            State nextState, DataObjectInStore vo, Object data) {
+        VolumeHostVO volHost = (VolumeHostVO) vo;
+        Long oldUpdated = volHost.getUpdatedCount();
+        Date oldUpdatedTime = volHost.getUpdated();
+    
+        
+        SearchCriteria<VolumeHostVO> sc = updateStateSearch.create();
+        sc.setParameters("id", volHost.getId());
+        sc.setParameters("state", currentState);
+        sc.setParameters("updatedCount", volHost.getUpdatedCount());
+
+        volHost.incrUpdatedCount();
+
+        UpdateBuilder builder = getUpdateBuilder(vo);
+        builder.set(vo, "state", nextState);
+        builder.set(vo, "updated", new Date());
+
+        int rows = update((VolumeHostVO) vo, sc);
+        if (rows == 0 && s_logger.isDebugEnabled()) {
+            VolumeHostVO dbVol = findByIdIncludingRemoved(volHost.getId());
+            if (dbVol != null) {
+                StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
+                str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
+                        .append(dbVol.getUpdated());
+                str.append(": New Data={id=").append(volHost.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(volHost.getUpdatedCount())
+                        .append("; updatedTime=").append(volHost.getUpdated());
+                str.append(": stale Data={id=").append(volHost.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated)
+                        .append("; updatedTime=").append(oldUpdatedTime);
+            } else {
+                s_logger.debug("Unable to update objectIndatastore: id=" + volHost.getId() + ", as there is no such object exists in the database anymore");
+            }
+        }
+        return rows > 0;
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/download/DownloadListener.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/download/DownloadListener.java b/server/src/com/cloud/storage/download/DownloadListener.java
index 036d40a..d0b1868 100755
--- a/server/src/com/cloud/storage/download/DownloadListener.java
+++ b/server/src/com/cloud/storage/download/DownloadListener.java
@@ -46,11 +46,11 @@ import com.cloud.host.HostVO;
 import com.cloud.storage.Storage;
 import com.cloud.storage.StorageManager;
 import com.cloud.storage.VMTemplateHostVO;
+import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.VolumeHostVO;
 import com.cloud.storage.VolumeVO;
 import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.Volume.Event;
-import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VMTemplateHostDao;
 import com.cloud.storage.dao.VolumeDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/download/DownloadMonitor.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/download/DownloadMonitor.java b/server/src/com/cloud/storage/download/DownloadMonitor.java
index 30ec3b1..897befa 100644
--- a/server/src/com/cloud/storage/download/DownloadMonitor.java
+++ b/server/src/com/cloud/storage/download/DownloadMonitor.java
@@ -18,6 +18,7 @@ package com.cloud.storage.download;
 
 import java.util.Map;
 
+
 import com.cloud.exception.StorageUnavailableException;
 import com.cloud.host.HostVO;
 import com.cloud.storage.VMTemplateVO;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
index 6d3cf2a..e12bc32 100755
--- a/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
+++ b/server/src/com/cloud/storage/download/DownloadMonitorImpl.java
@@ -37,10 +37,21 @@ import com.cloud.agent.AgentManager;
 import com.cloud.agent.Listener;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
-import com.cloud.agent.api.storage.*;
+
+import com.cloud.agent.api.storage.DeleteTemplateCommand;
+import com.cloud.agent.api.storage.DeleteVolumeCommand;
+import com.cloud.agent.api.storage.DownloadCommand;
+
 import com.cloud.agent.api.storage.DownloadCommand.Proxy;
 import com.cloud.agent.api.storage.DownloadCommand.ResourceType;
 import com.cloud.agent.api.storage.DownloadProgressCommand.RequestType;
+
+import com.cloud.agent.api.storage.DownloadProgressCommand;
+import com.cloud.agent.api.storage.ListTemplateAnswer;
+import com.cloud.agent.api.storage.ListTemplateCommand;
+import com.cloud.agent.api.storage.ListVolumeAnswer;
+import com.cloud.agent.api.storage.ListVolumeCommand;
+
 import com.cloud.agent.manager.Commands;
 import com.cloud.alert.AlertManager;
 import com.cloud.configuration.Config;
@@ -50,6 +61,7 @@ import com.cloud.dc.dao.ClusterDao;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.event.EventTypes;
 import com.cloud.event.UsageEventUtils;
+import com.cloud.event.dao.UsageEventDao;
 import com.cloud.exception.AgentUnavailableException;
 import com.cloud.exception.InvalidParameterValueException;
 import com.cloud.exception.StorageUnavailableException;
@@ -59,13 +71,31 @@ import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.resource.ResourceManager;
 import com.cloud.storage.Storage.ImageFormat;
-import com.cloud.storage.*;
+
+import com.cloud.storage.StorageManager;
+import com.cloud.storage.SwiftVO;
+import com.cloud.storage.VMTemplateHostVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc;
+import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
-import com.cloud.storage.dao.*;
+import com.cloud.storage.VMTemplateZoneVO;
+import com.cloud.storage.VolumeHostVO;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.StoragePoolHostDao;
+import com.cloud.storage.dao.SwiftDao;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.storage.dao.VMTemplateHostDao;
+import com.cloud.storage.dao.VMTemplatePoolDao;
+import com.cloud.storage.dao.VMTemplateSwiftDao;
+import com.cloud.storage.dao.VMTemplateZoneDao;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.storage.dao.VolumeHostDao;
+
 import com.cloud.storage.secondary.SecondaryStorageVmManager;
 import com.cloud.storage.swift.SwiftManager;
 import com.cloud.storage.template.TemplateConstants;
 import com.cloud.storage.template.TemplateInfo;
+import com.cloud.template.TemplateManager;
 import com.cloud.user.Account;
 import com.cloud.user.ResourceLimitService;
 import com.cloud.utils.component.ManagerBase;
@@ -80,6 +110,7 @@ import com.cloud.vm.SecondaryStorageVmVO;
 import com.cloud.vm.UserVmManager;
 import com.cloud.vm.VirtualMachine.State;
 import com.cloud.vm.dao.SecondaryStorageVmDao;
+
 import edu.emory.mathcs.backport.java.util.Collections;
 
 
@@ -124,6 +155,14 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
     ConfigurationDao _configDao;
     @Inject
     UserVmManager _vmMgr;
+
+    @Inject TemplateManager templateMgr;
+
+    
+    @Inject 
+    private UsageEventDao _usageEventDao;
+    
+
     @Inject
     private ClusterDao _clusterDao;
     @Inject
@@ -233,7 +272,7 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
         
 		if(destTmpltHost != null) {
 		    start();
-            String sourceChecksum = _vmMgr.getChecksum(srcTmpltHost.getHostId(), srcTmpltHost.getInstallPath());
+            String sourceChecksum = this.templateMgr.getChecksum(srcTmpltHost.getHostId(), srcTmpltHost.getInstallPath());
 			DownloadCommand dcmd =  
               new DownloadCommand(destServer.getStorageUrl(), url, template, TemplateConstants.DEFAULT_HTTP_AUTH_USER, _copyAuthPasswd, maxTemplateSizeInBytes); 
 			dcmd.setProxy(getHttpProxy());
@@ -473,6 +512,8 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
             long size = -1;
             if(vmTemplateHost!=null){
                 size = vmTemplateHost.getPhysicalSize();
+                template.setSize(size);
+                this._templateDao.update(template.getId(), template);
             }
             else{
                 s_logger.warn("Failed to get size for template" + template.getName());
@@ -510,6 +551,8 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
             long size = -1;
             if(volumeHost!=null){
                 size = volumeHost.getPhysicalSize();
+                volume.setSize(size);
+                this._volumeDao.update(volume.getId(), volume);
             }
             else{
                 s_logger.warn("Failed to get size for volume" + volume.getName());
@@ -925,7 +968,7 @@ public class DownloadMonitorImpl extends ManagerBase implements  DownloadMonitor
         s_logger.debug("Found " +templateHostRefList.size()+ " templates with no checksum. Will ask for computation");
         for(VMTemplateHostVO templateHostRef : templateHostRefList){
             s_logger.debug("Getting checksum for template - " + templateHostRef.getTemplateId());
-            String checksum = _vmMgr.getChecksum(hostId, templateHostRef.getInstallPath());
+            String checksum = this.templateMgr.getChecksum(hostId, templateHostRef.getInstallPath());
             VMTemplateVO template = _templateDao.findById(templateHostRef.getTemplateId());
             s_logger.debug("Setting checksum " +checksum+ " for template - " + template.getName());
             template.setChecksum(checksum);

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/listener/StoragePoolMonitor.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/listener/StoragePoolMonitor.java b/server/src/com/cloud/storage/listener/StoragePoolMonitor.java
index e848a87..df2df7b 100755
--- a/server/src/com/cloud/storage/listener/StoragePoolMonitor.java
+++ b/server/src/com/cloud/storage/listener/StoragePoolMonitor.java
@@ -20,6 +20,8 @@ import java.util.List;
 
 import javax.inject.Inject;
 
+import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.log4j.Logger;
 
 import com.cloud.agent.Listener;
@@ -37,17 +39,15 @@ import com.cloud.storage.OCFS2Manager;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageManagerImpl;
 import com.cloud.storage.StoragePoolStatus;
-import com.cloud.storage.StoragePoolVO;
-import com.cloud.storage.dao.StoragePoolDao;
 
 
 public class StoragePoolMonitor implements Listener {
     private static final Logger s_logger = Logger.getLogger(StoragePoolMonitor.class);
     private final StorageManagerImpl _storageManager;
-    private final StoragePoolDao _poolDao;
+    private final PrimaryDataStoreDao _poolDao;
     @Inject OCFS2Manager _ocfs2Mgr;
 
-    public StoragePoolMonitor(StorageManagerImpl mgr, StoragePoolDao poolDao) {
+    public StoragePoolMonitor(StorageManagerImpl mgr, PrimaryDataStoreDao poolDao) {
         this._storageManager = mgr;
         this._poolDao = poolDao;
 
@@ -80,7 +80,7 @@ public class StoragePoolMonitor implements Listener {
                     if (pool.getStatus() != StoragePoolStatus.Up) {
                         continue;
                     }
-                    if (!pool.getPoolType().isShared()) {
+                    if (!pool.isShared()) {
                         continue;
                     }
 
@@ -91,8 +91,8 @@ public class StoragePoolMonitor implements Listener {
                     Long hostId = host.getId();
                     s_logger.debug("Host " + hostId + " connected, sending down storage pool information ...");
                     try {
-                        _storageManager.connectHostToSharedPool(hostId, pool);
-                        _storageManager.createCapacityEntry(pool);
+                        _storageManager.connectHostToSharedPool(hostId, pool.getId());
+                        _storageManager.createCapacityEntry(pool.getId());
                     } catch (Exception e) {
                         s_logger.warn("Unable to connect host " + hostId + " to pool " + pool + " due to " + e.toString(), e);
                     }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java
index 877b97c..8f25514 100644
--- a/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java
+++ b/server/src/com/cloud/storage/resource/DummySecondaryStorageResource.java
@@ -46,8 +46,8 @@ import com.cloud.host.Host.Type;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.ServerResourceBase;
 import com.cloud.storage.Storage;
-import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.template.TemplateConstants;
 import com.cloud.storage.template.TemplateInfo;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/s3/S3Manager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/s3/S3Manager.java b/server/src/com/cloud/storage/s3/S3Manager.java
index 0e47d72..0f74e43 100644
--- a/server/src/com/cloud/storage/s3/S3Manager.java
+++ b/server/src/com/cloud/storage/s3/S3Manager.java
@@ -23,6 +23,7 @@ import java.util.List;
 import com.cloud.agent.api.to.S3TO;
 import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd;
 import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd;
+
 import com.cloud.dc.DataCenterVO;
 import com.cloud.exception.DiscoveryException;
 import com.cloud.storage.S3;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/s3/S3ManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/s3/S3ManagerImpl.java b/server/src/com/cloud/storage/s3/S3ManagerImpl.java
index 13fe2b7..61e5573 100644
--- a/server/src/com/cloud/storage/s3/S3ManagerImpl.java
+++ b/server/src/com/cloud/storage/s3/S3ManagerImpl.java
@@ -68,8 +68,8 @@ import com.cloud.storage.S3;
 import com.cloud.storage.S3VO;
 import com.cloud.storage.VMTemplateHostVO;
 import com.cloud.storage.VMTemplateS3VO;
-import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateZoneVO;
 import com.cloud.storage.dao.S3Dao;
 import com.cloud.storage.dao.VMTemplateDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
index fca89dc..46ac7af 100755
--- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
+++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
@@ -98,8 +98,8 @@ import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.SnapshotVO;
 import com.cloud.storage.Storage;
 import com.cloud.storage.VMTemplateHostVO;
-import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.dao.SnapshotDao;
 import com.cloud.storage.dao.StoragePoolHostDao;
 import com.cloud.storage.dao.VMTemplateDao;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
index e06da75..6b48b82 100755
--- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
@@ -28,12 +28,25 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd;
+import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd;
+import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd;
 import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
 import com.cloud.agent.AgentManager;
-import com.cloud.agent.api.*;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.BackupSnapshotAnswer;
+import com.cloud.agent.api.BackupSnapshotCommand;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.DeleteSnapshotBackupCommand;
+import com.cloud.agent.api.DeleteSnapshotsDirCommand;
+import com.cloud.agent.api.DownloadSnapshotFromS3Command;
+import com.cloud.agent.api.ManageSnapshotAnswer;
+import com.cloud.agent.api.ManageSnapshotCommand;
+import com.cloud.agent.api.downloadSnapshotFromSwiftCommand;
 import com.cloud.agent.api.to.S3TO;
 import com.cloud.agent.api.to.SwiftTO;
 import com.cloud.alert.AlertManager;
@@ -46,7 +59,11 @@ import com.cloud.dc.DataCenter;
 import com.cloud.dc.dao.ClusterDao;
 import com.cloud.dc.dao.DataCenterDao;
 import com.cloud.domain.dao.DomainDao;
-import com.cloud.event.*;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.ActionEventUtils;
+import com.cloud.event.EventTypes;
+import com.cloud.event.EventVO;
+import com.cloud.event.UsageEventUtils;
 import com.cloud.event.dao.EventDao;
 import com.cloud.event.dao.UsageEventDao;
 import com.cloud.exception.InvalidParameterValueException;
@@ -60,25 +77,46 @@ import com.cloud.org.Grouping;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
 import com.cloud.resource.ResourceManager;
 import com.cloud.server.ResourceTag.TaggedResourceType;
-import com.cloud.storage.*;
+import com.cloud.storage.Snapshot;
 import com.cloud.storage.Snapshot.Type;
+import com.cloud.storage.SnapshotPolicyVO;
+import com.cloud.storage.SnapshotScheduleVO;
+import com.cloud.storage.SnapshotVO;
+import com.cloud.storage.Storage;
 import com.cloud.storage.Storage.StoragePoolType;
-import com.cloud.storage.dao.*;
+import com.cloud.storage.StorageManager;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.Volume;
+import com.cloud.storage.VolumeManager;
+import com.cloud.storage.VolumeVO;
+import com.cloud.storage.dao.DiskOfferingDao;
+import com.cloud.storage.dao.SnapshotDao;
+import com.cloud.storage.dao.SnapshotPolicyDao;
+import com.cloud.storage.dao.SnapshotScheduleDao;
+import com.cloud.storage.dao.StoragePoolDao;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.storage.dao.VolumeDao;
 import com.cloud.storage.listener.SnapshotStateListener;
 import com.cloud.storage.s3.S3Manager;
 import com.cloud.storage.secondary.SecondaryStorageVmManager;
 import com.cloud.storage.swift.SwiftManager;
 import com.cloud.tags.ResourceTagVO;
 import com.cloud.tags.dao.ResourceTagDao;
-import com.cloud.user.*;
+import com.cloud.template.TemplateManager;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.user.AccountVO;
+import com.cloud.user.DomainManager;
+import com.cloud.user.ResourceLimitService;
+import com.cloud.user.User;
+import com.cloud.user.UserContext;
 import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.DateUtil;
 import com.cloud.utils.DateUtil.IntervalType;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.Ternary;
-
-import com.cloud.utils.component.Manager;
 import com.cloud.utils.component.ManagerBase;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.Filter;
@@ -86,7 +124,6 @@ import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.db.Transaction;
-import com.cloud.utils.db.*;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.fsm.NoTransitionException;
 import com.cloud.utils.fsm.StateMachine2;
@@ -95,6 +132,7 @@ import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.State;
 import com.cloud.vm.dao.UserVmDao;
+
 import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd;
 import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd;
 import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd;
@@ -105,9 +143,9 @@ import javax.ejb.Local;
 import javax.naming.ConfigurationException;
 import java.util.*;
 import com.cloud.vm.snapshot.VMSnapshot;
-import com.cloud.vm.snapshot.VMSnapshotVO;
 import com.cloud.vm.snapshot.dao.VMSnapshotDao;
 
+
 @Component
 @Local(value = { SnapshotManager.class, SnapshotService.class })
 public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager, SnapshotService {
@@ -170,9 +208,16 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
     private ResourceTagDao _resourceTagDao;
     @Inject
     private ConfigurationDao _configDao;
+
     @Inject 
     private VMSnapshotDao _vmSnapshotDao;
     String _name;
+
+    @Inject TemplateManager templateMgr;
+    @Inject VolumeManager volumeMgr;
+    @Inject DataStoreManager dataStoreMgr;
+    
+
     private int _totalRetries;
     private int _pauseInterval;
     private int _deltaSnapshotMax;
@@ -186,8 +231,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
     
     
     protected Answer sendToPool(Volume vol, Command cmd) {
-        StoragePool pool = _storagePoolDao.findById(vol.getPoolId());
-
+        StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
         long[] hostIdsToTryFirst = null;
         
         Long vmHostId = getHostIdForSnapshotOperation(vol);
@@ -252,7 +296,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         }
 
         // Send a ManageSnapshotCommand to the agent
-        String vmName = _storageMgr.getVmNameOnVolume(volume);
+        String vmName = this.volumeMgr.getVmNameOnVolume(volume);
         long volumeId = volume.getId();
         long preId = _snapshotDao.getLastSnapshot(volumeId, snapshotId);
 
@@ -264,8 +308,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
                 preSnapshotPath = preSnapshotVO.getPath();
             }
         }
-        StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId());
-
+        StoragePool srcPool = (StoragePool)dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
         // RBD volumes do not support snapshotting in the way CloudStack does it.
         // For now we leave the snapshot feature disabled for RBD volumes
         if (srcPool.getPoolType() == StoragePoolType.RBD) {
@@ -414,12 +457,12 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
                         if(activeSnapshots.size() > 1)
                             throw new CloudRuntimeException("There is other active snapshot tasks on the instance to which the volume is attached, please try again later");
                     }
-                    List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(userVm.getId(),
+                    /*List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(userVm.getId(),
                             VMSnapshot.State.Creating, VMSnapshot.State.Reverting, VMSnapshot.State.Expunging);
                     if (activeVMSnapshots.size() > 0) {
                         throw new CloudRuntimeException(
                                 "There is other active vm snapshot tasks on the instance to which the volume is attached, please try again later");
-                    }			
+                    }			*/
                 }
             }
 
@@ -530,7 +573,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         VolumeVO volume = _volsDao.findById(volumeId);
         Long dcId = volume.getDataCenterId();
         Long accountId = volume.getAccountId();
-        HostVO secHost = _storageMgr.getSecondaryStorageHost(dcId);
+        HostVO secHost = this.templateMgr.getSecondaryStorageHost(dcId);
         String secondaryStoragePoolUrl = secHost.getStorageUrl();
 
         Long swiftId = ss.getSwiftId();
@@ -581,7 +624,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
 
         final VolumeVO volume = _volsDao.findById(snapshot.getVolumeId());
         final Long zoneId = volume.getDataCenterId();
-        final HostVO secHost = _storageMgr.getSecondaryStorageHost(zoneId);
+        final HostVO secHost = this.templateMgr.getSecondaryStorageHost(zoneId);
 
         final S3TO s3 = _s3Mgr.getS3TO(snapshot.getS3Id());
         final List<String> backupUuids = determineBackupUuids(snapshot);
@@ -662,9 +705,9 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
                     prevSnapshotUuid = prevSnapshot.getPath();
                 }
             }
-            boolean isVolumeInactive = _storageMgr.volumeInactive(volume);
-            String vmName = _storageMgr.getVmNameOnVolume(volume);
-            StoragePoolVO srcPool = _storagePoolDao.findById(volume.getPoolId());
+            boolean isVolumeInactive = this.volumeMgr.volumeInactive(volume);
+            String vmName = this.volumeMgr.getVmNameOnVolume(volume);
+            StoragePool srcPool = (StoragePool)dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
             BackupSnapshotCommand backupSnapshotCommand = new BackupSnapshotCommand(secondaryStoragePoolUrl, dcId, accountId, volumeId, snapshot.getId(), volume.getPath(), srcPool, snapshotUuid,
                     snapshot.getName(), prevSnapshotUuid, prevBackupUuid, isVolumeInactive, vmName, _backupsnapshotwait);
 
@@ -735,7 +778,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
         if ( id != null) { 
             return _hostDao.findById(id);
         }
-        return _storageMgr.getSecondaryStorageHost(dcId);
+        return this.templateMgr.getSecondaryStorageHost(dcId);
     }
 
     private Long getSnapshotUserId() {
@@ -884,7 +927,7 @@ public class SnapshotManagerImpl extends ManagerBase implements SnapshotManager,
             secHost = _hostDao.findById(snapshot.getSecHostId());
         } else {
             Long dcId = snapshot.getDataCenterId();
-            secHost = _storageMgr.getSecondaryStorageHost(dcId);
+            secHost = this.templateMgr.getSecondaryStorageHost(dcId);
         }
         return secHost;
     }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/storage/upload/UploadMonitor.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/upload/UploadMonitor.java b/server/src/com/cloud/storage/upload/UploadMonitor.java
index aada1f4..1c3590e 100755
--- a/server/src/com/cloud/storage/upload/UploadMonitor.java
+++ b/server/src/com/cloud/storage/upload/UploadMonitor.java
@@ -16,6 +16,7 @@
 // under the License.
 package com.cloud.storage.upload;
 
+
 import com.cloud.async.AsyncJobManager;
 import com.cloud.host.HostVO;
 import com.cloud.storage.Upload.Mode;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/tags/dao/ResourceTagsDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/tags/dao/ResourceTagsDaoImpl.java b/server/src/com/cloud/tags/dao/ResourceTagsDaoImpl.java
index 9763956..a8e1393 100644
--- a/server/src/com/cloud/tags/dao/ResourceTagsDaoImpl.java
+++ b/server/src/com/cloud/tags/dao/ResourceTagsDaoImpl.java
@@ -17,6 +17,7 @@
 package com.cloud.tags.dao;
 
 import java.util.List;
+
 import javax.ejb.Local;
 
 import org.springframework.stereotype.Component;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/template/HyervisorTemplateAdapter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HyervisorTemplateAdapter.java
index fe6bc2a..fa72e75 100755
--- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java
+++ b/server/src/com/cloud/template/HyervisorTemplateAdapter.java
@@ -22,12 +22,21 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.UnknownHostException;
 import java.util.List;
+import java.util.concurrent.ExecutionException;
 
 import javax.ejb.Local;
 import javax.inject.Inject;
 
 import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
 import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
+import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
+import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
+import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.engine.subsystem.api.storage.ImageDataFactory;
+import org.apache.cloudstack.engine.subsystem.api.storage.ImageService;
+import org.apache.cloudstack.framework.async.AsyncCallFuture;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
@@ -43,10 +52,10 @@ import com.cloud.exception.ResourceAllocationException;
 import com.cloud.host.HostVO;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.TemplateType;
-import com.cloud.storage.VMTemplateHostVO;
-import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.TemplateProfile;
+import com.cloud.storage.VMTemplateHostVO;
 import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.storage.VMTemplateZoneVO;
 import com.cloud.storage.download.DownloadMonitor;
 import com.cloud.storage.secondary.SecondaryStorageVmManager;
@@ -70,11 +79,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
 	@Inject DownloadMonitor _downloadMonitor;
 	@Inject SecondaryStorageVmManager _ssvmMgr;
 	@Inject AgentManager _agentMgr;
+    @Inject DataStoreManager storeMgr;
+    @Inject ImageService imageService;
+    @Inject ImageDataFactory imageFactory;
+    @Inject TemplateManager templateMgr;
+
 
     @Override
     public String getName() {
         return TemplateAdapterType.Hypervisor.getName();
     }
+
+
 	
 	private String validateUrl(String url) {
 		try {
@@ -155,7 +171,18 @@ public class HyervisorTemplateAdapter extends TemplateAdapterBase implements Tem
 			throw new CloudRuntimeException("Unable to persist the template " + profile.getTemplate());
 		}
 		
-		_downloadMonitor.downloadTemplateToStorage(template, profile.getZoneId());
+		DataStore imageStore = this.templateMgr.getImageStore(profile.getImageStoreUuid(), profile.getZoneId());
+		
+		AsyncCallFuture<CommandResult> future = this.imageService.createTemplateAsync(this.imageFactory.getTemplate(template.getId()), imageStore);
+		try {
+            future.get();
+        } catch (InterruptedException e) {
+            s_logger.debug("create template Failed", e);
+            throw new CloudRuntimeException("create template Failed", e);
+        } catch (ExecutionException e) {
+            s_logger.debug("create template Failed", e);
+            throw new CloudRuntimeException("create template Failed", e);
+        }
 		_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
 		
         return template;

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/template/TemplateAdapter.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateAdapter.java b/server/src/com/cloud/template/TemplateAdapter.java
index 19cfef0..1f8f491 100755
--- a/server/src/com/cloud/template/TemplateAdapter.java
+++ b/server/src/com/cloud/template/TemplateAdapter.java
@@ -22,6 +22,7 @@ import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
 import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
 import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
+
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.storage.TemplateProfile;
@@ -65,5 +66,5 @@ public interface TemplateAdapter extends Adapter {
     public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits,
             Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured,
             Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
-            String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshKeyEnabled) throws ResourceAllocationException;	
+            String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshKeyEnabled, String imageStoreUuid) throws ResourceAllocationException;	
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/template/TemplateAdapterBase.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java
index fa677ac..c5074ad 100755
--- a/server/src/com/cloud/template/TemplateAdapterBase.java
+++ b/server/src/com/cloud/template/TemplateAdapterBase.java
@@ -22,14 +22,17 @@ import java.util.Map;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
 import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
+import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
 import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreRole;
 import org.apache.log4j.Logger;
 
-import org.apache.cloudstack.api.ApiConstants;
 import com.cloud.api.ApiDBUtils;
-import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
 import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.DataCenterVO;
@@ -43,10 +46,10 @@ import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.org.Grouping;
 import com.cloud.storage.GuestOS;
-import com.cloud.storage.TemplateProfile;
+import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.TemplateType;
-import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.TemplateProfile;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.storage.dao.VMTemplateHostDao;
 import com.cloud.storage.dao.VMTemplateZoneDao;
@@ -76,6 +79,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
 	protected @Inject UsageEventDao _usageEventDao;
 	protected @Inject HostDao _hostDao;
 	protected @Inject ResourceLimitService _resourceLimitMgr;
+	protected @Inject DataStoreManager storeMgr;
 	
 	@Override
 	public boolean stop() {
@@ -94,16 +98,26 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
             Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
             String accountName, Long domainId, String chksum, Boolean bootable, Map details) throws ResourceAllocationException {
 	    return prepare(isIso, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, format, guestOSId, zoneId, hypervisorType,
-	            chksum, bootable, null, null, details, false);
+	            chksum, bootable, null, null, details, false, null);
 	}
 	
 	public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits,
 			Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured,
 			Boolean isExtractable, String format, Long guestOSId, Long zoneId, HypervisorType hypervisorType,
-			String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled) throws ResourceAllocationException {
+			String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled,
+			String imageStoreUuid) throws ResourceAllocationException {
 		//Long accountId = null;
 		// parameters verification
 		
+	    String storeUuid = imageStoreUuid;
+        if (storeUuid != null) {
+            DataStore store = this.storeMgr.getDataStore(storeUuid, DataStoreRole.Image);
+            if (store == null) {
+                throw new InvalidParameterValueException("invalide image store uuid" + storeUuid);
+            }
+            
+        }
+        
 		if (isPublic == null) {
 			isPublic = Boolean.FALSE;
 		}
@@ -200,7 +214,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
         Long id = _tmpltDao.getNextInSequence(Long.class, "id");
         UserContext.current().setEventDetails("Id: " +id+ " name: " + name);
 		return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic,
-				featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled);
+				featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, imageStoreUuid);
 	}
 	
 	@Override
@@ -210,10 +224,12 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
         Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
         _accountMgr.checkAccess(caller, null, true, owner);
 	    
+    
+        
 		return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(),
 				cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(),
 				cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()),
-				cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled());
+				cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled(), cmd.getImageStoreUuid());
 	}
 
 	public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
@@ -224,7 +240,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
 	   
 		return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false,
 					true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(),
-					cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false);
+					cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false, cmd.getImageStoreUuid());
 	}
 	
 	protected VMTemplateVO persistTemplate(TemplateProfile profile) {
@@ -234,6 +250,7 @@ public abstract class TemplateAdapterBase extends AdapterBase implements Templat
 				profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(),
 				profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), 
 				profile.getDetails(), profile.getSshKeyEnabled());
+
         
 		if (zoneId == null || zoneId.longValue() == -1) {
             List<DataCenterVO> dcs = _dcDao.listAll();

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/00df9727/server/src/com/cloud/template/TemplateManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/template/TemplateManager.java b/server/src/com/cloud/template/TemplateManager.java
index ad145a9..1b05461 100755
--- a/server/src/com/cloud/template/TemplateManager.java
+++ b/server/src/com/cloud/template/TemplateManager.java
@@ -18,16 +18,19 @@ package com.cloud.template;
 
 import java.util.List;
 
+import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+
 import com.cloud.dc.DataCenterVO;
 import com.cloud.exception.InternalErrorException;
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.exception.StorageUnavailableException;
 import com.cloud.host.HostVO;
 import com.cloud.storage.StoragePool;
-import com.cloud.storage.StoragePoolVO;
 import com.cloud.storage.VMTemplateHostVO;
 import com.cloud.storage.VMTemplateStoragePoolVO;
 import com.cloud.storage.VMTemplateVO;
+import com.cloud.utils.Pair;
 
 /**
  * TemplateManager manages the templates stored on secondary storage. It is responsible for creating private/public templates.
@@ -91,4 +94,27 @@ public interface TemplateManager extends TemplateService{
 
     VMTemplateHostVO prepareISOForCreate(VMTemplateVO template, StoragePool pool);
 
+
+    VMTemplateHostVO findVmTemplateHost(long templateId,
+            StoragePool pool);
+
+    Pair<String, String> getAbsoluteIsoPath(long templateId, long dataCenterId);
+
+    String getSecondaryStorageURL(long zoneId);
+
+    HostVO getSecondaryStorageHost(long zoneId, long tmpltId);
+
+    VMTemplateHostVO getTemplateHostRef(long zoneId, long tmpltId,
+            boolean readyOnly);
+
+    HostVO getSecondaryStorageHost(long zoneId);
+
+    List<HostVO> getSecondaryStorageHosts(long zoneId);
+
+    Long getTemplateSize(long templateId, long zoneId);
+
+    DataStore getImageStore(String storeUuid, long zoneId);
+
+    String getChecksum(Long hostId, String templatePath);
+
 }


Mime
View raw message