cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mc...@apache.org
Subject [4/4] git commit: updated refs/heads/object_store to bb64672
Date Fri, 12 Apr 2013 01:10:14 GMT
Refactor DownloadMonitorImpl code, move some functionalities to
TemplateServiceImpl and VolumeServiceImpl.

Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/bb646727
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bb646727
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bb646727

Branch: refs/heads/object_store
Commit: bb64672715e50f232373f24b2562c434a6e2ab64
Parents: 582a1f0
Author: Min Chen <min.chen@citrix.com>
Authored: Thu Apr 11 18:09:42 2013 -0700
Committer: Min Chen <min.chen@citrix.com>
Committed: Thu Apr 11 18:09:42 2013 -0700

----------------------------------------------------------------------
 .../cloud/agent/api/ModifyStoragePoolAnswer.java   |   10 +-
 .../com/cloud/agent/api/StartupStorageCommand.java |   12 +-
 .../agent/api/storage/ListTemplateAnswer.java      |   10 +-
 .../cloud/agent/api/storage/ListVolumeAnswer.java  |   10 +-
 .../com/cloud/storage/template/TemplateInfo.java   |   81 ---
 .../com/cloud/storage/template/TemplateProp.java   |   81 +++
 api/src/com/cloud/template/TemplateApiService.java |  100 +++
 api/src/com/cloud/template/TemplateService.java    |  100 ---
 api/src/org/apache/cloudstack/api/BaseCmd.java     |    4 +-
 client/tomcatconf/applicationContext.xml.in        |    2 +-
 .../hypervisor/hyperv/resource/HypervResource.java |    4 +-
 .../resource/CifsSecondaryStorageResource.java     |    4 +-
 .../resource/LocalSecondaryStorageResource.java    |    4 +-
 .../resource/NfsSecondaryStorageResource.java      |   14 +-
 .../cloud/storage/template/DownloadManager.java    |    4 +-
 .../storage/template/DownloadManagerImpl.java      |   12 +-
 .../cloud/storage/template/TemplateLocation.java   |    4 +-
 .../engine/subsystem/api/storage/ImageService.java |   29 -
 .../subsystem/api/storage/TemplateService.java     |   35 +
 .../subsystem/api/storage/VolumeService.java       |   18 +-
 .../storage/datastore/db/SnapshotDataStoreDao.java |    2 -
 .../storage/datastore/db/TemplateDataStoreDao.java |    6 +-
 .../storage/datastore/db/TemplateDataStoreVO.java  |    6 +
 .../storage/datastore/db/VolumeDataStoreDao.java   |    7 +-
 .../storage/datastore/db/VolumeDataStoreVO.java    |    4 +-
 .../cloudstack/storage/image/ImageServiceImpl.java |  147 -----
 .../storage/image/TemplateServiceImpl.java         |  481 ++++++++++++++
 .../cloudstack/storage/test/volumeServiceTest.java |    4 +-
 .../storage/image/db/SnapshotDataStoreDaoImpl.java |   17 +-
 .../storage/image/db/TemplateDataStoreDaoImpl.java |   36 +-
 .../storage/image/db/VolumeDataStoreDaoImpl.java   |   46 +-
 .../cloudstack/storage/volume/VolumeObject.java    |    4 +
 .../storage/volume/VolumeServiceImpl.java          |  299 +++++++--
 .../kvm/resource/LibvirtComputingResource.java     |    4 +-
 .../com/cloud/ovm/hypervisor/OvmResourceBase.java  |    4 +-
 .../agent/manager/MockStorageManagerImpl.java      |   14 +-
 .../com/cloud/resource/AgentRoutingResource.java   |    4 +-
 .../hypervisor/vmware/resource/VmwareResource.java |    4 +-
 .../xen/resource/CitrixResourceBase.java           |    4 +-
 plugins/storage/image/default/pom.xml              |   10 +
 .../driver/CloudStackImageStoreDriverImpl.java     |    8 +-
 plugins/storage/image/s3/pom.xml                   |   10 +
 .../datastore/driver/S3ImageStoreDriverImpl.java   |    8 +-
 plugins/storage/image/sample/pom.xml               |   10 +
 plugins/storage/image/swift/pom.xml                |   10 +
 .../driver/SwiftImageStoreDriverImpl.java          |    8 +-
 .../src/com/cloud/storage/StorageManagerImpl.java  |    6 +-
 .../cloud/storage/download/DownloadListener.java   |  327 ++++++----
 .../cloud/storage/download/DownloadMonitor.java    |   17 +-
 .../storage/download/DownloadMonitorImpl.java      |  510 +--------------
 .../resource/DummySecondaryStorageResource.java    |   10 +-
 .../cloud/template/HypervisorTemplateAdapter.java  |    4 +-
 server/src/com/cloud/template/TemplateManager.java |    2 +-
 .../com/cloud/template/TemplateManagerImpl.java    |    8 +-
 54 files changed, 1377 insertions(+), 1202 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java
index df77985..ed7043a 100644
--- a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java
+++ b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java
@@ -18,16 +18,16 @@ package com.cloud.agent.api;
 
 import java.util.Map;
 
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 
 public class ModifyStoragePoolAnswer extends Answer {
     StoragePoolInfo poolInfo;
-    Map<String, TemplateInfo> templateInfo;
+    Map<String, TemplateProp> templateInfo;
 
     protected ModifyStoragePoolAnswer() {
     }
 
-    public ModifyStoragePoolAnswer(ModifyStoragePoolCommand cmd, long capacityBytes, long availableBytes, Map<String, TemplateInfo> tInfo) {
+    public ModifyStoragePoolAnswer(ModifyStoragePoolCommand cmd, long capacityBytes, long availableBytes, Map<String, TemplateProp> tInfo) {
         super(cmd);
         this.result = true;
         this.poolInfo = new StoragePoolInfo(null,
@@ -46,11 +46,11 @@ public class ModifyStoragePoolAnswer extends Answer {
     }
 
 
-    public Map<String, TemplateInfo> getTemplateInfo() {
+    public Map<String, TemplateProp> getTemplateInfo() {
         return templateInfo;
     }
 
-    public void setTemplateInfo(Map<String, TemplateInfo> templateInfo) {
+    public void setTemplateInfo(Map<String, TemplateProp> templateInfo) {
         this.templateInfo = templateInfo;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/agent/api/StartupStorageCommand.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/StartupStorageCommand.java b/api/src/com/cloud/agent/api/StartupStorageCommand.java
index 3c3b058..52ed3ff 100755
--- a/api/src/com/cloud/agent/api/StartupStorageCommand.java
+++ b/api/src/com/cloud/agent/api/StartupStorageCommand.java
@@ -22,13 +22,13 @@ import java.util.Map;
 import com.cloud.host.Host;
 import com.cloud.storage.Storage;
 import com.cloud.storage.Storage.StoragePoolType;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 
 
 public class StartupStorageCommand extends StartupCommand {
 
 	String parent;
-    Map<String, TemplateInfo> templateInfo;
+    Map<String, TemplateProp> templateInfo;
     long totalSize;
     StoragePoolInfo poolInfo;
     Storage.StorageResourceType resourceType;
@@ -40,7 +40,7 @@ public class StartupStorageCommand extends StartupCommand {
         super(Host.Type.Storage);
     }
 
-    public StartupStorageCommand(String parent, StoragePoolType fsType, long totalSize, Map<String, TemplateInfo> info) {
+    public StartupStorageCommand(String parent, StoragePoolType fsType, long totalSize, Map<String, TemplateProp> info) {
         super(Host.Type.Storage);
         this.parent = parent;
         this.totalSize = totalSize;
@@ -50,7 +50,7 @@ public class StartupStorageCommand extends StartupCommand {
     }
 
 
-    public StartupStorageCommand(String parent, StoragePoolType fsType, Map<String, TemplateInfo> templateInfo, StoragePoolInfo poolInfo) {
+    public StartupStorageCommand(String parent, StoragePoolType fsType, Map<String, TemplateProp> templateInfo, StoragePoolInfo poolInfo) {
 		super(Host.Type.Storage);
 		this.parent = parent;
 		this.templateInfo = templateInfo;
@@ -79,11 +79,11 @@ public class StartupStorageCommand extends StartupCommand {
         return totalSize;
     }
 
-	public Map<String, TemplateInfo> getTemplateInfo() {
+	public Map<String, TemplateProp> getTemplateInfo() {
 		return templateInfo;
 	}
 
-	public void setTemplateInfo(Map<String, TemplateInfo> templateInfo) {
+	public void setTemplateInfo(Map<String, TemplateProp> templateInfo) {
 		this.templateInfo = templateInfo;
 	}
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java
index a4e2e25..4155a63 100644
--- a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java
+++ b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java
@@ -19,27 +19,27 @@ package com.cloud.agent.api.storage;
 import java.util.Map;
 
 import com.cloud.agent.api.Answer;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 
 public class ListTemplateAnswer extends Answer  {
     private String secUrl;
-    private Map<String, TemplateInfo> templateInfos;
+    private Map<String, TemplateProp> templateInfos;
 
 	public ListTemplateAnswer() {
 
 	}
 
-	public ListTemplateAnswer(String secUrl, Map<String, TemplateInfo> templateInfos) {
+	public ListTemplateAnswer(String secUrl, Map<String, TemplateProp> templateInfos) {
 	    super(null, true, "success");
 	    this.setSecUrl(secUrl);
 	    this.templateInfos = templateInfos;
 	}
 
-	public Map<String, TemplateInfo> getTemplateInfo() {
+	public Map<String, TemplateProp> getTemplateInfo() {
 	    return templateInfos;
 	}
 
-	public void setTemplateInfo(Map<String, TemplateInfo> templateInfos) {
+	public void setTemplateInfo(Map<String, TemplateProp> templateInfos) {
 	    this.templateInfos = templateInfos;
 	}
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java
index 6bbb2e8..31ea09b 100755
--- a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java
+++ b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java
@@ -19,27 +19,27 @@ package com.cloud.agent.api.storage;
 import java.util.Map;
 
 import com.cloud.agent.api.Answer;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 
 public class ListVolumeAnswer extends Answer {
 	private String secUrl;
-    private Map<Long, TemplateInfo> templateInfos;
+    private Map<Long, TemplateProp> templateInfos;
 
 	public ListVolumeAnswer() {
 
 	}
 
-	public ListVolumeAnswer(String secUrl, Map<Long, TemplateInfo> templateInfos) {
+	public ListVolumeAnswer(String secUrl, Map<Long, TemplateProp> templateInfos) {
 	    super(null, true, "success");
 	    this.setSecUrl(secUrl);
 	    this.templateInfos = templateInfos;
 	}
 
-	public Map<Long, TemplateInfo> getTemplateInfo() {
+	public Map<Long, TemplateProp> getTemplateInfo() {
 	    return templateInfos;
 	}
 
-	public void setTemplateInfo(Map<Long, TemplateInfo> templateInfos) {
+	public void setTemplateInfo(Map<Long, TemplateProp> templateInfos) {
 	    this.templateInfos = templateInfos;
 	}
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/storage/template/TemplateInfo.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/storage/template/TemplateInfo.java b/api/src/com/cloud/storage/template/TemplateInfo.java
deleted file mode 100644
index 6559d73..0000000
--- a/api/src/com/cloud/storage/template/TemplateInfo.java
+++ /dev/null
@@ -1,81 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.storage.template;
-
-public class TemplateInfo {
-    String templateName;
-    String installPath;
-    long size;
-    long physicalSize;
-    long id;
-    boolean isPublic;
-    boolean isCorrupted;
-
-    protected TemplateInfo() {
-
-    }
-
-    public TemplateInfo(String templateName, String installPath, long size, long physicalSize, boolean isPublic, boolean isCorrupted) {
-        this.templateName = templateName;
-        this.installPath = installPath;
-        this.size = size;
-        this.physicalSize = physicalSize;
-        this.isPublic = isPublic;
-        this.isCorrupted = isCorrupted;
-    }
-
-    public TemplateInfo(String templateName, String installPath, boolean isPublic, boolean isCorrupted) {
-        this(templateName, installPath, 0, 0, isPublic, isCorrupted);
-    }
-
-    public long getId() {
-        return id;
-    }
-
-    public String getTemplateName() {
-        return templateName;
-    }
-
-    public String getInstallPath() {
-        return installPath;
-    }
-
-    public boolean isPublic() {
-        return isPublic;
-    }
-
-    public boolean isCorrupted() {
-        return isCorrupted;
-    }
-
-    public void setInstallPath(String installPath) {
-        this.installPath = installPath;
-    }
-
-    public long getSize() {
-        return size;
-    }
-
-    public long getPhysicalSize() {
-        return physicalSize;
-    }
-
-    public void setSize(long size) {
-        this.size = size;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/storage/template/TemplateProp.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/storage/template/TemplateProp.java b/api/src/com/cloud/storage/template/TemplateProp.java
new file mode 100644
index 0000000..0a2efc1
--- /dev/null
+++ b/api/src/com/cloud/storage/template/TemplateProp.java
@@ -0,0 +1,81 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.storage.template;
+
+public class TemplateProp {
+    String templateName;
+    String installPath;
+    long size;
+    long physicalSize;
+    long id;
+    boolean isPublic;
+    boolean isCorrupted;
+
+    protected TemplateProp() {
+
+    }
+
+    public TemplateProp(String templateName, String installPath, long size, long physicalSize, boolean isPublic, boolean isCorrupted) {
+        this.templateName = templateName;
+        this.installPath = installPath;
+        this.size = size;
+        this.physicalSize = physicalSize;
+        this.isPublic = isPublic;
+        this.isCorrupted = isCorrupted;
+    }
+
+    public TemplateProp(String templateName, String installPath, boolean isPublic, boolean isCorrupted) {
+        this(templateName, installPath, 0, 0, isPublic, isCorrupted);
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public String getTemplateName() {
+        return templateName;
+    }
+
+    public String getInstallPath() {
+        return installPath;
+    }
+
+    public boolean isPublic() {
+        return isPublic;
+    }
+
+    public boolean isCorrupted() {
+        return isCorrupted;
+    }
+
+    public void setInstallPath(String installPath) {
+        this.installPath = installPath;
+    }
+
+    public long getSize() {
+        return size;
+    }
+
+    public long getPhysicalSize() {
+        return physicalSize;
+    }
+
+    public void setSize(long size) {
+        this.size = size;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/template/TemplateApiService.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/template/TemplateApiService.java b/api/src/com/cloud/template/TemplateApiService.java
new file mode 100755
index 0000000..50373fe
--- /dev/null
+++ b/api/src/com/cloud/template/TemplateApiService.java
@@ -0,0 +1,100 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.template;
+
+import java.net.URISyntaxException;
+import java.util.List;
+
+import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd;
+import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd;
+import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
+import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd;
+import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
+import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd;
+import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd;
+import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
+import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
+import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
+
+import com.cloud.exception.InternalErrorException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.StorageUnavailableException;
+import com.cloud.user.Account;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public interface TemplateApiService {
+
+    VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException;
+
+    VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws IllegalArgumentException, ResourceAllocationException;
+
+    VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException;
+
+    VirtualMachineTemplate prepareTemplate(long templateId, long zoneId);
+
+    boolean detachIso(long vmId);
+
+    boolean attachIso(long isoId, long vmId);
+
+    /**
+     * Deletes a template
+     *
+     * @param cmd
+     *            - the command specifying templateId
+     */
+    boolean deleteTemplate(DeleteTemplateCmd cmd);
+
+    /**
+     * Deletes a template
+     *
+     * @param cmd
+     *            - the command specifying isoId
+     * @return true if deletion is successful, false otherwise
+     */
+    boolean deleteIso(DeleteIsoCmd cmd);
+
+    /**
+     * Extracts an ISO
+     *
+     * @param cmd
+     *            - the command specifying the mode and id of the ISO
+     * @return extractId.
+     */
+    Long extract(ExtractIsoCmd cmd) throws InternalErrorException;
+
+    /**
+     * Extracts a Template
+     *
+     * @param cmd
+     *            - the command specifying the mode and id of the template
+     * @return extractId
+     */
+    Long extract(ExtractTemplateCmd cmd) throws InternalErrorException;
+
+    VirtualMachineTemplate getTemplate(long templateId);
+
+    List<String> listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd);
+
+    boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd);
+    
+    VirtualMachineTemplate createPrivateTemplateRecord(CreateTemplateCmd cmd,
+            Account templateOwner) throws ResourceAllocationException;
+
+    VirtualMachineTemplate createPrivateTemplate(CreateTemplateCmd command)
+            throws CloudRuntimeException;
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/com/cloud/template/TemplateService.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/template/TemplateService.java b/api/src/com/cloud/template/TemplateService.java
deleted file mode 100755
index 7e831fb..0000000
--- a/api/src/com/cloud/template/TemplateService.java
+++ /dev/null
@@ -1,100 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.template;
-
-import java.net.URISyntaxException;
-import java.util.List;
-
-import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd;
-import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd;
-import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
-import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd;
-import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
-import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd;
-import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd;
-import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
-import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
-import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
-
-import com.cloud.exception.InternalErrorException;
-import com.cloud.exception.ResourceAllocationException;
-import com.cloud.exception.StorageUnavailableException;
-import com.cloud.user.Account;
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public interface TemplateService {
-
-    VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException;
-
-    VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws IllegalArgumentException, ResourceAllocationException;
-
-    VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException;
-
-    VirtualMachineTemplate prepareTemplate(long templateId, long zoneId);
-
-    boolean detachIso(long vmId);
-
-    boolean attachIso(long isoId, long vmId);
-
-    /**
-     * Deletes a template
-     *
-     * @param cmd
-     *            - the command specifying templateId
-     */
-    boolean deleteTemplate(DeleteTemplateCmd cmd);
-
-    /**
-     * Deletes a template
-     *
-     * @param cmd
-     *            - the command specifying isoId
-     * @return true if deletion is successful, false otherwise
-     */
-    boolean deleteIso(DeleteIsoCmd cmd);
-
-    /**
-     * Extracts an ISO
-     *
-     * @param cmd
-     *            - the command specifying the mode and id of the ISO
-     * @return extractId.
-     */
-    Long extract(ExtractIsoCmd cmd) throws InternalErrorException;
-
-    /**
-     * Extracts a Template
-     *
-     * @param cmd
-     *            - the command specifying the mode and id of the template
-     * @return extractId
-     */
-    Long extract(ExtractTemplateCmd cmd) throws InternalErrorException;
-
-    VirtualMachineTemplate getTemplate(long templateId);
-
-    List<String> listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd);
-
-    boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd);
-    
-    VirtualMachineTemplate createPrivateTemplateRecord(CreateTemplateCmd cmd,
-            Account templateOwner) throws ResourceAllocationException;
-
-    VirtualMachineTemplate createPrivateTemplate(CreateTemplateCmd command)
-            throws CloudRuntimeException;
-
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/api/src/org/apache/cloudstack/api/BaseCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java
index 78a2af3..b845053 100644
--- a/api/src/org/apache/cloudstack/api/BaseCmd.java
+++ b/api/src/org/apache/cloudstack/api/BaseCmd.java
@@ -65,7 +65,7 @@ import com.cloud.storage.DataStoreProviderApiService;
 import com.cloud.storage.StorageService;
 import com.cloud.storage.VolumeApiService;
 import com.cloud.storage.snapshot.SnapshotService;
-import com.cloud.template.TemplateService;
+import com.cloud.template.TemplateApiService;
 import com.cloud.user.Account;
 import com.cloud.user.AccountService;
 import com.cloud.user.DomainService;
@@ -106,7 +106,7 @@ public abstract class BaseCmd {
     @Inject public VolumeApiService _volumeService;
     @Inject public ResourceService _resourceService;
     @Inject public NetworkService _networkService;
-    @Inject public TemplateService _templateService;
+    @Inject public TemplateApiService _templateService;
     @Inject public SecurityGroupService _securityGroupService;
     @Inject public SnapshotService _snapshotService;
     @Inject public ConsoleProxyService _consoleProxyService;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/client/tomcatconf/applicationContext.xml.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/applicationContext.xml.in b/client/tomcatconf/applicationContext.xml.in
index 206afd3..7ad3bb5 100644
--- a/client/tomcatconf/applicationContext.xml.in
+++ b/client/tomcatconf/applicationContext.xml.in
@@ -744,7 +744,7 @@
   <bean id="imageDataManagerImpl" class="org.apache.cloudstack.storage.image.manager.ImageDataManagerImpl" />
   <bean id="imageStoreHelper" class="org.apache.cloudstack.storage.image.datastore.ImageStoreHelper" />
   <bean id="imageFormatHelper" class="org.apache.cloudstack.storage.image.format.ImageFormatHelper" />
-  <bean id="imageServiceImpl" class="org.apache.cloudstack.storage.image.ImageServiceImpl" />
+  <bean id="templateServiceImpl" class="org.apache.cloudstack.storage.image.TemplateServiceImpl" />
   <bean id="iso" class="org.apache.cloudstack.engine.subsystem.api.storage.type.Iso" />
   <bean id="networkFileSystem" class="org.apache.cloudstack.storage.datastore.type.NetworkFileSystem" />
   <bean id="networkRestService" class="org.apache.cloudstack.engine.rest.service.api.NetworkRestService" />

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java b/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java
index 0f9b3dd..725f0cc 100755
--- a/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java
+++ b/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java
@@ -105,7 +105,7 @@ import com.cloud.resource.ServerResource;
 import com.cloud.resource.ServerResourceBase;
 import com.cloud.serializer.GsonHelper;
 import com.cloud.storage.Volume;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 import com.cloud.utils.Pair;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.DiskProfile;
@@ -765,7 +765,7 @@ public class HypervResource extends ServerResourceBase implements ServerResource
         try {
             StorageFilerTO pool = cmd.getPool();
             s_logger.info("Primary storage pool  details: " + pool.getHost() + " " + pool.getPath());
-            Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
+            Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>();
             // FIXME: get the actual storage capacity and storage stats of CSV volume
             // by running powershell cmdlet. This hardcoding just for prototype.
             ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/resource/CifsSecondaryStorageResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/resource/CifsSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/CifsSecondaryStorageResource.java
index 285005a..435e0f7 100755
--- a/core/src/com/cloud/storage/resource/CifsSecondaryStorageResource.java
+++ b/core/src/com/cloud/storage/resource/CifsSecondaryStorageResource.java
@@ -60,7 +60,7 @@ import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageLayer;
 import com.cloud.storage.template.DownloadManager;
 import com.cloud.storage.template.DownloadManagerImpl;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 import com.cloud.storage.template.UploadManager;
 import com.cloud.storage.template.UploadManagerImpl;
 import com.cloud.utils.NumbersUtil;
@@ -650,7 +650,7 @@ public class CifsSecondaryStorageResource extends ServerResourceBase implements
             return null;
         }*/
 
-        final StartupStorageCommand cmd = new StartupStorageCommand(_parent, StoragePoolType.NetworkFilesystem, getTotalSize(), new HashMap<String, TemplateInfo>());
+        final StartupStorageCommand cmd = new StartupStorageCommand(_parent, StoragePoolType.NetworkFilesystem, getTotalSize(), new HashMap<String, TemplateProp>());
 
         cmd.setResourceType(Storage.StorageResourceType.SECONDARY_STORAGE);
         cmd.setIqn(null);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/resource/LocalSecondaryStorageResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/resource/LocalSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/LocalSecondaryStorageResource.java
index c638c5d..89d0fe1 100644
--- a/core/src/com/cloud/storage/resource/LocalSecondaryStorageResource.java
+++ b/core/src/com/cloud/storage/resource/LocalSecondaryStorageResource.java
@@ -48,7 +48,7 @@ import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageLayer;
 import com.cloud.storage.template.DownloadManager;
 import com.cloud.storage.template.DownloadManagerImpl;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 import com.cloud.utils.component.ComponentContext;
 
 public class LocalSecondaryStorageResource extends ServerResourceBase implements SecondaryStorageResource {
@@ -109,7 +109,7 @@ public class LocalSecondaryStorageResource extends ServerResourceBase implements
 
     private Answer execute(ListTemplateCommand cmd) {
         String root = getRootDir();
-        Map<String, TemplateInfo> templateInfos = _dlMgr.gatherTemplateInfo(root);
+        Map<String, TemplateProp> templateInfos = _dlMgr.gatherTemplateInfo(root);
         return new ListTemplateAnswer(cmd.getSecUrl(), templateInfos);
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java
index e65cbe1..a8788c6 100755
--- a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java
+++ b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java
@@ -100,7 +100,7 @@ import com.cloud.storage.StorageLayer;
 import com.cloud.storage.template.DownloadManager;
 import com.cloud.storage.template.DownloadManagerImpl;
 import com.cloud.storage.template.DownloadManagerImpl.ZfsPathParser;
-import com.cloud.storage.template.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
 import com.cloud.storage.template.TemplateLocation;
 import com.cloud.storage.template.UploadManager;
 import com.cloud.storage.template.UploadManagerImpl;
@@ -1073,12 +1073,12 @@ SecondaryStorageResource {
         }
     }
 
-    Map<String, TemplateInfo> swiftListTemplate(SwiftTO swift) {
+    Map<String, TemplateProp> swiftListTemplate(SwiftTO swift) {
         String[] containers = swiftList(swift, "", "");
         if (containers == null) {
             return null;
         }
-        Map<String, TemplateInfo> tmpltInfos = new HashMap<String, TemplateInfo>();
+        Map<String, TemplateProp> tmpltInfos = new HashMap<String, TemplateProp>();
         for( String container : containers) {
             if ( container.startsWith("T-")) {
                 String ldir = _tmpltDir + "/" + UUID.randomUUID().toString();
@@ -1095,7 +1095,7 @@ SecondaryStorageResource {
                     s_logger.warn("Unable to load template location " + ldir + " due to " + e.toString(), e);
                     continue;
                 }
-                TemplateInfo tInfo = loc.getTemplateInfo();
+                TemplateProp tInfo = loc.getTemplateInfo();
                 tInfo.setInstallPath(container);
                 tmpltInfos.put(tInfo.getTemplateName(), tInfo);
                 loc.purge();
@@ -1111,11 +1111,11 @@ SecondaryStorageResource {
             return new Answer(cmd, true, null);
         }
         if (cmd.getSwift() != null) {
-            Map<String, TemplateInfo> templateInfos = swiftListTemplate(cmd.getSwift());
+            Map<String, TemplateProp> templateInfos = swiftListTemplate(cmd.getSwift());
             return new ListTemplateAnswer(cmd.getSwift().toString(), templateInfos);
         } else {
             String root = getRootDir(cmd.getSecUrl());
-            Map<String, TemplateInfo> templateInfos = _dlMgr.gatherTemplateInfo(root);
+            Map<String, TemplateProp> templateInfos = _dlMgr.gatherTemplateInfo(root);
             return new ListTemplateAnswer(cmd.getSecUrl(), templateInfos);
         }
     }
@@ -1126,7 +1126,7 @@ SecondaryStorageResource {
         }
 
         String root = getRootDir(cmd.getSecUrl());
-        Map<Long, TemplateInfo> templateInfos = _dlMgr.gatherVolumeInfo(root);
+        Map<Long, TemplateProp> templateInfos = _dlMgr.gatherVolumeInfo(root);
         return new ListVolumeAnswer(cmd.getSecUrl(), templateInfos);
 
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/template/DownloadManager.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/template/DownloadManager.java b/core/src/com/cloud/storage/template/DownloadManager.java
index f4f8a0f..82f4153 100644
--- a/core/src/com/cloud/storage/template/DownloadManager.java
+++ b/core/src/com/cloud/storage/template/DownloadManager.java
@@ -91,13 +91,13 @@ public interface DownloadManager extends Manager {
 	/**
 	 * @return list of template info for installed templates
 	 */
-	public Map<String, TemplateInfo> gatherTemplateInfo(String templateDir);
+	public Map<String, TemplateProp> gatherTemplateInfo(String templateDir);
 	
 	/**
 	/**
 	 * @return list of volume info for installed volumes
 	 */
-	public Map<Long, TemplateInfo> gatherVolumeInfo(String volumeDir);
+	public Map<Long, TemplateProp> gatherVolumeInfo(String volumeDir);
 
 
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/template/DownloadManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/template/DownloadManagerImpl.java b/core/src/com/cloud/storage/template/DownloadManagerImpl.java
index 22e78a0..db264c1 100755
--- a/core/src/com/cloud/storage/template/DownloadManagerImpl.java
+++ b/core/src/com/cloud/storage/template/DownloadManagerImpl.java
@@ -717,8 +717,8 @@ public class DownloadManagerImpl extends ManagerBase implements DownloadManager
     }
 
     @Override
-    public Map<String, TemplateInfo> gatherTemplateInfo(String rootDir) {
-        Map<String, TemplateInfo> result = new HashMap<String, TemplateInfo>();
+    public Map<String, TemplateProp> gatherTemplateInfo(String rootDir) {
+        Map<String, TemplateProp> result = new HashMap<String, TemplateProp>();
         String templateDir = rootDir + File.separator + _templateDir;
 
         if (! _storage.exists(templateDir)) {
@@ -741,7 +741,7 @@ public class DownloadManagerImpl extends ManagerBase implements DownloadManager
                 continue;
             }
 
-            TemplateInfo tInfo = loc.getTemplateInfo();
+            TemplateProp tInfo = loc.getTemplateInfo();
 
             if ((tInfo.size == tInfo.physicalSize) && (tInfo.installPath.endsWith(ImageFormat.OVA.getFileExtension()))) {
                 try {
@@ -774,8 +774,8 @@ public class DownloadManagerImpl extends ManagerBase implements DownloadManager
     }
 
     @Override
-    public Map<Long, TemplateInfo> gatherVolumeInfo(String rootDir) {	
-        Map<Long, TemplateInfo> result = new HashMap<Long, TemplateInfo>();
+    public Map<Long, TemplateProp> gatherVolumeInfo(String rootDir) {	
+        Map<Long, TemplateProp> result = new HashMap<Long, TemplateProp>();
         String volumeDir = rootDir + File.separator + _volumeDir;
 
         if (! _storage.exists(volumeDir)) {
@@ -798,7 +798,7 @@ public class DownloadManagerImpl extends ManagerBase implements DownloadManager
                 continue;
             }
 
-            TemplateInfo vInfo = loc.getTemplateInfo();
+            TemplateProp vInfo = loc.getTemplateInfo();
 
             if ((vInfo.size == vInfo.physicalSize) && (vInfo.installPath.endsWith(ImageFormat.OVA.getFileExtension()))) {
                 try {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/core/src/com/cloud/storage/template/TemplateLocation.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/storage/template/TemplateLocation.java b/core/src/com/cloud/storage/template/TemplateLocation.java
index 58d023a..515b1f2 100644
--- a/core/src/com/cloud/storage/template/TemplateLocation.java
+++ b/core/src/com/cloud/storage/template/TemplateLocation.java
@@ -156,8 +156,8 @@ public class TemplateLocation {
         return true;
     }
     
-    public TemplateInfo getTemplateInfo() {
-        TemplateInfo tmplInfo = new TemplateInfo();       
+    public TemplateProp getTemplateInfo() {
+        TemplateProp tmplInfo = new TemplateProp();       
         tmplInfo.id = Long.parseLong(_props.getProperty("id"));
         tmplInfo.installPath = _templatePath + File.separator + _props.getProperty("filename");
         if (_resourceType == ResourceType.VOLUME){

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageService.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageService.java
deleted file mode 100644
index 119f3b1..0000000
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/ImageService.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cloudstack.engine.subsystem.api.storage;
-
-import org.apache.cloudstack.framework.async.AsyncCallFuture;
-
-public interface ImageService {
-    AsyncCallFuture<CommandResult> createTemplateAsync(TemplateInfo template, DataStore store);
-    AsyncCallFuture<CommandResult> createTemplateFromSnapshotAsync(SnapshotInfo snapshot, TemplateInfo template, DataStore store);
-    AsyncCallFuture<CommandResult> createTemplateFromVolumeAsync(VolumeInfo volume, TemplateInfo template, DataStore store);
-    AsyncCallFuture<CommandResult> deleteTemplateAsync(TemplateInfo template);
-    
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java
new file mode 100644
index 0000000..6bb58e0
--- /dev/null
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/TemplateService.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cloudstack.engine.subsystem.api.storage;
+
+import org.apache.cloudstack.framework.async.AsyncCallFuture;
+
+
+
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+
+public interface TemplateService {
+    AsyncCallFuture<CommandResult> createTemplateAsync(TemplateInfo template, DataStore store);
+    AsyncCallFuture<CommandResult> createTemplateFromSnapshotAsync(SnapshotInfo snapshot, TemplateInfo template, DataStore store);
+    AsyncCallFuture<CommandResult> createTemplateFromVolumeAsync(VolumeInfo volume, TemplateInfo template, DataStore store);
+    AsyncCallFuture<CommandResult> deleteTemplateAsync(TemplateInfo template);
+
+    void handleSysTemplateDownload(HypervisorType hostHyper, Long dcId);
+    void handleTemplateSync(DataStore store);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
index 102c471..7175524 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/VolumeService.java
@@ -25,13 +25,13 @@ import com.cloud.exception.ConcurrentOperationException;
 
 
 public interface VolumeService {
-    
+
     public class VolumeApiResult extends CommandResult {
         private final VolumeInfo volume;
         public VolumeApiResult(VolumeInfo volume) {
             this.volume = volume;
         }
-        
+
         public VolumeInfo getVolume() {
             return this.volume;
         }
@@ -39,16 +39,16 @@ public interface VolumeService {
 
     /**
      * Creates the volume based on the given criteria
-     * 
+     *
      * @param cmd
-     * 
+     *
      * @return the volume object
      */
     AsyncCallFuture<VolumeApiResult> createVolumeAsync(VolumeInfo volume, DataStore store);
 
     /**
      * Delete volume
-     * 
+     *
      * @param volumeId
      * @return
      * @throws ConcurrentOperationException
@@ -56,12 +56,12 @@ public interface VolumeService {
     AsyncCallFuture<VolumeApiResult> expungeVolumeAsync(VolumeInfo volume);
 
     /**
-     * 
+     *
      */
     boolean cloneVolume(long volumeId, long baseVolId);
 
     /**
-     * 
+     *
      */
     AsyncCallFuture<VolumeApiResult> createVolumeFromSnapshot(VolumeInfo volume, DataStore store,  SnapshotInfo snapshot);
 
@@ -74,7 +74,9 @@ public interface VolumeService {
     boolean destroyVolume(long volumeId) throws ConcurrentOperationException;
 
     AsyncCallFuture<VolumeApiResult> registerVolume(VolumeInfo volume, DataStore store);
-    
+
     AsyncCallFuture<VolumeApiResult> resize(VolumeInfo volume);
 
+    void handleVolumeSync(DataStore store);
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java
index 91ffdaa..271ff41 100644
--- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java
+++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/SnapshotDataStoreDao.java
@@ -30,7 +30,5 @@ public interface SnapshotDataStoreDao extends GenericDao<SnapshotDataStoreVO, Lo
 
     public List<SnapshotDataStoreVO> listByStoreId(long id);
 
-    public List<SnapshotDataStoreVO> listLiveByStoreId(long id);
-
     public void deletePrimaryRecordsForStore(long id);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java
index 29c7859..f1fcdcc 100644
--- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java
+++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreDao.java
@@ -23,18 +23,20 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
 import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
 
 
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
 import com.cloud.utils.db.GenericDao;
 import com.cloud.utils.fsm.StateDao;
 
 public interface TemplateDataStoreDao extends GenericDao<TemplateDataStoreVO, Long>, StateDao<ObjectInDataStoreStateMachine.State, ObjectInDataStoreStateMachine.Event, DataObjectInStore>  {
 
-    public List<TemplateDataStoreVO> listByStoreId(long id);
 
-    public List<TemplateDataStoreVO> listLiveByStoreId(long id);
+    public List<TemplateDataStoreVO> listByStoreId(long id);
 
     public void deletePrimaryRecordsForStore(long id);
 
     List<TemplateDataStoreVO> listByTemplateStoreStatus(long templateId, long storeId, State... states);
 
+    List<TemplateDataStoreVO> listByTemplateStoreDownloadStatus(long templateId, long storeId, Status... status);
+
     TemplateDataStoreVO findByStoreTemplate(long storeId, long templateId);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java
index 312fd11..d7c8443 100755
--- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java
+++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/TemplateDataStoreVO.java
@@ -291,6 +291,12 @@ public class TemplateDataStoreVO implements StateObject<ObjectInDataStoreStateMa
         return this.state;
     }
 
+
+    public void setState(ObjectInDataStoreStateMachine.State state) {
+        this.state = state;
+    }
+
+
     public long getUpdatedCount() {
         return this.updatedCount;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreDao.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreDao.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreDao.java
index 58ffde1..fb5bcc5 100644
--- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreDao.java
+++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreDao.java
@@ -22,6 +22,7 @@ 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.utils.db.GenericDao;
 import com.cloud.utils.fsm.StateDao;
 
@@ -29,7 +30,9 @@ public interface VolumeDataStoreDao extends GenericDao<VolumeDataStoreVO, Long>,
 
     public List<VolumeDataStoreVO> listByStoreId(long id);
 
-    public List<VolumeDataStoreVO> listLiveByStoreId(long id);
-
     public void deletePrimaryRecordsForStore(long id);
+
+    public VolumeDataStoreVO findByVolumeId(long volumeId);
+
+    public VolumeDataStoreVO findByStoreVolume(long storeId, long volumeId);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java
index 185b12b..a7134ea 100755
--- a/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java
+++ b/engine/api/src/org/apache/cloudstack/storage/datastore/db/VolumeDataStoreVO.java
@@ -203,14 +203,14 @@ public class VolumeDataStoreVO implements StateObject<ObjectInDataStoreStateMach
 		this.state = ObjectInDataStoreStateMachine.State.Allocated;
 	}
 
-	public VolumeDataStoreVO(long hostId, long volumeId, long zoneId, Date lastUpdated,
+	public VolumeDataStoreVO(long hostId, long volumeId, Date lastUpdated,
 			int downloadPercent, Status downloadState,
 			String localDownloadPath, String errorString, String jobId,
 			String installPath, String downloadUrl, String checksum, ImageFormat format) {
 		//super();
 		this.dataStoreId = hostId;
 		this.volumeId = volumeId;
-		this.zoneId = zoneId;
+		//this.zoneId = zoneId;
 		this.lastUpdated = lastUpdated;
 		this.downloadPercent = downloadPercent;
 		this.downloadState = downloadState;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/storage/image/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java
----------------------------------------------------------------------
diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java
deleted file mode 100644
index f393fc4..0000000
--- a/engine/storage/image/src/org/apache/cloudstack/storage/image/ImageServiceImpl.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cloudstack.storage.image;
-
-import javax.inject.Inject;
-
-import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
-import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.ImageService;
-import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
-import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
-import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent;
-import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
-import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
-import org.apache.cloudstack.framework.async.AsyncCallFuture;
-import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
-import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
-import org.apache.cloudstack.framework.async.AsyncRpcConext;
-import org.apache.cloudstack.storage.datastore.DataObjectManager;
-import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
-import org.apache.cloudstack.storage.image.store.TemplateObject;
-import org.apache.log4j.Logger;
-import org.springframework.stereotype.Component;
-
-import com.cloud.utils.fsm.NoTransitionException;
-
-@Component
-public class ImageServiceImpl implements ImageService {
-    private static final Logger s_logger = Logger.getLogger(ImageServiceImpl.class);
-    @Inject
-    ObjectInDataStoreManager objectInDataStoreMgr;
-    @Inject
-    DataObjectManager dataObjectMgr;
-
-    class CreateTemplateContext<T> extends AsyncRpcConext<T> {
-        final TemplateInfo srcTemplate;
-        final DataStore store;
-        final AsyncCallFuture<CommandResult> future;
-        final DataObject templateOnStore;
-
-        public CreateTemplateContext(AsyncCompletionCallback<T> callback, TemplateInfo srcTemplate,
-                AsyncCallFuture<CommandResult> future,
-                DataStore store,
-                DataObject templateOnStore
-             ) {
-            super(callback);
-            this.srcTemplate = srcTemplate;
-            this.future = future;
-            this.store = store;
-            this.templateOnStore = templateOnStore;
-        }
-    }
-
-    @Override
-    public AsyncCallFuture<CommandResult> createTemplateAsync(
-            TemplateInfo template, DataStore store) {
-        TemplateObject to = (TemplateObject) template;
-        AsyncCallFuture<CommandResult> future = new AsyncCallFuture<CommandResult>();
-        // persist template_store_ref entry
-        DataObject templateOnStore = store.create(template);
-        // update template_store_ref state
-        templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.CreateOnlyRequested);
-
-        CreateTemplateContext<CommandResult> context = new CreateTemplateContext<CommandResult>(null,
-                template,
-                future,
-                store,
-                templateOnStore
-               );
-        AsyncCallbackDispatcher<ImageServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
-        caller.setCallback(caller.getTarget().createTemplateCallback(null, null)).setContext(context);
-        store.getDriver().createAsync(templateOnStore, caller);
-        return future;
-    }
-
-    protected Void createTemplateCallback(AsyncCallbackDispatcher<ImageServiceImpl, CreateCmdResult> callback,
-            CreateTemplateContext<CreateCmdResult> context) {
-        TemplateObject template = (TemplateObject)context.srcTemplate;
-        AsyncCallFuture<CommandResult> future = context.future;
-        CommandResult result = new CommandResult();
-        DataObject templateOnStore = context.templateOnStore;
-        CreateCmdResult callbackResult = callback.getResult();
-        if (callbackResult.isFailed()) {
-            try {
-                templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed);
-                template.stateTransit(TemplateEvent.OperationFailed);
-            } catch (NoTransitionException e) {
-               s_logger.debug("Failed to update template state", e);
-            }
-            result.setResult(callbackResult.getResult());
-            future.complete(result);
-            return null;
-        }
-
-        try {
-            templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed);
-            template.stateTransit(TemplateEvent.OperationSucceeded);
-        } catch (NoTransitionException e) {
-            s_logger.debug("Failed to transit state", e);
-            result.setResult(e.toString());
-            future.complete(result);
-            return null;
-        }
-
-        future.complete(result);
-        return null;
-    }
-
-    @Override
-    public AsyncCallFuture<CommandResult> deleteTemplateAsync(
-            TemplateInfo template) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public AsyncCallFuture<CommandResult> createTemplateFromSnapshotAsync(
-            SnapshotInfo snapshot, TemplateInfo template, DataStore store) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public AsyncCallFuture<CommandResult> createTemplateFromVolumeAsync(
-            VolumeInfo volume, TemplateInfo template, DataStore store) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java
----------------------------------------------------------------------
diff --git a/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java
new file mode 100644
index 0000000..3dcb86b
--- /dev/null
+++ b/engine/storage/image/src/org/apache/cloudstack/storage/image/TemplateServiceImpl.java
@@ -0,0 +1,481 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cloudstack.storage.image;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.inject.Inject;
+
+import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
+import org.apache.cloudstack.engine.subsystem.api.storage.DataObject;
+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.TemplateService;
+import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateEvent;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
+import com.cloud.storage.template.TemplateProp;
+import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
+import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
+import org.apache.cloudstack.framework.async.AsyncCallFuture;
+import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
+import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
+import org.apache.cloudstack.framework.async.AsyncRpcConext;
+import org.apache.cloudstack.storage.datastore.DataObjectManager;
+import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
+import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
+import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
+import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
+import org.apache.cloudstack.storage.image.store.TemplateObject;
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.agent.AgentManager;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.DeleteTemplateCommand;
+import com.cloud.agent.api.storage.ListTemplateAnswer;
+import com.cloud.agent.api.storage.ListTemplateCommand;
+import com.cloud.alert.AlertManager;
+import com.cloud.dc.DataCenterVO;
+import com.cloud.dc.dao.ClusterDao;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.exception.AgentUnavailableException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.host.HostVO;
+import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.storage.VMTemplateVO;
+import com.cloud.storage.VMTemplateZoneVO;
+import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
+import com.cloud.storage.dao.VMTemplateDao;
+import com.cloud.storage.dao.VMTemplateZoneDao;
+import com.cloud.storage.dao.VolumeDao;
+import com.cloud.storage.download.DownloadMonitor;
+import com.cloud.storage.secondary.SecondaryStorageVmManager;
+import com.cloud.user.AccountManager;
+import com.cloud.user.ResourceLimitService;
+import com.cloud.utils.UriUtils;
+import com.cloud.utils.fsm.NoTransitionException;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.dao.UserVmDao;
+
+@Component
+public class TemplateServiceImpl implements TemplateService {
+    private static final Logger s_logger = Logger.getLogger(TemplateServiceImpl.class);
+    @Inject
+    ObjectInDataStoreManager _objectInDataStoreMgr;
+    @Inject
+    DataObjectManager _dataObjectMgr;
+    @Inject
+    DataStoreManager _storeMgr;
+    @Inject
+    ResourceLimitService _resourceLimitMgr;
+    @Inject
+    AccountManager _accountMgr;
+    @Inject
+    AlertManager _alertMgr;
+    @Inject
+    VMTemplateDao _templateDao;
+    @Inject
+    TemplateDataStoreDao _vmTemplateStoreDao;
+    @Inject
+    VolumeDataStoreDao _volumeStoreDao;
+    @Inject
+    DownloadMonitor _dlMonitor;
+    @Inject
+    AgentManager _agentMgr;
+    @Inject
+    SecondaryStorageVmManager _ssvmMgr;
+    @Inject
+    DataCenterDao _dcDao = null;
+    @Inject
+    VMTemplateZoneDao _vmTemplateZoneDao;
+    @Inject
+    ClusterDao _clusterDao;
+    @Inject
+    UserVmDao _userVmDao;
+    @Inject
+    VolumeDao _volumeDao;
+
+
+    class CreateTemplateContext<T> extends AsyncRpcConext<T> {
+        final TemplateInfo srcTemplate;
+        final DataStore store;
+        final AsyncCallFuture<CommandResult> future;
+        final DataObject templateOnStore;
+
+        public CreateTemplateContext(AsyncCompletionCallback<T> callback, TemplateInfo srcTemplate,
+                AsyncCallFuture<CommandResult> future,
+                DataStore store,
+                DataObject templateOnStore
+             ) {
+            super(callback);
+            this.srcTemplate = srcTemplate;
+            this.future = future;
+            this.store = store;
+            this.templateOnStore = templateOnStore;
+        }
+    }
+
+    @Override
+    public AsyncCallFuture<CommandResult> createTemplateAsync(
+            TemplateInfo template, DataStore store) {
+        TemplateObject to = (TemplateObject) template;
+        AsyncCallFuture<CommandResult> future = new AsyncCallFuture<CommandResult>();
+        // persist template_store_ref entry
+        DataObject templateOnStore = store.create(template);
+        // update template_store_ref state
+        templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.CreateOnlyRequested);
+
+        CreateTemplateContext<CommandResult> context = new CreateTemplateContext<CommandResult>(null,
+                template,
+                future,
+                store,
+                templateOnStore
+               );
+        AsyncCallbackDispatcher<TemplateServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
+        caller.setCallback(caller.getTarget().createTemplateCallback(null, null)).setContext(context);
+        store.getDriver().createAsync(templateOnStore, caller);
+        return future;
+    }
+
+
+    @Override
+    public void handleSysTemplateDownload(HypervisorType hostHyper, Long dcId) {
+        Set<VMTemplateVO> toBeDownloaded = new HashSet<VMTemplateVO>();
+        List<DataStore> ssHosts = this._storeMgr.getImageStoresByScope(new ZoneScope(dcId));
+        if (ssHosts == null || ssHosts.isEmpty()){
+            return;
+        }
+
+        /*Download all the templates in zone with the same hypervisortype*/
+        for ( DataStore ssHost : ssHosts) {
+            List<VMTemplateVO> rtngTmplts = _templateDao.listAllSystemVMTemplates();
+            List<VMTemplateVO> defaultBuiltin = _templateDao.listDefaultBuiltinTemplates();
+
+
+            for (VMTemplateVO rtngTmplt : rtngTmplts) {
+                if (rtngTmplt.getHypervisorType() == hostHyper) {
+                    toBeDownloaded.add(rtngTmplt);
+                }
+            }
+
+            for (VMTemplateVO builtinTmplt : defaultBuiltin) {
+                if (builtinTmplt.getHypervisorType() == hostHyper) {
+                    toBeDownloaded.add(builtinTmplt);
+                }
+            }
+
+            for (VMTemplateVO template: toBeDownloaded) {
+                TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao.findByStoreTemplate(ssHost.getId(), template.getId());
+                if (tmpltHost == null || tmpltHost.getState() != ObjectInDataStoreStateMachine.State.Ready) {
+                    _dlMonitor.downloadTemplateToStorage(template, ssHost, null);
+                }
+            }
+        }
+    }
+
+
+
+
+
+    @Override
+    public void handleTemplateSync(DataStore store) {
+        if (store == null) {
+            s_logger.warn("Huh? image store is null");
+            return;
+        }
+        long storeId = store.getId();
+        Long zoneId = store.getScope().getScopeId();
+
+        Map<String, TemplateProp> templateInfos = listTemplate(store);
+        if (templateInfos == null) {
+            return;
+        }
+
+        Set<VMTemplateVO> toBeDownloaded = new HashSet<VMTemplateVO>();
+        List<VMTemplateVO> allTemplates = null;
+        if (zoneId == null){
+            // region wide store
+            allTemplates = _templateDao.listAll();
+        }
+        else{
+            // zone wide store
+            allTemplates = _templateDao.listAllInZone(zoneId);
+        }
+        List<VMTemplateVO> rtngTmplts = _templateDao.listAllSystemVMTemplates();
+        List<VMTemplateVO> defaultBuiltin = _templateDao.listDefaultBuiltinTemplates();
+
+        if (rtngTmplts != null) {
+            for (VMTemplateVO rtngTmplt : rtngTmplts) {
+                if (!allTemplates.contains(rtngTmplt)) {
+                    allTemplates.add(rtngTmplt);
+                }
+            }
+        }
+
+        if (defaultBuiltin != null) {
+            for (VMTemplateVO builtinTmplt : defaultBuiltin) {
+                if (!allTemplates.contains(builtinTmplt)) {
+                    allTemplates.add(builtinTmplt);
+                }
+            }
+        }
+
+        toBeDownloaded.addAll(allTemplates);
+
+        for (VMTemplateVO tmplt : allTemplates) {
+            String uniqueName = tmplt.getUniqueName();
+            TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId());
+            if (templateInfos.containsKey(uniqueName)) {
+                TemplateProp tmpltInfo = templateInfos.remove(uniqueName);
+                toBeDownloaded.remove(tmplt);
+                if (tmpltStore != null) {
+                    s_logger.info("Template Sync found " + uniqueName + " already in the template host table");
+                    if (tmpltStore.getDownloadState() != Status.DOWNLOADED) {
+                        tmpltStore.setErrorString("");
+                    }
+                    if (tmpltInfo.isCorrupted()) {
+                        tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR);
+                        String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId();
+                        tmpltStore.setErrorString(msg);
+                        s_logger.info("msg");
+                        if (tmplt.getUrl() == null) {
+                            msg = "Private Template (" + tmplt + ") with install path " + tmpltInfo.getInstallPath() + "is corrupted, please check in image store: " + tmpltStore.getDataStoreId();
+                            s_logger.warn(msg);
+                        } else {
+                            toBeDownloaded.add(tmplt);
+                        }
+
+                    } else {
+                        tmpltStore.setDownloadPercent(100);
+                        tmpltStore.setDownloadState(Status.DOWNLOADED);
+                        tmpltStore.setInstallPath(tmpltInfo.getInstallPath());
+                        tmpltStore.setSize(tmpltInfo.getSize());
+                        tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize());
+                        tmpltStore.setLastUpdated(new Date());
+
+                        if (tmpltInfo.getSize() > 0) {
+                            long accountId = tmplt.getAccountId();
+                            try {
+                                _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(accountId),
+                                        com.cloud.configuration.Resource.ResourceType.secondary_storage,
+                                        tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl()));
+                            } catch (ResourceAllocationException e) {
+                                s_logger.warn(e.getMessage());
+                                _alertMgr.sendAlert(_alertMgr.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId,
+                                        null, e.getMessage(), e.getMessage());
+                            } finally {
+                                _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(),
+                                        com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                            }
+                        }
+                    }
+                    _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore);
+                } else {
+                    tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, tmpltInfo.getInstallPath(), tmplt.getUrl());
+                    tmpltStore.setSize(tmpltInfo.getSize());
+                    tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize());
+                    _vmTemplateStoreDao.persist(tmpltStore);
+                    this.associateTemplateToZone(tmplt.getId(), zoneId);
+                }
+
+                continue;
+            }
+            if (tmpltStore != null && tmpltStore.getDownloadState() != Status.DOWNLOADED) {
+                s_logger.info("Template Sync did not find " + uniqueName + " ready on server " + storeId + ", will request download to start/resume shortly");
+
+            } else if (tmpltStore == null) {
+                s_logger.info("Template Sync did not find " + uniqueName + " on the server " + storeId + ", will request download shortly");
+                TemplateDataStoreVO templtStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 0, Status.NOT_DOWNLOADED, null, null, null, null, tmplt.getUrl());
+                _vmTemplateStoreDao.persist(templtStore);
+                this.associateTemplateToZone(tmplt.getId(), zoneId);
+            }
+
+        }
+
+        if (toBeDownloaded.size() > 0) {
+            /* Only download templates whose hypervirsor type is in the zone */
+            List<HypervisorType> availHypers = _clusterDao.getAvailableHypervisorInZone(zoneId);
+            if (availHypers.isEmpty()) {
+                /*
+                 * This is for cloudzone, local secondary storage resource
+                 * started before cluster created
+                 */
+                availHypers.add(HypervisorType.KVM);
+            }
+            /* Baremetal need not to download any template */
+            availHypers.remove(HypervisorType.BareMetal);
+            availHypers.add(HypervisorType.None); // bug 9809: resume ISO
+                                                  // download.
+            for (VMTemplateVO tmplt : toBeDownloaded) {
+                if (tmplt.getUrl() == null) { // If url is null we can't
+                                              // initiate the download
+                    continue;
+                }
+                // check if there is a record for this template in this store
+                TemplateDataStoreVO tmpltHost = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId());
+
+                // if this is private template, and there is no record for this
+                // template in this store, skip
+                if (!tmplt.isPublicTemplate() && !tmplt.isFeatured()) {
+                    if (tmpltHost == null) {
+                        continue;
+                    }
+                }
+                if (availHypers.contains(tmplt.getHypervisorType())) {
+                     if (tmpltHost != null ) {
+                        continue;
+                    }
+                    s_logger.debug("Template " + tmplt.getName() + " needs to be downloaded to " + store.getName());
+                    //TODO: we should pass a callback here
+                    _dlMonitor.downloadTemplateToStorage(tmplt, store, null);
+                }
+            }
+        }
+
+        for (String uniqueName : templateInfos.keySet()) {
+            TemplateProp tInfo = templateInfos.get(uniqueName);
+            List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(tInfo.getId());
+            //check if there is any Vm using this ISO.
+            if (userVmUsingIso == null || userVmUsingIso.isEmpty()) {
+                DeleteTemplateCommand dtCommand = new DeleteTemplateCommand(store.getUri(), tInfo.getInstallPath());
+                try {
+                    HostVO ssAhost = _ssvmMgr.pickSsvmHost(store);
+                    _agentMgr.sendToSecStorage(ssAhost, dtCommand, null);
+                } catch (AgentUnavailableException e) {
+                    String err = "Failed to delete " + tInfo.getTemplateName() + " on secondary storage " + storeId + " which isn't in the database";
+                    s_logger.error(err);
+                    return;
+                }
+
+                String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + storeId + " since it isn't in the database";
+                s_logger.info(description);
+            }
+        }
+
+    }
+
+
+    // persist entry in template_zone_ref table. zoneId can be empty for region-wide image store, in that case,
+    // we will associate the template to all the zones.
+    private void associateTemplateToZone(long templateId, Long zoneId){
+        List<Long> dcs = new ArrayList<Long>();
+        if (zoneId != null ){
+            dcs.add(zoneId);
+        }
+        else{
+            List<DataCenterVO> zones = _dcDao.listAll();
+            for (DataCenterVO zone : zones){
+                dcs.add(zone.getId());
+            }
+        }
+        for (Long id : dcs) {
+            VMTemplateZoneVO tmpltZoneVO = _vmTemplateZoneDao.findByZoneTemplate(id, templateId);
+            if (tmpltZoneVO == null) {
+                tmpltZoneVO = new VMTemplateZoneVO(id, templateId, new Date());
+                _vmTemplateZoneDao.persist(tmpltZoneVO);
+            } else {
+                tmpltZoneVO.setLastUpdated(new Date());
+                _vmTemplateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO);
+            }
+        }
+    }
+
+
+    private Map<String, TemplateProp> listTemplate(DataStore ssHost) {
+        ListTemplateCommand cmd = new ListTemplateCommand(ssHost.getUri());
+        HostVO ssAhost = _ssvmMgr.pickSsvmHost(ssHost);
+        Answer answer = _agentMgr.sendToSecStorage(ssAhost, cmd);
+        if (answer != null && answer.getResult()) {
+            ListTemplateAnswer tanswer = (ListTemplateAnswer)answer;
+            return tanswer.getTemplateInfo();
+        } else {
+            if (s_logger.isDebugEnabled()) {
+                s_logger.debug("can not list template for secondary storage host " + ssHost.getId());
+            }
+        }
+
+        return null;
+    }
+
+
+    protected Void createTemplateCallback(AsyncCallbackDispatcher<TemplateServiceImpl, CreateCmdResult> callback,
+            CreateTemplateContext<CreateCmdResult> context) {
+        TemplateObject template = (TemplateObject)context.srcTemplate;
+        AsyncCallFuture<CommandResult> future = context.future;
+        CommandResult result = new CommandResult();
+        DataObject templateOnStore = context.templateOnStore;
+        CreateCmdResult callbackResult = callback.getResult();
+        if (callbackResult.isFailed()) {
+            try {
+                templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed);
+                template.stateTransit(TemplateEvent.OperationFailed);
+            } catch (NoTransitionException e) {
+               s_logger.debug("Failed to update template state", e);
+            }
+            result.setResult(callbackResult.getResult());
+            future.complete(result);
+            return null;
+        }
+
+        try {
+            templateOnStore.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed);
+            template.stateTransit(TemplateEvent.OperationSucceeded);
+        } catch (NoTransitionException e) {
+            s_logger.debug("Failed to transit state", e);
+            result.setResult(e.toString());
+            future.complete(result);
+            return null;
+        }
+
+        future.complete(result);
+        return null;
+    }
+
+    @Override
+    public AsyncCallFuture<CommandResult> deleteTemplateAsync(
+            TemplateInfo template) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public AsyncCallFuture<CommandResult> createTemplateFromSnapshotAsync(
+            SnapshotInfo snapshot, TemplateInfo template, DataStore store) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    @Override
+    public AsyncCallFuture<CommandResult> createTemplateFromVolumeAsync(
+            VolumeInfo volume, TemplateInfo template, DataStore store) {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java
----------------------------------------------------------------------
diff --git a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java
index 293d7fb..fcb8962 100644
--- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java
+++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/volumeServiceTest.java
@@ -39,7 +39,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManag
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreRole;
 import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
 import org.apache.cloudstack.engine.subsystem.api.storage.ImageDataFactory;
-import org.apache.cloudstack.engine.subsystem.api.storage.ImageService;
+import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
 import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
 import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
 import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
@@ -86,7 +86,7 @@ public class volumeServiceTest extends CloudStackTestNGBase {
 	//@Inject
 	//ImageDataStoreProviderManager imageProviderMgr;
 	@Inject
-	ImageService imageService;
+	TemplateService imageService;
 	@Inject
 	VolumeService volumeService;
 	@Inject

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb646727/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java
index 6a6e04a..c9ade1a 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/image/db/SnapshotDataStoreDaoImpl.java
@@ -42,21 +42,16 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase<SnapshotDataStoreVO
     private static final Logger s_logger = Logger.getLogger(SnapshotDataStoreDaoImpl.class);
     private SearchBuilder<SnapshotDataStoreVO> updateStateSearch;
     private SearchBuilder<SnapshotDataStoreVO> storeSearch;
-    private SearchBuilder<SnapshotDataStoreVO> liveStoreSearch;
 
     @Override
     public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
     	super.configure(name, params);
 
-    	storeSearch = createSearchBuilder();
+        storeSearch = createSearchBuilder();
         storeSearch.and("store_id", storeSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
+        storeSearch.and("destroyed", storeSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
         storeSearch.done();
 
-        liveStoreSearch = createSearchBuilder();
-        liveStoreSearch.and("store_id", liveStoreSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
-        liveStoreSearch.and("destroyed", liveStoreSearch.entity().getDestroyed(), SearchCriteria.Op.EQ);
-        liveStoreSearch.done();
-
         updateStateSearch = this.createSearchBuilder();
         updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
         updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
@@ -102,17 +97,11 @@ public class SnapshotDataStoreDaoImpl extends GenericDaoBase<SnapshotDataStoreVO
         return rows > 0;
     }
 
+
     @Override
     public List<SnapshotDataStoreVO> listByStoreId(long id) {
         SearchCriteria<SnapshotDataStoreVO> sc = storeSearch.create();
         sc.setParameters("store_id", id);
-        return listIncludingRemovedBy(sc);
-    }
-
-    @Override
-    public List<SnapshotDataStoreVO> listLiveByStoreId(long id) {
-        SearchCriteria<SnapshotDataStoreVO> sc = liveStoreSearch.create();
-        sc.setParameters("store_id", id);
         sc.setParameters("destroyed", false);
         return listIncludingRemovedBy(sc);
     }


Mime
View raw message