You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ah...@apache.org on 2013/06/25 01:51:37 UTC

[01/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Updated Branches:
  refs/heads/vmsync e7c34793f -> 049dd7242


CLOUDSTACK-2679: Install docs could point to more accurate XenServer download page


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

Branch: refs/heads/vmsync
Commit: 145c10ec3f88fb27350f0843231714e49276d0ac
Parents: d53f1c0
Author: Joe Brockmeier <jz...@zonker.net>
Authored: Sun Jun 23 13:17:31 2013 -0500
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 13:17:31 2013 -0500

----------------------------------------------------------------------
 docs/en-US/citrix-xenserver-installation.xml | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/145c10ec/docs/en-US/citrix-xenserver-installation.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/citrix-xenserver-installation.xml b/docs/en-US/citrix-xenserver-installation.xml
index a5118d7..9ea632a 100644
--- a/docs/en-US/citrix-xenserver-installation.xml
+++ b/docs/en-US/citrix-xenserver-installation.xml
@@ -103,7 +103,10 @@
             >https://www.citrix.com/English/ss/downloads/</ulink>, download the appropriate version
           of XenServer for your &PRODUCT; version (see <xref
             linkend="system-requirements-xenserver-hosts"/>). Install it using the Citrix XenServer
-          Installation Guide.</para>
+        Installation Guide.</para>
+    <note><title>Older Versions of XenServer</title>
+        <para>Note that you can download the most recent release of XenServer without having a Citrix account. If you wish to download older versions, you will need to create an account and look through the download archives.</para>
+    </note>
       </listitem>
       <listitem>
         <para>After installation, perform the following configuration steps, which are described in


[02/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-2679: Install docs could point to more accurate XenServer download page


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

Branch: refs/heads/vmsync
Commit: 5bfae23a1e2031f79f60d9354a4bab986bf1ecd6
Parents: 145c10e 3e430cc
Author: Joe Brockmeier <jz...@zonker.net>
Authored: Sun Jun 23 13:17:46 2013 -0500
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 13:17:46 2013 -0500

----------------------------------------------------------------------
 tools/marvin/marvin/TestCaseExecuteEngine.py | 43 ++++++++++++++---------
 1 file changed, 27 insertions(+), 16 deletions(-)
----------------------------------------------------------------------



[33/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Migration work


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

Branch: refs/heads/vmsync
Commit: 95fe42cc7c003ff5f34598106c408efe0f862faf
Parents: c0febea
Author: Alex Huang <al...@gmail.com>
Authored: Mon Jun 24 10:16:14 2013 -0700
Committer: Alex Huang <al...@gmail.com>
Committed: Mon Jun 24 10:16:37 2013 -0700

----------------------------------------------------------------------
 api/src/org/apache/cloudstack/jobs/JobInfo.java |  18 +-
 core/src/com/cloud/agent/api/StopCommand.java   |  14 +-
 .../src/com/cloud/vm/VirtualMachineManager.java |   3 +-
 .../components-api/src/com/cloud/vm/VmWork.java |  16 +-
 .../com/cloud/vm/VirtualMachineManagerImpl.java | 504 +++++++++++--------
 .../src/com/cloud/vm/VmWorkJobDispatcher.java   |   9 +-
 .../src/com/cloud/vm/VmWorkMigrate.java         |  78 +++
 .../src/com/cloud/vm/VmWorkStart.java           |  10 +-
 .../src/com/cloud/vm/VmWorkStop.java            |  15 +-
 .../apache/cloudstack/vm/jobs/VmWorkJobVO.java  |  26 +-
 .../framework/jobs/AsyncJobManager.java         |   3 +-
 .../jobs/impl/AsyncJobManagerImpl.java          |  16 +-
 .../framework/jobs/impl/OutcomeImpl.java        |  12 +-
 server/src/com/cloud/api/ApiGsonHelper.java     |   3 +-
 server/src/com/cloud/vm/UserVmManagerImpl.java  |  10 +-
 .../src/com/cloud/api/StringMapTypeAdapter.java |  46 --
 .../org/apache/cloudstack/utils/GsonUtils.java  |  48 ++
 17 files changed, 520 insertions(+), 311 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/api/src/org/apache/cloudstack/jobs/JobInfo.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/jobs/JobInfo.java b/api/src/org/apache/cloudstack/jobs/JobInfo.java
index 6a53123..ac8ffc3 100644
--- a/api/src/org/apache/cloudstack/jobs/JobInfo.java
+++ b/api/src/org/apache/cloudstack/jobs/JobInfo.java
@@ -23,10 +23,20 @@ import org.apache.cloudstack.api.InternalIdentity;
 
 public interface JobInfo extends Identity, InternalIdentity {
     public enum Status {
-        IN_PROGRESS,
-        SUCCEEDED,
-        FAILED,
-        CANCELLED;
+        IN_PROGRESS(false),
+        SUCCEEDED(true),
+        FAILED(true),
+        CANCELLED(true);
+        
+        private final boolean done;
+
+        private Status(boolean done) {
+            this.done = done;
+        }
+        
+        public boolean done() {
+            return done;
+        }
     }
 
     String getType();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/core/src/com/cloud/agent/api/StopCommand.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/api/StopCommand.java b/core/src/com/cloud/agent/api/StopCommand.java
index 1c67f38..7d3fd43 100755
--- a/core/src/com/cloud/agent/api/StopCommand.java
+++ b/core/src/com/cloud/agent/api/StopCommand.java
@@ -23,15 +23,17 @@ public class StopCommand extends RebootCommand {
     private boolean isProxy=false;
     private String urlPort=null;
     private String publicConsoleProxyIpAddress=null;
+    private boolean cleanupOnly;
 
     protected StopCommand() {
     }
 
-    public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress) {
+    public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress, boolean cleanupOnly) {
     	super(vm);
     	this.isProxy = isProxy;
     	this.urlPort = urlPort;
     	this.publicConsoleProxyIpAddress = publicConsoleProxyIpAddress;
+        this.cleanupOnly = cleanupOnly;
     }
 
     public StopCommand(VirtualMachine vm, String vnet) {
@@ -39,6 +41,10 @@ public class StopCommand extends RebootCommand {
         this.vnet = vnet;
     }
     
+    public boolean isCleanupOnly() {
+        return cleanupOnly;
+    }
+
     public StopCommand(VirtualMachine vm) {
         super(vm);
     }
@@ -57,15 +63,15 @@ public class StopCommand extends RebootCommand {
     }
 
 	public boolean isProxy() {
-		return this.isProxy;
+		return isProxy;
 	}
 
 	public String getURLPort() {
-		return this.urlPort;
+		return urlPort;
 	}
 
 	public String getPublicConsoleProxyIpAddress() {
-		return this.publicConsoleProxyIpAddress;
+		return publicConsoleProxyIpAddress;
 	}
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
----------------------------------------------------------------------
diff --git a/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java b/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
index 92f05f0..954d3b6 100644
--- a/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
+++ b/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
@@ -137,8 +137,7 @@ public interface VirtualMachineManager extends Manager {
 
     boolean migrateAway(VirtualMachine.Type type, long vmid, long hostId) throws InsufficientServerCapacityException, VirtualMachineMigrationException;
 
-    VirtualMachine migrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
-            VirtualMachineMigrationException;
+    Outcome<VirtualMachine> migrate(String vmUuid, long srcHostId, DeployDestination dest);
 
     VirtualMachine migrateWithStorage(String vmUuid, long srcId, long destId, Map<Volume, StoragePool> volumeToPool) throws ResourceUnavailableException,
             ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/components-api/src/com/cloud/vm/VmWork.java
----------------------------------------------------------------------
diff --git a/engine/components-api/src/com/cloud/vm/VmWork.java b/engine/components-api/src/com/cloud/vm/VmWork.java
index 733bfe7..4eb8bce 100644
--- a/engine/components-api/src/com/cloud/vm/VmWork.java
+++ b/engine/components-api/src/com/cloud/vm/VmWork.java
@@ -21,30 +21,22 @@ public class VmWork {
 	long accountId;
 	long vmId;
 
-	public VmWork() {
+    public VmWork(long userId, long accountId, long vmId) {
+        this.userId = userId;
+        this.accountId = accountId;
+        this.vmId = vmId;
 	}
 
 	public long getUserId() {
 		return userId;
 	}
 
-	public void setUserId(long userId) {
-		this.userId = userId;
-	}
-
 	public long getAccountId() {
 		return accountId;
 	}
 
-	public void setAccountId(long accountId) {
-		this.accountId = accountId;
-	}
-
 	public long getVmId() {
 		return vmId;
 	}
 
-	public void setVmId(long vmId) {
-		this.vmId = vmId;
-	}
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index 3a308a9..a1c2db4 100755
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -56,7 +56,6 @@ import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
 import org.apache.cloudstack.framework.messagebus.MessageBus;
 import org.apache.cloudstack.framework.messagebus.MessageDispatcher;
 import org.apache.cloudstack.framework.messagebus.MessageHandler;
-import org.apache.cloudstack.jobs.JobInfo;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.vm.jobs.VmWorkJobDao;
 import org.apache.cloudstack.vm.jobs.VmWorkJobVO;
@@ -72,9 +71,13 @@ import com.cloud.agent.api.CheckVirtualMachineAnswer;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.ClusterSyncAnswer;
 import com.cloud.agent.api.Command;
+import com.cloud.agent.api.MigrateAnswer;
+import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PlugNicAnswer;
 import com.cloud.agent.api.PlugNicCommand;
+import com.cloud.agent.api.PrepareForMigrationAnswer;
+import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.RebootAnswer;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.StartAnswer;
@@ -134,6 +137,8 @@ import com.cloud.org.Cluster;
 import com.cloud.resource.ResourceManager;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.storage.DiskOfferingVO;
+import com.cloud.storage.GuestOSVO;
+import com.cloud.storage.GuestOsCategory;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.VMTemplateVO;
@@ -162,6 +167,7 @@ import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.exception.ExecutionException;
 import com.cloud.utils.fsm.NoTransitionException;
+import com.cloud.utils.fsm.StateMachine;
 import com.cloud.utils.fsm.StateMachine2;
 import com.cloud.vm.VirtualMachine.Event;
 import com.cloud.vm.VirtualMachine.PowerState;
@@ -204,9 +210,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     protected static final ConfigKey<Long> VmJobTimeout = new ConfigKey<Long>(
             Long.class, "vm.job.timeout", "VM Orchestration", OrchestrationService.class, "600000", "Time in milliseconds to wait before attempting to cancel a job", true,
             "Milliseconds");
-    public static final ConfigKey<Long> PingInterval = new ConfigKey<Long>(
+    protected static final ConfigKey<Long> PingInterval = new ConfigKey<Long>(
             Long.class, "ping.interval", "Advanced", OrchestrationService.class, "60", "Ping interval in seconds", false, null);
 
+    protected static final StateMachine<Step, VirtualMachine.Event> MigrationStateMachine = new StateMachine<Step, VirtualMachine.Event>();
+    static {
+        MigrationStateMachine.addTransition(null, VirtualMachine.Event.MigrationRequested, Step.Prepare);
+        MigrationStateMachine.addTransition(Step.Prepare, VirtualMachine.Event.OperationSucceeded, Step.Migrating);
+        MigrationStateMachine.addTransition(Step.Prepare, VirtualMachine.Event.OperationFailed, Step.Error);
+        MigrationStateMachine.addTransition(Step.Migrating, VirtualMachine.Event.OperationSucceeded, Step.Started);
+        MigrationStateMachine.addTransition(Step.Migrating, VirtualMachine.Event.OperationFailed, Step.Error);
+        MigrationStateMachine.addTransition(Step.Started, VirtualMachine.Event.OperationSucceeded, Step.Done);
+        MigrationStateMachine.addTransition(Step.Started, VirtualMachine.Event.OperationFailed, Step.Error);
+    }
+
     @Inject
     protected EntityManager _entityMgr;
     @Inject
@@ -490,10 +507,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
         ReservationContextImpl.setComponents(_entityMgr);
         VirtualMachineProfileImpl.setComponents(_entityMgr);
+        VmWorkMigrate.init(_entityMgr);
 
         _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
 
-        _agentMgr.registerForHostEvents(this, true, true, true);
+        _agentMgr.registerForHost)Events(this, true, true, true);
         
         RootVolumeSearch = _entityMgr.createSearchBuilder(VolumeVO.class);
         VolumeVO rvsEntity = RootVolumeSearch.entity();
@@ -583,7 +601,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                     work = _workDao.persist(work);
                     ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
 
-                    if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
+                    if (stateTransitTo(vm, VirtualMachine.Event.StartRequested, null, work.getId())) {
                         if (s_logger.isDebugEnabled()) {
                             s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
                         }
@@ -648,7 +666,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 	        
 	        Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
 	        ReservationContextImpl context = new ReservationContextImpl(work.getUuid(), journal, caller, account);
-	        if (stateTransitTo(vm, Event.StartRequested, null, work.getUuid())) {
+            if (stateTransitTo(vm, VirtualMachine.Event.StartRequested, null, work.getUuid())) {
 	            if (s_logger.isDebugEnabled()) {
 	                s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
 	            }
@@ -666,22 +684,42 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         throw new ConcurrentOperationException("Unable to change the state of " + vm);
     }
     
+    @DB
     protected boolean changeState(VMInstanceVO vm, Event event, Long hostId, VmWorkJobVO work, Step step) throws NoTransitionException {
-        // FIXME: We should do this better.
         VmWorkJobVO.Step previousStep = work.getStep();
         
-        boolean result = false;
-        try {
-            result = stateTransitTo(vm, event, hostId);
-            return result;
-        } finally {
-            if (!result) {
-            	work.setStep(previousStep);
-            	_workJobDao.update(work.getId(), work);
-            }
+        Transaction txn = Transaction.currentTxn();
+
+        txn.start();
+        work.setStep(step);
+        boolean result = stateTransitTo(vm, event, hostId);
+        if (!result) {
+            work.setStep(previousStep);
         }
+        _workJobDao.update(work.getId(), work);
+        txn.commit();
+        return result;
     }
     
+    @DB
+    protected void changeState2(VMInstanceVO vm, VirtualMachine.Event vmEvent, Long hostId, VmWorkJobVO work, VirtualMachine.Event workEvent) throws NoTransitionException {
+        VmWorkJobVO.Step currentStep = work.getStep();
+        StateMachine<Step, Event> sm = work.getCmd() == VmWorkJobDispatcher.Migrate ? MigrationStateMachine : null;
+
+        Transaction txn = Transaction.currentTxn();
+
+        txn.start();
+        if (vmEvent != null) {
+            if (!stateTransitTo(vm, vmEvent, hostId)) {
+                throw new NoTransitionException("Unable to transit the vm state");
+            }
+        }
+        work.setStep(sm.getNextState(currentStep, workEvent));
+        _workJobDao.update(work.getId(), work);
+        txn.commit();
+        return;
+    }
+
     protected boolean areAffinityGroupsAssociated(VirtualMachineProfile vmProfile) {
         VirtualMachine vm = vmProfile.getVirtualMachine();
         long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
@@ -709,7 +747,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
         List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
 
-        if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
+        if (pendingWorkJobs.size() > 0) {
             assert (pendingWorkJobs.size() == 1);
             workJob = pendingWorkJobs.get(0);
         } else {
@@ -725,10 +763,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             workJob.setVmInstanceId(vm.getId());
 
             // save work context info (there are some duplications)
-            VmWorkStart workInfo = new VmWorkStart();
-            workInfo.setAccountId(callingAccount.getId());
-            workInfo.setUserId(callingUser.getId());
-            workInfo.setVmId(vm.getId());
+            VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId());
             workInfo.setPlan(planToDeploy);
             workInfo.setParams(params);
             workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
@@ -739,7 +774,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         txn.commit();
     	final long jobId = workJob.getId();
     	AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
-        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId());
+        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId(), null);
     }
 
     private Pair<DeploymentPlan, DeployDestination> findDestination(VirtualMachineProfileImpl profile, DeploymentPlan planRequested, boolean reuseVolume,
@@ -869,7 +904,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                 vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
                 vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
 
-                if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
+                if (!changeState(vm, VirtualMachine.Event.OperationRetry, destHostId, work, Step.Prepare)) {
                     throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
                 }
 
@@ -908,7 +943,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                             destHostId = finalHost.getId();
                         }
                         if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, reservation)) {
-                            if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
+                            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, destHostId, work, Step.Done)) {
                                 throw new ConcurrentOperationException("Unable to transition to a new state.");
                             }
                             startedVm = vm;
@@ -967,10 +1002,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                         VmWorkJobVO.Step prevStep = work.getStep();
                         _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Release);
                         if (prevStep == VmWorkJobVO.Step.Started || prevStep == VmWorkJobVO.Step.Starting) {
-                            cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false);
+                            cleanup(vmGuru, vmProfile, work, VirtualMachine.Event.OperationFailed, false);
                         } else {
                             //if step is not starting/started, send cleanup command with force=true
-                            cleanup(vmGuru, vmProfile, work, Event.OperationFailed, true);
+                            cleanup(vmGuru, vmProfile, work, VirtualMachine.Event.OperationFailed, true);
                         }
                     }
                 }
@@ -980,7 +1015,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         } finally {
             if (startedVm == null) {
                 try {
-                    changeState(vm, Event.OperationFailed, null, work, Step.Done);
+                    changeState(vm, VirtualMachine.Event.OperationFailed, null, work, Step.Done);
                 } catch (NoTransitionException e) {
                     throw new ConcurrentOperationException(e.getMessage());
                 }
@@ -1031,7 +1066,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         return true;
     }
 
-    protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, VmWorkJobVO work, Event event, boolean force) {
+    protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, VmWorkJobVO work, boolean force) {
         VirtualMachine vm = profile.getVirtualMachine();
         State state = vm.getState();
         s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
@@ -1096,7 +1131,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     
     @Override
     @DB
-    public Outcome<VirtualMachine> stop(final String vmUuid, boolean forced) {
+    public Outcome<VirtualMachine> stop(final String vmUuid, boolean cleanup) {
         CallContext cc = CallContext.current();
         Account account = cc.getCallingAccount();
         User user = cc.getCallingUser();
@@ -1126,11 +1161,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             workJob.setVmInstanceId(vm.getId());
 
             // save work context info (there are some duplications)
-            VmWorkStop workInfo = new VmWorkStop();
-            workInfo.setAccountId(account.getId());
-            workInfo.setUserId(user.getId());
-            workInfo.setVmId(vm.getId());
-            workInfo.setForceStop(forced);
+            VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), cleanup);
             workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
 
             _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
@@ -1141,7 +1172,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     	final long jobId = workJob.getId();
     	AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
     	
-        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOff, vm.getId());
+        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOff, vm.getId(), null);
     }
 
     public void orchestrateStop(String vmUuid, boolean forced) throws AgentUnavailableException,
@@ -1161,7 +1192,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             }
             
             try {
-                stateTransitTo(vm, Event.AgentReportStopped, null, null);
+                stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null, null);
             } catch (NoTransitionException e) {
                 s_logger.warn(e.getMessage());
             }
@@ -1174,7 +1205,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 
         try {
-            if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
+            if (!stateTransitTo(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) {
                 throw new ConcurrentOperationException("VM is being operated on.");
             }
         } catch (NoTransitionException e1) {
@@ -1194,12 +1225,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             }
 
             if (doCleanup) {
-                if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.StopRequested, forced)) {
+                if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, VirtualMachine.Event.StopRequested, forced)) {
                     try {
                         if (s_logger.isDebugEnabled()) {
                             s_logger.debug("Updating work item to Done, id:" + work.getId());
                         }
-                        changeState(vm, Event.AgentReportStopped, null, work, Step.Done);
+                        changeState(vm, VirtualMachine.Event.AgentReportStopped, null, work, Step.Done);
                         return;
                     } catch (NoTransitionException e) {
                         s_logger.warn("Unable to cleanup " + vm);
@@ -1234,7 +1265,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                 if (!forced) {
                     s_logger.warn("Unable to stop vm " + vm);
                     try {
-                        stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
+                        stateTransitTo(vm, VirtualMachine.Event.OperationFailed, vm.getHostId());
                     } catch (NoTransitionException e) {
                         s_logger.warn("Unable to transition the state " + vm);
                     }
@@ -1274,7 +1305,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                 _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Done);
             }
 
-            stateTransitTo(vm, Event.OperationSucceeded, null, null);
+            stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, null, null);
             return;
         } catch (NoTransitionException e) {
             s_logger.warn(e.getMessage());
@@ -1293,23 +1324,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
     @Override
     public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
-
-/*
- *  TODO ???
- * 
-        // if there are active vm snapshots task, state change is not allowed
-        if(_vmSnapshotMgr.hasActiveVMSnapshotTasks(vm.getId())) {
-            s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
-            return false;
-        }
-*/
         State oldState = vm.getState();
         if (oldState == State.Starting) {
-            if (e == Event.OperationSucceeded) {
+            if (e == VirtualMachine.Event.OperationSucceeded) {
                 vm.setLastHostId(hostId);
             }
         } else if (oldState == State.Stopping) {
-            if (e == Event.OperationSucceeded) {
+            if (e == VirtualMachine.Event.OperationSucceeded) {
                 vm.setLastHostId(vm.getHostId());
             }
         }
@@ -1417,173 +1438,245 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public VirtualMachine migrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException,
-            ManagementServerException,
-    	VirtualMachineMigrationException {
+    public Outcome<VirtualMachine> migrate(String vmUuid, long srcHostId, DeployDestination dest) {
+        CallContext context = CallContext.current();
+        User user = context.getCallingUser();
+        Account account = context.getCallingAccount();
+
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+
+        VmWorkJobVO workJob = null;
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+
+        _vmDao.lockRow(vm.getId(), true);
+
+        List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
+
+        if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
+            assert (pendingWorkJobs.size() == 1);
+            workJob = pendingWorkJobs.get(0);
+        } else {
+                    
+            workJob = new VmWorkJobVO(context.getContextId());
+
+            workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
+            workJob.setCmd(VmWorkJobDispatcher.Start);
+
+            workJob.setAccountId(account.getId());
+            workJob.setUserId(user.getId());
+            workJob.setStep(VmWorkJobVO.Step.Migrating);
+            workJob.setVmType(vm.getType());
+            workJob.setVmInstanceId(vm.getId());
+
+            // save work context info (there are some duplications)
+            VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), dest);
+            workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
+
+            _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
+        }
+
+        txn.commit();
+        final long jobId = workJob.getId();
+        AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
+        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId());
+
+    }
+
+    public void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws AgentUnavailableException, OperationTimedoutException {
+        AsyncJobExecutionContext jc = AsyncJobExecutionContext.getCurrentExecutionContext();
+
         VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
-        s_logger.info("Migrating " + vm + " to " + dest);
+        if (vm == null) {
+            throw new CloudRuntimeException("Unable to find the vm " + vm);
+        }
+
+        if (vm.getState() != State.Running || vm.getHostId() == null || vm.getHostId() != srcHostId ) {
+            if (s_logger.isDebugEnabled()) {
+                s_logger.debug("Proper conditions to migrate " + vm + " is not met.");
+            }
+            return;
+        }
         
-        return vm;
+        Host fromHost = _entityMgr.findById(Host.class, srcHostId);
+        if (fromHost == null) {
+            throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
+        }
+        long dstHostId = dest.getHost().getId();
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Migrating " + vm + " to " + dest);
+        }
+
+        short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
+        if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
+            alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
+        } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
+            alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
+        }
+
+        VirtualMachineProfile srcVm = new VirtualMachineProfileImpl(vm);
+        for (NicProfile nic : _networkMgr.getNicProfiles(vm)) {
+            srcVm.addNic(nic);
+        }
         
-        /*
-                long dstHostId = dest.getHost().getId();
-                Host fromHost = _hostDao.findById(srcHostId);
-                if (fromHost == null) {
-                    s_logger.info("Unable to find the host to migrate from: " + srcHostId);
-                    throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
-                }
+        VirtualMachineProfile dstVm = new VirtualMachineProfileImpl(vm);
+        _networkMgr.prepareNicForMigration(dstVm, dest);
+        _volumeMgr.prepareForMigration(dstVm, dest);
 
-                if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
-                    s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
-                    throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
-                }
+        VirtualMachineTO to = toVmTO(dstVm);
 
-                VirtualMachineGuru<T> vmGuru = getVmGuru(vm);
+        VmWorkJobVO work = _workJobDao.findById(jc.getJob().getId());
+        work.setStep(MigrationStateMachine.getNextState(null, VirtualMachine.Event.MigrationRequested));
+        work = _workJobDao.persist(work);
 
-                long vmId = vm.getId();
-                vm = vmGuru.findById(vmId);
-                if (vm == null) {
-                    if (s_logger.isDebugEnabled()) {
-                        s_logger.debug("Unable to find the vm " + vm);
-                    }
-                    throw new ManagementServerException("Unable to find a virtual machine with id " + vmId);
+        PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
+        PrepareForMigrationAnswer pfma = null;
+        try {
+            try {
+                pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
+                if (!pfma.getResult()) {
+                    String msg = "Unable to prepare for migration due to " + pfma.getDetails();
+                    throw new AgentUnavailableException(msg, dstHostId);
                 }
+            } catch (OperationTimedoutException e) {
+                throw new AgentUnavailableException("Unable to prepare host " + dstHostId, dstHostId);
+            }
+    
+            vm.setLastHostId(srcHostId);
+            changeState2(vm, VirtualMachine.Event.MigrationRequested, dstHostId, work, VirtualMachine.Event.OperationSucceeded);
+    
+            boolean isWindows = _entityMgr.findById(GuestOsCategory.class, _entityMgr.findById(GuestOSVO.class, vm.getGuestOSId()).getCategoryId()).getName()
+                    .equalsIgnoreCase("Windows");
+            MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
+            mc.setHostGuid(dest.getHost().getGuid());
 
-                if (vm.getState() != State.Running) {
-                    if (s_logger.isDebugEnabled()) {
-                        s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
-                    }
-                    throw new VirtualMachineMigrationException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
+            try {
+                MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
+                if (!ma.getResult()) {
+                    throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
                 }
-
-                short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
-                if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
-                    alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
-                } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
-                    alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
+            } catch (OperationTimedoutException e) {
+                if (!e.isActive()) {
+                    s_logger.warn("Active migration command so scheduling a restart for " + vm);
+                    _haMgr.scheduleRestart(vm, true);
                 }
+                throw new CloudRuntimeException("Operation timed out on migrating " + vm);
+            }
 
-        VirtualMachineProfile<VMInstanceVO> vmSrc = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
-        for(NicProfile nic: _networkMgr.getNicProfiles(vm)){
-            vmSrc.addNic(nic);
-        }
-        
-                VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
-                _networkMgr.prepareNicForMigration(profile, dest);
-                this.volumeMgr.prepareForMigration(profile, dest);
+            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
+                throw new CloudRuntimeException("Unable to change the state for " + vm);
+            }
 
-                VirtualMachineTO to = toVmTO(profile);
-                PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
+            try {
+                if (!checkVmOnHost(vm, dstHostId)) {
+                    throw new CloudRuntimeException("Unable to complete migration for " + vm);
+                }
+            } catch (OperationTimedoutException e) {
+                s_logger.warn("Unable to verify that " + vm + " has migrated but since the migrate command worked, it is assumed to have worked");
+            }
+            
+            _networkMgr.commitNicForMigration(srcVm, dstVm);
+            changeState2(vm, null, dstHostId, work, VirtualMachine.Event.OperationSucceeded);
 
-                VmWorkJobVO work = new VmWorkJobVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
-                work.setStep(Step.Prepare);
-                work.setResourceType(VmWorkJobVO.ResourceType.Host);
-                work.setResourceId(dstHostId);
-                work = _workDao.persist(work);
+        } catch (NoTransitionException e) {
+            throw new CloudRuntimeException("Unable to change state", e);
+        } finally {
+            Step step = work.getStep();
+            
+            if (step != Step.Done) {
+                s_logger.debug("Migration was unsuccessful.  Cleaning up: " + vm + " Step was at " + step);
 
-                PrepareForMigrationAnswer pfma = null;
+                _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName()
+                        + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed.  Please check logs.");
                 try {
-                    pfma = (PrepareForMigrationAnswer) _agentMgr.send(dstHostId, pfmc);
-                    if (!pfma.getResult()) {
-                        String msg = "Unable to prepare for migration due to " + pfma.getDetails();
-                        pfma = null;
-                        throw new AgentUnavailableException(msg, dstHostId);
-                    }
-                } catch (OperationTimedoutException e1) {
-                    throw new AgentUnavailableException("Operation timed out", dstHostId);
-                } finally {
-                    if (pfma == null) {
-                _networkMgr.rollbackNicForMigration(vmSrc, profile);
-                        work.setStep(Step.Done);
-                        _workDao.update(work.getId(), work);
-                    }
+                    _agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
+                } catch (AgentUnavailableException ae) {
+                    s_logger.info("Looks like the destination Host is unavailable for cleanup");
                 }
 
-                vm.setLastHostId(srcHostId);
                 try {
-                    if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
-                _networkMgr.rollbackNicForMigration(vmSrc, profile);
-                        s_logger.info("Migration cancelled because state has changed: " + vm);
-                        throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
-                    }
-                } catch (NoTransitionException e1) {
-            _networkMgr.rollbackNicForMigration(vmSrc, profile);
-                    s_logger.info("Migration cancelled because " + e1.getMessage());
-                    throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
+                    stateTransitTo(vm, VirtualMachine.Event.OperationFailed, srcHostId);
+                } catch (NoTransitionException e) {
+                    s_logger.warn(e.getMessage());
                 }
+                _networkMgr.rollbackNicForMigration(srcVm, dstVm);
+                
+                work.setStep(Step.Done);
+                _workJobDao.update(work.getId(), work);
+            }
+        }
+    }
 
-                boolean migrated = false;
-                try {
-                    boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
-                    MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
-                    mc.setHostGuid(dest.getHost().getGuid());
-
-                    try {
-                        MigrateAnswer ma = (MigrateAnswer) _agentMgr.send(vm.getLastHostId(), mc);
-                        if (!ma.getResult()) {
-                            s_logger.error("Unable to migrate due to " + ma.getDetails());
-                            return null;
-                        }
-                    } catch (OperationTimedoutException e) {
-                        if (e.isActive()) {
-                            s_logger.warn("Active migration command so scheduling a restart for " + vm);
-                            _haMgr.scheduleRestart(vm, true);
-                        }
-                        throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
-                    }
-
-                    try {
-                        if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
-                            throw new ConcurrentOperationException("Unable to change the state for " + vm);
-                        }
-                    } catch (NoTransitionException e1) {
-                        throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
-                    }
-
-                    try {
-                        if (!checkVmOnHost(vm, dstHostId)) {
-                            s_logger.error("Unable to complete migration for " + vm);
-                            try {
-                                _agentMgr.send(srcHostId, new Commands(cleanup(vm)), null);
-                            } catch (AgentUnavailableException e) {
-                                s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
-                            }
-                            cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
-                            return null;
-                        }
-                    } catch (OperationTimedoutException e) {
-                    }
+    /**
+     * Migration goes through the following steps.
+     *   Prepare - nics and storage are prepared
+     *   Migrating - migrating command was issued
+     *   Started - migrating command returned and was successful
+     *   Done - the vm was verified on the destination host.
+     * 
+     * In order to cleanup, we have to go through the above steps in reverse.
+     * 
+     * @param job - job that was recording the status
+     * @param vm - vm profile that needs to be cleaned up.
+     * @param vo - vo object representing the VM.
+     */
+    private void cleanupMigration(VmWorkJobVO job, VirtualMachineProfile vm, VMInstanceVO vo, boolean confirmedStopped) {
+        boolean uncertain = false;
+        boolean rollbackPreparation = false;
+        if (job == null) {
+            s_logger.info("Cleaning up " + vo + " with no job to track progress");
+            if (vo.getState() != VirtualMachine.State.Migrating) {
+                if (s_logger.isDebugEnabled()) {
+                    s_logger.debug("Requesting to clean up a vm that's not migrating: " + vo);
+                }
+                return;
+            }
+            if (checkVmOnHost(vo, vo.getLastHostId())) {
+                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getLastHostId());
+            } else if (checkVmOnHost(vo, vo.getHostId())) {
+                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId());
+            } else {
+                s_logger.warn("Unable to find " + vo + " on source " + vo.getLastHostId() + " or on destination " + vo.getHostId() + (!confirmedStopped ? ".  Either call Stop with cleanup option or wait for vmsync to check where the VM is." : "."));
+            }
+            
+            if (confirmedStopped) {
+                s_logger.info("Cleanup was requested on " + vo);
+                cleanup(getVmGuru(vo), vm, null, true);
+            }
+            return;
+        }
+        
+        Step step = job.getStep();
+        
+        s_logger.info("Cleaning up based on what stage the current job is at: " + step);
+        if (step == Step.Started) {
+            if (checkVmOnHost(vo, vo.getLastHostId())) {
+                changeState2(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId(), job, Event.OperationSucceeded);
+            } else {
+                changeState2(vo, VirtualMachine.Event.AgentReportStopped, vo.getHostId(), job, Event.OperationFailed);
+            }
+        } else if (step == Step.Migrating) {
+            s_logger.debug("We are at the migrating step.  We have to find out if the operation succeeded or ");
+        }
+        if (step == Step.Prepare) {
+            s_logger.debug("Prepare Step: ");
+            rollbackPreparation = true;
+        }
 
-                    migrated = true;
-                    return vm;
-                } finally {
-                    if (!migrated) {
-                        s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
-                _networkMgr.rollbackNicForMigration(vmSrc, profile);
+        if (uncertain) {
+            Long srcHostId = vo.getLastHostId();
+            Long dstHostId = vo.getHostId();
 
-                        _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone "
-                                + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed.  Please check logs.");
-                        try {
-                            _agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
-                        } catch (AgentUnavailableException ae) {
-                            s_logger.info("Looks like the destination Host is unavailable for cleanup");
-                        }
+            if (!checkVmOnHost(vo, srcHostId)) {
+                changeState2(vo, Event.OperationFailed, job,)
+            }
 
-                        try {
-                            stateTransitTo(vm, Event.OperationFailed, srcHostId);
-                        } catch (NoTransitionException e) {
-                            s_logger.warn(e.getMessage());
-                        }
-            }else{
-                _networkMgr.commitNicForMigration(vmSrc, profile);
-                    }
+        }
 
-                    work.setStep(Step.Done);
-                    _workDao.update(work.getId(), work);
-                }
-        */
     }
 
+
     private void filterPoolListForVolumesForMigration(VirtualMachineProfile profile, Host host, Map<Volume, StoragePool> volumeToPool) {
         List<VolumeVO> allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId());
         for (VolumeVO volume : allVolumes) {
@@ -1644,7 +1737,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             throws ConcurrentOperationException {
         // Put the vm in migrating state.
         try {
-            if (!changeState(vm, Event.MigrationRequested, hostId, work, Step.Migrating)) {
+            if (!changeState(vm, VirtualMachine.Event.MigrationRequested, hostId, work, Step.Migrating)) {
                 s_logger.info("Migration cancelled because state has changed: " + vm);
                 throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
             }
@@ -1658,7 +1751,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             throws ConcurrentOperationException {
         // Put the vm in running state.
         try {
-            if (!changeState(vm, Event.OperationSucceeded, hostId, work, Step.Started)) {
+            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, hostId, work, Step.Started)) {
                 s_logger.error("Unable to change the state for " + vm);
                 throw new ConcurrentOperationException("Unable to change the state for " + vm);
             }
@@ -1734,7 +1827,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                     } catch (AgentUnavailableException e) {
                         s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                     }
-                    cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
+                    cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, VirtualMachine.Event.AgentReportStopped, true);
                     return null;
                 }
             } catch (OperationTimedoutException e) {
@@ -1751,7 +1844,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                         " and pod " + dc.getName(), "Migrate Command failed.  Please check logs.");
                 try {
                     _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
-                    stateTransitTo(vm, Event.OperationFailed, srcHostId);
+                    stateTransitTo(vm, VirtualMachine.Event.OperationFailed, srcHostId);
                 } catch (AgentUnavailableException e) {
                     s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
                 } catch (NoTransitionException e) {
@@ -2465,7 +2558,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                     if (serverState == State.Starting) {
                         if (fullSync) {
                             try {
-                                ensureVmRunningContext(hostId, vm, Event.AgentReportRunning);
+                                ensureVmRunningContext(hostId, vm, VirtualMachine.Event.AgentReportRunning);
                             } catch (OperationTimedoutException e) {
                                 s_logger.error("Exception during update for running vm: " + vm, e);
                                 return null;
@@ -3241,7 +3334,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
                     vm.setLastHostId(srcHostId);
                     try {
-                        if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
+                        if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, VirtualMachine.Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
                             s_logger.info("Migration cancelled because state has changed: " + vm);
                             throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
                         }
@@ -3289,7 +3382,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                                 } catch (AgentUnavailableException e) {
                                     s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                                 }
-                                cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
+                                cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, VirtualMachine.Event.AgentReportStopped, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
                                 return null;
                             }
                         } catch (OperationTimedoutException e) {
@@ -3310,7 +3403,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                             }
 
                             try {
-                                stateTransitTo(vm, Event.OperationFailed, srcHostId);
+                                stateTransitTo(vm, VirtualMachine.Event.OperationFailed, srcHostId);
                             } catch (NoTransitionException e) {
                                 s_logger.warn(e.getMessage());
                             }
@@ -3659,17 +3752,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     public class VmOutcome extends OutcomeImpl<VirtualMachine> {
         private long _vmId;
 
-        public VmOutcome(final AsyncJob job, final PowerState desiredPowerState, final long vmId) {
+        public VmOutcome(final AsyncJob job, final PowerState desiredPowerState, final long vmId, final Long srcHostIdForMigration) {
             super(VirtualMachine.class, job, _jobCheckInterval.value(), new Predicate() {
                 @Override
                 public boolean checkCondition() {
                     VMInstanceVO instance = _vmDao.findById(vmId);
-                    if (instance.getPowerState() == desiredPowerState)
+                    if (instance.getPowerState() == desiredPowerState && (srcHostIdForMigration != null && instance.getPowerHostId() != srcHostIdForMigration))
                         return true;
 
-                    VmWorkJobVO workJob = _workJobDao.findById(job.getId());
-                    if (workJob.getStatus() != JobInfo.Status.IN_PROGRESS)
-                        return true;
+
 
                     return false;
                 }
@@ -3682,4 +3773,5 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             return _vmDao.findById(_vmId);
         }
     }
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java b/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java
index 3de9c16..f869bf6 100644
--- a/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java
+++ b/engine/orchestration/src/com/cloud/vm/VmWorkJobDispatcher.java
@@ -30,9 +30,8 @@ import org.apache.cloudstack.framework.jobs.AsyncJob;
 import org.apache.cloudstack.framework.jobs.AsyncJobDispatcher;
 import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 import org.apache.cloudstack.jobs.JobInfo;
+import org.apache.cloudstack.utils.GsonUtils;
 
-import com.cloud.api.StringMapTypeAdapter;
-import com.cloud.user.dao.AccountDao;
 import com.cloud.utils.component.AdapterBase;
 import com.cloud.utils.db.EntityManager;
 import com.cloud.vm.dao.VMInstanceDao;
@@ -44,7 +43,7 @@ public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatch
     static {
         GsonBuilder gBuilder = new GsonBuilder();
         gBuilder.setVersion(1.3);
-        gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter());
+        gBuilder.registerTypeAdapter(Map.class, new GsonUtils.StringMapTypeAdapter());
         s_gson = gBuilder.create();
     }
 
@@ -61,11 +60,11 @@ public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatch
     public static final String VM_WORK_JOB_WAKEUP_DISPATCHER = "VmWorkJobWakeupDispatcher";
     public final static String Start = "start";
     public final static String Stop = "stop";
+    public final static String Migrate = "migrate";
 
     @Inject
     private VirtualMachineManagerImpl _vmMgr;
 	@Inject private AsyncJobManager _asyncJobMgr;
-    @Inject private AccountDao _accountDao;
     @Inject private VMInstanceDao _instanceDao;
     @Inject
     private EntityManager _entityMgr;
@@ -97,7 +96,7 @@ public class VmWorkJobDispatcher extends AdapterBase implements AsyncJobDispatch
                 _vmMgr.orchestrateStart(vm.getUuid(), start.getParams(), start.getPlan());
             } else if (cmd.equals(Stop)) {
                 VmWorkStop stop = (VmWorkStop)work;
-                _vmMgr.orchestrateStop(vm.getUuid(), stop.isForceStop());
+                _vmMgr.orchestrateStop(vm.getUuid(), stop.isCleanup());
             }
             _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, null);
         } catch(Throwable e) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java b/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java
new file mode 100644
index 0000000..85892fd
--- /dev/null
+++ b/engine/orchestration/src/com/cloud/vm/VmWorkMigrate.java
@@ -0,0 +1,78 @@
+// 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.vm;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.Pod;
+import com.cloud.deploy.DeployDestination;
+import com.cloud.host.Host;
+import com.cloud.org.Cluster;
+import com.cloud.storage.StoragePool;
+import com.cloud.storage.Volume;
+import com.cloud.utils.db.EntityManager;
+
+public class VmWorkMigrate extends VmWork {
+    Long zoneId;
+    Long podId;
+    Long clusterId;
+    Long hostId;
+    private Map<String, String> storage;
+
+    public VmWorkMigrate(long userId, long accountId, long vmId, DeployDestination dst) {
+        super(userId, accountId, vmId);
+        zoneId = dst.getDataCenter() != null ? dst.getDataCenter().getId() : null;
+        podId = dst.getPod() != null ? dst.getPod().getId() : null;
+        clusterId = dst.getCluster() != null ? dst.getCluster().getId() : null;
+        hostId = dst.getHost() != null ? dst.getHost().getId() : null;
+        if (dst.getStorageForDisks() != null) {
+            storage = new HashMap<String, String>(dst.getStorageForDisks().size());
+            for (Map.Entry<Volume, StoragePool> entry : dst.getStorageForDisks().entrySet()) {
+                storage.put(entry.getKey().getUuid(), entry.getValue().getUuid());
+            }
+        } else {
+            storage = null;
+        }
+    }
+
+    public DeployDestination getDeployDestination() {
+        DataCenter zone = zoneId != null ? s_entityMgr.findById(DataCenter.class, zoneId) : null;
+        Pod pod = podId != null ? s_entityMgr.findById(Pod.class, podId) : null;
+        Cluster cluster = clusterId != null ? s_entityMgr.findById(Cluster.class, clusterId) : null;
+        Host host = hostId != null ? s_entityMgr.findById(Host.class, hostId) : null;
+        
+        Map<Volume, StoragePool> vols = null;
+
+        if (storage != null) {
+            vols = new HashMap<Volume, StoragePool>(storage.size());
+            for (Map.Entry<String, String> entry : storage.entrySet()) {
+                vols.put(s_entityMgr.findByUuid(Volume.class, entry.getKey()), s_entityMgr.findByUuid(StoragePool.class, entry.getValue()));
+            }
+        }
+
+        DeployDestination dest = new DeployDestination(zone, pod, cluster, host, vols);
+        return dest;
+    }
+
+    static private EntityManager s_entityMgr;
+
+    static public void init(EntityManager entityMgr) {
+        s_entityMgr = entityMgr;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/orchestration/src/com/cloud/vm/VmWorkStart.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkStart.java b/engine/orchestration/src/com/cloud/vm/VmWorkStart.java
index 107009e..f8e7c43 100644
--- a/engine/orchestration/src/com/cloud/vm/VmWorkStart.java
+++ b/engine/orchestration/src/com/cloud/vm/VmWorkStart.java
@@ -21,9 +21,10 @@ import java.io.Serializable;
 import java.util.HashMap;
 import java.util.Map;
 
+import org.apache.log4j.Logger;
+
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper;
-import org.apache.log4j.Logger;
 
 import com.cloud.deploy.DataCenterDeployment;
 import com.cloud.deploy.DeploymentPlan;
@@ -47,7 +48,8 @@ public class VmWorkStart extends VmWork {
 	// use serialization friendly map
 	private Map<String, String> rawParams;
 
-	public VmWorkStart() {
+    public VmWorkStart(long userId, long accountId, long vmId) {
+        super(userId, accountId, vmId);
 	}
 
 	public DeploymentPlan getPlan() {
@@ -62,7 +64,7 @@ public class VmWorkStart extends VmWork {
 			}
 			
 			DeploymentPlan plan = new DataCenterDeployment(
-					dcId, podId, clusterId, hostId, poolId, physicalNetworkId, 
+					dcId, podId, clusterId, hostId, poolId, physicalNetworkId,
 					context);
 			return plan;
 		}
@@ -90,7 +92,7 @@ public class VmWorkStart extends VmWork {
 	}
 
 	public void setRawParams(Map<String, String> params) {
-		this.rawParams = params;
+		rawParams = params;
 	}
 	
 	public Map<VirtualMachineProfile.Param, Object> getParams() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/orchestration/src/com/cloud/vm/VmWorkStop.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VmWorkStop.java b/engine/orchestration/src/com/cloud/vm/VmWorkStop.java
index d6d226f..2312f24 100644
--- a/engine/orchestration/src/com/cloud/vm/VmWorkStop.java
+++ b/engine/orchestration/src/com/cloud/vm/VmWorkStop.java
@@ -18,17 +18,14 @@ package com.cloud.vm;
 
 public class VmWorkStop extends VmWork {
 
-	private boolean forceStop;
+	private final boolean cleanup;
 	
-	public VmWorkStop() {
-		forceStop = false;
+    public VmWorkStop(long userId, long accountId, long vmId, boolean cleanup) {
+        super(userId, accountId, vmId);
+        this.cleanup = cleanup;
 	}
 	
-	public void setForceStop(boolean value) {
-		forceStop = value;
-	}
-	
-	public boolean isForceStop() {
-		return forceStop;
+	public boolean isCleanup() {
+		return cleanup;
 	}
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/engine/schema/src/org/apache/cloudstack/vm/jobs/VmWorkJobVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/org/apache/cloudstack/vm/jobs/VmWorkJobVO.java b/engine/schema/src/org/apache/cloudstack/vm/jobs/VmWorkJobVO.java
index ca52263..e8c0304 100644
--- a/engine/schema/src/org/apache/cloudstack/vm/jobs/VmWorkJobVO.java
+++ b/engine/schema/src/org/apache/cloudstack/vm/jobs/VmWorkJobVO.java
@@ -35,14 +35,26 @@ import com.cloud.vm.VirtualMachine;
 @PrimaryKeyJoinColumn(name="id")
 public class VmWorkJobVO extends AsyncJobVO {
 
+    // These steps are rather arbiturary.  What's recorded depends on the
+    // the operation being performed.
 	public enum Step {
-        Prepare,
-        Starting,
-        Started,
-        Release,
-        Done,
-        Migrating,
-        Reconfiguring
+        Prepare(false),
+        Starting(true),
+        Started(false),
+        Release(false),
+        Done(false),
+        Migrating(true),
+        Reconfiguring(false),
+        Error(false);
+        
+        boolean updateState; // Should the VM State be updated after this step?
+        private Step(boolean updateState) {
+            this.updateState = updateState;
+        }
+        
+        boolean updateState() {
+            return updateState;
+        }
     }
 	
     @Column(name="step")

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java
----------------------------------------------------------------------
diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java
index f172581..bc06101 100644
--- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java
+++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/AsyncJobManager.java
@@ -117,8 +117,7 @@ public interface AsyncJobManager extends Manager {
      * @return true, predicate condition is satisfied
      * 			false, wait is timed out
      */
-    @Deprecated
-    boolean waitAndCheck(String[] wakupTopicsOnMessageBus, long checkIntervalInMilliSeconds,
+    boolean waitAndCheck(AsyncJob job, String[] wakupTopicsOnMessageBus, long checkIntervalInMilliSeconds,
     	long timeoutInMiliseconds, Predicate predicate);
 
     AsyncJob queryJob(long jobId, boolean updatePollTime);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java
----------------------------------------------------------------------
diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java
index 4dee7e9..f65e25e 100644
--- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java
+++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java
@@ -19,6 +19,7 @@ package org.apache.cloudstack.framework.jobs.impl;
 
 import java.io.File;
 import java.io.FileInputStream;
+import java.util.Arrays;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -582,17 +583,26 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager,
     }
     
     @Override
-    public boolean waitAndCheck(String[] wakupTopicsOnMessageBus, long checkIntervalInMilliSeconds,
+    public boolean waitAndCheck(AsyncJob job, String[] wakeupTopicsOnMessageBus, long checkIntervalInMilliSeconds,
         long timeoutInMiliseconds, Predicate predicate) {
     	
     	MessageDetector msgDetector = new MessageDetector();
-    	msgDetector.open(_messageBus, wakupTopicsOnMessageBus);
+        String[] topics = Arrays.copyOf(wakeupTopicsOnMessageBus, wakeupTopicsOnMessageBus.length + 1);
+        topics[topics.length - 1] = AsyncJob.Topics.JOB_STATE;
+
+        msgDetector.open(_messageBus, topics);
     	try {
     		long startTick = System.currentTimeMillis();
     		while(System.currentTimeMillis() - startTick < timeoutInMiliseconds) {
     			msgDetector.waitAny(checkIntervalInMilliSeconds);
-    			if(predicate.checkCondition())
+                job = _jobDao.findById(job.getId());
+                if (job.getStatus().done()) {
+                    return true;
+                }
+
+                if (predicate.checkCondition()) {
     				return true;
+                }
     		}
     	} finally {
     		msgDetector.close();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java
----------------------------------------------------------------------
diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java
index 8a8b8d6..c65d9c5 100644
--- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java
+++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/OutcomeImpl.java
@@ -22,7 +22,6 @@ import java.util.concurrent.TimeoutException;
 
 import org.apache.cloudstack.framework.jobs.AsyncJob;
 import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
-import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 import org.apache.cloudstack.framework.jobs.Outcome;
 
 import com.cloud.utils.Predicate;
@@ -36,9 +35,9 @@ public class OutcomeImpl<T> implements Outcome<T> {
 
     protected T _result;
 
-    private static AsyncJobManager s_jobMgr;
+    private static AsyncJobManagerImpl s_jobMgr;
 
-    public static void init(AsyncJobManager jobMgr) {
+    public static void init(AsyncJobManagerImpl jobMgr) {
         s_jobMgr = jobMgr;
     }
 
@@ -62,7 +61,7 @@ public class OutcomeImpl<T> implements Outcome<T> {
 
     @Override
     public T get() throws InterruptedException, ExecutionException {
-        s_jobMgr.waitAndCheck(_topics, _checkIntervalInMs, -1, _predicate);
+        s_jobMgr.waitAndCheck(getJob(), _topics, _checkIntervalInMs, -1, _predicate);
         try {
             AsyncJobExecutionContext.getCurrentExecutionContext().disjoinJob(_job.getId());
         } catch (Throwable e) {
@@ -74,7 +73,7 @@ public class OutcomeImpl<T> implements Outcome<T> {
 
     @Override
     public T get(long timeToWait, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
-        s_jobMgr.waitAndCheck(_topics, _checkIntervalInMs, unit.toMillis(timeToWait), _predicate);
+        s_jobMgr.waitAndCheck(getJob(), _topics, _checkIntervalInMs, unit.toMillis(timeToWait), _predicate);
         try {
             AsyncJobExecutionContext.getCurrentExecutionContext().disjoinJob(_job.getId());
         } catch (Throwable e) {
@@ -120,4 +119,7 @@ public class OutcomeImpl<T> implements Outcome<T> {
 
     }
 
+    public Predicate getPredicate() {
+        return _predicate;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/server/src/com/cloud/api/ApiGsonHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiGsonHelper.java b/server/src/com/cloud/api/ApiGsonHelper.java
index c24808b..8b1fb16 100644
--- a/server/src/com/cloud/api/ApiGsonHelper.java
+++ b/server/src/com/cloud/api/ApiGsonHelper.java
@@ -30,6 +30,7 @@ import org.apache.log4j.Logger;
 import com.google.gson.GsonBuilder;
 
 import org.apache.cloudstack.api.ResponseObject;
+import org.apache.cloudstack.utils.GsonUtils;
 
 import com.cloud.serializer.Param;
 import com.cloud.utils.DateUtil;
@@ -42,7 +43,7 @@ public class ApiGsonHelper {
         s_gBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
         s_gBuilder.setVersion(1.3);
         s_gBuilder.registerTypeAdapter(ResponseObject.class, new ResponseObjectTypeAdapter());
-        s_gBuilder.registerTypeAdapter(Map.class, new StringMapTypeAdapter());
+        s_gBuilder.registerTypeAdapter(Map.class, new GsonUtils.StringMapTypeAdapter());
     }
 
     public static GsonBuilder getBuilder() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 32ba298..52580b6 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -62,6 +62,7 @@ import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity;
 import org.apache.cloudstack.engine.service.api.OrchestrationService;
 import org.apache.cloudstack.framework.jobs.AsyncJobManager;
+import org.apache.cloudstack.framework.jobs.Outcome;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 
@@ -3885,7 +3886,14 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         if (uservm != null) {
             collectVmDiskStatistics(uservm);
         }
-        return _itMgr.migrate(vm.getUuid(), srcHostId, dest);
+        Outcome<VirtualMachine> outcome = _itMgr.migrate(vm.getUuid(), srcHostId, dest);
+        try {
+            return outcome.get();
+        } catch (InterruptedException e) {
+            throw new CloudRuntimeException("Interrupted while waiting for the outcome of " + outcome.getJob());
+        } catch (java.util.concurrent.ExecutionException e) {
+            throw new CloudRuntimeException("Unable to start virtual machine", e.getCause());
+        }
     }
 
     private boolean checkIfHostIsDedicated(HostVO host) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/utils/src/com/cloud/api/StringMapTypeAdapter.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/api/StringMapTypeAdapter.java b/utils/src/com/cloud/api/StringMapTypeAdapter.java
deleted file mode 100644
index 55f4ae3..0000000
--- a/utils/src/com/cloud/api/StringMapTypeAdapter.java
+++ /dev/null
@@ -1,46 +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.api;
-
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import com.google.gson.JsonDeserializationContext;
-import com.google.gson.JsonDeserializer;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-
-@SuppressWarnings("rawtypes")
-public class StringMapTypeAdapter implements JsonDeserializer<Map> {
-    @Override
-    
-    public Map deserialize(JsonElement src, Type srcType,
-            JsonDeserializationContext context) throws JsonParseException {
-
-        Map<String, String> obj = new HashMap<String, String>();
-        JsonObject json = src.getAsJsonObject();
-        
-        for(Entry<String, JsonElement> entry : json.entrySet()) {
-            obj.put(entry.getKey(), entry.getValue().getAsString());
-        }
-        
-        return obj;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95fe42cc/utils/src/org/apache/cloudstack/utils/GsonUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/utils/GsonUtils.java b/utils/src/org/apache/cloudstack/utils/GsonUtils.java
new file mode 100644
index 0000000..7d50c7d
--- /dev/null
+++ b/utils/src/org/apache/cloudstack/utils/GsonUtils.java
@@ -0,0 +1,48 @@
+// 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.utils;
+
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+
+@SuppressWarnings("rawtypes")
+
+public class GsonUtils {
+    public static class StringMapTypeAdapter implements JsonDeserializer<Map> {
+        
+        @Override
+        public Map deserialize(JsonElement src, Type srcType, JsonDeserializationContext context) throws JsonParseException {
+
+            Map<String, String> obj = new HashMap<String, String>();
+            JsonObject json = src.getAsJsonObject();
+
+            for (Entry<String, JsonElement> entry : json.entrySet()) {
+                obj.put(entry.getKey(), entry.getValue().getAsString());
+            }
+
+            return obj;
+        }
+    }
+}
\ No newline at end of file


[38/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/VolumeManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/VolumeManagerImpl.java
index 8726465,4e7b335..235adf6
--- a/server/src/com/cloud/storage/VolumeManagerImpl.java
+++ b/server/src/com/cloud/storage/VolumeManagerImpl.java
@@@ -36,6 -31,6 +31,7 @@@ import java.util.concurrent.ExecutionEx
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
++import org.apache.commons.lang.StringUtils;
  import org.apache.log4j.Logger;
  import org.springframework.stereotype.Component;
  
@@@ -43,12 -38,13 +39,12 @@@ import org.apache.cloudstack.api.BaseCm
  import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
  import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
  import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
+ import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd;
  import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd;
  import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.UpdateVolumeCmd;
  import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd;
 -
 -import com.cloud.storage.dao.*;
 -import org.apache.cloudstack.api.command.user.volume.*;
 +import org.apache.cloudstack.context.CallContext;
- 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.DataStoreProviderManager;
@@@ -66,20 -60,32 +60,30 @@@ import org.apache.cloudstack.engine.sub
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
  import org.apache.cloudstack.framework.async.AsyncCallFuture;
 +import org.apache.cloudstack.framework.jobs.AsyncJob;
 +import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
+ import org.apache.cloudstack.storage.command.AttachAnswer;
+ import org.apache.cloudstack.storage.command.AttachCommand;
+ import org.apache.cloudstack.storage.command.CommandResult;
+ import org.apache.cloudstack.storage.command.DettachCommand;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+ 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.datastore.db.VolumeDataStoreVO;
+ import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
- import com.cloud.agent.api.AttachVolumeAnswer;
- import com.cloud.agent.api.AttachVolumeCommand;
+ import com.cloud.agent.api.storage.CreateVolumeOVAAnswer;
+ import com.cloud.agent.api.storage.CreateVolumeOVACommand;
+ import com.cloud.agent.api.to.DataTO;
+ import com.cloud.agent.api.to.DiskTO;
  import com.cloud.agent.api.to.VirtualMachineTO;
- import com.cloud.agent.api.to.VolumeTO;
  import com.cloud.alert.AlertManager;
  import com.cloud.api.ApiDBUtils;
 -import com.cloud.async.AsyncJobExecutor;
 -import com.cloud.async.AsyncJobManager;
 -import com.cloud.async.AsyncJobVO;
 -import com.cloud.async.BaseAsyncJobExecutor;
  import com.cloud.capacity.CapacityManager;
  import com.cloud.capacity.dao.CapacityDao;
  import com.cloud.configuration.Config;
@@@ -135,8 -140,6 +138,7 @@@ import com.cloud.storage.dao.VMTemplate
  import com.cloud.storage.dao.VMTemplateS3Dao;
  import com.cloud.storage.dao.VMTemplateSwiftDao;
  import com.cloud.storage.dao.VolumeDao;
 +import com.cloud.storage.dao.VolumeDetailsDao;
- import com.cloud.storage.dao.VolumeHostDao;
  import com.cloud.storage.download.DownloadMonitor;
  import com.cloud.storage.s3.S3Manager;
  import com.cloud.storage.secondary.SecondaryStorageVmManager;
@@@ -333,8 -341,7 +339,7 @@@ public class VolumeManagerImpl extends 
      private final int _customDiskOfferingMaxSize = 1024;
      private long _maxVolumeSizeInGb;
      private boolean _recreateSystemVmEnabled;
-     protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
 -
 +    
      public VolumeManagerImpl() {
          _volStateMachine = Volume.State.getStateMachine();
      }
@@@ -509,9 -516,10 +514,10 @@@
          newVol.setDeviceId(oldVol.getDeviceId());
          newVol.setInstanceId(oldVol.getInstanceId());
          newVol.setRecreatable(oldVol.isRecreatable());
+         newVol.setFormat(oldVol.getFormat());
          return _volsDao.persist(newVol);
      }
 -
 +    
      @DB
      protected VolumeInfo createVolumeFromSnapshot(VolumeVO volume,
              SnapshotVO snapshot) {
@@@ -538,13 -546,13 +544,13 @@@
              while ((pool = storageMgr.findStoragePool(dskCh, dc, pod.first(), null, null,
                      null, poolsToAvoid)) != null) {
                  break;
 -
 +                
              }
          }
 -
 +        
          VolumeInfo vol = volFactory.getVolume(volume.getId());
          DataStore store = dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
-         SnapshotInfo snapInfo = snapshotFactory.getSnapshot(snapshot.getId());
+         SnapshotInfo snapInfo = snapshotFactory.getSnapshot(snapshot.getId(), DataStoreRole.Image);
          AsyncCallFuture<VolumeApiResult> future = volService.createVolumeFromSnapshot(vol, store, snapInfo);
          try {
              VolumeApiResult result = future.get();
@@@ -742,15 -744,11 +742,11 @@@
          // volume.setSize(size);
          volume.setInstanceId(null);
          volume.setUpdated(new Date());
- 
+         volume.setDomainId((owner == null) ? Domain.ROOT_DOMAIN : owner
+                 .getDomainId());
+         volume.setFormat(ImageFormat.valueOf(format));
          volume = _volsDao.persist(volume);
-         try {
-             stateTransitTo(volume, Event.UploadRequested);
-         } catch (NoTransitionException e) {
-             // TODO Auto-generated catch block
-             e.printStackTrace();
-         }
 -        UserContext.current().setEventDetails("Volume Id: " + volume.getId());
 +        CallContext.current().setEventDetails("Volume Id: " + volume.getId());
  
          // Increment resource count during allocation; if actual creation fails,
          // decrement it
@@@ -1370,6 -1369,7 +1367,7 @@@
              vol.setDeviceId(1l);
          }
  
 -        vol.setFormat(this.getSupportedImageFormatForCluster(vm.getHypervisorType()));
++        vol.setFormat(getSupportedImageFormatForCluster(vm.getHypervisorType()));
          vol = _volsDao.persist(vol);
  
          // Save usage event and update resource count for user vm volumes
@@@ -1399,6 -1399,7 +1397,7 @@@
  
          VolumeVO vol = new VolumeVO(type, name, vm.getDataCenterId(),
                  owner.getDomainId(), owner.getId(), offering.getId(), size);
 -        vol.setFormat(this.getSupportedImageFormatForCluster(template.getHypervisorType()));
++        vol.setFormat(getSupportedImageFormatForCluster(template.getHypervisorType()));
          if (vm != null) {
              vol.setInstanceId(vm.getId());
          }
@@@ -1437,18 -1438,16 +1436,16 @@@
          }
          return toDiskProfile(vol, offering);
      }
 -
 + 
-     private String getSupportedImageFormatForCluster(Long clusterId) {
-         ClusterVO cluster = ApiDBUtils.findClusterById(clusterId);
- 
-         if (cluster.getHypervisorType() == HypervisorType.XenServer) {
-             return "vhd";
-         } else if (cluster.getHypervisorType() == HypervisorType.KVM) {
-             return "qcow2";
-         } else if (cluster.getHypervisorType() == HypervisorType.VMware) {
-             return "ova";
-         } else if (cluster.getHypervisorType() == HypervisorType.Ovm) {
-             return "raw";
+     private  ImageFormat getSupportedImageFormatForCluster(HypervisorType hyperType) {
+         if (hyperType == HypervisorType.XenServer) {
+             return ImageFormat.VHD;
+         } else if (hyperType == HypervisorType.KVM) {
+             return ImageFormat.QCOW2;
+         } else if (hyperType == HypervisorType.VMware) {
+             return ImageFormat.OVA;
+         } else if (hyperType == HypervisorType.Ovm) {
+             return ImageFormat.RAW;
          } else {
              return null;
          }
@@@ -1513,7 -1510,11 +1508,11 @@@
                          ResourceType.primary_storage, new Long(volume.getSize()));
              }
          }
-         return vol;
+ 
 -        VolumeVO volVO = this._volsDao.findById(vol.getId());
 -        volVO.setFormat(this.getSupportedImageFormatForCluster(rootDiskHyperType));
 -        this._volsDao.update(volVO.getId(), volVO);
 -        return this.volFactory.getVolume(volVO.getId());
++        VolumeVO volVO = _volsDao.findById(vol.getId());
++        volVO.setFormat(getSupportedImageFormatForCluster(rootDiskHyperType));
++        _volsDao.update(volVO.getId(), volVO);
++        return volFactory.getVolume(volVO.getId());
      }
  
      private boolean needMoveVolume(VolumeVO rootVolumeOfVm, VolumeInfo volume) {
@@@ -2246,20 -2239,14 +2226,14 @@@
          if (vm.getType() == VirtualMachine.Type.User) {
              UserVmVO userVM = (UserVmVO) vm.getVirtualMachine();
              if (userVM.getIsoId() != null) {
-                 Pair<String, String> isoPathPair = _tmpltMgr.getAbsoluteIsoPath(
-                         userVM.getIsoId(), userVM.getDataCenterId());
-                 if (isoPathPair != null) {
-                     String isoPath = isoPathPair.first();
-                     VolumeTO iso = new VolumeTO(vm.getId(), Volume.Type.ISO,
-                             StoragePoolType.ISO, null, null, null, isoPath, 0,
-                             null, null);
+                 DataTO dataTO = tmplFactory.getTemplate(userVM.getIsoId(), DataStoreRole.Image, userVM.getDataCenterId()).getTO();
+                 DiskTO iso = new DiskTO(dataTO, 3L, Volume.Type.ISO);
 -                vm.addDisk(iso);
 +                    vm.addDisk(iso);
 +                }
              }
          }
--    }
 -
  
 +   
  
      private static enum VolumeTaskType {
          RECREATE,
@@@ -2470,10 -2457,12 +2444,12 @@@
                  pool = (StoragePool)dataStoreMgr.getDataStore(result.second().getId(), DataStoreRole.Primary);
                  vol = result.first();
              }
-             vm.addDisk(new VolumeTO(vol, pool));
+             DataTO volumeTO = volFactory.getVolume(vol.getId()).getTO();
+             DiskTO disk = new DiskTO(volumeTO, vol.getDeviceId(), vol.getVolumeType());
+             vm.addDisk(disk);
          }
      }
 -
 +    
      private Long getDeviceId(long vmId, Long deviceId) {
          // allocate deviceId
          List<VolumeVO> vols = _volsDao.findByInstance(vmId);
@@@ -2509,49 -2498,9 +2485,9 @@@
          return _volStateMachine.transitTo(vol, event, null, _volsDao);
      }
  
 +    
-     private String validateUrl(String url) {
-         try {
-             URI uri = new URI(url);
-             if ((uri.getScheme() == null)
-                     || (!uri.getScheme().equalsIgnoreCase("http")
-                             && !uri.getScheme().equalsIgnoreCase("https") && !uri
-                             .getScheme().equalsIgnoreCase("file"))) {
-                 throw new IllegalArgumentException(
-                         "Unsupported scheme for url: " + url);
-             }
  
-             int port = uri.getPort();
-             if (!(port == 80 || port == 443 || port == -1)) {
-                 throw new IllegalArgumentException(
-                         "Only ports 80 and 443 are allowed");
-             }
-             String host = uri.getHost();
-             try {
-                 InetAddress hostAddr = InetAddress.getByName(host);
-                 if (hostAddr.isAnyLocalAddress()
-                         || hostAddr.isLinkLocalAddress()
-                         || hostAddr.isLoopbackAddress()
-                         || hostAddr.isMulticastAddress()) {
-                     throw new IllegalArgumentException(
-                             "Illegal host specified in url");
-                 }
-                 if (hostAddr instanceof Inet6Address) {
-                     throw new IllegalArgumentException(
-                             "IPV6 addresses not supported ("
-                                     + hostAddr.getHostAddress() + ")");
-                 }
-             } catch (UnknownHostException uhe) {
-                 throw new IllegalArgumentException("Unable to resolve " + host);
-             }
--
-             return uri.toString();
-         } catch (URISyntaxException e) {
-             throw new IllegalArgumentException("Invalid URL " + url);
-         }
--
-     }
 +    
      @Override
      public boolean canVmRestartOnAnotherServer(long vmId) {
          List<VolumeVO> vols = _volsDao.findCreatedByInstance(vmId);
@@@ -2628,6 -2562,188 +2549,188 @@@
  
  
      @Override
+     public Snapshot takeSnapshot(Long volumeId, Long policyId, Long snapshotId, Account account) throws ResourceAllocationException {
+         VolumeInfo volume = volFactory.getVolume(volumeId);
+         if (volume == null) {
+             throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
+         }
+ 
+         if (volume.getState() != Volume.State.Ready) {
+             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
+         }
+ 
+         CreateSnapshotPayload payload = new CreateSnapshotPayload();
+         payload.setSnapshotId(snapshotId);
+         payload.setSnapshotPolicyId(policyId);
+         payload.setAccount(account);
+         volume.addPayload(payload);
+         return volService.takeSnapshot(volume);
+     }
+ 
+     @Override
+     public Snapshot allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException {
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+ 
+         VolumeInfo volume = volFactory.getVolume(volumeId);
+         if (volume == null) {
+             throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
+         }
+         DataCenter zone = _dcDao.findById(volume.getDataCenterId());
+         if (zone == null) {
+             throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
+         }
+ 
+         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) {
+             throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
+         }
+ 
+         if (volume.getState() != Volume.State.Ready) {
+             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
+         }
+ 
+         if ( volume.getTemplateId() != null ) {
+             VMTemplateVO  template = _templateDao.findById(volume.getTemplateId());
+             if( template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM ) {
+                 throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
+             }
+         }
+ 
+         StoragePool storagePool = (StoragePool)volume.getDataStore();
+         if (storagePool == null) {
+             throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
+         }
+ 
+         return snapshotMgr.allocSnapshot(volumeId, policyId);
+     }
+ 
+ 
+     @Override
+     @ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
+     public String extractVolume(ExtractVolumeCmd cmd) {
+         Long volumeId = cmd.getId();
+         Long zoneId = cmd.getZoneId();
+         String mode = cmd.getMode();
 -        Account account = UserContext.current().getCaller();
++        Account account = CallContext.current().getCallingAccount();
+ 
+         if (!_accountMgr.isRootAdmin(account.getType()) && ApiDBUtils.isExtractionDisabled()) {
+             throw new PermissionDeniedException("Extraction has been disabled by admin");
+         }
+ 
+         VolumeVO volume = _volumeDao.findById(volumeId);
+         if (volume == null) {
+             InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
+             ex.addProxyObject(volumeId.toString(), "volumeId");
+             throw ex;
+         }
+ 
+         // perform permission check
+         _accountMgr.checkAccess(account, null, true, volume);
+ 
+         if (_dcDao.findById(zoneId) == null) {
+             throw new InvalidParameterValueException("Please specify a valid zone.");
+         }
+         if (volume.getPoolId() == null) {
+             throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
+         }
+         // Extract activity only for detached volumes or for volumes whose
+         // instance is stopped
+         if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
+             s_logger.debug("Invalid state of the volume with ID: " + volumeId
+                     + ". It should be either detached or the VM should be in stopped state.");
+             PermissionDeniedException ex = new PermissionDeniedException(
+                     "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
+             ex.addProxyObject(volume.getUuid(), "volumeId");
+             throw ex;
+         }
+ 
+         if (volume.getVolumeType() != Volume.Type.DATADISK) {
+             // Datadisk dont have any template dependence.
+ 
+             VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
+             if (template != null) { // For ISO based volumes template = null and
+                 // we allow extraction of all ISO based
+                 // volumes
+                 boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
+                 if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) {
+                     // Global admins are always allowed to extract
+                     PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
+                     ex.addProxyObject(volume.getUuid(), "volumeId");
+                     throw ex;
+                 }
+             }
+         }
+ 
+         Upload.Mode extractMode;
+         if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) {
+             throw new InvalidParameterValueException("Please specify a valid extract Mode ");
+         } else {
+             extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD;
+         }
+ 
+         // Clean up code to remove all those previous uploadVO and uploadMonitor code. Previous code is trying to fake an async operation purely in
+         // db table with uploadVO and async_job entry, but internal implementation is actually synchronous.
 -        StoragePool srcPool = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
 -        ImageStoreEntity secStore = (ImageStoreEntity) this.dataStoreMgr.getImageStore(zoneId);
++        StoragePool srcPool = (StoragePool) dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
++        ImageStoreEntity secStore = (ImageStoreEntity) dataStoreMgr.getImageStore(zoneId);
+         String secondaryStorageURL = secStore.getUri();
+ 
 -        String value = this._configDao.getValue(Config.CopyVolumeWait.toString());
++        String value = _configDao.getValue(Config.CopyVolumeWait.toString());
+         int copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue()));
+         // Copy volume from primary to secondary storage
 -        VolumeInfo srcVol = this.volFactory.getVolume(volume.getId());
 -        AsyncCallFuture<VolumeApiResult> cvAnswer = this.volService.copyVolume(srcVol, secStore);
++        VolumeInfo srcVol = volFactory.getVolume(volume.getId());
++        AsyncCallFuture<VolumeApiResult> cvAnswer = volService.copyVolume(srcVol, secStore);
+         // Check if you got a valid answer.
+         VolumeApiResult cvResult = null;
+         try {
+             cvResult = cvAnswer.get();
+         } catch (InterruptedException e1) {
+             s_logger.debug("failed copy volume", e1);
+             throw new CloudRuntimeException("Failed to copy volume", e1);
+         } catch (ExecutionException e1) {
+             s_logger.debug("failed copy volume", e1);
+             throw new CloudRuntimeException("Failed to copy volume", e1);
+         }
+         if (cvResult == null || cvResult.isFailed()) {
+             String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage.";
+             throw new CloudRuntimeException(errorString);
+         }
+ 
+         VolumeInfo vol = cvResult.getVolume();
+         String volumeLocalPath = vol.getPath();
+         String volumeName = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(volumeLocalPath, "/"), ".");
+         // volss, handle the ova special case;
+         if (getFormatForPool(srcPool) == "ova") {
+             // TODO: need to handle this for S3 as secondary storage
+             CreateVolumeOVACommand cvOVACmd = new CreateVolumeOVACommand(secondaryStorageURL, volumeLocalPath, volumeName, srcPool, copyvolumewait);
+             CreateVolumeOVAAnswer OVAanswer = null;
+ 
+             try {
+                 cvOVACmd.setContextParam("hypervisor", HypervisorType.VMware.toString());
+                 // for extract volume, create the ova file here;
+                 OVAanswer = (CreateVolumeOVAAnswer) storageMgr.sendToPool(srcPool, cvOVACmd);
+             } catch (StorageUnavailableException e) {
+                 s_logger.debug("Storage unavailable");
+             }
+         }
+         return secStore.createEntityExtractUrl(vol.getPath(), vol.getFormat());
+     }
+ 
+     private String getFormatForPool(StoragePool pool) {
+         ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId());
+ 
+         if (cluster.getHypervisorType() == HypervisorType.XenServer) {
+             return "vhd";
+         } else if (cluster.getHypervisorType() == HypervisorType.KVM) {
+             return "qcow2";
+         } else if (cluster.getHypervisorType() == HypervisorType.VMware) {
+             return "ova";
+         } else if (cluster.getHypervisorType() == HypervisorType.Ovm) {
+             return "raw";
+         } else {
+             return null;
+         }
+     }
+ 
+     @Override
      public String getVmNameFromVolumeId(long volumeId) {
          Long instanceId;
          VolumeVO volume = _volsDao.findById(volumeId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
index d4e360a,954c7e9..59aa6b3
--- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
+++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
@@@ -29,9 -29,12 +29,14 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
 +import org.apache.log4j.Logger;
 +
 +import org.apache.cloudstack.context.CallContext;
+ 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.ZoneScope;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
 -import org.apache.log4j.Logger;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
@@@ -47,7 -50,9 +52,7 @@@ import com.cloud.agent.api.StartupSecon
  import com.cloud.agent.api.StopAnswer;
  import com.cloud.agent.api.check.CheckSshAnswer;
  import com.cloud.agent.api.check.CheckSshCommand;
+ import com.cloud.agent.api.to.NfsTO;
 -import com.cloud.agent.api.to.NicTO;
 -import com.cloud.agent.api.to.VirtualMachineTO;
  import com.cloud.agent.manager.Commands;
  import com.cloud.capacity.dao.CapacityDao;
  import com.cloud.cluster.ClusterManager;
@@@ -108,9 -112,8 +107,9 @@@ import com.cloud.utils.DateUtil
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.Pair;
  import com.cloud.utils.component.ManagerBase;
++import com.cloud.utils.db.EntityManager;
  import com.cloud.utils.db.GlobalLock;
  import com.cloud.utils.db.SearchCriteria.Op;
- import com.cloud.utils.db.EntityManager;
  import com.cloud.utils.db.SearchCriteria2;
  import com.cloud.utils.db.SearchCriteriaService;
  import com.cloud.utils.events.SubscriptionMgr;
@@@ -227,9 -223,15 +219,15 @@@ public class SecondaryStorageManagerImp
      protected IPAddressDao _ipAddressDao = null;
      @Inject
      protected RulesManager _rulesMgr;
+     @Inject
+     TemplateManager templateMgr;
 -
 +    
      @Inject
      KeystoreManager _keystoreMgr;
+     @Inject
+     DataStoreManager _dataStoreMgr;
+     @Inject
+     ImageStoreDao _imageStoreDao;
      private long _capacityScanInterval = DEFAULT_CAPACITY_SCAN_INTERVAL;
      private int _secStorageVmMtuSize;
  
@@@ -285,24 -292,30 +283,30 @@@
                  return false;
              }
  
-             List<HostVO> ssHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId);
-             for( HostVO ssHost : ssHosts ) {
-                 String secUrl = ssHost.getStorageUrl();
 -            List<DataStore> ssStores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
++            List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
+              for( DataStore ssStore : ssStores ) {
+                  if (!(ssStore.getTO() instanceof NfsTO ))
+                      continue; // only do this for Nfs
+                 String secUrl = ssStore.getUri();
                  SecStorageSetupCommand setupCmd = null;
                  if (!_useSSlCopy) {
-                 	setupCmd = new SecStorageSetupCommand(secUrl, null);
+                 	setupCmd = new SecStorageSetupCommand(ssStore.getTO(), secUrl, null);
                  } else {
                  	Certificates certs = _keystoreMgr.getCertificates(ConsoleProxyManager.CERTIFICATE_NAME);
-                 	setupCmd = new SecStorageSetupCommand(secUrl, certs);
+                 	setupCmd = new SecStorageSetupCommand(ssStore.getTO(), secUrl, certs);
                  }
 -
 +                
                  Answer answer = _agentMgr.easySend(ssHostId, setupCmd);
                  if (answer != null && answer.getResult()) {
                      SecStorageSetupAnswer an = (SecStorageSetupAnswer) answer;
-                     ssHost.setParent(an.get_dir());
-                     _hostDao.update(ssHost.getId(), ssHost);
+                     if (an.get_dir() != null){
+                         // update the parent path in image_store table for this image store
 -                        ImageStoreVO svo = this._imageStoreDao.findById(ssStore.getId());
++                        ImageStoreVO svo = _imageStoreDao.findById(ssStore.getId());
+                         svo.setParent(an.get_dir());
+                         _imageStoreDao.update(ssStore.getId(), svo);
+                     }
                      if (s_logger.isDebugEnabled()) {
-                         s_logger.debug("Successfully programmed secondary storage " + ssHost.getName() + " in secondary storage VM " + secStorageVm.getInstanceName());
+                         s_logger.debug("Successfully programmed secondary storage " + ssStore.getName() + " in secondary storage VM " + secStorageVm.getInstanceName());
                      }
                  } else {
                      if (s_logger.isDebugEnabled()) {
@@@ -330,31 -345,13 +336,13 @@@
                  }
              }
          }
+         */
          return true;
      }
 -
 -
 -
 -
 +    
 +    
-     @Override
-     public boolean deleteHost(Long hostId) {
-         List<SnapshotVO> snapshots = _snapshotDao.listByHostId(hostId);
-         if( snapshots != null && !snapshots.isEmpty()) {
-             throw new CloudRuntimeException("Can not delete this secondary storage since it contains atleast one or more snapshots ");
-         }
-         if (!_swiftMgr.isSwiftEnabled()) {
-             List<Long> list = _templateDao.listPrivateTemplatesByHost(hostId);
-             if (list != null && !list.isEmpty()) {
-                 throw new CloudRuntimeException("Can not delete this secondary storage since it contains private templates ");
-             }
-         }
-         _vmTemplateHostDao.deleteByHost(hostId);
-         HostVO host = _hostDao.findById(hostId);
-         host.setGuid(null);
-         _hostDao.update(hostId, host);
-         _hostDao.remove(hostId);
 +        
-         return true;
-     }
 +    
      @Override
      public boolean generateVMSetupCommand(Long ssAHostId) {
          HostVO ssAHost = _hostDao.findById(ssAHostId);
@@@ -515,8 -512,8 +503,8 @@@
      }
  
      protected Map<String, Object> createSecStorageVmInstance(long dataCenterId, SecondaryStorageVm.Role role) {
-         HostVO secHost = findSecondaryStorageHost(dataCenterId);
-         if (secHost == null) {
 -        DataStore secStore = this._dataStoreMgr.getImageStore(dataCenterId);
++        DataStore secStore = _dataStoreMgr.getImageStore(dataCenterId);
+         if (secStore == null) {
              String msg = "No secondary storage available in zone " + dataCenterId + ", cannot create secondary storage vm";
              s_logger.warn(msg);
              throw new CloudRuntimeException(msg);
@@@ -729,33 -719,30 +714,30 @@@
                  return false;
              }
  
-             boolean templateReady = false;
-             if (template != null) {
-                 VMTemplateHostVO templateHostRef = _vmTemplateHostDao.findByHostTemplate(secHost.getId(), template.getId());
-                 templateReady = (templateHostRef != null) && (templateHostRef.getDownloadState() == Status.DOWNLOADED);
 -            List<DataStore> stores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(dataCenterId));
++            List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dataCenterId));
+             if (stores.size() < 1) {
+                 s_logger.debug("No image store added  in zone " + dataCenterId + ", wait until it is ready to launch secondary storage vm");
+                 return false;
              }
  
-             if (templateReady) {
+             DataStore store = templateMgr.getImageStore(dataCenterId, template.getId());
+             if (store == null) {
+                 if (s_logger.isDebugEnabled()) {
+                     s_logger.debug("No secondary storage available in zone " + dataCenterId + ", wait until it is ready to launch secondary storage vm");
+                 }
+                 return false;
+             }
  
 -            List<Pair<Long, Integer>> l = _storagePoolHostDao.getDatacenterStoragePoolHostInfo(dataCenterId, !_useLocalStorage);
 -            if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
 -                return true;
 -            } else {
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Primary storage is not ready, wait until it is ready to launch secondary storage vm. dcId: " + dataCenterId + " system.vm.use.local.storage: " + _useLocalStorage +
 -                            "If you want to use local storage to start ssvm, need to set system.vm.use.local.storage to true");
 +                List<Pair<Long, Integer>> l = _storagePoolHostDao.getDatacenterStoragePoolHostInfo(dataCenterId, !_useLocalStorage);
 +                if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
- 
 +                    return true;
 +                } else {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Primary storage is not ready, wait until it is ready to launch secondary storage vm. dcId: " + dataCenterId + " system.vm.use.local.storage: " + _useLocalStorage +
 +                        		"If you want to use local storage to start ssvm, need to set system.vm.use.local.storage to true");
 +                    }
                  }
-             } else {
-                 if (s_logger.isDebugEnabled()) {
-                     if (template == null) {
-                         s_logger.debug("Zone host is ready, but secondary storage vm template does not exist");
-                     } else {
-                         s_logger.debug("Zone host is ready, but secondary storage vm template: " + template.getId() + " is not ready on secondary storage: " + secHost.getId());
-                     }
-                 }
--            }
+ 
          }
          return false;
      }
@@@ -1011,31 -1006,33 +993,31 @@@
          return "secStorageVm." + id;
      }
  
 -    @Override
 -    public SecondaryStorageVmVO findByName(String name) {
 -        if (!VirtualMachineName.isValidSecStorageVmName(name, null)) {
 -            return null;
 -        }
 -        return findById(VirtualMachineName.getSystemVmId(name));
 -    }
 -
 -    @Override
 -    public SecondaryStorageVmVO findById(long id) {
 -        return _secStorageVmDao.findById(id);
 -    }
 -
 -    @Override
 -    public SecondaryStorageVmVO persist(SecondaryStorageVmVO vm) {
 -        return _secStorageVmDao.persist(vm);
 -    }
 +//    @Override
 +//    public SecondaryStorageVmVO findByName(String name) {
 +//        if (!VirtualMachineName.isValidSecStorageVmName(name, null)) {
 +//            return null;
 +//        }
 +//        return findById(VirtualMachineName.getSystemVmId(name));
 +//    }
 +
 +//    @Override
 +//    public SecondaryStorageVmVO findById(long id) {
 +//        return _secStorageVmDao.findById(id);
 +//    }
 +//
 +//    @Override
 +//    public SecondaryStorageVmVO persist(SecondaryStorageVmVO vm) {
 +//        return _secStorageVmDao.persist(vm);
 +//    }
  
      @Override
 -    public boolean finalizeVirtualMachineProfile(VirtualMachineProfile<SecondaryStorageVmVO> profile, DeployDestination dest, ReservationContext context) {
 -
 -    	SecondaryStorageVmVO vm = profile.getVirtualMachine();
 -        Map<String, String> details = _vmDetailsDao.findDetails(vm.getId());
 -        vm.setDetails(details);
 +    public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) {
  
 -        DataStore secStore = this._dataStoreMgr.getImageStore(dest.getDataCenter().getId());
 +        SecondaryStorageVmVO ssVm = _secStorageVmDao.findById(profile.getId());
 +    	
-         HostVO secHost = _ssvmMgr.findSecondaryStorageHost(dest.getDataCenter().getId());
-         assert (secHost != null);
++        DataStore secStore = _dataStoreMgr.getImageStore(dest.getDataCenter().getId());
+         assert (secStore != null);
  
          StringBuilder buf = profile.getBootArgsBuilder();
          buf.append(" template=domP type=secstorage");
@@@ -1281,9 -1277,9 +1263,9 @@@
          List<SecondaryStorageVmVO> ssVms = _secStorageVmDao.getSecStorageVmListInStates(SecondaryStorageVm.Role.templateProcessor, dataCenterId, State.Running, State.Migrating,
                  State.Starting,  State.Stopped, State.Stopping );
          int vmSize = (ssVms == null)? 0 : ssVms.size();
-         List<HostVO> ssHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dataCenterId);
-         int hostSize = (ssHosts == null)? 0 : ssHosts.size();
-         if ( hostSize > vmSize ) {
 -        List<DataStore> ssStores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(dataCenterId));
++        List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dataCenterId));
+         int storeSize = (ssStores == null)? 0 : ssStores.size();
+         if ( storeSize > vmSize ) {
              s_logger.info("No secondary storage vms found in datacenter id=" + dataCenterId + ", starting a new one");
              return new Pair<AfterScanAction, Object>(AfterScanAction.expand, SecondaryStorageVm.Role.templateProcessor);
          }
@@@ -1366,57 -1364,11 +1350,11 @@@
  
  	@Override
      public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
-         if (host.getType() == Host.Type.SecondaryStorage) {
-             deleteHost(host.getId());
-             return new DeleteHostAnswer(false);
-         }
-         return null;
-     }
- 
- 	@Override
-     public HostVO findSecondaryStorageHost(long dcId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
- 	    sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorage);
- 	    sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId);
- 	    List<HostVO> storageHosts = sc.list();
- 	    if (storageHosts == null || storageHosts.size() < 1) {
+ 	    // Since secondary storage is moved out of host table, this class should not handle delete secondary storage anymore.
 -        return null;
 +            return null;
-         } else {
-             Collections.shuffle(storageHosts);
-             return storageHosts.get(0);
-         }
-     }
- 
- 	@Override
-     public List<HostVO> listSecondaryStorageHostsInAllZones() {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
- 	    sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorage);
- 	    return sc.list();
      }
  
- 	@Override
-     public List<HostVO> listSecondaryStorageHostsInOneZone(long dataCenterId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
- 		sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId);
- 		sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorage);
- 	    return sc.list();
-     }
  
- 	@Override
-     public List<HostVO> listLocalSecondaryStorageHostsInOneZone(long dataCenterId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
- 		sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId);
- 		sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.LocalSecondaryStorage);
- 	    return sc.list();
-     }
- 
- 	@Override
-     public List<HostVO> listAllTypesSecondaryStorageHostsInOneZone(long dataCenterId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
- 		sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId);
- 		sc.addAnd(sc.getEntity().getType(), Op.IN, Host.Type.LocalSecondaryStorage, Host.Type.SecondaryStorage);
- 	    return sc.list();
-     }
  
  	@Override
      public List<HostVO> listUpAndConnectingSecondaryStorageVmHost(Long dcId) {
@@@ -1444,49 -1396,26 +1382,50 @@@
          }
          return null;
      }
 -
 -
 -    @Override
 -    public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm,
 -            ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException,
 -            InsufficientCapacityException {
 -        //not supported
 -        throw new UnsupportedOperationException("Plug nic is not supported for vm of type " + vm.getType());
 -    }
 -
 -
 -    @Override
 -    public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm,
 -            ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException {
 -        //not supported
 -        throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
 -    }
 +	
+ 
  	@Override
 -	public void prepareStop(VirtualMachineProfile<SecondaryStorageVmVO> profile) {
 -
 +    public void prepareStop(VirtualMachineProfile profile) {
  	}
 +	
 +//    @Override
 +//    public void vmWorkStart(VmWork work) {
 +//    	assert(work instanceof VmWorkStart);
 +//
 +//        SecondaryStorageVmVO vm = _secStorageVmDao.findById(work.getVmId());
 +//
 +//    	UserVO user = _entityMgr.findById(UserVO.class, work.getUserId());
 +//    	AccountVO account = _entityMgr.findById(AccountVO.class, work.getAccountId());
 +//
 +//    	try {
 +//	    	_itMgr.processVmStartWork(vm, ((VmWorkStart)work).getParams(),
 +//	    		user, account,  ((VmWorkStart)work).getPlan());
 +//
 +//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(JobInfo.Status.SUCCEEDED, null);
 +//    	} catch(Exception e) {
 +//    		s_logger.error("Exception in process VM-start work", e);
 +//    		String result = SerializerHelper.toObjectSerializedString(e);
 +//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(JobInfo.Status.FAILED, result);
 +//    	}
 +//    }
 +//
 +//    @Override
 +//    public void vmWorkStop(VmWork work) {
 +//    	assert(work instanceof VmWorkStop);
 +//
 +//        SecondaryStorageVmVO vm = _secStorageVmDao.findById(work.getVmId());
 +//
 +//    	UserVO user = _entityMgr.findById(UserVO.class, work.getUserId());
 +//    	AccountVO account = _entityMgr.findById(AccountVO.class, work.getAccountId());
 +//
 +//    	try {
 +//	    	_itMgr.processVmStopWork(vm, ((VmWorkStop)work).isForceStop(), user, account);
 +//
 +//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(JobInfo.Status.SUCCEEDED, null);
 +//    	} catch(Exception e) {
 +//    		s_logger.error("Exception in process VM-stop work", e);
 +//    		String result = SerializerHelper.toObjectSerializedString(e);
 +//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(JobInfo.Status.FAILED, result);
 +//    	}
 +//    }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
index 0c78c4c,ebe06e7..a1871c0
--- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
+++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java
@@@ -27,21 -26,26 +26,28 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
++import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
++
  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.context.CallContext;
+ 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.EndPoint;
+ import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
+ import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotStrategy;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
+ import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
- import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
- import org.apache.log4j.Logger;
- import org.springframework.stereotype.Component;
+ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
@@@ -58,7 -57,7 +59,6 @@@ import com.cloud.configuration.Config
  import com.cloud.configuration.Resource.ResourceType;
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.dc.ClusterVO;
- import com.cloud.dc.DataCenter;
 -import com.cloud.dc.DataCenterVO;
  import com.cloud.dc.dao.ClusterDao;
  import com.cloud.dc.dao.DataCenterDao;
  import com.cloud.domain.dao.DomainDao;
@@@ -75,11 -74,13 +75,13 @@@ import com.cloud.exception.StorageUnava
  import com.cloud.host.HostVO;
  import com.cloud.host.dao.HostDao;
  import com.cloud.hypervisor.Hypervisor.HypervisorType;
- 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.CreateSnapshotPayload;
++import com.cloud.storage.DataStoreRole;
  import com.cloud.storage.Snapshot;
  import com.cloud.storage.Snapshot.Type;
 -import com.cloud.storage.DataStoreRole;
  import com.cloud.storage.SnapshotPolicyVO;
  import com.cloud.storage.SnapshotScheduleVO;
  import com.cloud.storage.SnapshotVO;
@@@ -187,11 -196,15 +196,15 @@@ public class SnapshotManagerImpl extend
      @Inject TemplateManager templateMgr;
      @Inject VolumeManager volumeMgr;
      @Inject DataStoreManager dataStoreMgr;
-     @Inject List<SnapshotStrategy> snapshotStrategies;
+     @Inject SnapshotService snapshotSrv;
      @Inject VolumeDataFactory volFactory;
      @Inject SnapshotDataFactory snapshotFactory;
+     @Inject EndPointSelector _epSelector;
+ 	@Inject
+ 	private ResourceManager _resourceMgr;
+ 	@Inject
+ 	protected List<SnapshotStrategy> snapshotStrategies;
 -
 +    
  
      private int _totalRetries;
      private int _pauseInterval;
@@@ -258,7 -271,7 +271,7 @@@
      @DB
      @ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "creating snapshot", async = true)
      public Snapshot createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner) {
--        VolumeInfo volume = this.volFactory.getVolume(volumeId);
++        VolumeInfo volume = volFactory.getVolume(volumeId);
          if (volume == null) {
          	throw new InvalidParameterValueException("No such volume exist");
          }
@@@ -266,40 -279,26 +279,26 @@@
          if (volume.getState() != Volume.State.Ready) {
          	throw new InvalidParameterValueException("Volume is not in ready state");
          }
 -
 -
 +        
-         SnapshotInfo snapshot = null;
 +     
          boolean backedUp = false;
          // does the caller have the authority to act on this volume
 -        _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, volume);
 -
 -        SnapshotInfo snapshot = this.snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
 +        _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
 +        
- 
-         SnapshotInfo snap = this.snapshotFactory.getSnapshot(snapshotId);
-         SnapshotStrategy strategy = null;
-         for (SnapshotStrategy st : snapshotStrategies) {
-         	if (st.canHandle(snap)) {
-         		strategy = st;
-         		break;
-         	}
-         }
++        SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
  
          try {
-         	snapshot = strategy.takeSnapshot(volume, snapshotId);
-         	if (snapshot != null) {
 -        	postCreateSnapshot(volumeId, snapshot.getId(), policyId);
 -        	//Check if the snapshot was removed while backingUp. If yes, do not log snapshot create usage event
 -        	SnapshotVO freshSnapshot = _snapshotDao.findById(snapshot.getId());
 -        	if ((freshSnapshot != null) && backedUp) {
 -        		UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(),
 -        				snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null,
 -        				volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
 -        	}
 +        		postCreateSnapshot(volumeId, snapshot.getId(), policyId);
 +        		//Check if the snapshot was removed while backingUp. If yes, do not log snapshot create usage event
 +        		SnapshotVO freshSnapshot = _snapshotDao.findById(snapshot.getId());
 +        		if ((freshSnapshot != null) && backedUp) {
 +        			UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(),
 +        					snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null,
 +        					volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
 +        		}
  
 -        	_resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
 +                _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
-         	}
-         	if (backup) {
-         		this.backupSnapshot(snapshotId);
-         	}
+ 
          } catch(Exception e) {
              s_logger.debug("Failed to create snapshot", e);
              if (backup) {
@@@ -325,42 -318,18 +318,18 @@@
  
      @Override
      public Snapshot backupSnapshot(Long snapshotId) {
-     	 SnapshotInfo snapshot = this.snapshotFactory.getSnapshot(snapshotId);
-     	 if (snapshot == null) {
-     		 throw new CloudRuntimeException("Can't find snapshot:" + snapshotId);
-     	 }
-     	 
-     	 if (snapshot.getState() == Snapshot.State.BackedUp) {
-     	     return snapshot;
-     	 }
-     	 
-     	 SnapshotStrategy strategy = null;
-          for (SnapshotStrategy st : snapshotStrategies) {
-          	if (st.canHandle(snapshot)) {
-          		strategy = st;
-          		break;
-          	}
 -    	 SnapshotInfo snapshot = this.snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
++    	 SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
+     	 if (snapshot != null) {
+     		 throw new CloudRuntimeException("Already in the backup snapshot:" + snapshotId);
 -    	 }
 -
 -         return this.snapshotSrv.backupSnapshot(snapshot);
 +         }
 +         
-          return strategy.backupSnapshot(snapshot);
++         return snapshotSrv.backupSnapshot(snapshot);
      }
  
+     /*
      @Override
      public void downloadSnapshotsFromSwift(SnapshotVO ss) {
+ 
          long volumeId = ss.getVolumeId();
          VolumeVO volume = _volsDao.findById(volumeId);
          Long dcId = volume.getDataCenterId();
@@@ -443,11 -415,11 +415,11 @@@
                      e);
          }
  
-     }
+     }*/
 -
 +    
      @Override
-     public SnapshotVO getParentSnapshot(VolumeInfo volume, Snapshot snapshot) {
-     	 long preId = _snapshotDao.getLastSnapshot(volume.getId(), snapshot.getId());
+     public SnapshotVO getParentSnapshot(VolumeInfo volume) {
+     	 long preId = _snapshotDao.getLastSnapshot(volume.getId(), DataStoreRole.Primary);
  
           SnapshotVO preSnapshotVO = null;
           if (preId != 0 && !(volume.getLastPoolId() != null && !volume.getLastPoolId().equals(volume.getPoolId()))) {
@@@ -507,20 -479,19 +479,19 @@@
      @DB
      @ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_DELETE, eventDescription = "deleting snapshot", async = true)
      public boolean deleteSnapshot(long snapshotId) {
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
  
          // Verify parameters
-         SnapshotInfo snapshotCheck = this.snapshotFactory.getSnapshot(snapshotId);
 -        SnapshotVO snapshotCheck = this._snapshotDao.findById(snapshotId);
++        SnapshotVO snapshotCheck = _snapshotDao.findById(snapshotId);
          if (snapshotCheck == null) {
              throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
          }
 -
 +        
          _accountMgr.checkAccess(caller, null, true, snapshotCheck);
-         
-         SnapshotStrategy strategy = null;
-         for (SnapshotStrategy st : snapshotStrategies) {
-         	if (st.canHandle(snapshotCheck)) {
-         		strategy = st;
+         SnapshotStrategy snapshotStrategy = null;
 -        for (SnapshotStrategy strategy : this.snapshotStrategies) {
++        for (SnapshotStrategy strategy : snapshotStrategies) {
+         	if (strategy.canHandle(snapshotCheck)) {
+         		snapshotStrategy = strategy;
          		break;
          	}
          }
@@@ -546,21 -517,14 +517,14 @@@
  
      @Override
      public String getSecondaryStorageURL(SnapshotVO snapshot) {
-         HostVO secHost = getSecondaryStorageHost(snapshot);
-         if (secHost != null) {
-             return secHost.getStorageUrl();
 -        SnapshotDataStoreVO snapshotStore = this._snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image);
++        SnapshotDataStoreVO snapshotStore = _snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Image);
+         if (snapshotStore != null){
 -            DataStore store = this.dataStoreMgr.getDataStore(snapshotStore.getDataStoreId(), DataStoreRole.Image);
++            DataStore store = dataStoreMgr.getDataStore(snapshotStore.getDataStoreId(), DataStoreRole.Image);
+             if ( store != null ){
+                 return store.getUri();
 -            }
 +        }
-         throw new CloudRuntimeException("Can not find secondary storage");
+         }
+         throw new CloudRuntimeException("Can not find secondary storage hosting the snapshot");
      }
  
      @Override
@@@ -589,8 -552,8 +553,8 @@@
         _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
         Long domainId = domainIdRecursiveListProject.first();
         Boolean isRecursive = domainIdRecursiveListProject.second();
-        ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();        
+        ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
 -
 +        
          Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
          SearchBuilder<SnapshotVO> sb = _snapshotDao.createSearchBuilder();
          _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
@@@ -651,7 -616,7 +617,7 @@@
          }
  
          if (snapshotTypeStr != null) {
--            Type snapshotType = SnapshotVO.getSnapshotType((String) snapshotTypeStr);
++            Type snapshotType = SnapshotVO.getSnapshotType(snapshotTypeStr);
              if (snapshotType == null) {
                  throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr);
              }
@@@ -661,7 -626,7 +627,7 @@@
                  sc.setParameters("snapshotTypeEQ", snapshotType.ordinal());
              }
          } else if (intervalTypeStr != null && volumeId != null) {
--            Type type = SnapshotVO.getSnapshotType((String) intervalTypeStr);
++            Type type = SnapshotVO.getSnapshotType(intervalTypeStr);
              if (type == null) {
                  throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr);
              }
@@@ -694,42 -659,12 +660,12 @@@
                  // This volume doesn't have any snapshots. Nothing do delete.
                  continue;
              }
-             List<HostVO> ssHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dcId);
-             SwiftTO swift = _swiftMgr.getSwiftTO();
-             S3TO s3 = _s3Mgr.getS3TO();
- 
-             checkObjectStorageConfiguration(swift, s3);
-             StoragePoolVO pool = _primaryDataStoreDao.findById(volume.getPoolId());
-             if (swift == null && s3 == null) {
-                 for (HostVO ssHost : ssHosts) {
-                     DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(
-                             pool,null, null, ssHost.getStorageUrl(), dcId,
-                             accountId, volumeId, "", true);
-                     Answer answer = null;
-                     try {
-                         answer = _agentMgr.sendToSSVM(dcId, cmd);
-                     } catch (Exception e) {
-                         s_logger.warn("Failed to delete all snapshot for volume " + volumeId + " on secondary storage " + ssHost.getStorageUrl());
-                     }
-                     if ((answer != null) && answer.getResult()) {
-                         s_logger.debug("Deleted all snapshots for volume: " + volumeId + " under account: " + accountId);
-                     } else {
-                         success = false;
-                         if (answer != null) {
-                             s_logger.error(answer.getDetails());
-                         }
-                     }
-                 }
-             } else {
-                 DeleteSnapshotBackupCommand cmd = new DeleteSnapshotBackupCommand(
-                         pool,swift, s3, "", dcId, accountId, volumeId, "", true);
-                 Answer answer = null;
-                 try {
-                     answer = _agentMgr.sendToSSVM(dcId, cmd);
-                 } catch (Exception e) {
-                     final String storeType = s3 != null ? "S3" : "swift";
-                     s_logger.warn("Failed to delete all snapshot for volume " + volumeId + " on " + storeType);
-                 }
 -            List<DataStore> ssHosts = this.dataStoreMgr.getImageStoresByScope(new ZoneScope(dcId));
++            List<DataStore> ssHosts = dataStoreMgr.getImageStoresByScope(new ZoneScope(dcId));
+             for (DataStore ssHost : ssHosts) {
+                 String snapshotDir = TemplateConstants.DEFAULT_SNAPSHOT_ROOT_DIR + "/" + accountId + "/" + volumeId;
+                 DeleteSnapshotsDirCommand cmd = new DeleteSnapshotsDirCommand(ssHost.getTO(), snapshotDir);
+                 EndPoint ep = _epSelector.select(ssHost);
+                 Answer answer = ep.sendMessage(cmd);
                  if ((answer != null) && answer.getResult()) {
                      s_logger.debug("Deleted all snapshots for volume: " + volumeId + " under account: " + accountId);
                  } else {
@@@ -963,97 -899,121 +900,119 @@@
          return null;
      }
  
-     @Override
-     public SnapshotVO allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException {
-         Account caller = CallContext.current().getCallingAccount();
-         
-         VolumeVO volume = _volsDao.findById(volumeId);
-         if (volume == null) {
-             throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
-         }
-         DataCenter zone = _dcDao.findById(volume.getDataCenterId());
-         if (zone == null) {
-             throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
 -
 -
+     private boolean hostSupportSnapsthot(HostVO host) {
+ 		if (host.getHypervisorType() != HypervisorType.KVM) {
+ 			return true;
 -		}
 +        }
+ 		// Determine host capabilities
+ 		String caps = host.getCapabilities();
 -
 +        
-         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) {
-             throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
+ 		if (caps != null) {
+ 			String[] tokens = caps.split(",");
+ 			for (String token : tokens) {
+ 				if (token.contains("snapshot")) {
+ 					return true;
+ 				}
+ 			}
+ 		}
+ 		return false;
 -	}
 -
 +        }
 +        
-         if (volume.getState() != Volume.State.Ready) {
-             throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
+     private boolean supportedByHypervisor(VolumeInfo volume) {
+     	StoragePool storagePool = (StoragePool)volume.getDataStore();
+         ClusterVO cluster = _clusterDao.findById(storagePool.getClusterId());
+         if (cluster != null && cluster.getHypervisorType() == HypervisorType.Ovm) {
+             throw new InvalidParameterValueException("Ovm won't support taking snapshot");
          }
  
-         if ( volume.getTemplateId() != null ) {
-             VMTemplateVO  template = _templateDao.findById(volume.getTemplateId());
-             if( template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM ) {
-                 throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
+ 		if (volume.getHypervisorType().equals(HypervisorType.KVM)) {
+ 			List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(cluster.getId());
+ 			if (hosts != null && !hosts.isEmpty()) {
+ 				HostVO host = hosts.get(0);
+ 				if (!hostSupportSnapsthot(host)) {
+ 					throw new CloudRuntimeException("KVM Snapshot is not supported on cluster: " + host.getId());
+ 				}
 -			}
 -		}
 -
 +            }
 +        }
 +        
-         StoragePoolVO storagePoolVO = _storagePoolDao.findById(volume.getPoolId());
-         if (storagePoolVO == null) {
-             throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
-         }
- 
-         ClusterVO cluster = _clusterDao.findById(storagePoolVO.getClusterId());
-         if (cluster != null && cluster.getHypervisorType() == HypervisorType.Ovm) {
-             throw new InvalidParameterValueException("Ovm won't support taking snapshot");
-         }
- 
-         // Verify permissions
-         _accountMgr.checkAccess(caller, null, true, volume);
-         Type snapshotType = getSnapshotType(policyId);
-         Account owner = _accountMgr.getAccount(volume.getAccountId());
+ 		// if volume is attached to a vm in destroyed or expunging state; disallow
+ 		if (volume.getInstanceId() != null) {
+ 			UserVmVO userVm = _vmDao.findById(volume.getInstanceId());
+ 			if (userVm != null) {
+                 if (userVm.getState().equals(State.Destroyed) || userVm.getState().equals(State.Expunging)) {
+                     throw new CloudRuntimeException("Creating snapshot failed due to volume:" + volume.getId()
+                             + " is associated with vm:" + userVm.getInstanceName() + " is in "
+                             + userVm.getState().toString() + " state");
 -                }
++        }
+ 
+                 if (userVm.getHypervisorType() == HypervisorType.VMware
+                         || userVm.getHypervisorType() == HypervisorType.KVM) {
+                     List<SnapshotVO> activeSnapshots = _snapshotDao.listByInstanceId(volume.getInstanceId(),
+                             Snapshot.State.Creating, Snapshot.State.CreatedOnPrimary, Snapshot.State.BackingUp);
+                     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(),
+                         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");
+                 }
+ 			}
+ 		}
  
-         try{
-             _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
-             if (backup) {
-                 _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize()));
-             } else {
-                 _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long(volume.getSize()));
+ 		return true;
 -	}
 +            }
-         } catch (ResourceAllocationException e) {
-             if (snapshotType != Type.MANUAL){
-                 String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots";
-                 s_logger.warn(msg);
-                 _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg,
-                         "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit");
+     @Override
+     public SnapshotInfo takeSnapshot(VolumeInfo volume) throws ResourceAllocationException {
+         CreateSnapshotPayload payload = (CreateSnapshotPayload)volume.getpayload();
+         Long snapshotId = payload.getSnapshotId();
+         Account snapshotOwner = payload.getAccount();
 -        SnapshotInfo snapshot = this.snapshotFactory.getSnapshot(snapshotId, volume.getDataStore());
++        SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, volume.getDataStore());
+         boolean processed = false;
+ 
+         try {
+             for (SnapshotStrategy strategy : snapshotStrategies) {
+                 if (strategy.canHandle(snapshot)) {
+                     processed = true;
+                     snapshot = strategy.takeSnapshot(snapshot);
+                     break;
 -                }
              }
-             throw e;
 +        }
+             if (!processed) {
+                 throw new CloudRuntimeException("Can't find snapshot strategy to deal with snapshot:" + snapshotId);
+             }
+             postCreateSnapshot(volume.getId(), snapshotId, payload.getSnapshotPolicyId());
  
-         // Determine the name for this snapshot
-         // Snapshot Name: VMInstancename + volumeName + timeString
-         String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
+             UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_CREATE, snapshot.getAccountId(),
+                     snapshot.getDataCenterId(), snapshotId, snapshot.getName(), null, null,
+                     volume.getSize(), snapshot.getClass().getName(), snapshot.getUuid());
  
-         String snapshotName = volume.getUuid() + "_" + timeString;
  
-         // Create the Snapshot object and save it so we can return it to the
-         // user        
-         HypervisorType hypervisorType = this._volsDao.getHypervisorType(volumeId);
-         SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), null, snapshotName,
-                 (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), hypervisorType);
-         SnapshotVO snapshot = _snapshotDao.persist(snapshotVO);
-         if (snapshot == null) {
-             throw new CloudRuntimeException("Failed to create snapshot for volume: "+volumeId);
-         }
+             _resourceLimitMgr.incrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
+ 
+         } catch(Exception e) {
+             s_logger.debug("Failed to create snapshot", e);
 -            if (backup) {
 +        if (backup) {
-             _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage,
+                 _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage,
 -                        new Long(volume.getSize()));
 -            } else {
 +                    new Long(volume.getSize()));
 +        } else {
-             _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                 _resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.primary_storage,
 -                        new Long(volume.getSize()));
 -            }
 +                    new Long(volume.getSize()));
 +        }
+             throw new CloudRuntimeException("Failed to create snapshot", e);
+         }
          return snapshot;
      }
  
      @Override
      public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
 -
 + 
          String value = _configDao.getValue(Config.BackupSnapshotWait.toString());
          _backupsnapshotwait = NumbersUtil.parseInt(value, Integer.parseInt(Config.BackupSnapshotWait.getDefaultValue()));
--        backup = Boolean.parseBoolean(this._configDao.getValue(Config.BackupSnapshotAferTakingSnapshot.toString()));
++        backup = Boolean.parseBoolean(_configDao.getValue(Config.BackupSnapshotAferTakingSnapshot.toString()));
  
          Type.HOURLY.setMax(NumbersUtil.parseInt(_configDao.getValue("snapshot.max.hourly"), HOURLYMAX));
          Type.DAILY.setMax(NumbersUtil.parseInt(_configDao.getValue("snapshot.max.daily"), DAILYMAX));
@@@ -1134,4 -1094,61 +1093,61 @@@
      	}
      	return true;
      }
+ 
+     @Override
+     public Snapshot allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException {
 -        Account caller = UserContext.current().getCaller();
 -        VolumeInfo volume = this.volFactory.getVolume(volumeId);
++        Account caller = CallContext.current().getCallingAccount();
++        VolumeInfo volume = volFactory.getVolume(volumeId);
+         supportedByHypervisor(volume);
+ 
+         // Verify permissions
+         _accountMgr.checkAccess(caller, null, true, volume);
+         Type snapshotType = getSnapshotType(policyId);
+         Account owner = _accountMgr.getAccount(volume.getAccountId());
+ 
+         try{
+             _resourceLimitMgr.checkResourceLimit(owner, ResourceType.snapshot);
+             if (backup) {
+                 _resourceLimitMgr.checkResourceLimit(owner, ResourceType.secondary_storage, new Long(volume.getSize()));
+             } else {
+                 _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long(volume.getSize()));
+             }
+         } catch (ResourceAllocationException e) {
+             if (snapshotType != Type.MANUAL){
+                 String msg = "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots";
+                 s_logger.warn(msg);
+                 _alertMgr.sendAlert(AlertManager.ALERT_TYPE_UPDATE_RESOURCE_COUNT, 0L, 0L, msg,
+                         "Snapshot resource limit exceeded for account id : " + owner.getId() + ". Failed to create recurring snapshots; please use updateResourceLimit to increase the limit");
+             }
+             throw e;
+         }
+ 
+         // Determine the name for this snapshot
+         // Snapshot Name: VMInstancename + volumeName + timeString
+         String timeString = DateUtil.getDateDisplayString(DateUtil.GMT_TIMEZONE, new Date(), DateUtil.YYYYMMDD_FORMAT);
+ 
+         VMInstanceVO vmInstance = _vmDao.findById(volume.getInstanceId());
+         String vmDisplayName = "detached";
+         if (vmInstance != null) {
+             vmDisplayName = vmInstance.getHostName();
+         }
+         String snapshotName = vmDisplayName + "_" + volume.getName() + "_" + timeString;
+ 
+         HypervisorType hypervisorType = volume.getHypervisorType();
+         SnapshotVO snapshotVO = new SnapshotVO(volume.getDataCenterId(), volume.getAccountId(), volume.getDomainId(), volume.getId(), volume.getDiskOfferingId(), snapshotName,
+                 (short) snapshotType.ordinal(), snapshotType.name(), volume.getSize(), hypervisorType);
+ 
+         SnapshotVO snapshot = _snapshotDao.persist(snapshotVO);
+         if (snapshot == null) {
+             throw new CloudRuntimeException("Failed to create snapshot for volume: " + volume.getId());
+         }
+         if (backup) {
+             _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.secondary_storage,
+                     new Long(volume.getSize()));
+         } else {
+             _resourceLimitMgr.incrementResourceCount(volume.getAccountId(), ResourceType.primary_storage,
+                     new Long(volume.getSize()));
+         }
+         return snapshot;
+     }
  }


[49/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
merge is complete


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

Branch: refs/heads/vmsync
Commit: 7b7db0560ca40f2f76c25fadb1aaf5677a0ceb6b
Parents: a49109a f7b1d3d
Author: Alex Huang <al...@gmail.com>
Authored: Mon Jun 24 16:50:31 2013 -0700
Committer: Alex Huang <al...@gmail.com>
Committed: Mon Jun 24 16:50:31 2013 -0700

----------------------------------------------------------------------
 agent/src/com/cloud/agent/AgentShell.java       |    1 +
 api/src/com/cloud/agent/api/Answer.java         |    1 +
 .../CopyTemplateToPrimaryStorageAnswer.java     |   17 +
 .../cloud/agent/api/storage/PasswordAuth.java   |   39 +
 api/src/com/cloud/agent/api/storage/Proxy.java  |   72 +
 .../com/cloud/agent/api/to/DataObjectType.java  |   25 +
 api/src/com/cloud/agent/api/to/DataStoreTO.java |   26 +
 api/src/com/cloud/agent/api/to/DataTO.java      |   30 +
 api/src/com/cloud/agent/api/to/DiskTO.java      |   60 +
 .../com/cloud/agent/api/to/FirewallRuleTO.java  |   19 +-
 api/src/com/cloud/agent/api/to/NfsTO.java       |   60 +
 api/src/com/cloud/agent/api/to/S3TO.java        |   27 +-
 api/src/com/cloud/agent/api/to/SwiftTO.java     |   10 +-
 .../cloud/agent/api/to/VirtualMachineTO.java    |    6 +-
 api/src/com/cloud/agent/api/to/VolumeTO.java    |   37 +
 api/src/com/cloud/network/NetworkModel.java     |    2 +
 api/src/com/cloud/offering/DiskOffering.java    |   16 +
 api/src/com/cloud/offering/NetworkOffering.java |    1 +
 api/src/com/cloud/server/ManagementService.java |   45 -
 api/src/com/cloud/storage/DataStoreRole.java    |   54 +
 .../com/cloud/storage/GuestOSHypervisor.java    |   28 +
 api/src/com/cloud/storage/ImageStore.java       |   47 +
 api/src/com/cloud/storage/ScopeType.java        |   27 +
 api/src/com/cloud/storage/Snapshot.java         |    7 +-
 api/src/com/cloud/storage/Storage.java          |   17 +-
 api/src/com/cloud/storage/StoragePool.java      |    2 +-
 api/src/com/cloud/storage/StorageService.java   |   12 +
 api/src/com/cloud/storage/Upload.java           |    2 +-
 api/src/com/cloud/storage/Volume.java           |   10 +-
 api/src/com/cloud/storage/VolumeApiService.java |   28 +-
 .../storage/snapshot/SnapshotApiService.java    |  109 +
 .../cloud/storage/snapshot/SnapshotService.java |  109 -
 .../cloud/storage/template/TemplateInfo.java    |   81 -
 .../cloud/storage/template/TemplateProp.java    |   81 +
 .../com/cloud/template/TemplateApiService.java  |  106 +
 api/src/com/cloud/template/TemplateService.java |  100 -
 .../cloud/template/VirtualMachineTemplate.java  |    2 +
 api/src/com/cloud/vm/DiskProfile.java           |   36 +
 api/src/com/cloud/vm/VirtualMachine.java        |    2 +
 api/src/com/cloud/vm/VirtualMachineProfile.java |    8 +-
 .../org/apache/cloudstack/api/ApiConstants.java |    9 +-
 api/src/org/apache/cloudstack/api/BaseCmd.java  |    8 +-
 .../api/BaseUpdateTemplateOrIsoCmd.java         |    7 +
 .../cloudstack/api/ResponseGenerator.java       |   22 +-
 .../admin/host/AddSecondaryStorageCmd.java      |   36 +-
 .../admin/host/FindHostsForMigrationCmd.java    |    3 +-
 .../api/command/admin/host/ListHostsCmd.java    |    3 +-
 .../admin/internallb/ListInternalLBVMsCmd.java  |    6 -
 .../api/command/admin/ldap/LDAPConfigCmd.java   |   21 +-
 .../admin/network/CreateNetworkOfferingCmd.java |   10 +
 .../admin/offering/CreateDiskOfferingCmd.java   |   28 +
 .../offering/CreateServiceOfferingCmd.java      |   28 +
 .../admin/region/ListPortableIpRangesCmd.java   |    3 +-
 .../command/admin/router/ListRoutersCmd.java    |    7 -
 .../command/admin/storage/AddImageStoreCmd.java |  154 +
 .../api/command/admin/storage/AddS3Cmd.java     |   55 +-
 .../admin/storage/CreateCacheStoreCmd.java      |  123 +
 .../admin/storage/DeleteImageStoreCmd.java      |   80 +
 .../admin/storage/ListCacheStoresCmd.java       |  104 +
 .../admin/storage/ListImageStoresCmd.java       |  104 +
 .../api/command/admin/storage/ListS3sCmd.java   |   34 +-
 .../admin/storage/ListStoragePoolsCmd.java      |    8 +
 .../api/command/admin/swift/AddSwiftCmd.java    |   43 +-
 .../api/command/admin/swift/ListSwiftsCmd.java  |   28 +-
 .../admin/template/PrepareTemplateCmd.java      |    2 +-
 .../api/command/user/iso/ExtractIsoCmd.java     |   10 +-
 .../api/command/user/iso/ListIsosCmd.java       |   11 +-
 .../api/command/user/iso/RegisterIsoCmd.java    |    9 +-
 .../api/command/user/iso/UpdateIsoCmd.java      |    4 +-
 .../RevokeSecurityGroupEgressCmd.java           |    2 +-
 .../RevokeSecurityGroupIngressCmd.java          |    2 +-
 .../user/snapshot/CreateSnapshotCmd.java        |   26 +-
 .../command/user/template/CopyTemplateCmd.java  |    2 +-
 .../user/template/ExtractTemplateCmd.java       |   10 +-
 .../command/user/template/ListTemplatesCmd.java |   14 +-
 .../user/template/RegisterTemplateCmd.java      |   16 +-
 .../user/template/UpdateTemplateCmd.java        |    4 +-
 .../api/command/user/vm/UpdateVMCmd.java        |    7 +
 .../command/user/volume/CreateVolumeCmd.java    |    2 +-
 .../command/user/volume/ExtractVolumeCmd.java   |   23 +-
 .../command/user/volume/MigrateVolumeCmd.java   |   21 +-
 .../api/command/user/zone/ListZonesByCmd.java   |    8 +-
 .../api/response/ClusterResponse.java           |    7 -
 .../api/response/DiskOfferingResponse.java      |   28 +
 .../api/response/DomainRouterResponse.java      |   11 -
 .../cloudstack/api/response/HostResponse.java   |    7 -
 .../api/response/ImageStoreDetailResponse.java  |   86 +
 .../api/response/ImageStoreResponse.java        |  149 +
 .../api/response/NetworkOfferingResponse.java   |    7 +
 .../api/response/NetworkResponse.java           |    7 -
 .../cloudstack/api/response/PodResponse.java    |    7 -
 .../api/response/ServiceOfferingResponse.java   |   28 +
 .../api/response/SnapshotResponse.java          |   15 -
 .../api/response/StoragePoolResponse.java       |   10 -
 .../api/response/SystemVmResponse.java          |   11 -
 .../api/response/TemplateResponse.java          |   48 +-
 .../api/response/TemplateZoneResponse.java      |   90 +
 .../cloudstack/api/response/UserVmResponse.java |   14 +-
 .../cloudstack/api/response/VolumeResponse.java |   52 +-
 .../apache/cloudstack/query/QueryService.java   |   11 +
 .../test/AddSecondaryStorageCmdTest.java        |   67 +-
 .../api/command/test/AddSwiftCmdTest.java       |   97 -
 .../model/CloudStackServiceOfferingVO.java      |    9 +-
 .../dao/CloudStackConfigurationDaoImpl.java     |    3 +-
 .../dao/CloudStackSvcOfferingDaoImpl.java       |    6 +-
 .../persist/dao/CloudStackUserDaoImpl.java      |    1 +
 .../cloud/bridge/persist/dao/MHostDaoImpl.java  |    8 +-
 .../bridge/persist/dao/OfferingDaoImpl.java     |    8 +-
 .../cloud/bridge/persist/dao/SHostDaoImpl.java  |    8 +-
 .../persist/dao/UserCredentialsDaoImpl.java     |    1 +
 .../bridge/service/core/ec2/EC2Engine.java      |    2 +-
 .../classes/resources/messages.properties       |    6 +-
 .../classes/resources/messages_ja.properties    |  525 ++-
 .../classes/resources/messages_zh_CN.properties |  418 +-
 client/pom.xml                                  |   26 +-
 client/tomcatconf/applicationContext.xml.in     |   41 +-
 client/tomcatconf/commands.properties.in        |   10 +
 client/tomcatconf/componentContext.xml.in       |   10 -
 client/tomcatconf/log4j-cloud.xml.in            |    8 +
 client/tomcatconf/nonossComponentContext.xml.in |    8 -
 .../cloud/agent/api/AttachVolumeCommand.java    |   36 +
 .../agent/api/CleanupSnapshotBackupCommand.java |   75 -
 .../cloud/agent/api/ComputeChecksumCommand.java |   16 +-
 .../agent/api/DeleteObjectFromSwiftCommand.java |   61 -
 .../agent/api/DeleteSnapshotBackupAnswer.java   |   32 -
 .../agent/api/DeleteSnapshotBackupCommand.java  |   96 -
 .../agent/api/DeleteSnapshotsDirCommand.java    |   34 +-
 .../agent/api/DeleteTemplateFromS3Command.java  |  106 -
 .../agent/api/MigrateWithStorageAnswer.java     |   10 +-
 .../api/MigrateWithStorageCompleteAnswer.java   |    9 +-
 .../agent/api/ModifyStoragePoolAnswer.java      |   10 +-
 .../src/com/cloud/agent/api/ScaleVmCommand.java |    3 +-
 .../cloud/agent/api/SecStorageSetupCommand.java |   15 +-
 .../com/cloud/agent/api/SnapshotCommand.java    |    4 +-
 core/src/com/cloud/agent/api/StartCommand.java  |   10 +-
 .../cloud/agent/api/StartupStorageCommand.java  |   12 +-
 core/src/com/cloud/agent/api/StopCommand.java   |   14 +-
 .../agent/api/routing/DhcpEntryCommand.java     |   10 +-
 .../api/routing/NetworkElementCommand.java      |    1 +
 .../agent/api/routing/SavePasswordCommand.java  |    6 +-
 .../agent/api/routing/UserDataCommand.java      |    6 +-
 .../cloud/agent/api/routing/VmDataCommand.java  |   10 +-
 .../api/storage/AbstractDownloadCommand.java    |    2 +-
 .../agent/api/storage/CopyVolumeAnswer.java     |    1 +
 .../agent/api/storage/CopyVolumeCommand.java    |    6 +-
 .../cloud/agent/api/storage/CreateAnswer.java   |    1 +
 .../cloud/agent/api/storage/CreateCommand.java  |   32 +-
 .../storage/CreatePrivateTemplateAnswer.java    |    4 +-
 .../api/storage/DeleteTemplateCommand.java      |   40 -
 .../agent/api/storage/DeleteVolumeCommand.java  |   38 -
 .../agent/api/storage/DownloadCommand.java      |  219 -
 .../api/storage/DownloadProgressCommand.java    |   48 -
 .../agent/api/storage/ListTemplateAnswer.java   |   12 +-
 .../agent/api/storage/ListTemplateCommand.java  |   31 +-
 .../agent/api/storage/ListVolumeAnswer.java     |   12 +-
 .../agent/api/storage/ListVolumeCommand.java    |    9 +-
 .../storage/ManageVolumeAvailabilityAnswer.java |    1 +
 .../storage/PrimaryStorageDownloadAnswer.java   |    1 +
 .../storage/PrimaryStorageDownloadCommand.java  |    9 +
 .../agent/api/storage/ResizeVolumeAnswer.java   |    2 +-
 .../agent/api/storage/UpgradeDiskAnswer.java    |    4 +-
 .../cloud/agent/api/storage/UploadCommand.java  |    1 -
 .../virtualnetwork/VirtualRoutingResource.java  |    8 +
 .../cloud/agent/transport/ArrayTypeAdaptor.java |    6 +-
 .../agent/transport/InterfaceTypeAdaptor.java   |   66 +
 .../hyperv/resource/HypervResource.java         |    4 +-
 core/src/com/cloud/serializer/GsonHelper.java   |    9 +
 .../com/cloud/storage/GuestOSHypervisorVO.java  |   73 +
 .../storage/resource/StorageProcessor.java      |   45 +
 .../StorageSubsystemCommandHandler.java         |   27 +
 .../StorageSubsystemCommandHandlerBase.java     |  139 +
 .../template/HttpTemplateDownloader.java        |   94 +-
 .../storage/template/S3TemplateDownloader.java  |  418 ++
 .../storage/template/TemplateConstants.java     |   11 +-
 .../storage/template/TemplateLocation.java      |   76 +-
 .../storage/command/DownloadCommand.java        |  184 +
 .../command/DownloadProgressCommand.java        |   49 +
 .../com/cloud/agent/transport/RequestTest.java  |   58 +-
 .../agent/test/BackupSnapshotCommandTest.java   |   38 +-
 .../api/agent/test/CheckNetworkAnswerTest.java  |  205 +
 .../api/agent/test/SnapshotCommandTest.java     |    8 +-
 .../agent/api/test/ResizeVolumeCommandTest.java |  229 -
 developer/pom.xml                               |    3 +-
 docs/en-US/Release_Notes.xml                    |    9 +-
 docs/en-US/about-password-encryption.xml        |    2 +-
 docs/en-US/add-gateway-vpc.xml                  |   17 +-
 docs/en-US/building-devcloud.xml                |    2 +-
 docs/en-US/citrix-xenserver-installation.xml    |    5 +-
 docs/en-US/database-replication.xml             |   12 +-
 docs/en-US/management-server-install-client.xml |    4 +-
 .../management-server-install-db-external.xml   |    2 +-
 .../management-server-install-db-local.xml      |    4 +-
 .../management-server-install-multi-node.xml    |    4 +-
 docs/en-US/region-add.xml                       |    6 +-
 docs/en-US/source-build.xml                     |    4 +-
 .../subsystem/api/storage/ClusterScope.java     |   10 +-
 .../subsystem/api/storage/CommandResult.java    |   52 -
 .../api/storage/CopyCommandResult.java          |    9 +-
 .../subsystem/api/storage/CreateCmdResult.java  |   24 +-
 .../api/storage/DataMigrationSubSystem.java     |   29 -
 .../api/storage/DataMotionService.java          |   34 +
 .../api/storage/DataMotionStrategy.java         |   38 +
 .../subsystem/api/storage/DataObject.java       |   37 +-
 .../api/storage/DataObjectInStore.java          |   12 +-
 .../subsystem/api/storage/DataObjectType.java   |   25 -
 .../engine/subsystem/api/storage/DataStore.java |   14 +
 .../subsystem/api/storage/DataStoreDriver.java  |   26 +-
 .../api/storage/DataStoreLifeCycle.java         |   17 +-
 .../subsystem/api/storage/DataStoreManager.java |   19 +-
 .../api/storage/DataStoreProvider.java          |   33 +-
 .../api/storage/DataStoreProviderManager.java   |    9 +-
 .../subsystem/api/storage/DataStoreRole.java    |   54 -
 .../engine/subsystem/api/storage/EndPoint.java  |   12 +-
 .../subsystem/api/storage/EndPointSelector.java |   31 +
 .../engine/subsystem/api/storage/HostScope.java |   16 +-
 .../api/storage/HypervisorHostListener.java     |    1 +
 .../subsystem/api/storage/ImageDataFactory.java |   26 -
 .../api/storage/ImageDataStoreProvider.java     |   24 -
 .../subsystem/api/storage/ImageService.java     |   29 -
 .../api/storage/ImageStoreProvider.java         |   28 +
 .../storage/ObjectInDataStoreStateMachine.java  |   29 +-
 .../api/storage/PrimaryDataStoreDriver.java     |    6 +-
 .../api/storage/PrimaryDataStoreInfo.java       |   16 +-
 .../api/storage/PrimaryDataStoreLifeCycle.java  |    1 -
 .../api/storage/PrimaryDataStoreParameters.java |   40 +-
 .../engine/subsystem/api/storage/Scope.java     |   10 +-
 .../engine/subsystem/api/storage/ScopeType.java |   27 -
 .../api/storage/SnapshotDataFactory.java        |    9 +-
 .../subsystem/api/storage/SnapshotInfo.java     |   17 +-
 .../subsystem/api/storage/SnapshotProfile.java  |    9 +-
 .../subsystem/api/storage/SnapshotResult.java   |   48 +
 .../subsystem/api/storage/SnapshotService.java  |   28 +
 .../subsystem/api/storage/SnapshotStrategy.java |   16 +-
 .../api/storage/StorageCacheManager.java        |   40 +
 .../subsystem/api/storage/StorageEvent.java     |    4 +-
 .../api/storage/StorageOrchestrator.java        |   68 -
 .../api/storage/StoragePoolAllocator.java       |   27 +-
 .../subsystem/api/storage/StorageSubSystem.java |   29 -
 .../api/storage/TemplateDataFactory.java        |   31 +
 .../subsystem/api/storage/TemplateEvent.java    |    5 +-
 .../subsystem/api/storage/TemplateInfo.java     |    7 +-
 .../subsystem/api/storage/TemplateProfile.java  |  287 --
 .../subsystem/api/storage/TemplateService.java  |   64 +
 .../subsystem/api/storage/TemplateState.java    |    6 +-
 .../api/storage/VolumeDataFactory.java          |    3 +-
 .../subsystem/api/storage/VolumeInfo.java       |   28 +-
 .../subsystem/api/storage/VolumeProfile.java    |   34 -
 .../subsystem/api/storage/VolumeService.java    |   32 +-
 .../engine/subsystem/api/storage/ZoneScope.java |    6 +-
 .../api/storage/disktype/DiskFormat.java        |    5 +-
 .../subsystem/api/storage/type/BaseImage.java   |    6 +-
 .../subsystem/api/storage/type/DataDisk.java    |    6 +-
 .../engine/subsystem/api/storage/type/Iso.java  |    6 +-
 .../subsystem/api/storage/type/RootDisk.java    |    6 +-
 .../subsystem/api/storage/type/Unknown.java     |    6 +-
 .../api/storage/type/VolumeTypeBase.java        |   54 +-
 .../api/storage/type/VolumeTypeHelper.java      |   34 +-
 .../storage/command/AttachAnswer.java           |   47 +
 .../storage/command/AttachCommand.java          |   55 +
 .../command/AttachPrimaryDataStoreAnswer.java   |   56 +
 .../command/AttachPrimaryDataStoreCmd.java      |   39 +
 .../storage/command/CommandResult.java          |   52 +
 .../storage/command/CopyCmdAnswer.java          |   37 +
 .../cloudstack/storage/command/CopyCommand.java |   55 +
 .../storage/command/CreateObjectAnswer.java     |   43 +
 .../storage/command/CreateObjectCommand.java    |   45 +
 .../command/CreatePrimaryDataStoreCmd.java      |   38 +
 .../storage/command/DeleteCommand.java          |   45 +
 .../storage/command/DettachAnswer.java          |   47 +
 .../storage/command/DettachCommand.java         |   55 +
 .../command/DownloadSystemTemplateCommand.java  |  129 +
 .../command/StorageSubSystemCommand.java        |   23 +
 .../datastore/db/DataStoreProviderDao.java      |   25 -
 .../datastore/db/DataStoreProviderDaoImpl.java  |   38 -
 .../datastore/db/DataStoreProviderVO.java       |   60 -
 .../storage/datastore/db/ImageStoreDao.java     |   37 +
 .../datastore/db/ImageStoreDetailVO.java        |   82 +
 .../datastore/db/ImageStoreDetailsDao.java      |   30 +
 .../storage/datastore/db/ImageStoreVO.java      |  193 +
 .../datastore/db/PrimaryDataStoreDao.java       |  112 +-
 .../datastore/db/PrimaryDataStoreDaoImpl.java   |  554 ++-
 .../datastore/db/PrimaryDataStoreDetailVO.java  |   22 +-
 .../db/PrimaryDataStoreDetailsDao.java          |    3 +-
 .../db/PrimaryDataStoreDetailsDaoImpl.java      |   71 -
 .../datastore/db/SnapshotDataStoreDao.java      |   40 +
 .../datastore/db/SnapshotDataStoreVO.java       |  260 ++
 .../datastore/db/StoragePoolDetailVO.java       |   22 +-
 .../datastore/db/StoragePoolDetailsDao.java     |    5 +-
 .../storage/datastore/db/StoragePoolVO.java     |   40 +-
 .../datastore/db/TemplateDataStoreDao.java      |   63 +
 .../datastore/db/TemplateDataStoreVO.java       |  372 ++
 .../datastore/db/VolumeDataStoreDao.java        |   41 +
 .../storage/datastore/db/VolumeDataStoreVO.java |  348 ++
 .../image/datastore/ImageStoreEntity.java       |   46 +
 .../storage/image/datastore/ImageStoreInfo.java |   27 +
 .../cloudstack/storage/to/ImageStoreTO.java     |   79 +
 .../storage/to/PrimaryDataStoreTO.java          |  103 +
 .../cloudstack/storage/to/SnapshotObjectTO.java |  126 +
 .../cloudstack/storage/to/TemplateObjectTO.java |  199 +
 .../cloudstack/storage/to/VolumeObjectTO.java   |  215 +
 .../engine/subsystem/api/storage/ScopeTest.java |   18 +-
 .../src/com/cloud/agent/AgentManager.java       |    3 -
 .../src/com/cloud/agent/Listener.java           |   38 +-
 .../src/com/cloud/network/NetworkManager.java   |    1 +
 .../src/com/cloud/storage/VolumeManager.java    |    1 +
 .../com/cloud/vm/VirtualMachineManagerImpl.java |   14 +-
 .../cloud/vm/VirtualMachineManagerImplTest.java |   16 +-
 engine/pom.xml                                  |   18 +-
 .../com/cloud/network/rules/FirewallRuleVO.java |    7 +
 .../cloud/network/vpc/dao/VpcGatewayDao.java    |    2 +
 .../network/vpc/dao/VpcGatewayDaoImpl.java      |    8 +
 .../com/cloud/offerings/NetworkOfferingVO.java  |   10 +-
 .../src/com/cloud/storage/DiskOfferingVO.java   |  152 +-
 .../com/cloud/storage/GuestOSCategoryVO.java    |   23 +-
 .../schema/src/com/cloud/storage/GuestOSVO.java |   35 +-
 .../com/cloud/storage/LaunchPermissionVO.java   |   11 +-
 engine/schema/src/com/cloud/storage/S3VO.java   |   24 +-
 .../src/com/cloud/storage/SnapshotPolicyVO.java |   40 +-
 .../com/cloud/storage/SnapshotScheduleVO.java   |   80 +-
 .../src/com/cloud/storage/SnapshotVO.java       |  129 +-
 .../com/cloud/storage/StoragePoolHostAssoc.java |   16 +-
 .../com/cloud/storage/StoragePoolHostVO.java    |   94 +-
 .../com/cloud/storage/StoragePoolWorkVO.java    |   38 +-
 .../schema/src/com/cloud/storage/SwiftVO.java   |   31 +-
 .../schema/src/com/cloud/storage/UploadVO.java  |  288 +-
 .../com/cloud/storage/VMTemplateDetailVO.java   |   79 +-
 .../src/com/cloud/storage/VMTemplateHostVO.java |  393 +-
 .../src/com/cloud/storage/VMTemplateS3VO.java   |   34 +-
 .../cloud/storage/VMTemplateStoragePoolVO.java  |  379 +-
 .../com/cloud/storage/VMTemplateSwiftVO.java    |    3 +-
 .../src/com/cloud/storage/VMTemplateVO.java     |  273 +-
 .../src/com/cloud/storage/VMTemplateZoneVO.java |  128 +-
 .../src/com/cloud/storage/VolumeHostVO.java     |  415 +-
 .../schema/src/com/cloud/storage/VolumeVO.java  |   80 +-
 .../com/cloud/storage/dao/DiskOfferingDao.java  |    8 +-
 .../cloud/storage/dao/DiskOfferingDaoImpl.java  |   57 +-
 .../cloud/storage/dao/GuestOSCategoryDao.java   |    2 +-
 .../storage/dao/GuestOSCategoryDaoImpl.java     |   10 +-
 .../src/com/cloud/storage/dao/GuestOSDao.java   |    2 +-
 .../com/cloud/storage/dao/GuestOSDaoImpl.java   |   18 +-
 .../cloud/storage/dao/LaunchPermissionDao.java  |   28 +-
 .../storage/dao/LaunchPermissionDaoImpl.java    |   31 +-
 .../src/com/cloud/storage/dao/S3DaoImpl.java    |    3 +-
 .../src/com/cloud/storage/dao/SnapshotDao.java  |   31 +-
 .../com/cloud/storage/dao/SnapshotDaoImpl.java  |  152 +-
 .../cloud/storage/dao/SnapshotPolicyDao.java    |   12 +-
 .../storage/dao/SnapshotPolicyDaoImpl.java      |   45 +-
 .../cloud/storage/dao/SnapshotScheduleDao.java  |    5 +-
 .../storage/dao/SnapshotScheduleDaoImpl.java    |   87 +-
 .../storage/dao/StoragePoolDetailsDaoImpl.java  |   35 +-
 .../storage/dao/StoragePoolHostDaoImpl.java     |   18 +-
 .../cloud/storage/dao/StoragePoolWorkDao.java   |    3 +-
 .../storage/dao/StoragePoolWorkDaoImpl.java     |   62 +-
 .../src/com/cloud/storage/dao/SwiftDaoImpl.java |    2 +-
 .../src/com/cloud/storage/dao/UploadDao.java    |   11 +-
 .../com/cloud/storage/dao/UploadDaoImpl.java    |  111 +-
 .../com/cloud/storage/dao/VMTemplateDao.java    |   79 +-
 .../cloud/storage/dao/VMTemplateDaoImpl.java    | 1493 +++----
 .../cloud/storage/dao/VMTemplateDetailsDao.java |   10 +-
 .../storage/dao/VMTemplateDetailsDaoImpl.java   |   60 +-
 .../cloud/storage/dao/VMTemplateHostDao.java    |   15 +-
 .../storage/dao/VMTemplateHostDaoImpl.java      |  550 +--
 .../cloud/storage/dao/VMTemplatePoolDao.java    |   36 +-
 .../storage/dao/VMTemplatePoolDaoImpl.java      |  433 +-
 .../cloud/storage/dao/VMTemplateS3DaoImpl.java  |   25 +-
 .../cloud/storage/dao/VMTemplateZoneDao.java    |   14 +-
 .../storage/dao/VMTemplateZoneDaoImpl.java      |  112 +-
 .../src/com/cloud/storage/dao/VolumeDao.java    |    9 +-
 .../com/cloud/storage/dao/VolumeDaoImpl.java    |  358 +-
 .../com/cloud/storage/dao/VolumeHostDao.java    |   13 +-
 .../cloud/storage/dao/VolumeHostDaoImpl.java    |   37 +-
 .../src/com/cloud/upgrade/DatabaseCreator.java  |    7 +
 .../com/cloud/upgrade/dao/Upgrade410to420.java  |  326 +-
 .../schema/src/com/cloud/vm/VMInstanceVO.java   |   42 +-
 .../com/cloud/vm/VirtualMachineProfileImpl.java |   12 +-
 .../com/cloud/vm/dao/DomainRouterDaoImpl.java   |   18 +-
 .../lb/dao/ApplicationLoadBalancerRuleDao.java  |    1 +
 .../dao/ApplicationLoadBalancerRuleDaoImpl.java |   18 +
 engine/storage/backup/pom.xml                   |   50 -
 .../storage/backup/BackupMotionService.java     |   23 -
 .../storage/backup/BackupService.java           |   26 -
 engine/storage/cache/pom.xml                    |   50 +
 .../cache/allocator/StorageCacheAllocator.java  |   26 +
 .../allocator/StorageCacheRandomAllocator.java  |   56 +
 .../cache/manager/StorageCacheManagerImpl.java  |  254 ++
 .../StorageCacheReplacementAlgorithm.java       |   26 +
 .../StorageCacheReplacementAlgorithmLRU.java    |  106 +
 engine/storage/datamotion/pom.xml               |   62 +
 .../motion/AncientDataMotionStrategy.java       |  414 ++
 .../storage/motion/DataMotionServiceImpl.java   |   75 +
 .../storage/image/ImageDataFactoryImpl.java     |   93 -
 .../storage/image/ImageOrchestrator.java        |   29 -
 .../storage/image/ImageServiceImpl.java         |  235 -
 .../storage/image/TemplateDataFactoryImpl.java  |  105 +
 .../storage/image/TemplateServiceImpl.java      |  610 +++
 .../image/downloader/ImageDownloader.java       |   25 -
 .../driver/AncientImageDataStoreDriverImpl.java |  254 --
 .../driver/DefaultImageDataStoreDriverImpl.java |  126 -
 .../storage/image/manager/ImageDataManager.java |   30 -
 .../image/manager/ImageDataManagerImpl.java     |   50 -
 .../manager/ImageDataStoreManagerImpl.java      |   94 -
 .../manager/ImageStoreProviderManagerImpl.java  |  130 +
 .../store/AncientImageDataStoreProvider.java    |  101 -
 .../image/store/DefaultImageDataStoreImpl.java  |  145 -
 .../store/DefaultImageDataStoreProvider.java    |   82 -
 .../storage/image/store/ImageStoreImpl.java     |  198 +
 .../storage/image/store/TemplateObject.java     |  400 +-
 .../DefaultImageDataStoreLifeCycle.java         |  108 -
 .../lifecycle/ImageDataStoreLifeCycle.java      |   24 -
 .../store/lifecycle/ImageStoreLifeCycle.java    |   24 +
 engine/storage/imagemotion/pom.xml              |   62 -
 .../motion/DefaultImageMotionStrategy.java      |  158 -
 .../image/motion/ImageMotionServiceImpl.java    |   70 -
 .../image/motion/ImageMotionStrategy.java       |   24 -
 engine/storage/integration-test/pom.xml         |   50 +-
 .../MockLocalNfsSecondaryStorageResource.java   |  135 +
 .../storage/allocator/StorageAllocatorTest.java |  737 ++--
 .../StorageAllocatorTestConfiguration.java      |   47 +-
 ...StorageCacheReplacementAlgorithmLRUTest.java |  226 +
 .../apache/cloudstack/storage/test/AopTest.java |    2 +-
 .../cloudstack/storage/test/AopTestAdvice.java  |   20 +-
 .../storage/test/ChildTestConfiguration.java    |  157 +-
 .../storage/test/CloudStackTestNGBase.java      |  132 +-
 .../test/DirectAgentManagerSimpleImpl.java      |   88 +-
 .../storage/test/DirectAgentTest.java           |   66 +-
 ...HostEndpointRpcServerDirectCallResource.java |   70 -
 .../MockHypervisorHostEndPointRpcServer.java    |   72 -
 .../storage/test/MockLocalHostEndPoint.java     |   39 +
 .../storage/test/MockRpcCallBack.java           |   12 +-
 .../storage/test/MockStorageMotionStrategy.java |    5 +-
 .../cloudstack/storage/test/S3TemplateTest.java |  180 +
 .../cloudstack/storage/test/SnapshotTest.java   |  500 +++
 .../storage/test/StorageFactoryBean.java        |   11 +-
 .../cloudstack/storage/test/StorageTest.java    |   11 +-
 .../cloudstack/storage/test/TemplateTest.java   |  167 +
 .../cloudstack/storage/test/TestHttp.java       |   17 +-
 .../apache/cloudstack/storage/test/TestNG.java  |    5 +-
 .../cloudstack/storage/test/TestNGAop.java      |    6 +-
 .../cloudstack/storage/test/VolumeTest.java     |  433 ++
 .../storage/test/VolumeTestVmware.java          |  444 ++
 .../storage/test/volumeServiceTest.java         |  618 +--
 .../test/resource/s3_testng.xml                 |   47 +
 .../test/resource/storageContext.xml            |   77 +-
 .../integration-test/test/resource/testng.xml   |   19 +-
 engine/storage/pom.xml                          |    7 +-
 engine/storage/snapshot/pom.xml                 |    5 +
 .../snapshot/SnapshotDataFactoryImpl.java       |   51 +-
 .../storage/snapshot/SnapshotObject.java        |  353 +-
 .../storage/snapshot/SnapshotServiceImpl.java   |  390 +-
 .../snapshot/SnapshotStateMachineManager.java   |    2 +-
 .../SnapshotStateMachineManagerImpl.java        |   47 +-
 .../storage/snapshot/SnapshotStrategyBase.java  |   38 +
 .../snapshot/XenserverSnapshotStrategy.java     |  204 +
 .../storage/snapshot/db/SnapshotDao2.java       |   25 -
 .../storage/snapshot/db/SnapshotDao2Impl.java   |   28 -
 .../storage/snapshot/db/SnapshotVO.java         |  296 --
 .../strategy/AncientSnapshotStrategy.java       |  613 ---
 .../test/src/SnapshotDataFactoryTest.java       |   23 +-
 .../org/apache/cloudstack/storage/BaseType.java |    1 +
 .../storage/HostEndpointRpcServer.java          |   29 -
 .../storage/HypervisorHostEndPoint.java         |   75 -
 .../HypervisorHostEndPointRpcServer.java        |  119 -
 .../cloudstack/storage/LocalHostEndpoint.java   |  101 +
 .../cloudstack/storage/RemoteHostEndPoint.java  |  178 +
 .../allocator/AbstractStoragePoolAllocator.java |   87 +-
 .../ClusterScopeStoragePoolAllocator.java       |   26 +-
 .../GarbageCollectingStoragePoolAllocator.java  |   18 +-
 .../allocator/LocalStoragePoolAllocator.java    |   15 +-
 .../allocator/UseLocalForRootAllocator.java     |    7 +-
 .../allocator/ZoneWideStoragePoolAllocator.java |   20 +-
 .../backup/SnapshotOnBackupStoreInfo.java       |    5 +-
 .../backup/datastore/BackupStoreInfo.java       |    5 +-
 .../command/AttachPrimaryDataStoreAnswer.java   |   55 -
 .../command/AttachPrimaryDataStoreCmd.java      |   38 -
 .../cloudstack/storage/command/CopyCmd.java     |   45 -
 .../storage/command/CopyCmdAnswer.java          |   33 -
 .../CopyTemplateToPrimaryStorageAnswer.java     |   16 -
 .../storage/command/CreateObjectAnswer.java     |   48 -
 .../storage/command/CreateObjectCommand.java    |   45 -
 .../command/CreatePrimaryDataStoreCmd.java      |   37 -
 .../CreateVolumeFromBaseImageCommand.java       |   49 -
 .../storage/command/DeleteCommand.java          |   44 -
 .../command/StorageSubSystemCommand.java        |   23 -
 .../storage/datastore/DataObjectManager.java    |   11 +-
 .../datastore/DataObjectManagerImpl.java        |  174 +-
 .../storage/datastore/DataStoreManagerImpl.java |   47 +-
 .../datastore/ObjectInDataStoreManager.java     |   18 +-
 .../datastore/ObjectInDataStoreManagerImpl.java |  334 +-
 .../storage/datastore/PrimaryDataStore.java     |    3 +-
 .../datastore/PrimaryDataStoreEntityImpl.java   |   22 +-
 .../PrimaryDataStoreProviderManager.java        |    3 +-
 .../datastore/protocol/DataStoreProtocol.java   |    8 +-
 .../provider/DataStoreProviderManagerImpl.java  |   75 +-
 .../storage/db/ObjectInDataStoreDao.java        |    3 +-
 .../storage/db/ObjectInDataStoreDaoImpl.java    |   29 +-
 .../storage/db/ObjectInDataStoreVO.java         |  100 +-
 .../endpoint/DefaultEndPointSelector.java       |  128 +-
 .../storage/endpoint/EndPointSelector.java      |   40 -
 .../storage/image/BaseImageStoreDriverImpl.java |  216 +
 .../storage/image/ImageDataStoreDriver.java     |   24 -
 .../storage/image/ImageStoreDriver.java         |   28 +
 .../storage/image/TemplateEntityImpl.java       |   14 +-
 .../storage/image/datastore/ImageDataStore.java |   35 -
 .../image/datastore/ImageDataStoreHelper.java   |   60 -
 .../image/datastore/ImageDataStoreInfo.java     |   26 -
 .../image/datastore/ImageDataStoreManager.java  |   31 -
 .../image/datastore/ImageStoreHelper.java       |  118 +
 .../datastore/ImageStoreProviderManager.java    |   42 +
 .../storage/image/db/ImageDaoStoreDaoImpl.java  |   38 -
 .../storage/image/db/ImageDataStoreDao.java     |   25 -
 .../image/db/ImageDataStoreProviderDao.java     |   25 -
 .../image/db/ImageDataStoreProviderDaoImpl.java |   40 -
 .../image/db/ImageDataStoreProviderVO.java      |   49 -
 .../storage/image/db/ImageDataStoreVO.java      |  110 -
 .../storage/image/db/ImageStoreDaoImpl.java     |  107 +
 .../image/db/ImageStoreDetailsDaoImpl.java      |   88 +
 .../image/db/SnapshotDataStoreDaoImpl.java      |  168 +
 .../image/db/TemplateDataStoreDaoImpl.java      |  325 ++
 .../image/db/VolumeDataStoreDaoImpl.java        |  172 +
 .../image/motion/ImageMotionService.java        |    8 +-
 .../motion/AncientDataMotionStrategy.java       |  806 ----
 .../storage/motion/DataMotionDriver.java        |   25 -
 .../storage/motion/DataMotionService.java       |   37 -
 .../storage/motion/DataMotionServiceImpl.java   |   77 -
 .../storage/motion/DataMotionStrategy.java      |   40 -
 .../storage/snapshot/SnapshotEntityImpl.java    |  316 +-
 .../storage/snapshot/SnapshotService.java       |   27 -
 .../cloudstack/storage/to/ImageDataStoreTO.java |   36 -
 .../storage/to/ImageOnPrimaryDataStoreTO.java   |   44 -
 .../storage/to/NfsPrimaryDataStoreTO.java       |   44 -
 .../storage/to/PrimaryDataStoreTO.java          |   48 -
 .../cloudstack/storage/to/TemplateTO.java       |   51 -
 .../apache/cloudstack/storage/to/VolumeTO.java  |   77 -
 .../datastore/PrimaryDataStoreHelper.java       |   32 +-
 .../db/PrimaryDataStoreDetailsDaoImpl.java      |   74 +
 .../volume/db/TemplatePrimaryDataStoreDao.java  |    4 +-
 .../db/TemplatePrimaryDataStoreDaoImpl.java     |   43 +-
 .../volume/db/TemplatePrimaryDataStoreVO.java   |   18 +-
 .../storage/volume/db/VolumeDao2.java           |   82 -
 .../storage/volume/db/VolumeDao2Impl.java       |  440 --
 .../cloudstack/storage/volume/db/VolumeVO.java  |  418 --
 .../datastore/DefaultPrimaryDataStore.java      |  343 --
 .../storage/datastore/PrimaryDataStoreImpl.java |  349 ++
 .../DefaultPrimaryDataStoreDriverImpl.java      |  249 --
 .../driver/PrimaryDataStoreDriver.java          |   16 -
 .../DefaultPrimaryDataStoreLifeCycleImpl.java   |  147 -
 ...aultPrimaryDataStoreProviderManagerImpl.java |   85 -
 .../PrimaryDataStoreProviderManagerImpl.java    |   84 +
 .../datastore/provider/DefaultHostListener.java |   36 +-
 .../DefaultPrimaryDatastoreProviderImpl.java    |   83 -
 .../PrimaryDataStoreProviderManager.java        |   16 -
 .../storage/volume/TemplateInstallStrategy.java |   28 -
 .../volume/TemplateInstallStrategyImpl.java     |  289 --
 .../storage/volume/VolumeDataFactoryImpl.java   |   25 +-
 .../storage/volume/VolumeEntityImpl.java        |  204 -
 .../storage/volume/VolumeMotionService.java     |   23 -
 .../cloudstack/storage/volume/VolumeObject.java |  361 +-
 .../storage/volume/VolumeServiceImpl.java       |  613 ++-
 .../storage/volume/test/ConfiguratorTest.java   |   64 +-
 .../cloudstack/storage/volume/test/Server.java  |   17 +-
 .../storage/volume/test/TestConfiguration.java  |    2 +-
 .../storage/volume/test/TestInProcessAsync.java |    7 +-
 .../async/AsyncCallbackDispatcher.java          |   30 +-
 patches/systemvm/debian/buildsystemvm.sh        |   37 +-
 .../debian/config/etc/init.d/cloud-early-config |    7 +-
 .../debian/config/root/createIpAlias.sh         |    5 +-
 .../systemvm/debian/config/root/edithosts.sh    |    4 +-
 .../debian/config/root/firewallRule_egress.sh   |   26 +-
 .../systemvm/debian/config/root/savepassword.sh |    4 +-
 patches/systemvm/debian/config/root/userdata.sh |    4 +-
 .../baremetal/manager/AddBaremetalHostCmd.java  |   48 -
 .../baremetal/manager/BareMetalDiscoverer.java  |    3 +-
 .../manager/BareMetalTemplateAdapter.java       |  128 +-
 .../baremetal/manager/BaremetalManagerImpl.java |    1 +
 .../networkservice/AddBaremetalDhcpCmd.java     |  154 -
 .../AddBaremetalKickStartPxeCmd.java            |   37 -
 .../networkservice/AddBaremetalPxeCmd.java      |  148 -
 .../AddBaremetalPxePingServerCmd.java           |   82 -
 .../BareMetalPingServiceImpl.java               |    2 +
 .../networkservice/BareMetalResourceBase.java   |   28 +-
 .../networkservice/BaremetalDhcpElement.java    |    6 +-
 .../networkservice/BaremetalDhcpManager.java    |    2 +
 .../BaremetalDhcpManagerImpl.java               |    6 +-
 .../BaremetalKickStartServiceImpl.java          |    2 +
 .../networkservice/BaremetalPxeManager.java     |    4 +-
 .../networkservice/BaremetalPxeManagerImpl.java |    7 +-
 .../networkservice/BaremetalPxeService.java     |    2 +
 .../cloudstack/api/AddBaremetalDhcpCmd.java     |  156 +
 .../cloudstack/api/AddBaremetalHostCmd.java     |   50 +
 .../api/AddBaremetalKickStartPxeCmd.java        |   39 +
 .../cloudstack/api/AddBaremetalPxeCmd.java      |  149 +
 .../api/AddBaremetalPxePingServerCmd.java       |   84 +
 .../kvm/resource/BridgeVifDriver.java           |   14 +-
 .../kvm/resource/DirectVifDriver.java           |    8 +-
 .../kvm/resource/LibvirtComputingResource.java  |  256 +-
 .../kvm/resource/LibvirtConnection.java         |   23 +-
 .../kvm/resource/LibvirtDomainXMLParser.java    |   40 +-
 .../hypervisor/kvm/resource/LibvirtVMDef.java   |   82 +-
 .../hypervisor/kvm/resource/OvsVifDriver.java   |   16 +-
 .../kvm/storage/KVMStorageProcessor.java        |  862 ++++
 .../kvm/storage/KVMStorageResource.java         |   87 +
 .../cloud/ovm/hypervisor/OvmResourceBase.java   |   31 +-
 .../cloud/agent/manager/MockStorageManager.java |   13 +-
 .../agent/manager/MockStorageManagerImpl.java   |   69 +-
 .../agent/manager/SimulatorManagerImpl.java     |   34 +-
 .../com/cloud/resource/AgentResourceBase.java   |   29 +-
 .../cloud/resource/AgentRoutingResource.java    |    4 +-
 .../cloud/resource/AgentStorageResource.java    |    2 +-
 .../com/cloud/resource/SimulatorDiscoverer.java |    6 +-
 .../resource/SimulatorSecondaryDiscoverer.java  |   15 +-
 .../resource/SimulatorStorageProcessor.java     |  187 +
 .../com/cloud/hypervisor/guru/VMwareGuru.java   |   25 +-
 .../vmware/VmwareServerDiscoverer.java          |    2 +-
 .../vmware/manager/VmwareManagerImpl.java       |   19 +-
 .../manager/VmwareStorageManagerImpl.java       |   38 +-
 .../vmware/resource/VmwareResource.java         |  344 +-
 .../VmwareSecondaryStorageResourceHandler.java  |  126 +-
 .../resource/VmwareStorageProcessor.java        | 1283 ++++++
 .../motion/VmwareStorageMotionStrategy.java     |    9 +-
 .../vmware/VmwareDatacenterApiUnitTest.java     |   23 +-
 .../motion/VmwareStorageMotionStrategyTest.java |    2 +-
 .../src/com/cloud/hypervisor/XenServerGuru.java |    1 +
 .../xen/discoverer/XcpServerDiscoverer.java     |  156 +-
 .../hypervisor/xen/resource/CitrixHelper.java   |    4 +
 .../xen/resource/CitrixResourceBase.java        |  144 +-
 .../hypervisor/xen/resource/XcpOssResource.java |   42 +-
 .../xen/resource/XenServer56FP1Resource.java    |   59 +-
 .../xen/resource/XenServer610Resource.java      |   23 +-
 .../xen/resource/XenServerStorageProcessor.java | 1516 +++++++
 .../xen/resource/XenServerStorageResource.java  |  662 ---
 .../motion/XenServerStorageMotionStrategy.java  |   11 +-
 .../resources/components-example.xml            |    8 -
 .../element/InternalLoadBalancerElement.java    |   42 +-
 .../lb/InternalLoadBalancerVMManagerImpl.java   |   27 +-
 .../network/resource/JuniperSrxResource.java    |   86 +-
 plugins/pom.xml                                 |    4 +
 .../allocator/RandomStoragePoolAllocator.java   |   21 +-
 plugins/storage/image/default/pom.xml           |   71 +
 .../driver/CloudStackImageStoreDriverImpl.java  |   95 +
 .../CloudStackImageStoreLifeCycleImpl.java      |  155 +
 .../CloudStackImageStoreProviderImpl.java       |  103 +
 plugins/storage/image/s3/pom.xml                |   15 +
 .../driver/S3ImageStoreDriverImpl.java          |   92 +
 .../lifecycle/S3ImageStoreLifeCycleImpl.java    |  135 +
 .../provider/S3ImageStoreProviderImpl.java      |  100 +
 plugins/storage/image/sample/pom.xml            |   71 +
 .../driver/SampleImageStoreDriverImpl.java      |   53 +
 .../SampleImageStoreLifeCycleImpl.java          |   82 +
 .../provider/SampleImageStoreProviderImpl.java  |   96 +
 plugins/storage/image/swift/pom.xml             |   71 +
 .../driver/SwiftImageStoreDriverImpl.java       |   55 +
 .../lifecycle/SwiftImageStoreLifeCycleImpl.java |  116 +
 .../provider/SwiftImageStoreProviderImpl.java   |  102 +
 .../CloudStackPrimaryDataStoreDriverImpl.java   |  485 +--
 ...CloudStackPrimaryDataStoreLifeCycleImpl.java |  152 +-
 .../CloudStackPrimaryDataStoreProviderImpl.java |   14 +-
 plugins/storage/volume/sample/pom.xml           |   56 +
 .../SamplePrimaryDataStoreDriverImpl.java       |  181 +
 .../SamplePrimaryDataStoreLifeCycleImpl.java    |  122 +
 .../SamplePrimaryDatastoreProviderImpl.java     |   79 +
 .../driver/SolidfirePrimaryDataStoreDriver.java |   54 +-
 .../SolidfirePrimaryDataStoreProvider.java      |   57 +-
 .../cloudstack/storage/test/AopTestAdvice.java  |   20 +-
 .../storage/test/ChildTestConfiguration.java    |   47 +-
 .../storage/test/TestConfiguration.java         |   17 +-
 .../cloudstack/storage/test/VolumeTest.java     |  169 +-
 python/lib/cloudutils/networkConfig.py          |    2 +-
 scripts/network/juniper/security-policy-add.xml |    3 +-
 scripts/storage/qcow2/createtmplt.sh            |    4 +-
 scripts/storage/qcow2/managesnapshot.sh         |    2 +-
 .../create_privatetemplate_from_snapshot_xen.sh |   98 +
 .../cloud/agent/manager/AgentManagerImpl.java   |   24 -
 .../com/cloud/agent/manager/AgentMonitor.java   |    2 +-
 .../manager/ClusteredAgentManagerImpl.java      |    4 +-
 .../agent/manager/SynchronousListener.java      |    4 +-
 .../impl/UserConcentratedAllocator.java         |   58 +-
 server/src/com/cloud/api/ApiDBUtils.java        |   90 +-
 server/src/com/cloud/api/ApiResponseHelper.java |  678 ++-
 .../com/cloud/api/query/QueryManagerImpl.java   | 1078 +++--
 .../com/cloud/api/query/ViewResponseHelper.java |   74 +
 .../api/query/dao/DiskOfferingJoinDaoImpl.java  |    5 +
 .../api/query/dao/DomainRouterJoinDaoImpl.java  |    1 -
 .../cloud/api/query/dao/HostJoinDaoImpl.java    |    1 -
 .../cloud/api/query/dao/ImageStoreJoinDao.java  |   36 +
 .../api/query/dao/ImageStoreJoinDaoImpl.java    |  162 +
 .../query/dao/ServiceOfferingJoinDaoImpl.java   |    4 +
 .../api/query/dao/StoragePoolJoinDaoImpl.java   |   56 +-
 .../cloud/api/query/dao/TemplateJoinDao.java    |   44 +
 .../api/query/dao/TemplateJoinDaoImpl.java      |  463 ++
 .../com/cloud/api/query/dao/UserVmJoinDao.java  |    2 +
 .../cloud/api/query/dao/UserVmJoinDaoImpl.java  |   26 +-
 .../cloud/api/query/dao/VolumeJoinDaoImpl.java  |    6 +-
 .../cloud/api/query/vo/DiskOfferingJoinVO.java  |   42 +
 .../cloud/api/query/vo/DomainRouterJoinVO.java  |   12 -
 .../src/com/cloud/api/query/vo/HostJoinVO.java  |   11 -
 .../cloud/api/query/vo/ImageStoreJoinVO.java    |  207 +
 .../api/query/vo/ServiceOfferingJoinVO.java     |   41 +
 .../cloud/api/query/vo/StoragePoolJoinVO.java   |   22 +-
 .../com/cloud/api/query/vo/TemplateJoinVO.java  | 1030 +++++
 .../com/cloud/api/query/vo/UserVmJoinVO.java    |   24 +-
 .../com/cloud/api/query/vo/VolumeJoinVO.java    |   58 +-
 .../src/com/cloud/capacity/CapacityManager.java |    2 +-
 .../com/cloud/capacity/CapacityManagerImpl.java |    4 +-
 .../cloud/capacity/ComputeCapacityListener.java |    4 +-
 .../cloud/capacity/StorageCapacityListener.java |    4 +-
 server/src/com/cloud/configuration/Config.java  |   19 +-
 .../configuration/ConfigurationManager.java     |   16 +-
 .../configuration/ConfigurationManagerImpl.java | 1284 ++++--
 .../src/com/cloud/consoleproxy/AgentHook.java   |    9 +-
 .../com/cloud/consoleproxy/AgentHookBase.java   |   21 +-
 .../consoleproxy/ConsoleProxyListener.java      |    4 +-
 .../cloud/consoleproxy/ConsoleProxyManager.java |    1 -
 .../consoleproxy/ConsoleProxyManagerImpl.java   |   33 +-
 .../deploy/DeploymentPlanningManagerImpl.java   |    2 +-
 .../com/cloud/ha/UserVmDomRInvestigator.java    |    3 +-
 .../cloud/hypervisor/HypervisorGuruBase.java    |   17 +-
 .../kvm/discoverer/LibvirtServerDiscoverer.java |   99 +-
 .../ExternalFirewallDeviceManagerImpl.java      |   24 +-
 .../com/cloud/network/NetworkManagerImpl.java   |   41 +-
 .../src/com/cloud/network/NetworkModelImpl.java |   11 +
 .../com/cloud/network/NetworkServiceImpl.java   |   81 +-
 .../cloud/network/NetworkUsageManagerImpl.java  |    2 +-
 .../com/cloud/network/SshKeysDistriMonitor.java |    4 +-
 .../element/CloudZonesNetworkElement.java       |    5 +-
 .../network/firewall/FirewallManagerImpl.java   |   31 +
 .../VirtualNetworkApplianceManagerImpl.java     |   53 +-
 .../cloud/network/rules/FirewallManager.java    |    1 +
 .../network/security/SecurityGroupListener.java |    4 +-
 .../cloud/network/vpc/NetworkACLManager.java    |    2 +-
 .../network/vpc/NetworkACLManagerImpl.java      |   28 +-
 .../network/vpc/NetworkACLServiceImpl.java      |   51 +-
 .../com/cloud/network/vpc/VpcManagerImpl.java   |    7 +-
 .../com/cloud/resource/ResourceManagerImpl.java | 1042 ++---
 .../resourcelimit/ResourceLimitManagerImpl.java |   19 +-
 .../cloud/server/ConfigurationServerImpl.java   |   17 +-
 .../src/com/cloud/server/ManagementServer.java  |    2 +
 .../com/cloud/server/ManagementServerImpl.java  |  385 +-
 server/src/com/cloud/server/StatsCollector.java |  204 +-
 .../cloud/storage/CreateSnapshotPayload.java    |   50 +
 .../cloud/storage/LocalStoragePoolListener.java |    4 +-
 .../src/com/cloud/storage/StorageManager.java   |   10 +
 .../com/cloud/storage/StorageManagerImpl.java   | 1234 +++---
 .../src/com/cloud/storage/TemplateProfile.java  |   79 +-
 .../com/cloud/storage/VolumeManagerImpl.java    |  435 +-
 .../cloud/storage/dao/GuestOSHypervisorDao.java |   27 +
 .../storage/dao/GuestOSHypervisorDaoImpl.java   |   49 +
 .../download/DownloadAbandonedState.java        |    7 +-
 .../storage/download/DownloadActiveState.java   |    4 +-
 .../storage/download/DownloadCompleteState.java |    3 +-
 .../storage/download/DownloadErrorState.java    |    8 +-
 .../storage/download/DownloadListener.java      |  430 +-
 .../cloud/storage/download/DownloadMonitor.java |   29 +-
 .../storage/download/DownloadMonitorImpl.java   | 1132 +----
 .../cloud/storage/download/DownloadState.java   |    2 +-
 .../storage/download/NotDownloadedState.java    |    3 +-
 .../storage/listener/StoragePoolMonitor.java    |    6 +-
 .../storage/listener/StorageSyncListener.java   |    4 +-
 .../resource/DummySecondaryStorageResource.java |   14 +-
 server/src/com/cloud/storage/s3/S3Manager.java  |    5 +-
 .../src/com/cloud/storage/s3/S3ManagerImpl.java |  106 +-
 .../secondary/SecondaryStorageListener.java     |    4 +-
 .../secondary/SecondaryStorageManagerImpl.java  |  183 +-
 .../secondary/SecondaryStorageVmManager.java    |   14 +-
 .../cloud/storage/snapshot/SnapshotManager.java |   18 +-
 .../storage/snapshot/SnapshotManagerImpl.java   |  420 +-
 .../cloud/storage/swift/SwiftManagerImpl.java   |   15 +-
 .../cloud/storage/upload/UploadListener.java    |  123 +-
 .../com/cloud/storage/upload/UploadMonitor.java |   13 +-
 .../cloud/storage/upload/UploadMonitorImpl.java |  133 +-
 .../template/HypervisorTemplateAdapter.java     |  458 +-
 .../src/com/cloud/template/TemplateAdapter.java |   15 +-
 .../com/cloud/template/TemplateAdapterBase.java |   43 +-
 .../src/com/cloud/template/TemplateManager.java |   41 +-
 .../com/cloud/template/TemplateManagerImpl.java | 1498 +++----
 server/src/com/cloud/test/DatabaseConfig.java   |   28 +
 server/src/com/cloud/vm/UserVmManagerImpl.java  |   88 +-
 server/src/com/cloud/vm/dao/NicIpAliasDao.java  |    1 -
 .../src/com/cloud/vm/dao/NicIpAliasDaoImpl.java |    9 -
 .../com/cloud/agent/MockAgentManagerImpl.java   |   10 +-
 .../com/cloud/async/TestAsyncJobManager.java    |    2 +-
 .../network/DedicateGuestVlanRangesTest.java    |    4 +-
 .../cloud/network/MockFirewallManagerImpl.java  |    5 +
 .../com/cloud/network/MockNetworkModelImpl.java |    6 +
 .../cloud/resource/MockResourceManagerImpl.java |    1 +
 .../vm/VmWorkMockVirtualMachineManagerImpl.java |    6 +-
 .../cloud/vpc/MockConfigurationManagerImpl.java |    8 +-
 .../com/cloud/vpc/MockNetworkModelImpl.java     |    6 +
 .../networkoffering/ChildTestConfiguration.java |    6 +-
 .../CreateNetworkOfferingTest.java              |   20 +-
 .../resource/CifsSecondaryStorageResource.java  |  755 ----
 .../LocalNfsSecondaryStorageResource.java       |  233 +
 .../resource/LocalSecondaryStorageResource.java |   24 +-
 .../resource/NfsSecondaryStorageResource.java   | 1632 ++++---
 .../resource/SecondaryStorageDiscoverer.java    |   79 +-
 .../resource/SecondaryStorageResource.java      |    3 +-
 .../storage/template/DownloadManager.java       |   37 +-
 .../storage/template/DownloadManagerImpl.java   |  287 +-
 setup/bindir/cloud-set-guest-sshkey.in          |   44 +-
 setup/db/db/schema-410to420.sql                 |  345 +-
 setup/db/templates.simulator.sql                |    8 +-
 setup/db/templates.sql                          |    5 +
 setup/dev/advanced.cfg                          |    3 +-
 setup/dev/advancedsg.cfg                        |    3 +-
 setup/dev/basic.cfg                             |    3 +-
 test/integration/component/test_accounts.py     |   21 +-
 test/integration/component/test_baremetal.py    |  123 +
 test/integration/component/test_blocker_bugs.py |  303 --
 .../component/test_explicit_dedication.py       |    3 -
 .../component/test_implicit_planner.py          |    3 -
 .../component/test_netscaler_configs.py         |    2 +-
 test/integration/component/test_netscaler_lb.py |    4 +-
 .../component/test_netscaler_nw_off.py          |    5 +-
 .../component/test_recurring_snapshots.py       |  405 ++
 .../component/test_redundant_router.py          | 4096 +-----------------
 .../component/test_redundant_router_cleanups.py |  675 +++
 ...test_redundant_router_deployment_planning.py | 1006 +++++
 .../test_redundant_router_network_rules.py      | 1416 ++++++
 .../component/test_redundant_router_services.py |  376 ++
 .../component/test_redundant_router_upgrades.py |  486 +++
 .../component/test_shared_networks.py           |    1 +
 test/integration/component/test_snapshot_gc.py  |  474 ++
 .../component/test_snapshot_limits.py           |  384 ++
 test/integration/component/test_snapshots.py    | 2171 +++-------
 .../component/test_storage_motion.py            |    3 -
 test/integration/component/test_volumes.py      |   68 +-
 test/integration/component/test_vpc.py          |   44 +-
 test/integration/component/test_vpc_network.py  |   80 +-
 .../component/test_vpc_network_lbrules.py       |    3 -
 .../component/test_vpc_network_pfrules.py       |    3 -
 .../component/test_vpc_network_staticnatrule.py |    3 -
 .../integration/component/test_vpc_offerings.py |   52 +-
 test/integration/smoke/test_network.py          |    2 +-
 test/integration/smoke/test_nic.py              |    3 -
 test/integration/smoke/test_resource_detail.py  |    3 -
 test/integration/smoke/test_scale_vm.py         |   16 +-
 test/integration/smoke/test_snapshots.py        |  345 ++
 test/integration/smoke/test_ssvm.py             |   42 +-
 test/integration/smoke/test_vm_life_cycle.py    |   38 +-
 test/integration/smoke/test_volumes.py          |    4 +-
 test/pom.xml                                    |    2 +-
 tools/apidoc/gen_toc.py                         |    8 +-
 .../definitions/devcloud/definition.rb          |    6 +-
 .../definitions/systemvmtemplate/definition.rb  |    2 +-
 .../definitions/systemvmtemplate/postinstall.sh |    5 +
 .../systemvmtemplate64/definition.rb            |    2 +-
 tools/devcloud/devcloud.cfg                     |    4 +-
 tools/devcloud/devcloud_s3.cfg                  |  141 +
 tools/marvin/marvin/TestCaseExecuteEngine.py    |   43 +-
 tools/marvin/marvin/__init__.py                 |    4 +-
 tools/marvin/marvin/asyncJobMgr.py              |   46 +-
 tools/marvin/marvin/cloudstackConnection.py     |    2 +-
 tools/marvin/marvin/cloudstackException.py      |   22 +-
 tools/marvin/marvin/cloudstackTestCase.py       |   11 +-
 tools/marvin/marvin/cloudstackTestClient.py     |   69 +-
 tools/marvin/marvin/codegenerator.py            |  143 +-
 tools/marvin/marvin/configGenerator.py          |  351 +-
 tools/marvin/marvin/dbConnection.py             |   41 +-
 tools/marvin/marvin/deployAndRun.py             |   53 +-
 tools/marvin/marvin/deployDataCenter.py         |  219 +-
 tools/marvin/marvin/integration/lib/utils.py    |    2 +-
 tools/marvin/marvin/jsonHelper.py               |  279 +-
 tools/marvin/marvin/marvinPlugin.py             |   79 +-
 tools/marvin/marvin/remoteSSHClient.py          |   58 +-
 .../marvin/sandbox/advanced/advanced_env.py     |    1 +
 .../marvin/sandbox/advancedsg/advancedsg_env.py |    1 +
 tools/marvin/marvin/sandbox/basic/basic_env.py  |    1 +
 tools/marvin/marvin/settings.py                 |   10 +-
 tools/marvin/marvin/testSetupSuccess.py         |   40 +-
 ui/css/cloudstack3.css                          |   71 +-
 ui/dictionary.jsp                               |    4 +
 ui/scripts/cloudStack.js                        |   32 +-
 ui/scripts/configuration.js                     |  158 +-
 ui/scripts/docs.js                              |    6 +-
 ui/scripts/globalSettings.js                    |    2 +-
 ui/scripts/instances.js                         |  132 +-
 ui/scripts/network.js                           |   65 +-
 ui/scripts/sharedFunctions.js                   |    6 +-
 ui/scripts/system.js                            | 2321 +++++++---
 ui/scripts/ui-custom/physicalResources.js       |    7 +-
 ui/scripts/ui-custom/zoneChart.js               |    9 +-
 ui/scripts/ui/dialog.js                         |    4 +-
 ui/scripts/ui/widgets/listView.js               |    4 +
 ui/scripts/ui/widgets/multiEdit.js              |    2 +-
 ui/scripts/zoneWizard.js                        |  396 +-
 utils/src/com/cloud/utils/S3Utils.java          |  102 +-
 utils/src/com/cloud/utils/UriUtils.java         |   82 +
 utils/src/com/cloud/utils/script/Script.java    |   10 +-
 .../test/com/cloud/utils/testcase/NioTest.java  |   14 +-
 .../hypervisor/vmware/util/VmwareClient.java    |    7 +-
 889 files changed, 51206 insertions(+), 35863 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/com/cloud/server/ManagementService.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/com/cloud/vm/VirtualMachine.java
----------------------------------------------------------------------
diff --cc api/src/com/cloud/vm/VirtualMachine.java
index fe0ea76,c172fbf..ce2d90e
--- a/api/src/com/cloud/vm/VirtualMachine.java
+++ b/api/src/com/cloud/vm/VirtualMachine.java
@@@ -161,7 -158,10 +161,9 @@@ public interface VirtualMachine extend
          }
      }
  
+     public static final String IsDynamicScalingEnabled = "enable.dynamic.scaling";
+ 
      public enum Event {
 -        CreateRequested,
          StartRequested,
          StopRequested,
          DestroyRequested,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/com/cloud/vm/VirtualMachineProfile.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/BaseCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/ResponseGenerator.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/ResponseGenerator.java
index 386b16c,d8d07cb..dca26fb
--- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java
+++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java
@@@ -117,79 -188,11 +118,80 @@@ import org.apache.cloudstack.region.Por
  import org.apache.cloudstack.region.Region;
  import org.apache.cloudstack.usage.Usage;
  
 +import com.cloud.capacity.Capacity;
 +import com.cloud.configuration.ResourceCount;
 +import com.cloud.configuration.ResourceLimit;
 +import com.cloud.dc.DataCenter;
 +import com.cloud.dc.Pod;
 +import com.cloud.dc.StorageNetworkIpRange;
 +import com.cloud.dc.Vlan;
 +import com.cloud.domain.Domain;
 +import com.cloud.event.Event;
 +import com.cloud.host.Host;
 +import com.cloud.hypervisor.HypervisorCapabilities;
 +import com.cloud.network.GuestVlan;
 +import com.cloud.network.IpAddress;
 +import com.cloud.network.Network;
 +import com.cloud.network.Network.Service;
 +import com.cloud.network.Networks.IsolationType;
 +import com.cloud.network.PhysicalNetwork;
 +import com.cloud.network.PhysicalNetworkServiceProvider;
 +import com.cloud.network.PhysicalNetworkTrafficType;
 +import com.cloud.network.RemoteAccessVpn;
 +import com.cloud.network.Site2SiteCustomerGateway;
 +import com.cloud.network.Site2SiteVpnConnection;
 +import com.cloud.network.Site2SiteVpnGateway;
 +import com.cloud.network.VirtualRouterProvider;
 +import com.cloud.network.VpnUser;
 +import com.cloud.network.as.AutoScalePolicy;
 +import com.cloud.network.as.AutoScaleVmGroup;
 +import com.cloud.network.as.AutoScaleVmProfile;
 +import com.cloud.network.as.Condition;
 +import com.cloud.network.as.Counter;
 +import com.cloud.network.router.VirtualRouter;
 +import com.cloud.network.rules.FirewallRule;
 +import com.cloud.network.rules.HealthCheckPolicy;
 +import com.cloud.network.rules.LoadBalancer;
 +import com.cloud.network.rules.PortForwardingRule;
 +import com.cloud.network.rules.StaticNatRule;
 +import com.cloud.network.rules.StickinessPolicy;
 +import com.cloud.network.security.SecurityGroup;
 +import com.cloud.network.security.SecurityRule;
 +import com.cloud.network.vpc.NetworkACL;
 +import com.cloud.network.vpc.NetworkACLItem;
 +import com.cloud.network.vpc.PrivateGateway;
 +import com.cloud.network.vpc.StaticRoute;
 +import com.cloud.network.vpc.Vpc;
 +import com.cloud.network.vpc.VpcOffering;
 +import com.cloud.offering.DiskOffering;
 +import com.cloud.offering.NetworkOffering;
 +import com.cloud.offering.ServiceOffering;
 +import com.cloud.org.Cluster;
 +import com.cloud.projects.Project;
 +import com.cloud.projects.ProjectAccount;
 +import com.cloud.projects.ProjectInvitation;
 +import com.cloud.region.ha.GlobalLoadBalancerRule;
 +import com.cloud.server.ResourceTag;
 +import com.cloud.storage.GuestOS;
+ import com.cloud.storage.ImageStore;
 -import java.text.DecimalFormat;
 -import java.util.EnumSet;
 -import java.util.List;
 -import java.util.Map;
 +import com.cloud.storage.S3;
 +import com.cloud.storage.Snapshot;
 +import com.cloud.storage.StoragePool;
 +import com.cloud.storage.Swift;
 +import com.cloud.storage.Volume;
 +import com.cloud.storage.snapshot.SnapshotPolicy;
 +import com.cloud.storage.snapshot.SnapshotSchedule;
 +import com.cloud.template.VirtualMachineTemplate;
 +import com.cloud.user.Account;
 +import com.cloud.user.User;
 +import com.cloud.user.UserAccount;
 +import com.cloud.uservm.UserVm;
 +import com.cloud.utils.net.Ip;
 +import com.cloud.vm.InstanceGroup;
 +import com.cloud.vm.Nic;
 +import com.cloud.vm.NicSecondaryIp;
 +import com.cloud.vm.VirtualMachine;
 +import com.cloud.vm.snapshot.VMSnapshot;
  
  public interface ResponseGenerator {
      UserResponse createUserResponse(UserAccount user);
@@@ -293,8 -296,14 +295,10 @@@
  
      SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group);
  
-     ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode);
+     ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode, String url);
+ 
+     ExtractResponse createExtractResponse(Long id, Long zoneId, Long accountId, String mode, String url);
  
 -    String toSerializedString(CreateCmdResponse response, String responseType);
 -
 -    AsyncJobResponse createAsyncJobResponse(AsyncJob job);
 -
      EventResponse createEventResponse(Event event);
  
      //List<EventResponse> createEventResponse(EventJoinVO... events);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
index d876bae,14725d3..e29e794
--- a/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java
@@@ -16,24 -16,22 +16,23 @@@
  // under the License.
  package org.apache.cloudstack.api.command.admin.host;
  
- import java.util.List;
- 
 +import org.apache.log4j.Logger;
 +
  import org.apache.cloudstack.api.APICommand;
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.ApiErrorCode;
  import org.apache.cloudstack.api.BaseCmd;
  import org.apache.cloudstack.api.Parameter;
  import org.apache.cloudstack.api.ServerApiException;
- import org.apache.cloudstack.api.response.HostResponse;
+ import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
+ import org.apache.cloudstack.api.response.ImageStoreResponse;
  import org.apache.cloudstack.api.response.ZoneResponse;
 -import org.apache.log4j.Logger;
  
  import com.cloud.exception.DiscoveryException;
- import com.cloud.host.Host;
+ import com.cloud.storage.ImageStore;
  import com.cloud.user.Account;
  
- @APICommand(name = "addSecondaryStorage", description="Adds secondary storage.", responseObject=HostResponse.class)
+ @APICommand(name = "addSecondaryStorage", description="Adds secondary storage.", responseObject=ImageStoreResponse.class)
  public class AddSecondaryStorageCmd extends BaseCmd {
      public static final Logger s_logger = Logger.getLogger(AddSecondaryStorageCmd.class.getName());
      private static final String s_name = "addsecondarystorageresponse";
@@@ -77,17 -78,19 +79,19 @@@
  
      @Override
      public void execute(){
-         try {
-             List<? extends Host> result = _resourceService.discoverHosts(this);
-             HostResponse hostResponse = null;
-             if (result != null && result.size() > 0) {
-                 for (Host host : result) {
-                     // There should only be one secondary storage host per add
-                     hostResponse = _responseGenerator.createHostResponse(host);
-                     hostResponse.setResponseName(getCommandName());
-                     hostResponse.setObjectName("secondarystorage");
-                     this.setResponseObject(hostResponse);
-                 }
+         AddImageStoreCmd cmd = new AddImageStoreCmd();
 -        cmd.setUrl(this.getUrl());
 -        cmd.setZoneId(this.getZoneId());
++        cmd.setUrl(getUrl());
++        cmd.setZoneId(getZoneId());
+         cmd.setProviderName("NFS");
+ 
+         try{
+             ImageStore result = _storageService.discoverImageStore(cmd);
+             ImageStoreResponse storeResponse = null;
+             if (result != null ) {
+                     storeResponse = _responseGenerator.createImageStoreResponse(result);
+                     storeResponse.setResponseName(getCommandName());
+                     storeResponse.setObjectName("secondarystorage");
 -                    this.setResponseObject(storeResponse);
++                    setResponseObject(storeResponse);
              } else {
                  throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage");
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/host/FindHostsForMigrationCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java
index fd1ad57,68370e8..106d561
--- a/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/internallb/ListInternalLBVMsCmd.java
@@@ -76,10 -75,7 +76,7 @@@ public class ListInternalLBVMsCmd exten
  
      @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="if true is passed for this parameter, list only VPC Internal LB VMs")
      private Boolean forVpc;
 -     
 +    
-     @Parameter(name=ApiConstants.ZONE_TYPE, type=CommandType.STRING, description="the network type of the zone that the virtual machine belongs to")
-     private String zoneType;
-     
  
      /////////////////////////////////////////////////////
      /////////////////// Accessors ///////////////////////
@@@ -124,10 -120,7 +121,7 @@@
      public String getRole() {
          return Role.INTERNAL_LB_VM.toString();
      }
 -  
 +    
-     public String getZoneType() {
-         return zoneType;
-     }
  
      /////////////////////////////////////////////////////
      /////////////// API Implementation///////////////////

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java
index 7f31800,38f58ec..d2163b8
--- a/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java
@@@ -17,16 -17,19 +17,20 @@@
  package org.apache.cloudstack.api.command.admin.ldap;
  
  
+ import java.util.ArrayList;
+ import java.util.List;
+ 
  import javax.naming.NamingException;
  
 +import org.apache.log4j.Logger;
 +
  import org.apache.cloudstack.api.APICommand;
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.BaseCmd;
  import org.apache.cloudstack.api.Parameter;
  import org.apache.cloudstack.api.ServerApiException;
  import org.apache.cloudstack.api.response.LDAPConfigResponse;
+ import org.apache.cloudstack.api.response.ListResponse;
 -import org.apache.log4j.Logger;
  
  import com.cloud.exception.ConcurrentOperationException;
  import com.cloud.exception.InsufficientCapacityException;
@@@ -91,7 -94,7 +95,7 @@@ public class LDAPConfigCmd extends Base
      }
  
      public void setBindDN(String bdn) {
--        this.bindDN=bdn;
++        bindDN=bdn;
      }
  
      public String getQueryFilter() {
@@@ -159,9 -162,16 +163,16 @@@
                if (getListAll()){
                    // return the existing conf
                    LDAPConfigCmd cmd = _configService.listLDAPConfig(this);
-                   LDAPConfigResponse lr = _responseGenerator.createLDAPConfigResponse(cmd.getHostname(), cmd.getPort(), cmd.getUseSSL(), cmd.getQueryFilter(), cmd.getSearchBase(), cmd.getBindDN());
-                   lr.setResponseName(getCommandName());
-                   this.setResponseObject(lr);
+                   ListResponse<LDAPConfigResponse> response = new ListResponse<LDAPConfigResponse>();
+                   List<LDAPConfigResponse> responses = new ArrayList<LDAPConfigResponse>();
+ 
+                   if(!cmd.getHostname().equals("")) {
+                   	responses.add(_responseGenerator.createLDAPConfigResponse(cmd.getHostname(), cmd.getPort(), cmd.getUseSSL(), cmd.getQueryFilter(), cmd.getSearchBase(), cmd.getBindDN()));
+                   }
+                   
+                   response.setResponses(responses);
+                   response.setResponseName(getCommandName());
 -                  this.setResponseObject(response);
++                  setResponseObject(response);
                }
                else if (getHostname()==null || getSearchBase() == null || getQueryFilter() == null) {
                    throw new InvalidParameterValueException("You need to provide hostname, searchbase and queryfilter to configure your LDAP server");
@@@ -171,7 -181,7 +182,7 @@@
                    if (result){
                        LDAPConfigResponse lr = _responseGenerator.createLDAPConfigResponse(getHostname(), getPort(), getUseSSL(), getQueryFilter(), getSearchBase(), getBindDN());
                        lr.setResponseName(getCommandName());
--                      this.setResponseObject(lr);
++                      setResponseObject(lr);
                    }
                }
            }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
index 3d330a5,462b529..9f18a27
--- a/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java
@@@ -16,22 -16,24 +16,25 @@@
  // under the License.
  package org.apache.cloudstack.api.command.admin.swift;
  
+ import java.util.HashMap;
+ import java.util.Map;
+ 
 +import org.apache.log4j.Logger;
 +
  import org.apache.cloudstack.api.APICommand;
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.ApiErrorCode;
  import org.apache.cloudstack.api.BaseCmd;
  import org.apache.cloudstack.api.Parameter;
  import org.apache.cloudstack.api.ServerApiException;
- import org.apache.cloudstack.api.response.HostResponse;
- import org.apache.cloudstack.api.response.SwiftResponse;
+ import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
+ import org.apache.cloudstack.api.response.ImageStoreResponse;
 -import org.apache.log4j.Logger;
  
  import com.cloud.exception.DiscoveryException;
- import com.cloud.storage.Swift;
+ import com.cloud.storage.ImageStore;
  import com.cloud.user.Account;
  
- @APICommand(name = "addSwift", description = "Adds Swift.", responseObject = HostResponse.class, since="3.0.0")
+ @APICommand(name = "addSwift", description = "Adds Swift.", responseObject = ImageStoreResponse.class, since="3.0.0")
  public class AddSwiftCmd extends BaseCmd {
      public static final Logger s_logger = Logger.getLogger(AddSwiftCmd.class.getName());
      private static final String s_name = "addswiftresponse";
@@@ -88,21 -90,29 +91,29 @@@
  
      @Override
      public void execute(){
-         try {
-             Swift result = _resourceService.discoverSwift(this);
-             SwiftResponse swiftResponse = null;
-             if (result != null) {
-                 swiftResponse = _responseGenerator.createSwiftResponse(result);
-                 swiftResponse.setResponseName(getCommandName());
-                 swiftResponse.setObjectName("swift");
-                 this.setResponseObject(swiftResponse);
+         AddImageStoreCmd cmd = new AddImageStoreCmd();
+         cmd.setProviderName("Swift");
 -        cmd.setUrl(this.getUrl());
++        cmd.setUrl(getUrl());
+         Map<String, String> details = new HashMap<String, String>();
 -        details.put(ApiConstants.ACCOUNT, this.getAccount());
 -        details.put(ApiConstants.USERNAME, this.getUsername());
 -        details.put(ApiConstants.KEY, this.getKey());
++        details.put(ApiConstants.ACCOUNT, getAccount());
++        details.put(ApiConstants.USERNAME, getUsername());
++        details.put(ApiConstants.KEY, getKey());
+ 
+ 
+         try{
+             ImageStore result = _storageService.discoverImageStore(cmd);
+             ImageStoreResponse storeResponse = null;
+             if (result != null ) {
+                     storeResponse = _responseGenerator.createImageStoreResponse(result);
+                     storeResponse.setResponseName(getCommandName());
+                     storeResponse.setObjectName("secondarystorage");
 -                    this.setResponseObject(storeResponse);
++                    setResponseObject(storeResponse);
              } else {
-                 throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Swift");
+                 throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add secondary storage");
              }
          } catch (DiscoveryException ex) {
-             String errMsg = "Failed to add Swift due to " + ex.toString();
-             s_logger.warn(errMsg, ex);
-             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errMsg);
+             s_logger.warn("Exception: ", ex);
+             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
          }
      }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java
index 9e923d0,b0408f4..448cfd4
--- a/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java
@@@ -16,24 -16,18 +16,19 @@@
  // under the License.
  package org.apache.cloudstack.api.command.admin.swift;
  
- import java.util.ArrayList;
- import java.util.List;
- 
 +import org.apache.log4j.Logger;
 +
  import org.apache.cloudstack.api.APICommand;
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.BaseListCmd;
  import org.apache.cloudstack.api.Parameter;
- import org.apache.cloudstack.api.response.HostResponse;
+ import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd;
+ import org.apache.cloudstack.api.response.ImageStoreResponse;
  import org.apache.cloudstack.api.response.ListResponse;
- import org.apache.cloudstack.api.response.SwiftResponse;
 -import org.apache.log4j.Logger;
  
- import com.cloud.storage.Swift;
  import com.cloud.user.Account;
- import com.cloud.utils.Pair;
  
- @APICommand(name = "listSwifts", description = "List Swift.", responseObject = HostResponse.class, since="3.0.0")
+ @APICommand(name = "listSwifts", description = "List Swift.", responseObject = ImageStoreResponse.class, since="3.0.0")
  public class ListSwiftsCmd extends BaseListCmd {
      public static final Logger s_logger = Logger.getLogger(ListSwiftsCmd.class.getName());
      private static final String s_name = "listswiftsresponse";
@@@ -66,20 -60,11 +61,11 @@@
  
      @Override
      public void execute(){
-         Pair<List<? extends Swift>, Integer> result = _resourceService.listSwifts(this);
-         ListResponse<SwiftResponse> response = new ListResponse<SwiftResponse>();
-         List<SwiftResponse> swiftResponses = new ArrayList<SwiftResponse>();
  
-         if (result != null) {
-             for (Swift swift : result.first()) {
-                 SwiftResponse swiftResponse = _responseGenerator.createSwiftResponse(swift);
-                 swiftResponse.setResponseName(getCommandName());
-                 swiftResponse.setObjectName("swift");
-                 swiftResponses.add(swiftResponse);
-             }
-         }
-         response.setResponses(swiftResponses, result.second());
+         ListImageStoresCmd cmd = new ListImageStoresCmd();
+         cmd.setProvider("Swift");
+         ListResponse<ImageStoreResponse> response = _queryService.searchForImageStores(cmd);
          response.setResponseName(getCommandName());
--        this.setResponseObject(response);
++        setResponseObject(response);
      }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java
index 5dfa41c,dd0fc36..4d51e63
--- a/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java
@@@ -112,10 -112,10 +112,12 @@@ public class ExtractIsoCmd extends Base
          return s_name;
      }
  
 -    public AsyncJob.Type getInstanceType() {
 -        return AsyncJob.Type.Iso;
++    @Override
 +    public ApiCommandJobType getInstanceType() {
 +        return ApiCommandJobType.Iso;
      }
  
++    @Override
      public Long getInstanceId() {
          return getId();
      }
@@@ -123,13 -123,13 +125,13 @@@
      @Override
      public void execute(){
          try {
 -            UserContext.current().setEventDetails(getEventDescription());
 +            CallContext.current().setEventDetails(getEventDescription());
-             Long uploadId = _templateService.extract(this);
-             if (uploadId != null){
-                 ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode);
+             String uploadUrl = _templateService.extract(this);
+             if (uploadUrl != null) {
+                 ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl);
                  response.setResponseName(getCommandName());
                  response.setObjectName("iso");
--                this.setResponseObject(response);
++                setResponseObject(response);
              } else {
                  throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract iso");
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java
index 4b5a26a,73a7fc4..b1b9e0c
--- a/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java
@@@ -65,7 -64,7 +65,7 @@@ public class CreateSnapshotCmd extends 
              description = "policy id of the snapshot, if this is null, then use MANUAL_POLICY.")
      private Long policyId;
  
--    private String syncObjectType = BaseAsyncCmd.snapshotHostSyncObject;
++    private final String syncObjectType = BaseAsyncCmd.snapshotHostSyncObject;
  
      // ///////////////////////////////////////////////////
      // ///////////////// Accessors ///////////////////////
@@@ -153,10 -152,10 +153,10 @@@
  
      @Override
      public void create() throws ResourceAllocationException {
-         Snapshot snapshot = _snapshotService.allocSnapshot(getVolumeId(), getPolicyId());
 -        Snapshot snapshot = this._volumeService.allocSnapshot(getVolumeId(), getPolicyId());
++        Snapshot snapshot = _volumeService.allocSnapshot(getVolumeId(), getPolicyId());
          if (snapshot != null) {
--            this.setEntityId(snapshot.getId());
--            this.setEntityUuid(snapshot.getUuid());
++            setEntityId(snapshot.getId());
++            setEntityUuid(snapshot.getUuid());
          } else {
              throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot");
          }
@@@ -165,16 -164,20 +165,20 @@@
      @Override
      public void execute() {
          s_logger.info("VOLSS: createSnapshotCmd starts:" + System.currentTimeMillis());
 -        UserContext.current().setEventDetails("Volume Id: "+getVolumeId());
 +        CallContext.current().setEventDetails("Volume Id: "+getVolumeId());
-         Snapshot snapshot = _snapshotService.createSnapshot(getVolumeId(), getPolicyId(), getEntityId(), _accountService.getAccount(getEntityOwnerId()));
-         if (snapshot != null) {
-             SnapshotResponse response = _responseGenerator.createSnapshotResponse(snapshot);
-             response.setResponseName(getCommandName());
-             this.setResponseObject(response);
-         } else {
+         Snapshot snapshot;
+         try {
 -            snapshot = _volumeService.takeSnapshot(this.getVolumeId(), this.getPolicyId(), this.getEntityId(), _accountService.getAccount(getEntityOwnerId()));
++            snapshot = _volumeService.takeSnapshot(getVolumeId(), getPolicyId(), getEntityId(), _accountService.getAccount(getEntityOwnerId()));
+             if (snapshot != null) {
+                 SnapshotResponse response = _responseGenerator.createSnapshotResponse(snapshot);
+                 response.setResponseName(getCommandName());
 -                this.setResponseObject(response);
++                setResponseObject(response);
+             } else {
+                 throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId);
+             }
+         } catch (Exception e) {
              throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId);
          }
-         s_logger.info("VOLSS:  backupSnapshotCmd finishes:" + System.currentTimeMillis());
      }
  
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java
index 15cc053,f2dc595..fbaacdc
--- a/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java
@@@ -113,10 -114,10 +113,12 @@@ public class ExtractTemplateCmd extend
          return  "extracting template: " + getId() + " from zone: " + getZoneId();
      }
  
 -    public AsyncJob.Type getInstanceType() {
 -        return AsyncJob.Type.Template;
++    @Override
 +    public ApiCommandJobType getInstanceType() {
 +        return ApiCommandJobType.Template;
      }
  
++    @Override
      public Long getInstanceId() {
          return getId();
      }
@@@ -124,12 -125,12 +126,12 @@@
      @Override
      public void execute(){
          try {
 -            UserContext.current().setEventDetails(getEventDescription());
 +            CallContext.current().setEventDetails(getEventDescription());
-             Long uploadId = _templateService.extract(this);
-             if (uploadId != null){
-                 ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode);
+             String uploadUrl = _templateService.extract(this);
+             if (uploadUrl != null) {
+                 ExtractResponse response = _responseGenerator.createExtractResponse(id, zoneId, getEntityOwnerId(), mode, uploadUrl);
                  response.setResponseName(getCommandName());
--                this.setResponseObject(response);
++                setResponseObject(response);
              } else {
                  throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract template");
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
index b764b6d,0b937be..264b9d5
--- a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java
@@@ -29,11 -26,14 +29,12 @@@ import org.apache.cloudstack.api.BaseLi
  import org.apache.cloudstack.api.Parameter;
  import org.apache.cloudstack.api.response.ListResponse;
  import org.apache.cloudstack.api.response.TemplateResponse;
+ import org.apache.cloudstack.api.response.VolumeResponse;
  import org.apache.cloudstack.api.response.ZoneResponse;
 -import org.apache.log4j.Logger;
 +import org.apache.cloudstack.context.CallContext;
  
 -import com.cloud.async.AsyncJob;
  import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
  import com.cloud.user.Account;
 -import com.cloud.user.UserContext;
  import com.cloud.utils.Pair;
  
  @APICommand(name = "listTemplates", description="List all public, private, and privileged templates.", responseObject=TemplateResponse.class)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java
index 9905bb1,6a8e555..698b0c4
--- a/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java
@@@ -111,11 -110,7 +111,7 @@@ public class RegisterTemplateCmd extend
      @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class,
              description="Register template for the project")
      private Long projectId;
 -
 +    
-     @Parameter(name=ApiConstants.IMAGE_STORE_UUID, type=CommandType.STRING,
-             description="Image store uuid")
-     private String imageStoreUuid;
-     
      @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.")
      protected Map details;
  
@@@ -194,10 -192,7 +193,7 @@@
      public String getTemplateTag() {
          return templateTag;
      }
 -
 +    
-     public String getImageStoreUuid() {
-         return this.imageStoreUuid;
-     }
  
      public Map getDetails() {
          if (details == null || details.isEmpty()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java
----------------------------------------------------------------------


[39/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/server/ManagementServerImpl.java
index 362b8e0,97bac1b..fd0122c
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@@ -419,15 -395,9 +417,12 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.vpn.ResetVpnConnectionCmd;
  import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd;
  import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
- import org.apache.cloudstack.api.response.ExtractResponse;
 +import org.apache.cloudstack.config.Configuration;
 +import org.apache.cloudstack.context.CallContext;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
  import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
- import org.apache.cloudstack.framework.jobs.AsyncJob;
- import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
- import org.apache.cloudstack.jobs.JobInfo;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
  
@@@ -444,7 -410,7 +435,6 @@@ import com.cloud.alert.AlertManager
  import com.cloud.alert.AlertVO;
  import com.cloud.alert.dao.AlertDao;
  import com.cloud.api.ApiDBUtils;
- import com.cloud.api.ApiSerializerHelper;
 -import com.cloud.async.AsyncJobManager;
  import com.cloud.capacity.Capacity;
  import com.cloud.capacity.CapacityVO;
  import com.cloud.capacity.dao.CapacityDao;
@@@ -481,14 -447,6 +471,13 @@@ import com.cloud.event.ActionEventUtils
  import com.cloud.event.EventTypes;
  import com.cloud.event.EventVO;
  import com.cloud.event.dao.EventDao;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.InvalidParameterValueException;
 +import com.cloud.exception.ManagementServerException;
 +import com.cloud.exception.OperationTimedoutException;
 +import com.cloud.exception.PermissionDeniedException;
 +import com.cloud.exception.ResourceUnavailableException;
- import com.cloud.exception.StorageUnavailableException;
 +import com.cloud.exception.VirtualMachineMigrationException;
  import com.cloud.ha.HighAvailabilityManager;
  import com.cloud.host.DetailVO;
  import com.cloud.host.Host;
@@@ -603,6 -546,12 +587,7 @@@ import com.cloud.vm.dao.VMInstanceDao
  import edu.emory.mathcs.backport.java.util.Arrays;
  import edu.emory.mathcs.backport.java.util.Collections;
  
 -import org.apache.cloudstack.api.command.admin.region.AddRegionCmd;
 -import org.apache.cloudstack.api.command.admin.region.RemoveRegionCmd;
 -import org.apache.cloudstack.api.command.admin.region.UpdateRegionCmd;
 -import org.apache.cloudstack.api.command.admin.config.ListDeploymentPlannersCmd;
 -
+ 
  public class ManagementServerImpl extends ManagerBase implements ManagementServer {
      public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName());
  
@@@ -958,10 -909,7 +945,7 @@@
  
      @Override
      public Pair<List<? extends Cluster>, Integer> searchForClusters(ListClustersCmd cmd) {
-         Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
-         SearchCriteria<ClusterVO> sc = _clusterDao.createSearchCriteria();
- 
 -    	Object id = cmd.getId();
 +        Object id = cmd.getId();
          Object name = cmd.getClusterName();
          Object podId = cmd.getPodId();
          Long zoneId = cmd.getZoneId();
@@@ -969,11 -917,23 +953,24 @@@
          Object clusterType = cmd.getClusterType();
          Object allocationState = cmd.getAllocationState();
          String keyword = cmd.getKeyword();
 -        zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId);
 -
 +        
 +        zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), zoneId);
 +        
+ 
+     	Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
+ 
+         SearchBuilder<ClusterVO> sb = _clusterDao.createSearchBuilder();
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
+         sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
+         sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+         sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
+         sb.and("clusterType", sb.entity().getClusterType(), SearchCriteria.Op.EQ);
+         sb.and("allocationState", sb.entity().getAllocationState(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<ClusterVO> sc = sb.create();
          if (id != null) {
-             sc.addAnd("id", SearchCriteria.Op.EQ, id);
+             sc.setParameters("id", id);
          }
  
          if (name != null) {
@@@ -1418,9 -1375,17 +1412,18 @@@
          Long zoneId = cmd.getZoneId();
          Object keyword = cmd.getKeyword();
          Object allocationState = cmd.getAllocationState();
 -        zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), zoneId);
  
 +        zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), zoneId);
 +               
+ 
+     	Filter searchFilter = new Filter(HostPodVO.class, "dataCenterId", true, cmd.getStartIndex(), cmd.getPageSizeVal());
+         SearchBuilder<HostPodVO> sb = _hostPodDao.createSearchBuilder();
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
+         sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+         sb.and("allocationState", sb.entity().getAllocationState(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<HostPodVO> sc = sb.create();
          if (keyword != null) {
              SearchCriteria<HostPodVO> ssc = _hostPodDao.createSearchCriteria();
              ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
@@@ -1653,73 -1618,13 +1656,11 @@@
          return new Pair<List<? extends Configuration>, Integer>(result.first(), result.second());
      }
  
-     @Override
-     public Set<Pair<Long, Long>> listIsos(ListIsosCmd cmd) throws IllegalArgumentException, InvalidParameterValueException {
-         TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
-         Account caller = CallContext.current().getCallingAccount();
-         Map<String, String> tags = cmd.getTags();
--
-         boolean listAll = false;
-         if (isoFilter != null && isoFilter == TemplateFilter.all) {
-             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only");
-             }
-             listAll = true;
-         }
-         List<Long> permittedAccountIds = new ArrayList<Long>();
-         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
-                 cmd.getDomainId(), cmd.isRecursive(), null);
-         _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
-                 domainIdRecursiveListProject, listAll, false);
-         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
--
-         List<Account> permittedAccounts = new ArrayList<Account>();
-         for (Long accountId : permittedAccountIds) {
-             permittedAccounts.add(_accountMgr.getAccount(accountId));
-         }
- 
-         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
-         return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(),
-                 cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller,
-                 listProjectResourcesCriteria, tags);
-     }
- 
-     @Override
-     public Set<Pair<Long, Long>> listTemplates(ListTemplatesCmd cmd) throws IllegalArgumentException, InvalidParameterValueException {
-         TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
-         Long id = cmd.getId();
-         Map<String, String> tags = cmd.getTags();
-         Account caller = CallContext.current().getCallingAccount();
- 
-         boolean listAll = false;
-         if (templateFilter != null && templateFilter == TemplateFilter.all) {
-             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
-                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only");
-             }
-             listAll = true;
-         }
- 
-         List<Long> permittedAccountIds = new ArrayList<Long>();
-         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
-                 cmd.getDomainId(), cmd.isRecursive(), null);
-         _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject,
-                 listAll, false);
-         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
-         List<Account> permittedAccounts = new ArrayList<Account>();
-         for (Long accountId : permittedAccountIds) {
-             permittedAccounts.add(_accountMgr.getAccount(accountId));
-         }
- 
-         boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
-         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
- 
-         return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(),
-                 cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
-     }
- 
+     /* TODO: this method should go away. Keep here just in case that our latest refactoring using template_store_ref missed anything
+      * in handling Swift or S3.
      private Set<Pair<Long, Long>> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso,
              Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
-             List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
+             List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags, String zoneType) {
  
          VMTemplateVO template = null;
          if (templateId != null) {
@@@ -1835,7 -1731,8 +1767,8 @@@
          Boolean passwordEnabled = cmd.isPasswordEnabled();
          Boolean bootable = cmd.isBootable();
          Integer sortKey = cmd.getSortKey();
+         Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
  
          // verify that template exists
          VMTemplateVO template = _templateDao.findById(id);
@@@ -3302,211 -3212,10 +3244,9 @@@
          return _guestOSDao.findById(guestOsId);
      }
  
 -
      @Override
-     @ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
-     public Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException {
-         Long volumeId = cmd.getId();
-         String url = cmd.getUrl();
-         Long zoneId = cmd.getZoneId();
-         AsyncJob job = null; // FIXME: cmd.getJob();
-         String mode = cmd.getMode();
-         Account account = CallContext.current().getCallingAccount();
- 
-         if (!_accountMgr.isRootAdmin(account.getType()) && ApiDBUtils.isExtractionDisabled()) {
-             throw new PermissionDeniedException("Extraction has been disabled by admin");
-         }
- 
-         VolumeVO volume = _volumeDao.findById(volumeId);
-         if (volume == null) {
-             InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
-             ex.addProxyObject(volumeId.toString(), "volumeId");
-             throw ex;
-         }
- 
-         // perform permission check
-         _accountMgr.checkAccess(account, null, true, volume);
- 
-         if (_dcDao.findById(zoneId) == null) {
-             throw new InvalidParameterValueException("Please specify a valid zone.");
-         }
-         if (volume.getPoolId() == null) {
-             throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
-         }
-         // Extract activity only for detached volumes or for volumes whose
-         // instance is stopped
-         if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
-             s_logger.debug("Invalid state of the volume with ID: " + volumeId
-                     + ". It should be either detached or the VM should be in stopped state.");
-             PermissionDeniedException ex = new PermissionDeniedException(
-                     "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
-             ex.addProxyObject(volume.getUuid(), "volumeId");
-             throw ex;
-         }
- 
-         if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont
-             // have any
-             // template
-             // dependence.
- 
-             VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
-             if (template != null) { // For ISO based volumes template = null and
-                 // we allow extraction of all ISO based
-                 // volumes
-                 boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
-                 if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global
-                     // admins are always allowed to extract
-                     PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
-                     ex.addProxyObject(volume.getUuid(), "volumeId");
-                     throw ex;
-                 }
-             }
-         }
- 
-         Upload.Mode extractMode;
-         if (mode == null || (!mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString()))) {
-             throw new InvalidParameterValueException("Please specify a valid extract Mode ");
-         } else {
-             extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD;
-         }
- 
-         // If mode is upload perform extra checks on url and also see if there
-         // is an ongoing upload on the same.
-         if (extractMode == Upload.Mode.FTP_UPLOAD) {
-             URI uri = new URI(url);
-             if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) {
-                 throw new IllegalArgumentException("Unsupported scheme for url: " + url);
-             }
- 
-             String host = uri.getHost();
-             try {
-                 InetAddress hostAddr = InetAddress.getByName(host);
-                 if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress()) {
-                     throw new IllegalArgumentException("Illegal host specified in url");
-                 }
-                 if (hostAddr instanceof Inet6Address) {
-                     throw new IllegalArgumentException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
-                 }
-             } catch (UnknownHostException uhe) {
-                 throw new IllegalArgumentException("Unable to resolve " + host);
-             }
- 
-             if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) {
-                 throw new IllegalArgumentException(volume.getName()
-                         + " upload is in progress. Please wait for some time to schedule another upload for the same");
-             }
-         }
- 
-         long accountId = volume.getAccountId();
-         StoragePool srcPool = (StoragePool)dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
-         HostVO sserver = templateMgr.getSecondaryStorageHost(zoneId);
-         String secondaryStorageURL = sserver.getStorageUrl();
- 
-         List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME, UploadVO.Status.DOWNLOAD_URL_CREATED);
- 
-         if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) {
-             return extractURLList.get(0).getId(); // If download url already  Note: volss
-             // exists then return
-         } else {
-             UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME,
-                     url, extractMode);
-             s_logger.debug("Extract Mode - " + uploadJob.getMode());
-             uploadJob = _uploadDao.createForUpdate(uploadJob.getId());
- 
-             // Update the async AsyncJob
- 
-             ExtractResponse resultObj = new ExtractResponse(ApiDBUtils.findVolumeById(volumeId).getUuid(),
-                     volume.getName(), ApiDBUtils.findAccountById(accountId).getUuid(), UploadVO.Status.COPY_IN_PROGRESS.toString(),
-                     uploadJob.getUuid());
-             resultObj.setResponseName(cmd.getCommandName());
-             AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
-             if (asyncExecutionContext != null) {
-                 job = asyncExecutionContext.getJob();
-                 _asyncMgr.updateAsyncJobAttachment(job.getId(), Upload.Type.VOLUME.toString(), volumeId);
-                 _asyncMgr.updateAsyncJobStatus(job.getId(), JobInfo.Status.IN_PROGRESS.ordinal(), ApiSerializerHelper.toSerializedString(resultObj));
-             }
-             String value = _configs.get(Config.CopyVolumeWait.toString());
-             int copyvolumewait = NumbersUtil.parseInt(value, Integer.parseInt(Config.CopyVolumeWait.getDefaultValue()));
-             // Copy the volume from the source storage pool to secondary storage
-             CopyVolumeCommand cvCmd = new CopyVolumeCommand(volume.getId(), volume.getPath(), srcPool, secondaryStorageURL, true, copyvolumewait);
-             CopyVolumeAnswer cvAnswer = null;
-             try {
-                 cvAnswer = (CopyVolumeAnswer) _storageMgr.sendToPool(srcPool, cvCmd);
-             } catch (StorageUnavailableException e) {
-                 s_logger.debug("Storage unavailable");
-             }
- 
-             // Check if you got a valid answer.
-             if (cvAnswer == null || !cvAnswer.getResult()) {
-                 String errorString = "Failed to copy the volume from the source primary storage pool to secondary storage.";
- 
-                 // Update the async job.
-                 resultObj.setResultString(errorString);
-                 resultObj.setUploadStatus(UploadVO.Status.COPY_ERROR.toString());
-                 if (asyncExecutionContext != null) {
-                     _asyncMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, 0, ApiSerializerHelper.toSerializedString(resultObj));
-                 }
- 
-                 // Update the DB that volume couldn't be copied
-                 uploadJob.setUploadState(UploadVO.Status.COPY_ERROR);
-                 uploadJob.setErrorString(errorString);
-                 uploadJob.setLastUpdated(new Date());
-                 _uploadDao.update(uploadJob.getId(), uploadJob);
- 
-                 throw new CloudRuntimeException(errorString);
-             }
- 
-             String volumeLocalPath = "volumes/" + volume.getId() + "/" + cvAnswer.getVolumePath() + "." + getFormatForPool(srcPool);
-           //Fang:  volss, handle the ova special case;
-             if (getFormatForPool(srcPool) == "ova") {
-                 CreateVolumeOVACommand cvOVACmd = new CreateVolumeOVACommand(secondaryStorageURL, volumeLocalPath, cvAnswer.getVolumePath(), srcPool, copyvolumewait);
-                 CreateVolumeOVAAnswer  OVAanswer = null;
- 
-                 try {
-                         cvOVACmd.setContextParam("hypervisor", HypervisorType.VMware.toString());
-                         OVAanswer = (CreateVolumeOVAAnswer) _storageMgr.sendToPool(srcPool, cvOVACmd); //Fang: for extract volume, create the ova file here;
- 
-                 } catch (StorageUnavailableException e) {
-                     s_logger.debug("Storage unavailable");
-                 }
-             }
-             // Update the DB that volume is copied and volumePath
-             uploadJob.setUploadState(UploadVO.Status.COPY_COMPLETE);
-             uploadJob.setLastUpdated(new Date());
-             uploadJob.setInstallPath(volumeLocalPath);
-             _uploadDao.update(uploadJob.getId(), uploadJob);
- 
-             if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is
-                 // copied perform the actual
-                 // uploading
-                 _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr);
-                 return uploadJob.getId();
-             } else { // Volume is copied now make it visible under apache and
-                 // create a URL.
-                 _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId());
-                 return uploadJob.getId();
-             }
-         }
-     }
- 
-     private String getFormatForPool(StoragePool pool) {
-         ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId());
- 
-         if (cluster.getHypervisorType() == HypervisorType.XenServer) {
-             return "vhd";
-         } else if (cluster.getHypervisorType() == HypervisorType.KVM) {
-             return "qcow2";
-         } else if (cluster.getHypervisorType() == HypervisorType.VMware) {
-             return "ova";
-         } else if (cluster.getHypervisorType() == HypervisorType.Ovm) {
-             return "raw";
-         } else {
-             return null;
-         }
-     }
- 
-     @Override
      public InstanceGroupVO updateVmGroup(UpdateVMGroupCmd cmd) {
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Long groupId = cmd.getId();
          String groupName = cmd.getGroupName();
  
@@@ -3669,7 -3378,12 +3409,12 @@@
      	_encryptionKey = null;
      	_encryptionIV = null;
      }
 -
 +    
+     @Override
+     public boolean getExecuteInSequence() {
+         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     }
+ 
      private static String getBase64EncodedRandomKey(int nBits) {
  		SecureRandom random;
  		try {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/StorageManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/StorageManagerImpl.java
index 194cfd7,b3e8b96..55b214f
--- a/server/src/com/cloud/storage/StorageManagerImpl.java
+++ b/server/src/com/cloud/storage/StorageManagerImpl.java
@@@ -40,35 -41,52 +41,53 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
 +import org.apache.log4j.Logger;
 +import org.springframework.stereotype.Component;
 +
+ import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
 -import com.cloud.server.ConfigurationServer;
  import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd;
+ import org.apache.cloudstack.api.command.admin.storage.CreateCacheStoreCmd;
  import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd;
+ import org.apache.cloudstack.api.command.admin.storage.DeleteImageStoreCmd;
  import org.apache.cloudstack.api.command.admin.storage.DeletePoolCmd;
  import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd;
 +import org.apache.cloudstack.context.CallContext;
  import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider;
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager;
- 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.EndPointSelector;
  import org.apache.cloudstack.engine.subsystem.api.storage.HostScope;
  import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener;
- import org.apache.cloudstack.engine.subsystem.api.storage.ImageDataFactory;
 -import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
 -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
+ import org.apache.cloudstack.engine.subsystem.api.storage.ImageStoreProvider;
  import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo;
- import org.apache.cloudstack.engine.subsystem.api.storage.ScopeType;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
++import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
  import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
++import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
+ import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
  import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
  import org.apache.cloudstack.framework.async.AsyncCallFuture;
+ import org.apache.cloudstack.storage.command.DeleteCommand;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+ 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.datastore.db.VolumeDataStoreVO;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
@@@ -118,11 -132,10 +133,10 @@@ import com.cloud.hypervisor.HypervisorG
  import com.cloud.org.Grouping;
  import com.cloud.org.Grouping.AllocationState;
  import com.cloud.resource.ResourceState;
 +import com.cloud.server.ConfigurationServer;
  import com.cloud.server.ManagementServer;
  import com.cloud.server.StatsCollector;
--import com.cloud.service.dao.ServiceOfferingDao;
+ import com.cloud.service.ServiceOfferingVO;
  import com.cloud.storage.Storage.ImageFormat;
  import com.cloud.storage.Storage.StoragePoolType;
  import com.cloud.storage.Volume.Type;
@@@ -131,24 -143,19 +144,15 @@@ import com.cloud.storage.dao.SnapshotDa
  import com.cloud.storage.dao.StoragePoolHostDao;
  import com.cloud.storage.dao.StoragePoolWorkDao;
  import com.cloud.storage.dao.VMTemplateDao;
- import com.cloud.storage.dao.VMTemplateHostDao;
  import com.cloud.storage.dao.VMTemplatePoolDao;
- import com.cloud.storage.dao.VMTemplateS3Dao;
- 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.DiskOfferingVO;
 -import com.cloud.storage.download.DownloadMonitor;
  import com.cloud.storage.listener.StoragePoolMonitor;
  import com.cloud.storage.listener.VolumeStateListener;
- import com.cloud.storage.s3.S3Manager;
- import com.cloud.storage.secondary.SecondaryStorageVmManager;
- import com.cloud.storage.snapshot.SnapshotManager;
- import com.cloud.tags.dao.ResourceTagDao;
  import com.cloud.template.TemplateManager;
  import com.cloud.user.Account;
  import com.cloud.user.AccountManager;
  import com.cloud.user.User;
- import com.cloud.user.dao.AccountDao;
 -import com.cloud.user.UserContext;
  import com.cloud.user.dao.UserDao;
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.Pair;
@@@ -282,32 -259,37 +257,37 @@@ public class StorageManagerImpl extend
      @Inject
      SnapshotDataFactory snapshotFactory;
      @Inject
-     protected HypervisorCapabilitiesDao _hypervisorCapabilitiesDao;
-     @Inject
      ConfigurationServer _configServer;
- 
-     @Inject protected ResourceTagDao _resourceTagDao;
- 
- 
+     @Inject
+     DataStoreManager _dataStoreMgr;
+     @Inject
+     DataStoreProviderManager _dataStoreProviderMgr;
+     @Inject
+     private TemplateService _imageSrv;
+     @Inject
+     EndPointSelector _epSelector;
  
      protected List<StoragePoolAllocator> _storagePoolAllocators;
+ 
      public List<StoragePoolAllocator> getStoragePoolAllocators() {
 -        return _storagePoolAllocators;
 -    }
 +		return _storagePoolAllocators;
 +	}
- 	public void setStoragePoolAllocators(
- 			List<StoragePoolAllocator> _storagePoolAllocators) {
+ 
+     public void setStoragePoolAllocators(List<StoragePoolAllocator> _storagePoolAllocators) {
 -        this._storagePoolAllocators = _storagePoolAllocators;
 -    }
 +		this._storagePoolAllocators = _storagePoolAllocators;
 +	}
  
      protected List<StoragePoolDiscoverer> _discoverers;
+ 
      public List<StoragePoolDiscoverer> getDiscoverers() {
 -        return _discoverers;
 -    }
 +		return _discoverers;
 +	}
+ 
 -    public void setDiscoverers(List<StoragePoolDiscoverer> _discoverers) {
 -        this._discoverers = _discoverers;
 -    }
 +	public void setDiscoverers(List<StoragePoolDiscoverer> _discoverers) {
 +		this._discoverers = _discoverers;
 +	}
  
 -    protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
 +	protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
      protected GenericSearchBuilder<StoragePoolHostVO, Long> UpHostsInPoolSearch;
      protected SearchBuilder<VMInstanceVO> StoragePoolSearch;
      protected SearchBuilder<StoragePoolVO> LocalStorageSearch;
@@@ -389,11 -361,17 +359,17 @@@
              if (pool.getStatus() != StoragePoolStatus.Up) {
                  continue;
              }
+             if (pool.getScope() == ScopeType.ZONE) {
+                 if (pool.getHypervisor() != null && pool.getHypervisor() == type) {
+                     retPools.add(pool);
+                 }
+             } else {
 -                ClusterVO cluster = _clusterDao.findById(pool.getClusterId());
 -                if (type == cluster.getHypervisorType()) {
 -                    retPools.add(pool);
 -                }
 +            ClusterVO cluster = _clusterDao.findById(pool.getClusterId());
 +            if (type == cluster.getHypervisorType()) {
 +                retPools.add(pool);
              }
          }
++        }
          Collections.shuffle(retPools);
          return retPools;
      }
@@@ -441,23 -407,22 +405,22 @@@
      }
  
      @Override
-     public StoragePool findStoragePool(DiskProfile dskCh,
-             final DataCenterVO dc, HostPodVO pod, Long clusterId, Long hostId,
-             VMInstanceVO vm, final Set<StoragePool> avoid) {
+     public StoragePool findStoragePool(DiskProfile dskCh, final DataCenterVO dc, HostPodVO pod, Long clusterId, Long hostId, VMInstanceVO vm,
+             final Set<StoragePool> avoid) {
  
 -        VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
 +        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
          for (StoragePoolAllocator allocator : _storagePoolAllocators) {
 -
 -            ExcludeList avoidList = new ExcludeList();
 +        	
 +        	ExcludeList avoidList = new ExcludeList();
-         	for(StoragePool pool : avoid){
+             for (StoragePool pool : avoid) {
 -                avoidList.addPool(pool.getId());
 -            }
 -            DataCenterDeployment plan = new DataCenterDeployment(dc.getId(), pod.getId(), clusterId, hostId, null, null);
 -
 -            final List<StoragePool> poolList = allocator.allocateToPool(dskCh, profile, plan, avoidList, 1);
 -            if (poolList != null && !poolList.isEmpty()) {
 -                return (StoragePool) this.dataStoreMgr.getDataStore(poolList.get(0).getId(), DataStoreRole.Primary);
 -            }
 +        		avoidList.addPool(pool.getId());
 +        	}
 +        	DataCenterDeployment plan = new DataCenterDeployment(dc.getId(), pod.getId(), clusterId, hostId, null, null);
 +        	
 +        	final List<StoragePool> poolList = allocator.allocateToPool(dskCh, profile, plan, avoidList, 1);
 +        	if (poolList != null && !poolList.isEmpty()) {
-         		return (StoragePool)dataStoreMgr.getDataStore(poolList.get(0).getId(), DataStoreRole.Primary);
++                return (StoragePool) dataStoreMgr.getDataStore(poolList.get(0).getId(), DataStoreRole.Primary);
 +        	}
          }
          return null;
      }
@@@ -643,10 -564,9 +562,9 @@@
          return true;
      }
  
-     
      @Override
      public String getStoragePoolTags(long poolId) {
 -        return _configMgr.listToCsvTags(_storagePoolDao.searchForStoragePoolDetails(poolId, "true"));
 +        return StringUtils.listToCsvTags(_storagePoolDao.searchForStoragePoolDetails(poolId, "true"));
      }
  
      @Override
@@@ -705,22 -628,20 +626,20 @@@
                  params.put("details", pInfo.getDetails());
                  params.put("uuid", pInfo.getUuid());
                  params.put("providerName", provider.getName());
 -
 +                
                  store = lifeCycle.initialize(params);
              } else {
-                 store = dataStoreMgr.getDataStore(pool.getId(),
-                         DataStoreRole.Primary);
 -                store = (DataStore) dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
++                store = dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
              }
 -
 +            
-             HostScope scope = new HostScope(host.getId());
+             HostScope scope = new HostScope(host.getId(), host.getDataCenterId());
              lifeCycle.attachHost(store, scope, pInfo);
          } catch (Exception e) {
              s_logger.warn("Unable to setup the local storage pool for " + host, e);
              throw new ConnectionException(true, "Unable to setup the local storage pool for " + host, e);
          }
  
-         return dataStoreMgr.getDataStore(store.getId(),
-                 DataStoreRole.Primary);
 -        return (DataStore) dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
++        return dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
      }
  
      @Override
@@@ -803,16 -717,12 +715,12 @@@
  
          DataCenterVO zone = _dcDao.findById(cmd.getZoneId());
          if (zone == null) {
-             throw new InvalidParameterValueException(
-                     "unable to find zone by id " + zoneId);
+             throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
          }
          // Check if zone is disabled
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
-         if (Grouping.AllocationState.Disabled == zone.getAllocationState()
-                 && !_accountMgr.isRootAdmin(account.getType())) {
-             throw new PermissionDeniedException(
-                     "Cannot perform this operation, Zone is currently disabled: "
-                             + zoneId);
+         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
+             throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
          }
  
          Map<String, Object> params = new HashMap<String, Object>();
@@@ -958,9 -850,8 +848,8 @@@
      }
  
      @Override
-     public void connectHostToSharedPool(long hostId, long poolId)
-             throws StorageUnavailableException {
-         StoragePool pool = (StoragePool)dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary);
+     public void connectHostToSharedPool(long hostId, long poolId) throws StorageUnavailableException {
 -        StoragePool pool = (StoragePool) this.dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary);
++        StoragePool pool = (StoragePool) dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary);
          assert (pool.isShared()) : "Now, did you actually read the name of this method?";
          s_logger.debug("Adding pool " + pool.getName() + " to  host " + hostId);
  
@@@ -1001,9 -903,8 +901,8 @@@
              } else {
                  allocationState = _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(storagePool.getClusterId()));
              }
-             CapacityState capacityState = (allocationState == AllocationState.Disabled) ?
-                     CapacityState.Disabled : CapacityState.Enabled;
+             CapacityState capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled;
 -
 +            
              capacity.setCapacityState(capacityState);
              _capacityDao.persist(capacity);
          } else {
@@@ -1198,60 -1101,48 +1099,48 @@@
      public void cleanupSecondaryStorage(boolean recurring) {
          try {
              // Cleanup templates in secondary storage hosts
-             List<HostVO> secondaryStorageHosts = _ssvmMgr
-                     .listSecondaryStorageHostsInAllZones();
-             for (HostVO secondaryStorageHost : secondaryStorageHosts) {
 -            List<DataStore> imageStores = this.dataStoreMgr.getImageStoresByScope(new ZoneScope(null));
++            List<DataStore> imageStores = dataStoreMgr.getImageStoresByScope(new ZoneScope(null));
+             for (DataStore store : imageStores) {
                  try {
-                     long hostId = secondaryStorageHost.getId();
-                     List<VMTemplateHostVO> destroyedTemplateHostVOs = _vmTemplateHostDao
-                             .listDestroyed(hostId);
-                     s_logger.debug("Secondary storage garbage collector found "
-                             + destroyedTemplateHostVOs.size()
-                             + " templates to cleanup on secondary storage host: "
-                             + secondaryStorageHost.getName());
-                     for (VMTemplateHostVO destroyedTemplateHostVO : destroyedTemplateHostVOs) {
-                         if (!_tmpltMgr
-                                 .templateIsDeleteable(destroyedTemplateHostVO)) {
+                     long storeId = store.getId();
 -                    List<TemplateDataStoreVO> destroyedTemplateStoreVOs = this._templateStoreDao.listDestroyed(storeId);
++                    List<TemplateDataStoreVO> destroyedTemplateStoreVOs = _templateStoreDao.listDestroyed(storeId);
+                     s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateStoreVOs.size()
+                             + " templates to cleanup on secondary storage host: " + store.getName());
+                     for (TemplateDataStoreVO destroyedTemplateStoreVO : destroyedTemplateStoreVOs) {
+                         if (!_tmpltMgr.templateIsDeleteable(destroyedTemplateStoreVO.getTemplateId())) {
                              if (s_logger.isDebugEnabled()) {
-                                 s_logger.debug("Not deleting template at: "
-                                         + destroyedTemplateHostVO);
+                                 s_logger.debug("Not deleting template at: " + destroyedTemplateStoreVO);
                              }
                              continue;
                          }
  
                          if (s_logger.isDebugEnabled()) {
-                             s_logger.debug("Deleting template host: "
-                                     + destroyedTemplateHostVO);
+                             s_logger.debug("Deleting template store: " + destroyedTemplateStoreVO);
                          }
  
-                         String installPath = destroyedTemplateHostVO
-                                 .getInstallPath();
 -                        VMTemplateVO destroyedTemplate = this._vmTemplateDao.findById(destroyedTemplateStoreVO.getTemplateId());
++                        VMTemplateVO destroyedTemplate = _vmTemplateDao.findById(destroyedTemplateStoreVO.getTemplateId());
+                         if (destroyedTemplate == null) {
+                             s_logger.error("Cannot find template : " + destroyedTemplateStoreVO.getTemplateId() + " from template table");
+                             throw new CloudRuntimeException("Template " + destroyedTemplateStoreVO.getTemplateId()
+                                     + " is found in secondary storage, but not found in template table");
+                         }
+                         String installPath = destroyedTemplateStoreVO.getInstallPath();
  
+                         TemplateInfo tmpl = tmplFactory.getTemplate(destroyedTemplateStoreVO.getTemplateId(), store);
                          if (installPath != null) {
-                             Answer answer = _agentMgr.sendToSecStorage(
-                                     secondaryStorageHost,
-                                     new DeleteTemplateCommand(
-                                             secondaryStorageHost
-                                                     .getStorageUrl(),
-                                             destroyedTemplateHostVO
-                                                     .getInstallPath()));
+                             EndPoint ep = _epSelector.select(store);
+                             Command cmd = new DeleteCommand(tmpl.getTO());
+                             Answer answer = ep.sendMessage(cmd);
  
                              if (answer == null || !answer.getResult()) {
-                                 s_logger.debug("Failed to delete "
-                                         + destroyedTemplateHostVO
-                                         + " due to "
-                                         + ((answer == null) ? "answer is null"
-                                                 : answer.getDetails()));
+                                 s_logger.debug("Failed to delete " + destroyedTemplateStoreVO + " due to "
+                                         + ((answer == null) ? "answer is null" : answer.getDetails()));
                              } else {
-                                 _vmTemplateHostDao
-                                         .remove(destroyedTemplateHostVO.getId());
-                                 s_logger.debug("Deleted template at: "
-                                         + destroyedTemplateHostVO
-                                                 .getInstallPath());
+                                 _templateStoreDao.remove(destroyedTemplateStoreVO.getId());
+                                 s_logger.debug("Deleted template at: " + destroyedTemplateStoreVO.getInstallPath());
                              }
                          } else {
-                             _vmTemplateHostDao.remove(destroyedTemplateHostVO
-                                     .getId());
+                             _templateStoreDao.remove(destroyedTemplateStoreVO.getId());
                          }
                      }
                  } catch (Exception e) {
@@@ -1261,107 -1150,76 +1148,76 @@@
                  }
              }
  
-             // Cleanup snapshot in secondary storage hosts
-             for (HostVO secondaryStorageHost : secondaryStorageHosts) {
-                 try {
-                     long hostId = secondaryStorageHost.getId();
-                     List<Long> vIDs = findAllVolumeIdInSnapshotTable(hostId);
-                     if (vIDs == null) {
-                         continue;
-                     }
-                     for (Long volumeId : vIDs) {
-                         boolean lock = false;
+             // CleanUp snapshots on Secondary Storage.
+             for (DataStore store : imageStores) {
 -                try {
 +                        try {
-                             VolumeVO volume = _volsDao
-                                     .findByIdIncludingRemoved(volumeId);
-                             if (volume.getRemoved() == null) {
-                                 volume = _volsDao.acquireInLockTable(volumeId,
-                                         10);
-                                 if (volume == null) {
+                     List<SnapshotDataStoreVO> destroyedSnapshotStoreVOs = _snapshotStoreDao.listDestroyed(store.getId());
+                     s_logger.debug("Secondary storage garbage collector found " + destroyedSnapshotStoreVOs.size()
+                             + " snapshots to cleanup on secondary storage host: " + store.getName());
+                     for (SnapshotDataStoreVO destroyedSnapshotStoreVO : destroyedSnapshotStoreVOs) {
+                         // check if this snapshot has child
+                         SnapshotInfo snap = snapshotFactory.getSnapshot(destroyedSnapshotStoreVO.getSnapshotId(), store);
+                         if ( snap.getChild() != null ){
+                             s_logger.debug("Skip snapshot on store: " + destroyedSnapshotStoreVO + " , because it has child");
 -                            continue;
 -                        }
 +                                    continue;
 +                                }
-                                 lock = true;
-                             }
-                             List<String> snapshots = findAllSnapshotForVolume(volumeId);
-                             if (snapshots == null) {
-                                 continue;
-                             }
-                             CleanupSnapshotBackupCommand cmd = new CleanupSnapshotBackupCommand(
-                                     secondaryStorageHost.getStorageUrl(),
-                                     secondaryStorageHost.getDataCenterId(),
-                                     volume.getAccountId(), volumeId, snapshots);
- 
-                             Answer answer = _agentMgr.sendToSecStorage(
-                                     secondaryStorageHost, cmd);
-                             if ((answer == null) || !answer.getResult()) {
-                                 String details = "Failed to cleanup snapshots for volume "
-                                         + volumeId
-                                         + " due to "
-                                         + (answer == null ? "null" : answer
-                                                 .getDetails());
-                                 s_logger.warn(details);
+ 
+                         if (s_logger.isDebugEnabled()) {
+                             s_logger.debug("Deleting snapshot on store: " + destroyedSnapshotStoreVO);
 -                        }
 +                            }
-                         } catch (Exception e1) {
-                             s_logger.warn(
-                                     "problem cleaning up snapshots in secondary storage "
-                                             + secondaryStorageHost, e1);
-                         } finally {
-                             if (lock) {
-                                 _volsDao.releaseFromLockTable(volumeId);
+ 
+                         String installPath = destroyedSnapshotStoreVO.getInstallPath();
+ 
+                         if (installPath != null) {
+                             EndPoint ep = _epSelector.select(store);
+                             DeleteCommand cmd = new DeleteCommand(snap.getTO());
+                             Answer answer = ep.sendMessage(cmd);
+                             if (answer == null || !answer.getResult()) {
+                                 s_logger.debug("Failed to delete " + destroyedSnapshotStoreVO + " due to "
+                                         + ((answer == null) ? "answer is null" : answer.getDetails()));
+                             } else {
+                                 _volumeStoreDao.remove(destroyedSnapshotStoreVO.getId());
+                                 s_logger.debug("Deleted snapshot at: " + destroyedSnapshotStoreVO.getInstallPath());
                              }
+                         } else {
+                             _snapshotStoreDao.remove(destroyedSnapshotStoreVO.getId());
                          }
                      }
+ 
                  } catch (Exception e2) {
-                     s_logger.warn(
-                             "problem cleaning up snapshots in secondary storage "
-                                     + secondaryStorageHost, e2);
+                     s_logger.warn("problem cleaning up snapshots in secondary storage store " + store.getName(), e2);
                  }
+ 
              }
  
              // CleanUp volumes on Secondary Storage.
-             for (HostVO secondaryStorageHost : secondaryStorageHosts) {
+             for (DataStore store : imageStores) {
                  try {
-                     long hostId = secondaryStorageHost.getId();
-                     List<VolumeHostVO> destroyedVolumeHostVOs = _volumeHostDao
-                             .listDestroyed(hostId);
-                     s_logger.debug("Secondary storage garbage collector found "
-                             + destroyedVolumeHostVOs.size()
-                             + " templates to cleanup on secondary storage host: "
-                             + secondaryStorageHost.getName());
-                     for (VolumeHostVO destroyedVolumeHostVO : destroyedVolumeHostVOs) {
+                     List<VolumeDataStoreVO> destroyedStoreVOs = _volumeStoreDao.listDestroyed(store.getId());
+                     s_logger.debug("Secondary storage garbage collector found " + destroyedStoreVOs.size()
+                             + " volumes to cleanup on secondary storage host: " + store.getName());
+                     for (VolumeDataStoreVO destroyedStoreVO : destroyedStoreVOs) {
                          if (s_logger.isDebugEnabled()) {
-                             s_logger.debug("Deleting volume host: "
-                                     + destroyedVolumeHostVO);
+                             s_logger.debug("Deleting volume on store: " + destroyedStoreVO);
                          }
  
-                         String installPath = destroyedVolumeHostVO
-                                 .getInstallPath();
+                         String installPath = destroyedStoreVO.getInstallPath();
  
-                         if (installPath != null) {
-                             Answer answer = _agentMgr.sendToSecStorage(
-                                     secondaryStorageHost,
-                                     new DeleteVolumeCommand(
-                                             secondaryStorageHost
-                                                     .getStorageUrl(),
-                                             destroyedVolumeHostVO
-                                                     .getInstallPath()));
 -                        VolumeInfo vol = this.volFactory.getVolume(destroyedStoreVO.getVolumeId(), store);
++                        VolumeInfo vol = volFactory.getVolume(destroyedStoreVO.getVolumeId(), store);
  
+                         if (installPath != null) {
+                             EndPoint ep = _epSelector.select(store);
+                             DeleteCommand cmd = new DeleteCommand(vol.getTO());
+                             Answer answer = ep.sendMessage(cmd);
                              if (answer == null || !answer.getResult()) {
-                                 s_logger.debug("Failed to delete "
-                                         + destroyedVolumeHostVO
-                                         + " due to "
-                                         + ((answer == null) ? "answer is null"
-                                                 : answer.getDetails()));
+                                 s_logger.debug("Failed to delete " + destroyedStoreVO + " due to "
+                                         + ((answer == null) ? "answer is null" : answer.getDetails()));
                              } else {
-                                 _volumeHostDao.remove(destroyedVolumeHostVO
-                                         .getId());
-                                 s_logger.debug("Deleted volume at: "
-                                         + destroyedVolumeHostVO
-                                                 .getInstallPath());
+                                 _volumeStoreDao.remove(destroyedStoreVO.getId());
+                                 s_logger.debug("Deleted volume at: " + destroyedStoreVO.getInstallPath());
                              }
                          } else {
-                             _volumeHostDao
-                                     .remove(destroyedVolumeHostVO.getId());
+                             _volumeStoreDao.remove(destroyedStoreVO.getId());
                          }
                      }
  
@@@ -1391,12 -1246,11 +1244,11 @@@
  
      @Override
      @DB
-     public PrimaryDataStoreInfo preparePrimaryStorageForMaintenance(
-             Long primaryStorageId) throws ResourceUnavailableException,
+     public PrimaryDataStoreInfo preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException,
              InsufficientCapacityException {
 -        Long userId = UserContext.current().getCallerUserId();
 +        Long userId = CallContext.current().getCallingUserId();
          User user = _userDao.findById(userId);
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
  
          boolean restart = true;
          StoragePoolVO primaryStorage = null;
@@@ -1409,15 -1263,12 +1261,12 @@@
              throw new InvalidParameterValueException(msg);
          }
  
-         List<StoragePoolVO> spes = _storagePoolDao.listBy(
-                 primaryStorage.getDataCenterId(), primaryStorage.getPodId(),
-                 primaryStorage.getClusterId(), ScopeType.CLUSTER);
+         List<StoragePoolVO> spes = _storagePoolDao.listBy(primaryStorage.getDataCenterId(), primaryStorage.getPodId(), primaryStorage.getClusterId(),
+                 ScopeType.CLUSTER);
          for (StoragePoolVO sp : spes) {
              if (sp.getStatus() == StoragePoolStatus.PrepareForMaintenance) {
-                 throw new CloudRuntimeException(
-                         "Only one storage pool in a cluster can be in PrepareForMaintenance mode, "
-                                 + sp.getId()
+                 throw new CloudRuntimeException("Only one storage pool in a cluster can be in PrepareForMaintenance mode, " + sp.getId()
 -                        + " is already in  PrepareForMaintenance mode ");
 +                                + " is already in  PrepareForMaintenance mode ");
              }
          }
  
@@@ -1443,13 -1287,11 +1285,11 @@@
  
      @Override
      @DB
-     public PrimaryDataStoreInfo cancelPrimaryStorageForMaintenance(
-             CancelPrimaryStorageMaintenanceCmd cmd)
-             throws ResourceUnavailableException {
+     public PrimaryDataStoreInfo cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ResourceUnavailableException {
          Long primaryStorageId = cmd.getId();
 -        Long userId = UserContext.current().getCallerUserId();
 +        Long userId = CallContext.current().getCallingUserId();
          User user = _userDao.findById(userId);
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
          StoragePoolVO primaryStorage = null;
  
          primaryStorage = _storagePoolDao.findById(primaryStorageId);
@@@ -1460,24 -1302,17 +1300,17 @@@
              throw new InvalidParameterValueException(msg);
          }
  
-         if (primaryStorage.getStatus().equals(StoragePoolStatus.Up)
-                 || primaryStorage.getStatus().equals(
-                         StoragePoolStatus.PrepareForMaintenance)) {
-             throw new StorageUnavailableException("Primary storage with id "
-                     + primaryStorageId
-                     + " is not ready to complete migration, as the status is:"
-                     + primaryStorage.getStatus().toString(), primaryStorageId);
+         if (primaryStorage.getStatus().equals(StoragePoolStatus.Up) || primaryStorage.getStatus().equals(StoragePoolStatus.PrepareForMaintenance)) {
+             throw new StorageUnavailableException("Primary storage with id " + primaryStorageId
+                     + " is not ready to complete migration, as the status is:" + primaryStorage.getStatus().toString(), primaryStorageId);
          }
  
-         DataStoreProvider provider = dataStoreProviderMgr
-                 .getDataStoreProvider(primaryStorage.getStorageProviderName());
+         DataStoreProvider provider = dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
          DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle();
-         DataStore store = dataStoreMgr.getDataStore(
-                 primaryStorage.getId(), DataStoreRole.Primary);
+         DataStore store = dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
          lifeCycle.cancelMaintain(store);
 -
 +        
-         return (PrimaryDataStoreInfo) dataStoreMgr.getDataStore(
-                 primaryStorage.getId(), DataStoreRole.Primary);
+         return (PrimaryDataStoreInfo) dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
      }
  
      protected class StorageGarbageCollector implements Runnable {
@@@ -1499,21 -1334,17 +1332,17 @@@
      }
  
      @Override
-     public void onManagementNodeJoined(List<? extends ManagementServerHost> nodeList,
-             long selfNodeId) {
 -    public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) {
++    public void onManagementNodeJoined(List<? extends ManagementServerHost> nodeList, long selfNodeId) {
          // TODO Auto-generated method stub
  
      }
  
      @Override
-     public void onManagementNodeLeft(List<? extends ManagementServerHost> nodeList,
-             long selfNodeId) {
 -    public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) {
 -        for (ManagementServerHostVO vo : nodeList) {
++    public void onManagementNodeLeft(List<? extends ManagementServerHost> nodeList, long selfNodeId) {
 +        for (ManagementServerHost vo : nodeList) {
              if (vo.getMsid() == _serverId) {
-                 s_logger.info("Cleaning up storage maintenance jobs associated with Management server"
-                         + vo.getMsid());
-                 List<Long> poolIds = _storagePoolWorkDao
-                         .searchForPoolIdsForPendingWorkJobs(vo.getMsid());
+                 s_logger.info("Cleaning up storage maintenance jobs associated with Management server" + vo.getMsid());
+                 List<Long> poolIds = _storagePoolWorkDao.searchForPoolIdsForPendingWorkJobs(vo.getMsid());
                  if (poolIds.size() > 0) {
                      for (Long poolId : poolIds) {
                          StoragePoolVO pool = _storagePoolDao.findById(poolId);
@@@ -1548,18 -1375,21 +1373,21 @@@
              sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
          }
  
-         List<HostVO> hosts = new ArrayList<HostVO>();
+         List<Long> hosts = new ArrayList<Long>();
          if (hostId != null) {
-             hosts.add(ApiDBUtils.findHostById(hostId));
+             hosts.add(hostId);
          } else {
-             hosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId);
 -            List<DataStore> stores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
++            List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
+             if (stores != null) {
+                 for (DataStore store : stores) {
+                     hosts.add(store.getId());
+                 }
+             }
          }
  
-         CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0,
-                 CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE);
-         for (HostVO host : hosts) {
-             StorageStats stats = ApiDBUtils.getSecondaryStorageStatistics(host
-                     .getId());
+         CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0, CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE);
+         for (Long id : hosts) {
+             StorageStats stats = ApiDBUtils.getSecondaryStorageStatistics(id);
              if (stats == null) {
                  continue;
              }
@@@ -1873,4 -1651,294 +1649,294 @@@
          return null;
      }
  
+     @Override
+     public ImageStore discoverImageStore(AddImageStoreCmd cmd) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException {
+         String providerName = cmd.getProviderName();
+         DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName);
+ 
+         if (storeProvider == null) {
+             storeProvider = _dataStoreProviderMgr.getDefaultImageDataStoreProvider();
+             if (storeProvider == null) {
+                 throw new InvalidParameterValueException("can't find image store provider: " + providerName);
+             }
+             providerName = storeProvider.getName(); // ignored passed provider name and use default image store provider name
+         }
+ 
+         Long dcId = cmd.getZoneId();
+         String url = cmd.getUrl();
+         Map details = cmd.getDetails();
+         ScopeType scopeType = ScopeType.ZONE;
+         if (dcId == null) {
+             scopeType = ScopeType.REGION;
+         }
+ 
+         // check if scope is supported by store provider
+         if (!((ImageStoreProvider) storeProvider).isScopeSupported(scopeType)) {
+             throw new InvalidParameterValueException("Image store provider " + providerName + " does not support scope " + scopeType);
+         }
+ 
+         // check if we have already image stores from other different providers,
+         // we currently are not supporting image stores from different
+         // providers co-existing
+         List<ImageStoreVO> imageStores = _imageStoreDao.listImageStores();
+         for (ImageStoreVO store : imageStores) {
+             if (!store.getProviderName().equalsIgnoreCase(providerName)) {
+                 throw new InvalidParameterValueException("You can only add new image stores from the same provider " + store.getProviderName()
+                         + " already added");
+             }
+         }
+ 
+         if (dcId != null) {
+             // Check if the zone exists in the system
+             DataCenterVO zone = _dcDao.findById(dcId);
+             if (zone == null) {
+                 throw new InvalidParameterValueException("Can't find zone by id " + dcId);
+             }
+ 
 -            Account account = UserContext.current().getCaller();
++            Account account = CallContext.current().getCallingAccount();
+             if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
+                 PermissionDeniedException ex = new PermissionDeniedException(
+                         "Cannot perform this operation, Zone with specified id is currently disabled");
+                 ex.addProxyObject(zone.getUuid(), "dcId");
+                 throw ex;
+             }
+         }
+ 
+         Map<String, Object> params = new HashMap<String, Object>();
+         params.put("zoneId", dcId);
+         params.put("url", cmd.getUrl());
+         params.put("name", cmd.getName());
+         params.put("details", details);
+         params.put("scope", scopeType);
+         params.put("providerName", storeProvider.getName());
+         params.put("role", DataStoreRole.Image);
+ 
+         DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
+         DataStore store = null;
+         try {
+             store = lifeCycle.initialize(params);
+         } catch (Exception e) {
+             s_logger.debug("Failed to add data store", e);
+             throw new CloudRuntimeException("Failed to add data store", e);
+         }
+ 
+         if (((ImageStoreProvider) storeProvider).needDownloadSysTemplate()) {
+             // trigger system vm template download
 -            this._imageSrv.downloadBootstrapSysTemplate(store);
++            _imageSrv.downloadBootstrapSysTemplate(store);
+         }
+         else {
+             // populate template_store_ref table
 -            this._imageSrv.addSystemVMTemplatesToSecondary(store);
++            _imageSrv.addSystemVMTemplatesToSecondary(store);
+         }
+ 
+         // associate builtin template with zones associated with this image
+         // store
 -        this.associateCrosszoneTemplatesToZone(dcId);
++        associateCrosszoneTemplatesToZone(dcId);
+ 
+         return (ImageStore) _dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Image);
+     }
+ 
+     private void associateCrosszoneTemplatesToZone(Long zoneId) {
+         VMTemplateZoneVO tmpltZone;
+ 
+         List<VMTemplateVO> allTemplates = _vmTemplateDao.listAll();
+         List<Long> dcIds = new ArrayList<Long>();
+         if (zoneId != null) {
+             dcIds.add(zoneId);
+         } else {
+             List<DataCenterVO> dcs = _dcDao.listAll();
+             if (dcs != null) {
+                 for (DataCenterVO dc : dcs) {
+                     dcIds.add(dc.getId());
+                 }
+             }
+         }
+ 
+         for (VMTemplateVO vt : allTemplates) {
+             if (vt.isCrossZones()) {
+                 for (Long dcId : dcIds) {
+                     tmpltZone = _vmTemplateZoneDao.findByZoneTemplate(dcId, vt.getId());
+                     if (tmpltZone == null) {
+                         VMTemplateZoneVO vmTemplateZone = new VMTemplateZoneVO(dcId, vt.getId(), new Date());
+                         _vmTemplateZoneDao.persist(vmTemplateZone);
+                     }
+                 }
+             }
+         }
+     }
+ 
+     @Override
+     public boolean deleteImageStore(DeleteImageStoreCmd cmd) {
+         long storeId = cmd.getId();
 -        User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
++        User caller = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
+         // Verify that image store exists
+         ImageStoreVO store = _imageStoreDao.findById(storeId);
+         if (store == null) {
+             throw new InvalidParameterValueException("Image store with id " + storeId + " doesn't exist");
+         }
 -        _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), store.getDataCenterId());
++        _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
+ 
+         // Verify that there are no live snapshot, template, volume on the image
+         // store to be deleted
+         List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listByStoreId(storeId, DataStoreRole.Image);
+         if (snapshots != null && snapshots.size() > 0) {
+             throw new InvalidParameterValueException("Cannot delete image store with active snapshots backup!");
+         }
+         List<VolumeDataStoreVO> volumes = _volumeStoreDao.listByStoreId(storeId);
+         if (volumes != null && volumes.size() > 0) {
+             throw new InvalidParameterValueException("Cannot delete image store with active volumes backup!");
+         }
+ 
+         // search if there are user templates stored on this image store, excluding system, builtin templates
 -        List<TemplateJoinVO> templates = this._templateViewDao.listActiveTemplates(storeId);
++        List<TemplateJoinVO> templates = _templateViewDao.listActiveTemplates(storeId);
+         if (templates != null && templates.size() > 0) {
+             throw new InvalidParameterValueException("Cannot delete image store with active templates backup!");
+         }
+ 
+         // ready to delete
+         Transaction txn = Transaction.currentTxn();
+         txn.start();
+         // first delete from image_store_details table, we need to do that since
+         // we are not actually deleting record from main
+         // image_data_store table, so delete cascade will not work
+         _imageStoreDetailsDao.deleteDetails(storeId);
+         _snapshotStoreDao.deletePrimaryRecordsForStore(storeId);
+         _volumeStoreDao.deletePrimaryRecordsForStore(storeId);
+         _templateStoreDao.deletePrimaryRecordsForStore(storeId);
+         _imageStoreDao.remove(storeId);
+         txn.commit();
+         return true;
+     }
+ 
+     @Override
+     public ImageStore createCacheStore(CreateCacheStoreCmd cmd) {
+         String providerName = cmd.getProviderName();
+         DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName);
+ 
+         if (storeProvider == null) {
+             storeProvider = _dataStoreProviderMgr.getDefaultCacheDataStoreProvider();
+             if (storeProvider == null) {
+                 throw new InvalidParameterValueException("can't find cache store provider: " + providerName);
+             }
+         }
+ 
+         Long dcId = cmd.getZoneId();
+ 
+         ScopeType scopeType = null;
+         String scope = cmd.getScope();
+         if (scope != null) {
+             try {
+                 scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase());
+ 
+             } catch (Exception e) {
+                 throw new InvalidParameterValueException("invalid scope" + scope);
+             }
+ 
+             if (scopeType != ScopeType.ZONE) {
+                 throw new InvalidParameterValueException("Only zone wide cache storage is supported");
+             }
+         }
+ 
+         if (scopeType == ScopeType.ZONE && dcId == null) {
+             throw new InvalidParameterValueException("zone id can't be null, if scope is zone");
+         }
+ 
+         // Check if the zone exists in the system
+         DataCenterVO zone = _dcDao.findById(dcId);
+         if (zone == null) {
+             throw new InvalidParameterValueException("Can't find zone by id " + dcId);
+         }
+ 
 -        Account account = UserContext.current().getCaller();
++        Account account = CallContext.current().getCallingAccount();
+         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
+             PermissionDeniedException ex = new PermissionDeniedException(
+                     "Cannot perform this operation, Zone with specified id is currently disabled");
+             ex.addProxyObject(zone.getUuid(), "dcId");
+             throw ex;
+         }
+ 
+         Map<String, Object> params = new HashMap<String, Object>();
+         params.put("zoneId", dcId);
+         params.put("url", cmd.getUrl());
+         params.put("name", cmd.getUrl());
+         params.put("details", cmd.getDetails());
+         params.put("scope", scopeType);
+         params.put("providerName", storeProvider.getName());
+         params.put("role", DataStoreRole.ImageCache);
+ 
+         DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
+         DataStore store = null;
+         try {
+             store = lifeCycle.initialize(params);
+         } catch (Exception e) {
+             s_logger.debug("Failed to add data store", e);
+             throw new CloudRuntimeException("Failed to add data store", e);
+         }
+ 
+         return (ImageStore) _dataStoreMgr.getDataStore(store.getId(), DataStoreRole.ImageCache);
+     }
+ 
+     // get bytesReadRate from service_offering, disk_offering and vm.disk.throttling.bytes_read_rate
+     @Override
+     public Long getDiskBytesReadRate(ServiceOfferingVO offering, DiskOfferingVO diskOffering) {
+         if ((offering != null) && (offering.getBytesReadRate() != null) && (offering.getBytesReadRate() > 0)) {
+             return offering.getBytesReadRate();
+         } else if ((diskOffering != null) && (diskOffering.getBytesReadRate() != null) && (diskOffering.getBytesReadRate() > 0)) {
+             return diskOffering.getBytesReadRate();
+         } else {
+             Long bytesReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesReadRate.key()));
+             if ((bytesReadRate > 0) && ((offering == null) || (! offering.getSystemUse()))) {
+                 return bytesReadRate;
+             }
+         }
+         return 0L;
+     }
+ 
+     // get bytesWriteRate from service_offering, disk_offering and vm.disk.throttling.bytes_write_rate
+     @Override
+     public Long getDiskBytesWriteRate(ServiceOfferingVO offering, DiskOfferingVO diskOffering) {
+         if ((offering != null) && (offering.getBytesWriteRate() != null) && (offering.getBytesWriteRate() > 0)) {
+             return offering.getBytesWriteRate();
+         } else if ((diskOffering != null) && (diskOffering.getBytesWriteRate() != null) && (diskOffering.getBytesWriteRate() > 0)) {
+             return diskOffering.getBytesWriteRate();
+         } else {
+             Long bytesWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesWriteRate.key()));
+             if ((bytesWriteRate > 0) && ((offering == null) || (! offering.getSystemUse())))  {
+                 return bytesWriteRate;
+             }
+         }
+         return 0L;
+     }
+ 
+     // get iopsReadRate from service_offering, disk_offering and vm.disk.throttling.iops_read_rate
+     @Override
+     public Long getDiskIopsReadRate(ServiceOfferingVO offering, DiskOfferingVO diskOffering) {
+         if ((offering != null) && (offering.getIopsReadRate() != null) && (offering.getIopsReadRate() > 0)) {
+             return offering.getIopsReadRate();
+         } else if ((diskOffering != null) && (diskOffering.getIopsReadRate() != null) && (diskOffering.getIopsReadRate() > 0)) {
+             return diskOffering.getIopsReadRate();
+         } else {
+             Long iopsReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsReadRate.key()));
+             if ((iopsReadRate > 0) && ((offering == null) || (! offering.getSystemUse())))  {
+                 return iopsReadRate;
+             }
+         }
+         return 0L;
+     }
+ 
+     // get iopsWriteRate from service_offering, disk_offering and vm.disk.throttling.iops_write_rate
+     @Override
+     public Long getDiskIopsWriteRate(ServiceOfferingVO offering, DiskOfferingVO diskOffering) {
+         if ((offering != null) && (offering.getIopsWriteRate() != null) && (offering.getIopsWriteRate() > 0)) {
+             return offering.getIopsWriteRate();
+         } else if ((diskOffering != null) && (diskOffering.getIopsWriteRate() != null) && (diskOffering.getIopsWriteRate() > 0)) {
+             return diskOffering.getIopsWriteRate();
+         } else {
+             Long iopsWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsWriteRate.key()));
+             if ((iopsWriteRate > 0) && ((offering == null) || (! offering.getSystemUse())))  {
+                 return iopsWriteRate;
+             }
+         }
+         return 0L;
+     }
  }


[31/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-2916: admin is not able to login through UI after setting GP "cluster.cpu.allocated.capacity.notificationthreshold" to some string
CLOUDSTACK-2457:  No check for input values,special character,-ive values can be assigne to GLobal parameter "cluster.cpu.allocated.capacity.disablethreshold"

Added validation for float values and checking limit for weight based parameters by creating a set of parameters.
Signed off by : nitin mehta<ni...@citrix.com>


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

Branch: refs/heads/vmsync
Commit: f7b1d3d8d5be58a8032fc79eec4dd5711226b93a
Parents: da00066
Author: Harikrishna Patnala <ha...@citrix.com>
Authored: Mon Jun 24 19:57:29 2013 +0530
Committer: Nitin Mehta <ni...@citrix.com>
Committed: Mon Jun 24 20:00:09 2013 +0530

----------------------------------------------------------------------
 .../configuration/ConfigurationManagerImpl.java | 36 ++++++++++++++++++++
 test/integration/smoke/test_scale_vm.py         | 13 +++++--
 2 files changed, 46 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f7b1d3d8/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 89a640d..704162e 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -324,6 +324,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
     private int _maxVolumeSizeInGb = Integer.parseInt(Config.MaxVolumeSize.getDefaultValue());
     private long _defaultPageSize = Long.parseLong(Config.DefaultPageSize.getDefaultValue());
     protected Set<String> configValuesForValidation;
+    private Set<String> weightBasedParametersForValidation;
 
     @Override
     public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
@@ -336,6 +337,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
                 Long.parseLong(Config.DefaultPageSize.getDefaultValue()));
 
         populateConfigValuesForValidationSet();
+        weightBasedParametersForValidation();
         return true;
     }
 
@@ -361,6 +363,28 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         configValuesForValidation.add("incorrect.login.attempts.allowed");
     }
 
+    private void weightBasedParametersForValidation() {
+        weightBasedParametersForValidation = new HashSet<String>();
+        weightBasedParametersForValidation.add(Config.CPUCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.StorageAllocatedCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.StorageCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.MemoryCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.PublicIpCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.PrivateIpCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.SecondaryStorageCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.VlanCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.DirectNetworkPublicIpCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.LocalStorageCapacityThreshold.key());
+        weightBasedParametersForValidation.add(Config.StorageAllocatedCapacityDisableThreshold.key());
+        weightBasedParametersForValidation.add(Config.StorageCapacityDisableThreshold.key());
+        weightBasedParametersForValidation.add(Config.CPUCapacityDisableThreshold.key());
+        weightBasedParametersForValidation.add(Config.MemoryCapacityDisableThreshold.key());
+        weightBasedParametersForValidation.add(Config.AgentLoadThreshold.key());
+        weightBasedParametersForValidation.add(Config.VmUserDispersionWeight.key());
+
+
+    }
+
     @Override
     public boolean start() {
 
@@ -733,6 +757,18 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             }
         }
 
+        if (type.equals(Float.class)) {
+            try {
+                Float val = Float.parseFloat(value);
+                if (weightBasedParametersForValidation.contains(name) && (val < 0f || val > 1f)) {
+                    throw new InvalidParameterValueException("Please enter a value between 0 and 1 for the configuration parameter: "+ name);
+                }
+            } catch (NumberFormatException e) {
+                s_logger.error("There was an error trying to parse the float value for:" + name);
+                throw new InvalidParameterValueException("There was an error trying to parse the float value for:" + name);
+            }
+        }
+
         String range = c.getRange();
         if (range == null) {
             return null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f7b1d3d8/test/integration/smoke/test_scale_vm.py
----------------------------------------------------------------------
diff --git a/test/integration/smoke/test_scale_vm.py b/test/integration/smoke/test_scale_vm.py
index b23ddd1..fd8d61e 100644
--- a/test/integration/smoke/test_scale_vm.py
+++ b/test/integration/smoke/test_scale_vm.py
@@ -142,7 +142,7 @@ class TestScaleVm(cloudstackTestCase):
         #how does it work ??
         cls._cleanup = [
                         cls.small_offering,
-                        cls.account
+                        #cls.account
                         ]
 
     @classmethod
@@ -170,9 +170,10 @@ class TestScaleVm(cloudstackTestCase):
         
       
       
-        self.debug("Scaling VM-ID: %s to service offering: %s" % (
+        self.debug("Scaling VM-ID: %s to service offering: %s and state %s" % (
                                         self.virtual_machine.id,
-                                        self.big_offering.id
+                                        self.big_offering.id,
+					self.virtual_machine.state
                                         ))
         
         cmd = scaleVirtualMachine.scaleVirtualMachineCmd()
@@ -204,6 +205,12 @@ class TestScaleVm(cloudstackTestCase):
                         "Check virtual machine ID of scaled VM"
                         )
 
+        self.debug("Scaling VM-ID: %s from service offering: %s to new service offering %s and the response says %s" % (
+                                        self.virtual_machine.id,
+					self.virtual_machine.serviceofferingid,
+                                        self.big_offering.id,
+					vm_response.serviceofferingid
+                                        ))
         self.assertEqual(
                         vm_response.serviceofferingid,
                         self.big_offering.id,


[40/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/NetworkServiceImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkServiceImpl.java
index 1897ef6,5e900bb..cfb870d
--- a/server/src/com/cloud/network/NetworkServiceImpl.java
+++ b/server/src/com/cloud/network/NetworkServiceImpl.java
@@@ -1281,10 -1298,14 +1283,14 @@@ public class NetworkServiceImpl extend
                      throw new InvalidParameterValueException("Unable to find specified NetworkACL");
                  }
  
+                 if(aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
+                     //ACL is not default DENY/ALLOW
+                     // ACL should be associated with a VPC
 -                    if(!vpcId.equals(acl.getVpcId())){
 -                        throw new InvalidParameterValueException("ACL: "+aclId+" do not belong to the VPC");
 -                    }
 +                if(!vpcId.equals(acl.getVpcId())){
 +                    throw new InvalidParameterValueException("ACL: "+aclId+" do not belong to the VPC");
                  }
              }
++            }
              network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, 
                      networkDomain, owner, sharedDomainId, pNtwk, zoneId, aclType, subdomainAccess, vpcId, aclId, caller, displayNetwork);
          } else {
@@@ -2476,11 -2497,11 +2482,11 @@@
              addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
  
              // add baremetal as the defualt network service provider
-             /* addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId()); */
+             addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
 -
 +            
              //Add Internal Load Balancer element as a default network service provider
              addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
 -
 +            
              txn.commit();
              return pNetwork;
          } catch (Exception ex) {
@@@ -3013,27 -3037,48 +3022,48 @@@
              List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
              int dedicatedStartVlan = vlanTokens.get(0).intValue();
              int dedicatedEndVlan = vlanTokens.get(1).intValue();
-             guestVlanMapId = guestVlanMap.getId();
-             guestVlanMapAccountId = guestVlanMap.getAccountId();
- 
-             // Verify if range is already dedicated
-             if (startVlan >= dedicatedStartVlan && endVlan <= dedicatedEndVlan) {
-                 if (guestVlanMap.getAccountId() != vlanOwner.getAccountId()) {
-                     throw new InvalidParameterValueException("Vlan range is already dedicated to another account. Cannot dedicate guest vlan range " + vlan);
-                 } else {
-                     s_logger.debug("Vlan range " + vlan +" is already dedicated to the specified account" + accountName);
-                     return guestVlanMap;
+             if ((startVlan < dedicatedStartVlan & endVlan >= dedicatedStartVlan) ||
+                     (startVlan >= dedicatedStartVlan & startVlan <= dedicatedEndVlan)) {
+                 throw new InvalidParameterValueException("Vlan range is already dedicated. Cannot" +
+                         " dedicate guest vlan range " + vlan);
 +                }
              }
-             // Verify if range overlaps with an existing range
-             if (startVlan < dedicatedStartVlan & endVlan+1 >= dedicatedStartVlan & endVlan <= dedicatedEndVlan) { // extend to the left
-                 updatedVlanRange = startVlan + "-" + dedicatedEndVlan;
 -        }
+ 
+         // Sort the existing dedicated vlan ranges
+         Collections.sort(guestVlanMaps, new Comparator<AccountGuestVlanMapVO>() {
+             @Override
+             public int compare( AccountGuestVlanMapVO obj1 , AccountGuestVlanMapVO obj2) {
+                 List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
+                 List<Integer> vlanTokens2 = getVlanFromRange(obj2.getGuestVlanRange());
+                 return vlanTokens1.get(0).compareTo(vlanTokens2.get(0));
+             }
+         });
+ 
+         // Verify if vlan range extends an already dedicated range
+         for (int i=0; i < guestVlanMaps.size(); i++) {
+             guestVlanMapId = guestVlanMaps.get(i).getId();
+             guestVlanMapAccountId = guestVlanMaps.get(i).getAccountId();
+             List<Integer> vlanTokens1 = getVlanFromRange(guestVlanMaps.get(i).getGuestVlanRange());
+             // Range extends a dedicated vlan range to the left
+             if (endVlan == (vlanTokens1.get(0).intValue()-1)) {
+                 if(guestVlanMapAccountId == vlanOwnerId) {
+                     updatedVlanRange = startVlan + "-" + vlanTokens1.get(1).intValue();
+                 }
                  break;
-             } else if (startVlan >= dedicatedStartVlan & startVlan-1 <= dedicatedEndVlan & endVlan > dedicatedEndVlan) { // extend to right
-                 updatedVlanRange = dedicatedStartVlan + "-" +  endVlan;
+             }
+             // Range extends a dedicated vlan range to the right
+             if (startVlan == (vlanTokens1.get(1).intValue()+1) & guestVlanMapAccountId == vlanOwnerId) {
+                 if (i != (guestVlanMaps.size()-1)) {
+                     List<Integer> vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i+1).getGuestVlanRange());
+                     // Range extends 2 vlan ranges, both to the right and left
+                     if (endVlan == (vlanTokens2.get(0).intValue()-1) & guestVlanMaps.get(i+1).getAccountId() == vlanOwnerId) {
+                         _datacneter_vnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i+1).getId());
+                         _accountGuestVlanMapDao.remove(guestVlanMaps.get(i+1).getId());
+                         updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue();
 -                        break;
 +                break;
-             } else if (startVlan < dedicatedStartVlan & endVlan > dedicatedEndVlan){ // extend to the left and right
-                 updatedVlanRange = startVlan + "-" +  endVlan;
+                     }
+                 }
+                 updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + endVlan;
                  break;
              }
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/NetworkUsageManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/element/CloudZonesNetworkElement.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/element/CloudZonesNetworkElement.java
index f5d4268,bdd8e61..4e107a8
--- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java
+++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java
@@@ -215,7 -217,7 +215,8 @@@ public class CloudZonesNetworkElement e
              Commands cmds = new Commands(OnError.Continue);
              if (password != null && nic.isDefaultNic()) {
                  final String encodedPassword = PasswordGenerator.rot13(password);
-                 SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), uservm.getHostName());
 -                SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), uservm.getVirtualMachine().getHostName(), _networkMgr.getExecuteInSeqNtwkElmtCmd());
++                SavePasswordCommand cmd = new SavePasswordCommand(encodedPassword, nic.getIp4Address(), uservm.getHostName(),
++                        _networkMgr.getExecuteInSeqNtwkElmtCmd());
                  cmds.addCommand("password", cmd);
              }
              String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(uservm.getServiceOfferingId()).getDisplayText();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index efd247b,5a8cf5d..9bceb32
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@@ -787,19 -788,19 +789,19 @@@ public class VirtualNetworkApplianceMan
      protected VirtualNetworkApplianceManagerImpl() {
      }
  
 -    @Override
 -    public Long convertToId(final String vmName) {
 -        if (!VirtualMachineName.isValidRouterName(vmName, _instance)) {
 -            return null;
 -        }
 -
 -        return VirtualMachineName.getRouterId(vmName);
 -    }
 +//    @Override
 +//    public Long convertToId(final String vmName) {
 +//        if (!VirtualMachineName.isValidRouterName(vmName, _instance)) {
 +//            return null;
 +//        }
 +//
 +//        return VirtualMachineName.getRouterId(vmName);
 +//    }
  
 -    private VmDataCommand generateVmDataCommand(VirtualRouter router, String vmPrivateIpAddress, String userData, 
 +    private VmDataCommand generateVmDataCommand(VirtualRouter router, String vmPrivateIpAddress, String userData,
              String serviceOffering, String zoneName, String guestIpAddress, String vmName,
              String vmInstanceName, long vmId, String vmUuid, String publicKey, long guestNetworkId) {
-         VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName);
+         VmDataCommand cmd = new VmDataCommand(vmPrivateIpAddress, vmName, _networkModel.getExecuteInSeqNtwkElmtCmd());
  
          cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
          cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
@@@ -1606,59 -1598,61 +1603,63 @@@
          DomainRouterVO router = null;
          for (Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext();) {
              HypervisorType hType = iter.next();
-             s_logger.debug("Allocating the domR with the hypervisor type " + hType);
 -            try {
 -                long id = _routerDao.getNextInSequence(Long.class, "id");
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Allocating the VR i="+ id + " in datacenter "  + dest.getDataCenter() + "with the hypervisor type " + hType);
 -                }
++            long id = _routerDao.getNextInSequence(Long.class, "id");
++            if (s_logger.isDebugEnabled()) {
++                s_logger.debug("Allocating the VR i="+ id + " in datacenter "  + dest.getDataCenter() + "with the hypervisor type " + hType);
++            }
+                 
 -                String templateName = null;
 -                switch (hType) {
 -                    case XenServer:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case KVM:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case VMware:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case Hyperv:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case LXC:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    default: break;
 -                }
 -                VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
 +            String templateName = null;
 +            switch (hType) {
 +            case XenServer:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case KVM:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case VMware:
 +                templateName = _configServer
 +                        .getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case Hyperv:
 +                templateName = _configServer
 +                        .getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case LXC:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            default:
 +                break;
 +            }
 +            VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
  
 -                if (template == null) {
 -                    s_logger.debug(hType + " won't support system vm, skip it");
 -                    continue;
 -                }
 -                
 -                boolean offerHA = routerOffering.getOfferHA();
 -                /* We don't provide HA to redundant router VMs, admin should own it all, and redundant router themselves are HA */
 -                if (isRedundant) {
 -                    offerHA = false;
 -                }
 +            if (template == null) {
 +                s_logger.debug(hType + " won't support system vm, skip it");
 +                continue;
 +            }
  
 -                router = new DomainRouterVO(id, routerOffering.getId(), vrProvider.getId(), 
 -                VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(),
 -                template.getGuestOSId(), owner.getDomainId(), owner.getId(), isRedundant, 0, false, 
 -                RedundantState.UNKNOWN, offerHA, false, vpcId);
 -                router.setRole(Role.VIRTUAL_ROUTER);
 -                router = _itMgr.allocate(router, template, routerOffering, networks, plan, null, owner);
 -            } catch (InsufficientCapacityException ex) {
 +            boolean offerHA = routerOffering.getOfferHA();
 +            /* We don't provide HA to redundant router VMs, admin should own it all, and redundant router themselves are HA */
 +            if (isRedundant) {
 +                offerHA = false;
 +            }
 +
 +            router = new DomainRouterVO(id, routerOffering.getId(), vrProvider.getId(),
 +                    VirtualMachineName.getRouterName(id, _instance), template.getId(), template.getHypervisorType(),
 +                    template.getGuestOSId(), owner.getDomainId(), owner.getId(), isRedundant, 0, false,
 +                    RedundantState.UNKNOWN, offerHA, false, vpcId);
 +            router.setRole(Role.VIRTUAL_ROUTER);
 +            router = _routerDao.persist(router);
 +            try {
 +                _itMgr.allocate(router.getInstanceName(), template, routerOffering, networks, plan, null, owner);
 +            } catch (CloudRuntimeException e) {
                  if (allocateRetry < 2 && iter.hasNext()) {
 -                    s_logger.debug("Failed to allocate the VR with hypervisor type " + hType + ", retrying one more time");
 +                    _routerDao.remove(router.getId());
 +                    allocateRetry++;
 +                    s_logger.debug("Failed to allocate the VR with hypervisor type " + hType + ", retrying one more time: " + e.toString());
                      continue;
 -                } else {
 -                    throw ex;
                  }
 -            } finally {
 -                allocateRetry++;
              }
 -
 +            router = _routerDao.findById(router.getId());
  
              if (startRouter) {
                  try {
@@@ -2350,8 -2352,9 +2351,9 @@@
          cmds.addCommand("getDomRVersion", command);
  
          // Network usage command to create iptables rules
 -        boolean forVpc = profile.getVirtualMachine().getVpcId() != null;
 +        boolean forVpc = router.getVpcId() != null;
+         if (!forVpc)
 -            cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIp4Address(), router.getHostName(), "create", forVpc));
 +        cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIp4Address(), router.getHostName(), "create", forVpc));
      }
  
      protected void finalizeUserDataAndDhcpOnStart(Commands cmds, DomainRouterVO router, Provider provider, Long guestNetworkId) {
@@@ -3346,7 -3358,7 +3349,7 @@@
          // password should be set only on default network element
          if (password != null && nic.isDefaultNic()) {
              String encodedPassword = PasswordGenerator.rot13(password);
--            // We would unset password for BACKUP router in the RvR, to prevent user from accidently reset the 
++            // We would unset password for BACKUP router in the RvR, to prevent user from accidently reset the
              // password again after BACKUP become MASTER
              if (router.getIsRedundantRouter() && router.getRedundantState() != RedundantState.MASTER) {
              	encodedPassword = PasswordGenerator.rot13("saved_password");
@@@ -3390,9 -3401,9 +3393,9 @@@
              }
          }
      }
 -    
 +
      private void createDhcpEntryCommand(VirtualRouter router, UserVm vm, NicVO nic, Commands cmds) {
-         DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getHostName(), nic.getIp6Address());
+         DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), vm.getHostName(), nic.getIp6Address(), _networkModel.getExecuteInSeqNtwkElmtCmd());
          DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
          Nic defaultNic = findGatewayIp(vm.getId());
          String gatewayIp = defaultNic.getGateway();
@@@ -3675,14 -3691,13 +3685,13 @@@
              rulesTO = new ArrayList<FirewallRuleTO>();
              for (FirewallRule rule : rules) {
                  FirewallRule.TrafficType traffictype = rule.getTrafficType();
 -                if(traffictype == FirewallRule.TrafficType.Ingress){
 +                if (traffictype == FirewallRule.TrafficType.Ingress) {
                      IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
 -                    FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(),Purpose.Firewall,traffictype);
 +                    FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(), Purpose.Firewall, traffictype);
                      rulesTO.add(ruleTO);
-                 }
-                 else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
-                     assert (rule.getSourceIpAddressId() == null) : "ipAddressId should be null for egress firewall rule. ";
-                     FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, "", Purpose.Firewall, traffictype);
+                 } else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress){
+                     assert (rule.getSourceIpAddressId()==null) : "ipAddressId should be null for egress firewall rule. ";
+                     FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null,"",Purpose.Firewall, traffictype);
                      rulesTO.add(ruleTO);
                  }
              }
@@@ -3861,7 -3888,9 +3880,7 @@@
      }
  
      @Override
-     public void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
+     public void processConnect(Host host, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
 -        UserContext context = UserContext.current();
 -        context.setAccountId(1);
          List<DomainRouterVO> routers = _routerDao.listIsolatedByHostId(host.getId());
          for (DomainRouterVO router : routers) {
              if (router.isStopPending()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/vpc/VpcManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/resource/ResourceManagerImpl.java
index effc4e0,fe91cb3..757843c
--- a/server/src/com/cloud/resource/ResourceManagerImpl.java
+++ b/server/src/com/cloud/resource/ResourceManagerImpl.java
@@@ -47,9 -45,11 +47,10 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd;
  import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd;
  import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd;
 +import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.region.dao.RegionDao;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  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.AgentManager.TapAgentsAction;
@@@ -169,32 -167,32 +170,31 @@@ import com.cloud.vm.dao.VMInstanceDao
  
  @Component
  @Local({ ResourceManager.class, ResourceService.class })
- public class ResourceManagerImpl extends ManagerBase implements ResourceManager, ResourceService,
- 		Manager {
- 	private static final Logger s_logger = Logger
- 			.getLogger(ResourceManagerImpl.class);
+ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, ResourceService, Manager {
+     private static final Logger s_logger = Logger.getLogger(ResourceManagerImpl.class);
  
      @Inject
 -    AccountManager _accountMgr;
 +    AccountManager                           _accountMgr;
      @Inject
 -    AgentManager _agentMgr;
 +    AgentManager                             _agentMgr;
      @Inject
 -    StorageManager _storageMgr;
 +    StorageManager                           _storageMgr;
      @Inject
 -    protected SecondaryStorageVmManager _secondaryStorageMgr;
 +    protected SecondaryStorageVmManager      _secondaryStorageMgr;
- 
+     @Inject
+     protected RegionDao _regionDao;
      @Inject
 -    protected DataCenterDao _dcDao;
 +    protected DataCenterDao                  _dcDao;
      @Inject
 -    protected HostPodDao _podDao;
 +    protected HostPodDao                     _podDao;
      @Inject
 -    protected ClusterDetailsDao _clusterDetailsDao;
 +    protected ClusterDetailsDao              _clusterDetailsDao;
      @Inject
 -    protected ClusterDao _clusterDao;
 +    protected ClusterDao                     _clusterDao;
      @Inject
 -    protected CapacityDao _capacityDao;
 +    protected CapacityDao 					 _capacityDao;
      @Inject
 -    protected HostDao _hostDao;
 +    protected HostDao                        _hostDao;
      @Inject
      protected SwiftManager _swiftMgr;
      @Inject
@@@ -229,34 -225,38 +229,38 @@@
      protected DedicatedResourceDao           _dedicatedDao;
  
      protected List<? extends Discoverer> _discoverers;
+ 
      public List<? extends Discoverer> getDiscoverers() {
 -        return _discoverers;
 -    }
 +		return _discoverers;
 +	}
+ 
 -    public void setDiscoverers(List<? extends Discoverer> _discoverers) {
 -        this._discoverers = _discoverers;
 -    }
 +	public void setDiscoverers(List<? extends Discoverer> _discoverers) {
 +		this._discoverers = _discoverers;
 +	}
  
 +	@Inject
 +    protected ClusterManager                 _clusterMgr;
      @Inject
 -    protected ClusterManager _clusterMgr;
 -    @Inject
 -    protected StoragePoolHostDao _storagePoolHostDao;
 +    protected StoragePoolHostDao             _storagePoolHostDao;
  
 -    protected List<PodAllocator> _podAllocators;
 +	protected List<PodAllocator> _podAllocators;
+ 
      public List<PodAllocator> getPodAllocators() {
 -        return _podAllocators;
 -    }
 +		return _podAllocators;
 +	}
+ 
 -    public void setPodAllocators(List<PodAllocator> _podAllocators) {
 -        this._podAllocators = _podAllocators;
 -    }
 +	public void setPodAllocators(List<PodAllocator> _podAllocators) {
 +		this._podAllocators = _podAllocators;
 +	}
  
 +	@Inject
 +    protected VMTemplateDao  _templateDao;
      @Inject
 -    protected VMTemplateDao _templateDao;
 -    @Inject
 -    protected ConfigurationManager _configMgr;
 +    protected ConfigurationManager 			 _configMgr;
      @Inject
 -    protected ClusterVSMMapDao _clusterVSMMapDao;
 +    protected ClusterVSMMapDao				 _clusterVSMMapDao;
  
 -    protected long _nodeId = ManagementServerNode.getManagementServerId();
 +    protected long                           _nodeId  = ManagementServerNode.getManagementServerId();
  
      protected HashMap<String, ResourceStateAdapter> _resourceStateAdapters = new HashMap<String, ResourceStateAdapter>();
  
@@@ -404,11 -387,10 +391,10 @@@
              throw ex;
          }
  
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
- 		if (Grouping.AllocationState.Disabled == zone.getAllocationState()
- 				&& !_accountMgr.isRootAdmin(account.getType())) {
+         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
 -            PermissionDeniedException ex = new PermissionDeniedException(
 -                    "Cannot perform this operation, Zone with specified id is currently disabled");
 +			PermissionDeniedException ex = new PermissionDeniedException(
 +					"Cannot perform this operation, Zone with specified id is currently disabled");
              ex.addProxyObject(zone.getUuid(), "dcId");
              throw ex;
          }
@@@ -510,9 -478,8 +482,8 @@@
              cluster = _clusterDao.persist(cluster);
          } catch (Exception e) {
              // no longer tolerate exception during the cluster creation phase
- 			CloudRuntimeException ex = new CloudRuntimeException(
- 					"Unable to create cluster " + clusterName
+             CloudRuntimeException ex = new CloudRuntimeException("Unable to create cluster " + clusterName
 -                    + " in pod and data center with specified ids", e);
 +							+ " in pod and data center with specified ids", e);
              // Get the pod VO object's table name.
              ex.addProxyObject(pod.getUuid(), "podId");
              ex.addProxyObject(zone.getUuid(), "dcId");
@@@ -576,16 -535,14 +539,14 @@@
  
              List<HostVO> hosts = new ArrayList<HostVO>();
              Map<? extends ServerResource, Map<String, String>> resources = null;
- 			resources = discoverer.find(dcId, podId, clusterId, uri, username,
- 					password, null);
+             resources = discoverer.find(dcId, podId, clusterId, uri, username, password, null);
  
              if (resources != null) {
- 				for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources
- 						.entrySet()) {
+                 for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
                      ServerResource resource = entry.getKey();
  
 -                    // For Hyper-V, we are here means agent have already started
 -                    // and connected to management server
 +					// For Hyper-V, we are here means agent have already started
 +					// and connected to management server
                      if (hypervisorType == Hypervisor.HypervisorType.Hyperv) {
                          break;
                      }
@@@ -614,12 -569,11 +573,11 @@@
      }
  
      @Override
- 	public Discoverer getMatchingDiscover(
- 			Hypervisor.HypervisorType hypervisorType) {
+     public Discoverer getMatchingDiscover(Hypervisor.HypervisorType hypervisorType) {
 -        for (Discoverer discoverer : _discoverers) {
 -            if (discoverer.getHypervisorType() == hypervisorType)
 +		for (Discoverer discoverer : _discoverers) {
 +			if (discoverer.getHypervisorType() == hypervisorType)
                  return discoverer;
 -        }
 +            }
          return null;
      }
  
@@@ -636,8 -588,7 +592,7 @@@
          String password = cmd.getPassword();
          List<String> hostTags = cmd.getHostTags();
  
- 		dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current()
- 				.getCallingAccount(), dcId);
 -        dcId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), dcId);
++        dcId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), dcId);
  
          // this is for standalone option
          if (clusterName == null && clusterId == null) {
@@@ -668,9 -620,8 +624,8 @@@
      }
  
      @Override
- 	public List<? extends Host> discoverHosts(AddSecondaryStorageCmd cmd)
- 			throws IllegalArgumentException, DiscoveryException,
+     public List<? extends Host> discoverHosts(AddSecondaryStorageCmd cmd) throws IllegalArgumentException, DiscoveryException,
 -            InvalidParameterValueException {
 +			InvalidParameterValueException {
          Long dcId = cmd.getZoneId();
          String url = cmd.getUrl();
          return discoverHostsFull(dcId, null, null, null, url, null, null, "SecondaryStorage", null, null, false);
@@@ -694,25 -645,25 +649,25 @@@
  
      @Override
      public List<S3VO> listS3s(final ListS3sCmd cmd) {
 -        return this._s3Mgr.listS3s(cmd);
 +        return _s3Mgr.listS3s(cmd);
      }
  
-     private List<HostVO> discoverHostsFull(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password, String hypervisorType, List<String> hostTags,
-             Map<String, String> params, boolean deferAgentCreation) throws IllegalArgumentException, DiscoveryException, InvalidParameterValueException {
+ 
+     private List<HostVO> discoverHostsFull(Long dcId, Long podId, Long clusterId, String clusterName, String url, String username, String password,
+             String hypervisorType, List<String> hostTags, Map<String, String> params, boolean deferAgentCreation) throws IllegalArgumentException,
+             DiscoveryException, InvalidParameterValueException {
          URI uri = null;
  
          // Check if the zone exists in the system
          DataCenterVO zone = _dcDao.findById(dcId);
          if (zone == null) {
- 			throw new InvalidParameterValueException("Can't find zone by id "
- 					+ dcId);
+             throw new InvalidParameterValueException("Can't find zone by id " + dcId);
          }
  
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
- 		if (Grouping.AllocationState.Disabled == zone.getAllocationState()
- 				&& !_accountMgr.isRootAdmin(account.getType())) {
+         if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getType())) {
 -            PermissionDeniedException ex = new PermissionDeniedException(
 -                    "Cannot perform this operation, Zone with specified id is currently disabled");
 +			PermissionDeniedException ex = new PermissionDeniedException(
 +					"Cannot perform this operation, Zone with specified id is currently disabled");
              ex.addProxyObject(zone.getUuid(), "dcId");
              throw ex;
          }
@@@ -755,23 -702,20 +706,20 @@@
  
          if (clusterId != null) {
              if (_clusterDao.findById(clusterId) == null) {
- 				throw new InvalidParameterValueException(
- 						"Can't find cluster by id " + clusterId);
+                 throw new InvalidParameterValueException("Can't find cluster by id " + clusterId);
 -            }
 +			}
  
- 			if (hypervisorType.equalsIgnoreCase(HypervisorType.VMware
- 					.toString())) {
+             if (hypervisorType.equalsIgnoreCase(HypervisorType.VMware.toString())) {
 -                // VMware only allows adding host to an existing cluster, as we
 -                // already have a lot of information
 -                // in cluster object, to simplify user input, we will construct
 -                // neccessary information here
 -                Map<String, String> clusterDetails = this._clusterDetailsDao.findDetails(clusterId);
 +				// VMware only allows adding host to an existing cluster, as we
 +				// already have a lot of information
 +				// in cluster object, to simplify user input, we will construct
 +				// neccessary information here
- 				Map<String, String> clusterDetails = _clusterDetailsDao
- 						.findDetails(clusterId);
++				Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
                  username = clusterDetails.get("username");
 -                assert (username != null);
 +				assert (username != null);
  
                  password = clusterDetails.get("password");
 -                assert (password != null);
 +				assert (password != null);
  
                  try {
                      uri = new URI(UriUtils.encodeURIComponent(url));
@@@ -808,11 -750,11 +754,11 @@@
                  }
              }
              clusterId = cluster.getId();
-             if (_clusterDetailsDao.findDetail(clusterId,"cpuOvercommitRatio") == null) {
-             ClusterDetailsVO cluster_cpu_detail = new ClusterDetailsVO(clusterId,"cpuOvercommitRatio","1");
-             ClusterDetailsVO cluster_memory_detail = new ClusterDetailsVO(clusterId,"memoryOvercommitRatio","1");
+             if (_clusterDetailsDao.findDetail(clusterId, "cpuOvercommitRatio") == null) {
+                 ClusterDetailsVO cluster_cpu_detail = new ClusterDetailsVO(clusterId, "cpuOvercommitRatio", "1");
+                 ClusterDetailsVO cluster_memory_detail = new ClusterDetailsVO(clusterId, "memoryOvercommitRatio", "1");
 -                _clusterDetailsDao.persist(cluster_cpu_detail);
 -                _clusterDetailsDao.persist(cluster_memory_detail);
 +            _clusterDetailsDao.persist(cluster_cpu_detail);
 +            _clusterDetailsDao.persist(cluster_memory_detail);
              }
  
          }
@@@ -836,10 -773,9 +777,9 @@@
          }
  
          List<HostVO> hosts = new ArrayList<HostVO>();
- 		s_logger.info("Trying to add a new host at " + url + " in data center "
- 				+ dcId);
+         s_logger.info("Trying to add a new host at " + url + " in data center " + dcId);
          boolean isHypervisorTypeSupported = false;
 -        for (Discoverer discoverer : _discoverers) {
 +		for (Discoverer discoverer : _discoverers) {
              if (params != null) {
                  discoverer.putParam(params);
              }
@@@ -850,43 -786,35 +790,35 @@@
              isHypervisorTypeSupported = true;
              Map<? extends ServerResource, Map<String, String>> resources = null;
  
- 			processResourceEvent(ResourceListener.EVENT_DISCOVER_BEFORE, dcId,
- 					podId, clusterId, uri, username, password, hostTags);
+             processResourceEvent(ResourceListener.EVENT_DISCOVER_BEFORE, dcId, podId, clusterId, uri, username, password, hostTags);
              try {
- 				resources = discoverer.find(dcId, podId, clusterId, uri,
- 						username, password, hostTags);
+                 resources = discoverer.find(dcId, podId, clusterId, uri, username, password, hostTags);
 -            } catch (DiscoveryException e) {
 +			} catch (DiscoveryException e) {
                  throw e;
              } catch (Exception e) {
- 				s_logger.info("Exception in host discovery process with discoverer: "
- 						+ discoverer.getName()
+                 s_logger.info("Exception in host discovery process with discoverer: " + discoverer.getName()
 -                        + ", skip to another discoverer if there is any");
 +						+ ", skip to another discoverer if there is any");
              }
- 			processResourceEvent(ResourceListener.EVENT_DISCOVER_AFTER,
- 					resources);
+             processResourceEvent(ResourceListener.EVENT_DISCOVER_AFTER, resources);
  
              if (resources != null) {
- 				for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources
- 						.entrySet()) {
+                 for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
                      ServerResource resource = entry.getKey();
                      /*
 -                     * For KVM, if we go to here, that means kvm agent is
 -                     * already connected to mgt svr.
 +					 * For KVM, if we go to here, that means kvm agent is
 +					 * already connected to mgt svr.
                       */
                      if (resource instanceof KvmDummyResourceBase) {
                          Map<String, String> details = entry.getValue();
                          String guid = details.get("guid");
- 						List<HostVO> kvmHosts = listAllUpAndEnabledHosts(
- 								Host.Type.Routing, clusterId, podId, dcId);
+                         List<HostVO> kvmHosts = listAllUpAndEnabledHosts(Host.Type.Routing, clusterId, podId, dcId);
                          for (HostVO host : kvmHosts) {
                              if (host.getGuid().equalsIgnoreCase(guid)) {
 -                                if (hostTags != null) {
 -                                    if (s_logger.isTraceEnabled()) {
 +								if (hostTags != null) {
 +									if (s_logger.isTraceEnabled()) {
- 										s_logger.trace("Adding Host Tags for KVM host, tags:  :"
- 												+ hostTags);
+                                         s_logger.trace("Adding Host Tags for KVM host, tags:  :" + hostTags);
                                      }
- 									_hostTagsDao
- 											.persist(host.getId(), hostTags);
+                                     _hostTagsDao.persist(host.getId(), hostTags);
                                  }
                                  hosts.add(host);
                                  return hosts;
@@@ -928,42 -854,33 +858,33 @@@
      }
  
      @DB
- 	protected boolean doDeleteHost(long hostId, boolean isForced,
- 			boolean isForceDeleteStorage) {
- 		User caller = _accountMgr.getActiveUser(CallContext.current()
- 				.getCallingUserId());
+     protected boolean doDeleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage) {
 -        User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
++        User caller = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
          // Verify that host exists
          HostVO host = _hostDao.findById(hostId);
          if (host == null) {
- 			throw new InvalidParameterValueException("Host with id " + hostId
- 					+ " doesn't exist");
+             throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist");
          }
- 		_accountMgr.checkAccessAndSpecifyAuthority(CallContext.current()
- 				.getCallingAccount(), host.getDataCenterId());
 -        _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), host.getDataCenterId());
++        _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), host.getDataCenterId());
  
          /*
 -         * TODO: check current agent status and updateAgentStatus to removed. If
 -         * it was already removed, that means someone is deleting host
 -         * concurrently, return. And consider the situation of CloudStack
 -         * shutdown during delete. A global lock?
 +		 * TODO: check current agent status and updateAgentStatus to removed. If
 +		 * it was already removed, that means someone is deleting host
 +		 * concurrently, return. And consider the situation of CloudStack
 +		 * shutdown during delete. A global lock?
           */
 -        AgentAttache attache = _agentMgr.findAttache(hostId);
 -        // Get storage pool host mappings here because they can be removed as a
 -        // part of handleDisconnect later
 -        // TODO: find out the bad boy, what's a buggy logic!
 +        AgentAttache attache = _attacheHandler.findAttache(hostId);
 +		// Get storage pool host mappings here because they can be removed as a
 +		// part of handleDisconnect later
 +		// TODO: find out the bad boy, what's a buggy logic!
- 		List<StoragePoolHostVO> pools = _storagePoolHostDao
- 				.listByHostIdIncludingRemoved(hostId);
+         List<StoragePoolHostVO> pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId);
  
 -        ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(
 +		ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(
- 				ResourceStateAdapter.Event.DELETE_HOST, false, host,
- 				new Boolean(isForced), new Boolean(isForceDeleteStorage));
+                 ResourceStateAdapter.Event.DELETE_HOST, false, host, new Boolean(isForced), new Boolean(isForceDeleteStorage));
  
          if (answer == null) {
- 			throw new CloudRuntimeException(
- 					"No resource adapter respond to DELETE_HOST event for "
- 							+ host.getName() + " id = " + hostId
- 							+ ", hypervisorType is " + host.getHypervisorType()
- 							+ ", host type is " + host.getType());
+             throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId
+                     + ", hypervisorType is " + host.getHypervisorType() + ", host type is " + host.getType());
          }
  
          if (answer.getIsException()) {
@@@ -1082,37 -987,29 +991,29 @@@
              List<HostVO> hosts = listAllHostsInCluster(cmd.getId());
              if (hosts.size() > 0) {
                  if (s_logger.isDebugEnabled()) {
- 					s_logger.debug("Cluster: " + cmd.getId()
- 							+ " still has hosts, can't remove");
+                     s_logger.debug("Cluster: " + cmd.getId() + " still has hosts, can't remove");
                  }
                  txn.rollback();
- 				throw new CloudRuntimeException("Cluster: " + cmd.getId()
- 						+ " cannot be removed. Cluster still has hosts");
+                 throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has hosts");
              }
  
 -            // don't allow to remove the cluster if it has non-removed storage
 -            // pools
 +			// don't allow to remove the cluster if it has non-removed storage
 +			// pools
- 			List<StoragePoolVO> storagePools = _storagePoolDao
- 					.listPoolsByCluster(cmd.getId());
+             List<StoragePoolVO> storagePools = _storagePoolDao.listPoolsByCluster(cmd.getId());
              if (storagePools.size() > 0) {
                  if (s_logger.isDebugEnabled()) {
- 					s_logger.debug("Cluster: " + cmd.getId()
- 							+ " still has storage pools, can't remove");
+                     s_logger.debug("Cluster: " + cmd.getId() + " still has storage pools, can't remove");
                  }
                  txn.rollback();
- 				throw new CloudRuntimeException("Cluster: " + cmd.getId()
- 						+ " cannot be removed. Cluster still has storage pools");
+                 throw new CloudRuntimeException("Cluster: " + cmd.getId() + " cannot be removed. Cluster still has storage pools");
              }
  
 -            if (_clusterDao.remove(cmd.getId())) {
 +			if (_clusterDao.remove(cmd.getId())) {
                  _capacityDao.removeBy(null, null, null, cluster.getId(), null);
 -                // If this cluster is of type vmware, and if the nexus vswitch
 -                // global parameter setting is turned
 +				// If this cluster is of type vmware, and if the nexus vswitch
 +				// global parameter setting is turned
                  // on, remove the row in cluster_vsm_map for this cluster id.
- 				if (hypervisorType == HypervisorType.VMware
- 						&& Boolean.parseBoolean(_configDao
- 								.getValue(Config.VmwareUseNexusVSwitch
- 										.toString()))) {
+                 if (hypervisorType == HypervisorType.VMware && Boolean.parseBoolean(_configDao.getValue(Config.VmwareUseNexusVSwitch.toString()))) {
                      _clusterVSMMapDao.removeByClusterId(cmd.getId());
                  }
  				// remove from dedicated resources
@@@ -1255,21 -1133,13 +1137,13 @@@
                      cluster.setManagedState(Managed.ManagedState.PrepareUnmanaged);
                      _clusterDao.update(cluster.getId(), cluster);
                      txn.commit();
- 					List<HostVO> hosts = listAllUpAndEnabledHosts(
- 							Host.Type.Routing, cluster.getId(),
- 							cluster.getPodId(), cluster.getDataCenterId());
+                     List<HostVO> hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId());
 -                    for (HostVO host : hosts) {
 +					for (HostVO host : hosts) {
- 						if (host.getType().equals(Host.Type.Routing)
- 								&& !host.getStatus().equals(Status.Down)
- 								&& !host.getStatus()
- 										.equals(Status.Disconnected)
- 								&& !host.getStatus().equals(Status.Up)
+                         if (host.getType().equals(Host.Type.Routing) && !host.getStatus().equals(Status.Down)
+                                 && !host.getStatus().equals(Status.Disconnected) && !host.getStatus().equals(Status.Up)
 -                                && !host.getStatus().equals(Status.Alert)) {
 +								&& !host.getStatus().equals(Status.Alert)) {
- 							String msg = "host " + host.getPrivateIpAddress()
- 									+ " should not be in "
- 									+ host.getStatus().toString() + " status";
- 							throw new CloudRuntimeException(
- 									"PrepareUnmanaged Failed due to " + msg);
+                             String msg = "host " + host.getPrivateIpAddress() + " should not be in " + host.getStatus().toString() + " status";
+                             throw new CloudRuntimeException("PrepareUnmanaged Failed due to " + msg);
                          }
                      }
  
@@@ -1286,13 -1156,9 +1160,9 @@@
                              Thread.sleep(5 * 1000);
                          } catch (Exception e) {
                          }
- 						hosts = listAllUpAndEnabledHosts(Host.Type.Routing,
- 								cluster.getId(), cluster.getPodId(),
- 								cluster.getDataCenterId());
+                         hosts = listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), cluster.getPodId(), cluster.getDataCenterId());
 -                        for (HostVO host : hosts) {
 +						for (HostVO host : hosts) {
- 							if (!host.getStatus().equals(Status.Down)
- 									&& !host.getStatus().equals(
- 											Status.Disconnected)
+                             if (!host.getStatus().equals(Status.Down) && !host.getStatus().equals(Status.Disconnected)
                                      && !host.getStatus().equals(Status.Alert)) {
                                  lsuccess = false;
                                  break;
@@@ -1368,27 -1227,20 +1231,20 @@@
          ResourceState currentState = host.getResourceState();
          ResourceState nextState = currentState.getNextState(event);
          if (nextState == null) {
- 			throw new NoTransitionException(
- 					"No next resource state found for current state ="
- 							+ currentState + " event =" + event);
+             throw new NoTransitionException("No next resource state found for current state =" + currentState + " event =" + event);
          }
  
 -        // TO DO - Make it more granular and have better conversion into
 -        // capacity type
 +		// TO DO - Make it more granular and have better conversion into
 +		// capacity type
  
 -        if (host.getType() == Type.Routing && host.getClusterId() != null) {
 +		if (host.getType() == Type.Routing && host.getClusterId() != null) {
- 			AllocationState capacityState = _configMgr
- 					.findClusterAllocationState(ApiDBUtils.findClusterById(host
- 							.getClusterId()));
- 			if (capacityState == AllocationState.Enabled
- 					&& nextState != ResourceState.Enabled) {
+             AllocationState capacityState = _configMgr.findClusterAllocationState(ApiDBUtils.findClusterById(host.getClusterId()));
+             if (capacityState == AllocationState.Enabled && nextState != ResourceState.Enabled) {
                  capacityState = AllocationState.Disabled;
              }
- 			_capacityDao.updateCapacityState(null, null, null, host.getId(),
- 					capacityState.toString());
+             _capacityDao.updateCapacityState(null, null, null, host.getId(), capacityState.toString());
          }
- 		return _hostDao.updateResourceState(currentState, event, nextState,
- 				host);
+         return _hostDao.updateResourceState(currentState, event, nextState, host);
      }
  
      private boolean doMaintain(final long hostId) {
@@@ -1453,17 -1299,12 +1303,12 @@@
  
          if (host == null) {
              s_logger.debug("Unable to find host " + hostId);
- 			throw new InvalidParameterValueException(
- 					"Unable to find host with ID: " + hostId
- 							+ ". Please specify a valid host ID.");
+             throw new InvalidParameterValueException("Unable to find host with ID: " + hostId + ". Please specify a valid host ID.");
          }
  
- 		if (_hostDao.countBy(host.getClusterId(),
- 				ResourceState.PrepareForMaintenance,
- 				ResourceState.ErrorInMaintenance) > 0) {
- 			throw new InvalidParameterValueException(
- 					"There are other servers in PrepareForMaintenance OR ErrorInMaintenance STATUS in cluster "
+         if (_hostDao.countBy(host.getClusterId(), ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance) > 0) {
+             throw new InvalidParameterValueException("There are other servers in PrepareForMaintenance OR ErrorInMaintenance STATUS in cluster "
 -                    + host.getClusterId());
 +							+ host.getClusterId());
          }
  
          if (_storageMgr.isLocalStorageActiveOnHost(host.getId())) {
@@@ -2016,15 -1799,9 +1803,9 @@@
                  }
              }
  
- 			host = createHostVO(
- 					cmds,
- 					resource,
- 					details,
- 					hostTags,
- 					ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT);
+             host = createHostVO(cmds, resource, details, hostTags, ResourceStateAdapter.Event.CREATE_HOST_VO_FOR_DIRECT_CONNECT);
              if (host != null) {
-                 attache = _attacheHandler.handleDirectConnectAgent(host, cmds,
- 						resource, forRebalance);
 -                attache = _agentMgr.handleDirectConnectAgent(host, cmds, resource, forRebalance);
++                attache = _attacheHandler.handleDirectConnectAgent(host, cmds, resource, forRebalance);
                  /* reload myself from database */
                  host = _hostDao.findById(host.getId());
              }
@@@ -2107,8 -1908,10 +1912,10 @@@
              }
  
              if (host != null) {
-                 if (!deferAgentCreation) { // if first host in cluster then create agent otherwise defer it to scan task
+                 if (!deferAgentCreation) { // if first host in cluster then
+                                            // create agent otherwise defer it to
+                                            // scan task
 -                    attache = _agentMgr.handleDirectConnectAgent(host, cmds, resource, forRebalance);
 +                    attache = _attacheHandler.handleDirectConnectAgent(host, cmds, resource, forRebalance);
                      host = _hostDao.findById(host.getId()); // reload
                  } else {
                      host = _hostDao.findById(host.getId()); // reload
@@@ -2156,12 -1960,10 +1964,10 @@@
      }
  
      @Override
- 	public Host createHostAndAgent(Long hostId, ServerResource resource,
- 			Map<String, String> details, boolean old, List<String> hostTags,
+     public Host createHostAndAgent(Long hostId, ServerResource resource, Map<String, String> details, boolean old, List<String> hostTags,
 -            boolean forRebalance) {
 +			boolean forRebalance) {
          _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Add);
- 		Host host = createHostAndAgent(resource, details, old, hostTags,
- 				forRebalance);
+         Host host = createHostAndAgent(resource, details, old, hostTags, forRebalance);
          _agentMgr.tapLoadingAgents(hostId, TapAgentsAction.Del);
          return host;
      }
@@@ -2177,7 -1977,7 +1981,7 @@@
  
          Map<String, String> details = hostDetails;
          String guid = details.get("guid");
- 		List<HostVO> currentHosts = listAllUpAndEnabledHostsInOneZoneByType(hostType, zoneId);
 -        List<HostVO> currentHosts = this.listAllUpAndEnabledHostsInOneZoneByType(hostType, zoneId);
++        List<HostVO> currentHosts = listAllUpAndEnabledHostsInOneZoneByType(hostType, zoneId);
          for (HostVO currentHost : currentHosts) {
              if (currentHost.getGuid().equals(guid)) {
                  return currentHost;
@@@ -2200,23 -1998,16 +2002,16 @@@
          // a host-only private network. Don't check for conflicts with the
          // private IP address table.
          if (serverPrivateIP != serverPublicIP) {
- 			if (!_privateIPAddressDao.mark(dc.getId(), pod.getId(),
- 					serverPrivateIP)) {
+             if (!_privateIPAddressDao.mark(dc.getId(), pod.getId(), serverPrivateIP)) {
                  // If the server's private IP address is already in the
                  // database, return false
- 				List<DataCenterIpAddressVO> existingPrivateIPs = _privateIPAddressDao
- 						.listByPodIdDcIdIpAddress(pod.getId(), dc.getId(),
+                 List<DataCenterIpAddressVO> existingPrivateIPs = _privateIPAddressDao.listByPodIdDcIdIpAddress(pod.getId(), dc.getId(),
 -                        serverPrivateIP);
 +								serverPrivateIP);
  
- 				assert existingPrivateIPs.size() <= 1 : " How can we get more than one ip address with "
- 						+ serverPrivateIP;
+                 assert existingPrivateIPs.size() <= 1 : " How can we get more than one ip address with " + serverPrivateIP;
                  if (existingPrivateIPs.size() > 1) {
- 					throw new IllegalArgumentException(
- 							"The private ip address of the server ("
- 									+ serverPrivateIP
- 									+ ") is already in use in pod: "
- 									+ pod.getName() + " and zone: "
- 									+ dc.getName());
+                     throw new IllegalArgumentException("The private ip address of the server (" + serverPrivateIP + ") is already in use in pod: "
+                             + pod.getName() + " and zone: " + dc.getName());
                  }
                  if (existingPrivateIPs.size() == 1) {
                      DataCenterIpAddressVO vo = existingPrivateIPs.get(0);
@@@ -2232,33 -2019,23 +2023,23 @@@
              }
          }
  
- 		if (serverPublicIP != null
- 				&& !_publicIPAddressDao
- 						.mark(dc.getId(), new Ip(serverPublicIP))) {
+         if (serverPublicIP != null && !_publicIPAddressDao.mark(dc.getId(), new Ip(serverPublicIP))) {
              // If the server's public IP address is already in the database,
              // return false
- 			List<IPAddressVO> existingPublicIPs = _publicIPAddressDao
- 					.listByDcIdIpAddress(dc.getId(), serverPublicIP);
+             List<IPAddressVO> existingPublicIPs = _publicIPAddressDao.listByDcIdIpAddress(dc.getId(), serverPublicIP);
              if (existingPublicIPs.size() > 0) {
- 				throw new IllegalArgumentException(
- 						"The public ip address of the server ("
- 								+ serverPublicIP
- 								+ ") is already in use in zone: "
+                 throw new IllegalArgumentException("The public ip address of the server (" + serverPublicIP + ") is already in use in zone: "
 -                        + dc.getName());
 +								+ dc.getName());
              }
          }
      }
  
      @Override
- 	public HostVO fillRoutingHostVO(HostVO host, StartupRoutingCommand ssCmd,
- 			HypervisorType hyType, Map<String, String> details,
+     public HostVO fillRoutingHostVO(HostVO host, StartupRoutingCommand ssCmd, HypervisorType hyType, Map<String, String> details,
 -            List<String> hostTags) {
 +			List<String> hostTags) {
          if (host.getPodId() == null) {
- 			s_logger.error("Host " + ssCmd.getPrivateIpAddress()
- 					+ " sent incorrect pod, pod id is null");
- 			throw new IllegalArgumentException("Host "
- 					+ ssCmd.getPrivateIpAddress()
- 					+ " sent incorrect pod, pod id is null");
+             s_logger.error("Host " + ssCmd.getPrivateIpAddress() + " sent incorrect pod, pod id is null");
+             throw new IllegalArgumentException("Host " + ssCmd.getPrivateIpAddress() + " sent incorrect pod, pod id is null");
          }
  
          ClusterVO clusterVO = _clusterDao.findById(host.getClusterId());
@@@ -2305,49 -2074,35 +2078,35 @@@
          }
  
          if (s_logger.isDebugEnabled()) {
- 			s_logger.debug("Deleting Host: " + host.getId() + " Guid:"
- 					+ host.getGuid());
+             s_logger.debug("Deleting Host: " + host.getId() + " Guid:" + host.getGuid());
          }
  
- 		User caller = _accountMgr.getActiveUser(CallContext.current()
- 				.getCallingUserId());
 -        User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
++        User caller = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
  
 -        if (forceDestroyStorage) {
 -            // put local storage into mainenance mode, will set all the VMs on
 -            // this local storage into stopped state
 +		if (forceDestroyStorage) {
 +			// put local storage into mainenance mode, will set all the VMs on
 +			// this local storage into stopped state
- 		    StoragePoolVO storagePool = _storageMgr.findLocalStorageOnHost(host
- 					.getId());
+             StoragePoolVO storagePool = _storageMgr.findLocalStorageOnHost(host.getId());
              if (storagePool != null) {
- 				if (storagePool.getStatus() == StoragePoolStatus.Up
- 						|| storagePool.getStatus() == StoragePoolStatus.ErrorInMaintenance) {
+                 if (storagePool.getStatus() == StoragePoolStatus.Up || storagePool.getStatus() == StoragePoolStatus.ErrorInMaintenance) {
 -                    try {
 +					try {
- 						StoragePool pool = _storageSvr
- 								.preparePrimaryStorageForMaintenance(storagePool
- 										.getId());
+                         StoragePool pool = _storageSvr.preparePrimaryStorageForMaintenance(storagePool.getId());
 -                        if (pool == null) {
 -                            s_logger.debug("Failed to set primary storage into maintenance mode");
 +						if (pool == null) {
 +							s_logger.debug("Failed to set primary storage into maintenance mode");
  
- 							throw new UnableDeleteHostException(
- 									"Failed to set primary storage into maintenance mode");
+                             throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode");
                          }
                      } catch (Exception e) {
- 						s_logger.debug("Failed to set primary storage into maintenance mode, due to: "
- 								+ e.toString());
- 						throw new UnableDeleteHostException(
- 								"Failed to set primary storage into maintenance mode, due to: "
- 										+ e.toString());
+                         s_logger.debug("Failed to set primary storage into maintenance mode, due to: " + e.toString());
+                         throw new UnableDeleteHostException("Failed to set primary storage into maintenance mode, due to: " + e.toString());
                      }
                  }
  
- 				List<VMInstanceVO> vmsOnLocalStorage = _storageMgr
- 						.listByStoragePool(storagePool.getId());
+                 List<VMInstanceVO> vmsOnLocalStorage = _storageMgr.listByStoragePool(storagePool.getId());
                  for (VMInstanceVO vm : vmsOnLocalStorage) {
                      try {
 -                        if (!_vmMgr.destroy(vm, caller, _accountMgr.getAccount(vm.getAccountId()))) {
 +                        if (!_vmMgr.destroy(vm.getUuid())) {
- 							String errorMsg = "There was an error Destory the vm: "
- 									+ vm
- 									+ " as a part of hostDelete id="
- 									+ host.getId();
+                             String errorMsg = "There was an error Destory the vm: " + vm + " as a part of hostDelete id=" + host.getId();
                              s_logger.warn(errorMsg);
                              throw new UnableDeleteHostException(errorMsg);
                          }
@@@ -2369,28 -2121,21 +2125,17 @@@
                      // Stop HA disabled vms and HA enabled vms in Stopping state
                      // Restart HA enabled vms
                      for (VMInstanceVO vm : vms) {
- 						if (!vm.isHaEnabled()
- 								|| vm.getState() == State.Stopping) {
- 							s_logger.debug("Stopping vm: " + vm
- 									+ " as a part of deleteHost id="
- 									+ host.getId());
+                         if (!vm.isHaEnabled() || vm.getState() == State.Stopping) {
+                             s_logger.debug("Stopping vm: " + vm + " as a part of deleteHost id=" + host.getId());
                              try {
 -                                if (!_vmMgr.advanceStop(vm, true, caller, _accountMgr.getAccount(vm.getAccountId()))) {
 -                                    String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId();
 -                                    s_logger.warn(errorMsg);
 -                                    throw new UnableDeleteHostException(errorMsg);
 -                                }
 +                                _vmMgr.easyStop(vm.getUuid());
                              } catch (Exception e) {
- 								String errorMsg = "There was an error stopping the vm: "
- 										+ vm
- 										+ " as a part of hostDelete id="
- 										+ host.getId();
+                                 String errorMsg = "There was an error stopping the vm: " + vm + " as a part of hostDelete id=" + host.getId();
                                  s_logger.debug(errorMsg, e);
- 								throw new UnableDeleteHostException(errorMsg
- 										+ "," + e.getMessage());
- 							}
- 						} else if (vm.isHaEnabled()
- 								&& (vm.getState() == State.Running || vm
- 										.getState() == State.Starting)) {
- 							s_logger.debug("Scheduling restart for vm: " + vm
- 									+ " " + vm.getState() + " on the host id="
- 									+ host.getId());
+                                 throw new UnableDeleteHostException(errorMsg + "," + e.getMessage());
+                             }
+                         } else if (vm.isHaEnabled() && (vm.getState() == State.Running || vm.getState() == State.Starting)) {
+                             s_logger.debug("Scheduling restart for vm: " + vm + " " + vm.getState() + " on the host id=" + host.getId());
                              _haMgr.scheduleRestart(vm, false);
                          }
                      }
@@@ -2412,19 -2155,17 +2155,17 @@@
              return true;
          }
  
 -        /*
 -         * TODO: think twice about returning true or throwing out exception, I
 -         * really prefer to exception that always exposes bugs
 -         */
 +		/*
 +		 * TODO: think twice about returning true or throwing out exception, I
 +		 * really prefer to exception that always exposes bugs
 +		 */
- 		if (host.getResourceState() != ResourceState.PrepareForMaintenance
- 				&& host.getResourceState() != ResourceState.Maintenance
+         if (host.getResourceState() != ResourceState.PrepareForMaintenance && host.getResourceState() != ResourceState.Maintenance
 -                && host.getResourceState() != ResourceState.ErrorInMaintenance) {
 +				&& host.getResourceState() != ResourceState.ErrorInMaintenance) {
- 			throw new CloudRuntimeException(
- 					"Cannot perform cancelMaintenance when resource state is "
- 							+ host.getResourceState() + ", hostId = " + hostId);
+             throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = "
+                     + hostId);
          }
  
 -        /* TODO: move to listener */
 +		/* TODO: move to listener */
          _haMgr.cancelScheduledMigrations(host);
          List<VMInstanceVO> vms = _haMgr.findTakenMigrationWork();
          for (VMInstanceVO vm : vms) {
@@@ -2436,11 -2176,10 +2176,10 @@@
          }
  
          try {
- 			resourceStateTransitTo(host,
- 					ResourceState.Event.AdminCancelMaintenance, _nodeId);
+             resourceStateTransitTo(host, ResourceState.Event.AdminCancelMaintenance, _nodeId);
              _agentMgr.pullAgentOutMaintenance(hostId);
  
 -            // for kvm, need to log into kvm host, restart cloudstack-agent
 +			// for kvm, need to log into kvm host, restart cloudstack-agent
              if (host.getHypervisorType() == HypervisorType.KVM) {
                  _hostDao.loadDetails(host);
                  String password = host.getDetail("password");
@@@ -2577,15 -2300,14 +2300,14 @@@
              return doUpdateHostPassword(cmd.getHostId());
          } else {
              // get agents for the cluster
 -            List<HostVO> hosts = this.listAllHostsInCluster(cmd.getClusterId());
 +            List<HostVO> hosts = listAllHostsInCluster(cmd.getClusterId());
              for (HostVO h : hosts) {
                  try {
 -                    /*
 -                     * FIXME: this is a buggy logic, check with alex. Shouldn't
 -                     * return if propagation return non null
 -                     */
 +					/*
 +					 * FIXME: this is a buggy logic, check with alex. Shouldn't
 +					 * return if propagation return non null
 +					 */
- 					Boolean result = _clusterMgr.propagateResourceEvent(
- 							h.getId(), ResourceState.Event.UpdatePassword);
+                     Boolean result = _clusterMgr.propagateResourceEvent(h.getId(), ResourceState.Event.UpdatePassword);
                      if (result != null) {
                          return result;
                      }
@@@ -2702,17 -2407,14 +2407,14 @@@
      }
  
      @Override
- 	public List<HostVO> listAllNotInMaintenanceHostsInOneZone(Type type,
- 			Long dcId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2
- 				.create(HostVO.class);
+     public List<HostVO> listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId) {
+         SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
 -        if (dcId != null) {
 +		if (dcId != null) {
              sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId);
          }
          sc.addAnd(sc.getEntity().getType(), Op.EQ, type);
- 		sc.addAnd(sc.getEntity().getResourceState(), Op.NIN,
- 				ResourceState.Maintenance, ResourceState.ErrorInMaintenance,
+         sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance,
 -                ResourceState.PrepareForMaintenance, ResourceState.Error);
 +				ResourceState.PrepareForMaintenance, ResourceState.Error);
          return sc.list();
      }
  
@@@ -2779,12 -2474,10 +2474,10 @@@
      }
  
      @Override
- 	public Pair<HostPodVO, Long> findPod(VirtualMachineTemplate template,
- 			ServiceOfferingVO offering, DataCenterVO dc, long accountId,
+     public Pair<HostPodVO, Long> findPod(VirtualMachineTemplate template, ServiceOfferingVO offering, DataCenterVO dc, long accountId,
 -            Set<Long> avoids) {
 -        for (PodAllocator allocator : _podAllocators) {
 +			Set<Long> avoids) {
 +		for (PodAllocator allocator : _podAllocators) {
- 			final Pair<HostPodVO, Long> pod = allocator.allocateTo(template,
- 					offering, dc, accountId, avoids);
+             final Pair<HostPodVO, Long> pod = allocator.allocateTo(template, offering, dc, accountId, avoids);
              if (pod != null) {
                  return pod;
              }
@@@ -2860,11 -2551,9 +2551,9 @@@
          return pcs;
      }
  
 -    @Override
 +	@Override
- 	public List<HostVO> listAllUpAndEnabledHostsInOneZoneByHypervisor(
- 			HypervisorType type, long dcId) {
- 		SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2
- 				.create(HostVO.class);
+     public List<HostVO> listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType type, long dcId) {
+         SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
          sc.addAnd(sc.getEntity().getHypervisorType(), Op.EQ, type);
          sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId);
          sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
index d0a4797,b5c060d..9cfb84b
--- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
+++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java
@@@ -29,12 -29,12 +29,14 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
- import org.apache.cloudstack.acl.SecurityChecker.AccessType;
- import org.apache.cloudstack.context.CallContext;
- 
 +import org.apache.log4j.Logger;
 +import org.springframework.stereotype.Component;
 +
+ import org.apache.cloudstack.acl.SecurityChecker.AccessType;
++import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
+ 
  import com.cloud.alert.AlertManager;
  import com.cloud.configuration.Config;
  import com.cloud.configuration.Resource;
@@@ -65,12 -66,12 +67,10 @@@ import com.cloud.projects.dao.ProjectAc
  import com.cloud.projects.dao.ProjectDao;
  import com.cloud.service.ServiceOfferingVO;
  import com.cloud.service.dao.ServiceOfferingDao;
--import com.cloud.storage.VMTemplateHostVO;
  import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
  import com.cloud.storage.VMTemplateVO;
  import com.cloud.storage.dao.SnapshotDao;
  import com.cloud.storage.dao.VMTemplateDao;
--import com.cloud.storage.dao.VMTemplateHostDao;
  import com.cloud.storage.dao.VolumeDao;
  import com.cloud.storage.dao.VolumeDaoImpl.SumCount;
  import com.cloud.user.Account;


[03/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-1999: Fix cloud/cloudstack due to new packaging


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

Branch: refs/heads/vmsync
Commit: 2e06da552c9561c0ec8612d47b39e66b78bf1cb3
Parents: 5bfae23
Author: Sebastien Goasguen <ru...@gmail.com>
Authored: Wed Apr 17 12:24:52 2013 -0400
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 13:48:26 2013 -0500

----------------------------------------------------------------------
 docs/en-US/about-password-encryption.xml             | 2 +-
 docs/en-US/management-server-install-db-external.xml | 2 +-
 docs/en-US/management-server-install-db-local.xml    | 4 ++--
 docs/en-US/management-server-install-multi-node.xml  | 4 ++--
 docs/en-US/region-add.xml                            | 6 +++---
 5 files changed, 9 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e06da55/docs/en-US/about-password-encryption.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/about-password-encryption.xml b/docs/en-US/about-password-encryption.xml
index 6c11c57..a13ff60 100644
--- a/docs/en-US/about-password-encryption.xml
+++ b/docs/en-US/about-password-encryption.xml
@@ -60,6 +60,6 @@
     over a known port.</para>
   <para>The encryption type, database secret key, and Management Server secret key are set during
     &PRODUCT; installation. They are all parameters to the &PRODUCT; database setup script
-    (cloud-setup-databases). The default values are file, password, and password. It is, of course,
+    (cloudstack-setup-databases). The default values are file, password, and password. It is, of course,
     highly recommended that you change these to more secure keys.</para>
 </section>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e06da55/docs/en-US/management-server-install-db-external.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/management-server-install-db-external.xml b/docs/en-US/management-server-install-db-external.xml
index a28dee5..2950720 100644
--- a/docs/en-US/management-server-install-db-external.xml
+++ b/docs/en-US/management-server-install-db-external.xml
@@ -132,7 +132,7 @@ bind-address = 0.0.0.0</programlisting>
              server node IP. If not specified, the local IP address will be used.</para>
         </listitem>
       </itemizedlist>
-      <programlisting language="Bash">cloud-setup-databases cloud:&lt;dbpassword&gt;@&lt;ip address mysql server&gt; \
+      <programlisting language="Bash">cloudstack-setup-databases cloud:&lt;dbpassword&gt;@&lt;ip address mysql server&gt; \
 --deploy-as=root:&lt;password&gt; \
 -e &lt;encryption_type&gt; \
 -m &lt;management_server_key&gt; \

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e06da55/docs/en-US/management-server-install-db-local.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/management-server-install-db-local.xml b/docs/en-US/management-server-install-db-local.xml
index 310327f..ff5ab60 100644
--- a/docs/en-US/management-server-install-db-local.xml
+++ b/docs/en-US/management-server-install-db-local.xml
@@ -135,7 +135,7 @@ binlog-format = 'ROW'</programlisting>
             server node IP. If not specified, the local IP address will be used.</para>
         </listitem>
       </itemizedlist>
-      <programlisting language="Bash">cloud-setup-databases cloud:&lt;dbpassword&gt;@localhost \
+      <programlisting language="Bash">cloudstack-setup-databases cloud:&lt;dbpassword&gt;@localhost \
 --deploy-as=root:&lt;password&gt; \
 -e &lt;encryption_type&gt; \
 -m &lt;management_server_key&gt; \
@@ -160,7 +160,7 @@ binlog-format = 'ROW'</programlisting>
     <listitem>
       <para>Now that the database is set up, you can finish configuring the OS for the Management
         Server. This command will set up iptables, sudoers, and start the Management Server.</para>
-      <programlisting><prompt>#</prompt> cloud-setup-management</programlisting>
+      <programlisting><prompt>#</prompt> cloudstack-setup-management</programlisting>
       <para>You should see the message “&PRODUCT; Management Server setup is done.”</para>
     </listitem>
   </orderedlist>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e06da55/docs/en-US/management-server-install-multi-node.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/management-server-install-multi-node.xml b/docs/en-US/management-server-install-multi-node.xml
index 21cf28f..ae925bf 100644
--- a/docs/en-US/management-server-install-multi-node.xml
+++ b/docs/en-US/management-server-install-multi-node.xml
@@ -53,12 +53,12 @@ linkend="sect-source-buildrpm"/> or <xref linkend="sect-source-builddebs"/> as
       <para>Configure the database client. Note the absence of the --deploy-as argument in this
         case. (For more details about the arguments to this command, see <xref
           linkend="management-server-install-db-external"/>.) </para>
-      <programlisting><prompt>#</prompt> cloud-setup-databases cloud:<replaceable>dbpassword</replaceable>@<replaceable>dbhost</replaceable> -e <replaceable>encryption_type</replaceable> -m <replaceable>management_server_key</replaceable> -k <replaceable>database_key</replaceable> -i <replaceable>management_server_ip</replaceable>
+      <programlisting><prompt>#</prompt> cloudstack-setup-databases cloud:<replaceable>dbpassword</replaceable>@<replaceable>dbhost</replaceable> -e <replaceable>encryption_type</replaceable> -m <replaceable>management_server_key</replaceable> -k <replaceable>database_key</replaceable> -i <replaceable>management_server_ip</replaceable>
       </programlisting>
     </listitem>
     <listitem>
       <para>Configure the OS and start the Management Server:</para>
-      <programlisting><prompt>#</prompt> cloud-setup-management</programlisting>
+      <programlisting><prompt>#</prompt> cloudstack-setup-management</programlisting>
       <para>The Management Server on this node should now be running.</para>
     </listitem>
     <listitem>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2e06da55/docs/en-US/region-add.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/region-add.xml b/docs/en-US/region-add.xml
index 960777c..802e462 100644
--- a/docs/en-US/region-add.xml
+++ b/docs/en-US/region-add.xml
@@ -45,7 +45,7 @@
                     the additional command-line flag <code>-r &lt;region_id&gt;</code> to set a
                     region ID for the new region. The default region is automatically assigned a
                     region ID of 1, so your first additional region might be region 2.</para>
-      <programlisting>cloud-setup-databases cloud:&lt;dbpassword&gt;@localhost --deploy-as=root:&lt;password&gt; -e &lt;encryption_type&gt; -m &lt;management_server_key&gt; -k &lt;database_key&gt; -r &lt;region_id&gt;</programlisting>
+      <programlisting>cloudstack-setup-databases cloud:&lt;dbpassword&gt;@localhost --deploy-as=root:&lt;password&gt; -e &lt;encryption_type&gt; -m &lt;management_server_key&gt; -k &lt;database_key&gt; -r &lt;region_id&gt;</programlisting>
       </listitem>
       <listitem><para>By the end of the installation procedure, the Management Server should have been started. Be sure that the Management Server installation was successful and complete.</para></listitem>
       <listitem><para>Add region 2 to region 1. Use the API command addRegion. (For information about how to make an API call, see the Developer's Guide.)</para>
@@ -82,7 +82,7 @@
             However, you must repeat certain steps additional times for each additional region:</para>
         <orderedlist>
             <listitem><para>Install &PRODUCT; in each additional region. Set the region ID for each region during the database setup step.</para>
-                <programlisting>cloud-setup-databases cloud:&lt;dbpassword&gt;@localhost --deploy-as=root:&lt;password&gt; -e &lt;encryption_type&gt; -m &lt;management_server_key&gt; -k &lt;database_key&gt; -r &lt;region_id&gt;</programlisting></listitem>
+                <programlisting>cloudstack-setup-databases cloud:&lt;dbpassword&gt;@localhost --deploy-as=root:&lt;password&gt; -e &lt;encryption_type&gt; -m &lt;management_server_key&gt; -k &lt;database_key&gt; -r &lt;region_id&gt;</programlisting></listitem>
             <listitem><para>Once the Management Server is running, add your new region to all existing regions by
                     repeatedly calling the API command addRegion. For example, if you were adding
                     region 3:</para>
@@ -125,4 +125,4 @@ http://&lt;IP_of_region_3_Management_Server&gt;:8080/client/api?command=addRegio
 
 http://&lt;IP_of_region_2_Management_Server&gt;:8080/client/api?command=removeRegion&amp;id=3&amp;apiKey=miVr6X7u6bN_sdahOBpjNejPgEsT35eXq-jB8CG20YI3yaxXcgpyuaIRmFI_EJTVwZ0nUkkJbPmY3y2bciKwFQ&amp;signature=Lxx1DM40AjcXU%2FcaiK8RAP0O1hU%3D</programlisting>
     </section>
-</section>
\ No newline at end of file
+</section>


[15/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cloudstack


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

Branch: refs/heads/vmsync
Commit: 390022c4eaa1d7c6de9e89006f56defc0eb0ebd2
Parents: 3c88dd4 7c46cc9
Author: Sateesh Chodapuneedi <sa...@apache.org>
Authored: Mon Jun 24 11:07:25 2013 +0530
Committer: Sateesh Chodapuneedi <sa...@apache.org>
Committed: Mon Jun 24 11:07:25 2013 +0530

----------------------------------------------------------------------
 server/src/com/cloud/network/NetworkServiceImpl.java | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
----------------------------------------------------------------------



[29/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3084: Added check to disallow -ve number for ACL rule


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

Branch: refs/heads/vmsync
Commit: bd5ad442d0f82467cf10fea409511a5dea0a5704
Parents: 390022c
Author: Kishan Kavala <ki...@cloud.com>
Authored: Mon Jun 24 17:13:52 2013 +0530
Committer: Kishan Kavala <ki...@cloud.com>
Committed: Mon Jun 24 17:20:29 2013 +0530

----------------------------------------------------------------------
 .../src/com/cloud/network/vpc/NetworkACLServiceImpl.java | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bd5ad442/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
index b0c807e..4c97869 100644
--- a/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
+++ b/server/src/com/cloud/network/vpc/NetworkACLServiceImpl.java
@@ -308,7 +308,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
         }
 
         validateNetworkACLItem(aclItemCmd.getSourcePortStart(), aclItemCmd.getSourcePortEnd(), aclItemCmd.getSourceCidrList(),
-                aclItemCmd.getProtocol(), aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getAction());
+                aclItemCmd.getProtocol(), aclItemCmd.getIcmpCode(), aclItemCmd.getIcmpType(), aclItemCmd.getAction(), aclItemCmd.getNumber());
 
         return _networkAclMgr.createNetworkACLItem(aclItemCmd.getSourcePortStart(),
                 aclItemCmd.getSourcePortEnd(), aclItemCmd.getProtocol(), aclItemCmd.getSourceCidrList(), aclItemCmd.getIcmpCode(),
@@ -316,7 +316,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
     }
 
     private void validateNetworkACLItem(Integer portStart, Integer portEnd, List<String> sourceCidrList, String protocol, Integer icmpCode,
-                                        Integer icmpType, String action) {
+                                        Integer icmpType, String action, Integer number) {
 
         if (portStart != null && !NetUtils.isValidPort(portStart)) {
             throw new InvalidParameterValueException("publicPort is an invalid value: " + portStart);
@@ -388,6 +388,11 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
                 throw new InvalidParameterValueException("Invalid action. Allowed actions are Allow and Deny");
             }
         }
+
+        //Check for valid number
+        if(number != null && number < 1){
+            throw new InvalidParameterValueException("Invalid number. Number cannot be < 1");
+        }
     }
 
     @Override
@@ -526,7 +531,7 @@ public class NetworkACLServiceImpl extends ManagerBase implements NetworkACLServ
         }
 
         validateNetworkACLItem((sourcePortStart == null) ? aclItem.getSourcePortStart() : sourcePortStart, (sourcePortEnd == null) ? aclItem.getSourcePortEnd() : sourcePortEnd,
-                sourceCidrList, protocol, icmpCode, (icmpType == null) ? aclItem.getIcmpType() : icmpType, action);
+                sourceCidrList, protocol, icmpCode, (icmpType == null) ? aclItem.getIcmpType() : icmpType, action, number);
 
         return _networkAclMgr.updateNetworkACLItem(id, protocol, sourceCidrList, trafficType, action, number, sourcePortStart,
                 sourcePortEnd, icmpCode, icmpType);


[30/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3124: Deletion of ACL associated with a tier/ pvt gateway should not be allowed. Check for associated tiers/gateways before deletion


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

Branch: refs/heads/vmsync
Commit: da0006618f5bd33cea1e51e65208ade2ebcfaf7b
Parents: e9df9c2
Author: Kishan Kavala <ki...@cloud.com>
Authored: Mon Jun 24 17:53:15 2013 +0530
Committer: Kishan Kavala <ki...@cloud.com>
Committed: Mon Jun 24 17:58:29 2013 +0530

----------------------------------------------------------------------
 .../src/com/cloud/network/vpc/dao/VpcGatewayDao.java    |  2 ++
 .../com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java    |  8 ++++++++
 .../com/cloud/network/vpc/NetworkACLManagerImpl.java    | 12 ++++++++++++
 3 files changed, 22 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/da000661/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDao.java b/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDao.java
index 24d9deb..42144b6 100644
--- a/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDao.java
+++ b/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDao.java
@@ -30,4 +30,6 @@ public interface VpcGatewayDao extends GenericDao<VpcGatewayVO, Long>{
     Long getNetworkAclIdForPrivateIp(long vpcId, long networkId, String ipaddr);
 
     List<VpcGatewayVO> listByVpcIdAndType(long vpcId, VpcGateway.Type type);
+
+    List<VpcGatewayVO> listByAclIdAndType(long aclId, VpcGateway.Type type);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/da000661/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java b/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java
index 6a2f8bd..a8cb2b3 100644
--- a/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java
+++ b/engine/schema/src/com/cloud/network/vpc/dao/VpcGatewayDaoImpl.java
@@ -41,6 +41,7 @@ public class VpcGatewayDaoImpl extends GenericDaoBase<VpcGatewayVO, Long> implem
         AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), SearchCriteria.Op.EQ);
         AllFieldsSearch.and("networkid", AllFieldsSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
         AllFieldsSearch.and("ipaddress", AllFieldsSearch.entity().getIp4Address(), SearchCriteria.Op.EQ);
+        AllFieldsSearch.and("aclId", AllFieldsSearch.entity().getNetworkACLId(), SearchCriteria.Op.EQ);
         AllFieldsSearch.done();
     }
 
@@ -86,4 +87,11 @@ public class VpcGatewayDaoImpl extends GenericDaoBase<VpcGatewayVO, Long> implem
         return listBy(sc);
     }
 
+    @Override
+    public List<VpcGatewayVO> listByAclIdAndType(long aclId, VpcGateway.Type type) {
+        SearchCriteria<VpcGatewayVO> sc = AllFieldsSearch.create();
+        sc.setParameters("aclId", aclId);
+        sc.setParameters("type", type);
+        return listBy(sc);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/da000661/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java
index c2d092a..4881b73 100644
--- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java
+++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java
@@ -122,6 +122,18 @@ public class NetworkACLManagerImpl extends ManagerBase implements NetworkACLMana
         if(aclItems.size() > 0){
             throw new CloudRuntimeException("ACL is not empty. Cannot delete network ACL: "+acl.getUuid());
         }
+
+        List<NetworkVO> networks = _networkDao.listByAclId(acl.getId());
+        if(networks != null && networks.size() > 0){
+            throw new CloudRuntimeException("ACL is still associated with "+networks.size()+" tier(s). Cannot delete network ACL: "+acl.getUuid());
+        }
+
+        List<VpcGatewayVO> pvtGateways = _vpcGatewayDao.listByAclIdAndType(acl.getId(), VpcGateway.Type.Private);
+
+        if(pvtGateways != null && pvtGateways.size() > 0){
+            throw new CloudRuntimeException("ACL is still associated with "+pvtGateways.size()+" private gateway(s). Cannot delete network ACL: "+acl.getUuid());
+        }
+
         return _networkACLDao.remove(acl.getId());
     }
 


[28/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3149: Allow default ACLs when creating tier with ACL


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

Branch: refs/heads/vmsync
Commit: 7c46cc958049c815337f42bfde788bbe9fba4811
Parents: 90838d7
Author: Kishan Kavala <ki...@cloud.com>
Authored: Mon Jun 24 16:16:14 2013 +0530
Committer: Kishan Kavala <ki...@cloud.com>
Committed: Mon Jun 24 16:22:02 2013 +0530

----------------------------------------------------------------------
 server/src/com/cloud/network/NetworkServiceImpl.java | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7c46cc95/server/src/com/cloud/network/NetworkServiceImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java
index e7de69e..5e900bb 100755
--- a/server/src/com/cloud/network/NetworkServiceImpl.java
+++ b/server/src/com/cloud/network/NetworkServiceImpl.java
@@ -1298,8 +1298,12 @@ public class NetworkServiceImpl extends ManagerBase implements  NetworkService {
                     throw new InvalidParameterValueException("Unable to find specified NetworkACL");
                 }
 
-                if(!vpcId.equals(acl.getVpcId())){
-                    throw new InvalidParameterValueException("ACL: "+aclId+" do not belong to the VPC");
+                if(aclId != NetworkACL.DEFAULT_DENY && aclId != NetworkACL.DEFAULT_ALLOW) {
+                    //ACL is not default DENY/ALLOW
+                    // ACL should be associated with a VPC
+                    if(!vpcId.equals(acl.getVpcId())){
+                        throw new InvalidParameterValueException("ACL: "+aclId+" do not belong to the VPC");
+                    }
                 }
             }
             network = _vpcMgr.createVpcGuestNetwork(networkOfferingId, name, displayText, gateway, cidr, vlanId, 


[14/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3151 [VMware] CloudStack does case sensitive processing of names of VMware objects.

Signed-off-by: Sateesh Chodapuneedi <sa...@apache.org>


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

Branch: refs/heads/vmsync
Commit: 3c88dd4f801fe255d918fd1de6a962a8ab4fda4d
Parents: 90838d7
Author: Sateesh Chodapuneedi <sa...@apache.org>
Authored: Mon Jun 24 11:06:16 2013 +0530
Committer: Sateesh Chodapuneedi <sa...@apache.org>
Committed: Mon Jun 24 11:06:16 2013 +0530

----------------------------------------------------------------------
 .../src/com/cloud/hypervisor/vmware/util/VmwareClient.java    | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c88dd4f/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java
----------------------------------------------------------------------
diff --git a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java
index 87c7909..1b75e2d 100644
--- a/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java
+++ b/vmware-base/src/com/cloud/hypervisor/vmware/util/VmwareClient.java
@@ -24,17 +24,17 @@ import java.util.Map;
 import java.util.StringTokenizer;
 
 import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLSession;
 import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLSession;
 import javax.xml.ws.BindingProvider;
 import javax.xml.ws.handler.MessageContext;
 
-
 import com.vmware.vim25.DynamicProperty;
 import com.vmware.vim25.InvalidCollectorVersionFaultMsg;
 import com.vmware.vim25.InvalidPropertyFaultMsg;
 import com.vmware.vim25.LocalizedMethodFault;
 import com.vmware.vim25.ManagedObjectReference;
+import com.vmware.vim25.ObjectContent;
 import com.vmware.vim25.ObjectSpec;
 import com.vmware.vim25.ObjectUpdate;
 import com.vmware.vim25.ObjectUpdateKind;
@@ -51,7 +51,6 @@ import com.vmware.vim25.TraversalSpec;
 import com.vmware.vim25.UpdateSet;
 import com.vmware.vim25.VimPortType;
 import com.vmware.vim25.VimService;
-import com.vmware.vim25.ObjectContent;
 
 /**
  * A wrapper class to handle Vmware vsphere connection and disconnection.
@@ -554,7 +553,7 @@ public class VmwareClient {
             if (type == null || type.equals(mor.getType())) {
                 if (propary.size() > 0) {
                     String propval = (String) propary.get(0).getVal();
-                    if (propval != null && name.equals(propval))
+                    if (propval != null && name.equalsIgnoreCase(propval))
                         return mor;
                 }
             }


[37/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/upload/UploadListener.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/upload/UploadListener.java
index 038cc38,d3b7af9..5d7a4ba
--- a/server/src/com/cloud/storage/upload/UploadListener.java
+++ b/server/src/com/cloud/storage/upload/UploadListener.java
@@@ -24,15 -23,18 +23,21 @@@ import java.util.Map
  import java.util.Timer;
  import java.util.TimerTask;
  
+ import javax.inject.Inject;
+ 
 +import org.apache.log4j.Level;
 +import org.apache.log4j.Logger;
 +
  import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd;
  import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
  import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd;
  import org.apache.cloudstack.api.response.ExtractResponse;
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+ import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
+ import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
+ import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
 -import org.apache.log4j.Level;
 -import org.apache.log4j.Logger;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 +import org.apache.cloudstack.jobs.JobInfo;
  
  import com.cloud.agent.Listener;
  import com.cloud.agent.api.AgentControlAnswer;
@@@ -46,9 -48,9 +51,8 @@@ import com.cloud.agent.api.storage.Uplo
  import com.cloud.agent.api.storage.UploadProgressCommand;
  import com.cloud.agent.api.storage.UploadProgressCommand.RequestType;
  import com.cloud.api.ApiDBUtils;
 -import com.cloud.async.AsyncJobManager;
 -import com.cloud.async.AsyncJobResult;
 +import com.cloud.api.ApiSerializerHelper;
- import com.cloud.exception.AgentUnavailableException;
- import com.cloud.host.HostVO;
+ import com.cloud.host.Host;
  import com.cloud.storage.Storage;
  import com.cloud.storage.Upload.Status;
  import com.cloud.storage.Upload.Type;
@@@ -59,401 -61,420 +63,420 @@@ import com.cloud.utils.exception.CloudR
  
  public class UploadListener implements Listener {
  
- 
 -    private static final class StatusTask extends TimerTask {
 -        private final UploadListener ul;
 -        private final RequestType reqType;
 +	private static final class StatusTask extends TimerTask {
 +		private final UploadListener ul;
 +		private final RequestType reqType;
  
- 		public StatusTask( UploadListener ul,  RequestType req) {
- 			reqType = req;
+         public StatusTask(UploadListener ul, RequestType req) {
 -            this.reqType = req;
 -            this.ul = ul;
 -        }
++            reqType = req;
 +			this.ul = ul;
 +		}
  
 -        @Override
 -        public void run() {
 -            ul.sendCommand(reqType);
 +		@Override
 +		public void run() {
 +		  ul.sendCommand(reqType);
  
 -        }
 -    }
 +		}
 +	}
  
 -    private static final class TimeoutTask extends TimerTask {
 -        private final UploadListener ul;
 +	private static final class TimeoutTask extends TimerTask {
 +		private final UploadListener ul;
  
- 		public TimeoutTask( UploadListener ul) {
+         public TimeoutTask(UploadListener ul) {
 -            this.ul = ul;
 -        }
 +			this.ul = ul;
 +		}
  
 -        @Override
 -        public void run() {
 -            ul.checkProgress();
 -        }
 -    }
 +		@Override
 +		public void run() {
 +		  ul.checkProgress();
 +		}
 +	}
  
 -    public static final Logger s_logger = Logger.getLogger(UploadListener.class.getName());
 -    public static final int SMALL_DELAY = 100;
 -    public static final long STATUS_POLL_INTERVAL = 10000L;
 +	public static final Logger s_logger = Logger.getLogger(UploadListener.class.getName());
 +	public static final int SMALL_DELAY = 100;
 +	public static final long STATUS_POLL_INTERVAL = 10000L;
  
- 	public static final String UPLOADED=Status.UPLOADED.toString();
- 	public static final String NOT_UPLOADED=Status.NOT_UPLOADED.toString();
- 	public static final String UPLOAD_ERROR=Status.UPLOAD_ERROR.toString();
- 	public static final String UPLOAD_IN_PROGRESS=Status.UPLOAD_IN_PROGRESS.toString();
- 	public static final String UPLOAD_ABANDONED=Status.ABANDONED.toString();
- 	public static final Map<String,String> responseNameMap;
- 	static{
- 	    Map<String, String>tempMap = new HashMap<String, String>();
+     public static final String UPLOADED = Status.UPLOADED.toString();
+     public static final String NOT_UPLOADED = Status.NOT_UPLOADED.toString();
+     public static final String UPLOAD_ERROR = Status.UPLOAD_ERROR.toString();
+     public static final String UPLOAD_IN_PROGRESS = Status.UPLOAD_IN_PROGRESS.toString();
+     public static final String UPLOAD_ABANDONED = Status.ABANDONED.toString();
+     public static final Map<String, String> responseNameMap;
+     static {
+         Map<String, String> tempMap = new HashMap<String, String>();
          tempMap.put(Type.ISO.toString(), ExtractIsoCmd.getStaticName());
          tempMap.put(Type.TEMPLATE.toString(), ExtractTemplateCmd.getStaticName());
          tempMap.put(Type.VOLUME.toString(), ExtractVolumeCmd.getStaticName());
-         tempMap.put("DEFAULT","extractresponse");
+         tempMap.put("DEFAULT", "extractresponse");
          responseNameMap = Collections.unmodifiableMap(tempMap);
 -    }
 +	}
  
- 
- 	private HostVO sserver;
+     private DataStore sserver;
  
 -    private boolean uploadActive = true;
 +	private boolean uploadActive = true;
  
 -    private UploadDao uploadDao;
 +	private UploadDao uploadDao;
  
 -    private final UploadMonitorImpl uploadMonitor;
 +	private final UploadMonitorImpl uploadMonitor;
  
 -    private UploadState currState;
 +	private UploadState currState;
  
 -    private UploadCommand cmd;
 +	private UploadCommand cmd;
  
 -    private Timer timer;
 +	private Timer timer;
  
 -    private StatusTask statusTask;
 -    private TimeoutTask timeoutTask;
 -    private Date lastUpdated = new Date();
 -    private String jobId;
 -    private Long accountId;
 -    private String typeName;
 -    private Type type;
 -    private long asyncJobId;
 -    private long eventId;
 -    private AsyncJobManager asyncMgr;
 -    private ExtractResponse resultObj;
 +	private StatusTask statusTask;
 +	private TimeoutTask timeoutTask;
 +	private Date lastUpdated = new Date();
 +	private String jobId;
 +	private Long accountId;
 +	private String typeName;
 +	private Type type;
 +	private long asyncJobId;
 +	private long eventId;
 +	private AsyncJobManager asyncMgr;
 +	private ExtractResponse resultObj;
+     @Inject
+     EndPointSelector _epSelector;
  
 -    public AsyncJobManager getAsyncMgr() {
 -        return asyncMgr;
 -    }
 +	public AsyncJobManager getAsyncMgr() {
 +		return asyncMgr;
 +	}
  
 -    public void setAsyncMgr(AsyncJobManager asyncMgr) {
 -        this.asyncMgr = asyncMgr;
 -    }
 +	public void setAsyncMgr(AsyncJobManager asyncMgr) {
 +		this.asyncMgr = asyncMgr;
 +	}
  
 -    public long getAsyncJobId() {
 -        return asyncJobId;
 -    }
 +	public long getAsyncJobId() {
 +		return asyncJobId;
 +	}
  
 -    public void setAsyncJobId(long asyncJobId) {
 -        this.asyncJobId = asyncJobId;
 -    }
 +	public void setAsyncJobId(long asyncJobId) {
 +		this.asyncJobId = asyncJobId;
 +	}
  
 -    public long getEventId() {
 -        return eventId;
 -    }
 +	public long getEventId() {
 +		return eventId;
 +	}
  
 -    public void setEventId(long eventId) {
 -        this.eventId = eventId;
 -    }
 +	public void setEventId(long eventId) {
 +		this.eventId = eventId;
 +	}
  
 -    private final Map<String, UploadState> stateMap = new HashMap<String, UploadState>();
 -    private Long uploadId;
 +	private final Map<String,  UploadState> stateMap = new HashMap<String, UploadState>();
 +	private Long uploadId;
  
- 	public UploadListener(HostVO host, Timer _timer, UploadDao uploadDao,
+     public UploadListener(DataStore host, Timer _timer, UploadDao uploadDao,
 -            UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd,
 -            Long accountId, String typeName, Type type, long eventId, long asyncJobId, AsyncJobManager asyncMgr) {
 -        this.sserver = host;
 -        this.uploadDao = uploadDao;
 -        this.uploadMonitor = uploadMonitor;
 -        this.cmd = cmd;
 -        this.uploadId = uploadObj.getId();
 -        this.accountId = accountId;
 -        this.typeName = typeName;
 -        this.type = type;
 -        initStateMachine();
 -        this.currState = getState(Status.NOT_UPLOADED.toString());
 -        this.timer = _timer;
 -        this.timeoutTask = new TimeoutTask(this);
 -        this.timer.schedule(timeoutTask, 3 * STATUS_POLL_INTERVAL);
 -        this.eventId = eventId;
 -        this.asyncJobId = asyncJobId;
 -        this.asyncMgr = asyncMgr;
 -        String extractId = null;
 +			UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd,
 +			Long accountId, String typeName, Type type, long eventId, long asyncJobId, AsyncJobManager asyncMgr) {
 +		sserver = host;
 +		this.uploadDao = uploadDao;
 +		this.uploadMonitor = uploadMonitor;
 +		this.cmd = cmd;
 +		uploadId = uploadObj.getId();
 +		this.accountId = accountId;
 +		this.typeName = typeName;
 +		this.type = type;
 +		initStateMachine();
- 		currState = getState(Status.NOT_UPLOADED.toString());
- 		timer = _timer;
- 		timeoutTask = new TimeoutTask(this);
- 		timer.schedule(timeoutTask, 3*STATUS_POLL_INTERVAL);
++        currState = getState(Status.NOT_UPLOADED.toString());
++        timer = _timer;
++        timeoutTask = new TimeoutTask(this);
++        timer.schedule(timeoutTask, 3 * STATUS_POLL_INTERVAL);
 +		this.eventId = eventId;
 +		this.asyncJobId = asyncJobId;
 +		this.asyncMgr = asyncMgr;
 +		String extractId = null;
- 		if ( type == Type.VOLUME ){
+         if (type == Type.VOLUME) {
 -            extractId = ApiDBUtils.findVolumeById(uploadObj.getTypeId()).getUuid();
 -        }
 +		    extractId = ApiDBUtils.findVolumeById(uploadObj.getTypeId()).getUuid();
 +		}
- 		else{
+         else {
 -            extractId = ApiDBUtils.findTemplateById(uploadObj.getTypeId()).getUuid();
 -        }
 -        this.resultObj = new ExtractResponse(extractId, typeName, ApiDBUtils.findAccountById(accountId).getUuid(), Status.NOT_UPLOADED.toString(),
 -                ApiDBUtils.findUploadById(uploadId).getUuid());
 -        resultObj.setResponseName(responseNameMap.get(type.toString()));
 +		    extractId = ApiDBUtils.findTemplateById(uploadObj.getTypeId()).getUuid();
 +		}
 +		resultObj = new ExtractResponse(extractId, typeName, ApiDBUtils.findAccountById(accountId).getUuid(), Status.NOT_UPLOADED.toString(),
 +		        ApiDBUtils.findUploadById(uploadId).getUuid());
 +		resultObj.setResponseName(responseNameMap.get(type.toString()));
- 		updateDatabase(Status.NOT_UPLOADED, cmd.getUrl(),"");
+         updateDatabase(Status.NOT_UPLOADED, cmd.getUrl(), "");
 -    }
 +	}
  
 -    public UploadListener(UploadMonitorImpl monitor) {
 -        uploadMonitor = monitor;
 -    }
 +	public UploadListener(UploadMonitorImpl monitor) {
 +	    uploadMonitor = monitor;
 +	}
  
 -    public void checkProgress() {
 -        transition(UploadEvent.TIMEOUT_CHECK, null);
 -    }
 +	public void checkProgress() {
 +		transition(UploadEvent.TIMEOUT_CHECK, null);
 +	}
  
 -    @Override
 -    public int getTimeout() {
 -        return -1;
 -    }
 +	@Override
 +	public int getTimeout() {
 +		return -1;
 +	}
  
 -    @Override
 -    public boolean isRecurring() {
 -        return false;
 -    }
 +	@Override
 +	public boolean isRecurring() {
 +		return false;
 +	}
  
 -    public void setCommand(UploadCommand _cmd) {
 -        this.cmd = _cmd;
 -    }
 +	public void setCommand(UploadCommand _cmd) {
 +		cmd = _cmd;
 +	}
  
 -    public void setJobId(String _jobId) {
 -        this.jobId = _jobId;
 -    }
 +	public void setJobId(String _jobId) {
 +		jobId = _jobId;
 +	}
  
 -    public String getJobId() {
 -        return jobId;
 -    }
 +	public String getJobId() {
 +		return jobId;
 +	}
  
 -    @Override
 -    public boolean processAnswers(long agentId, long seq, Answer[] answers) {
 -        boolean processed = false;
 +	@Override
 +	public boolean processAnswers(long agentId, long seq, Answer[] answers) {
 +		boolean processed = false;
-     	if(answers != null & answers.length > 0) {
-     		if(answers[0] instanceof UploadAnswer) {
+         if (answers != null & answers.length > 0) {
+             if (answers[0] instanceof UploadAnswer) {
 -                final UploadAnswer answer = (UploadAnswer)answers[0];
 -                if (getJobId() == null) {
 -                    setJobId(answer.getJobId());
 +    			final UploadAnswer answer = (UploadAnswer)answers[0];
 +    			if (getJobId() == null) {
 +    				setJobId(answer.getJobId());
-     			} else if (!getJobId().equalsIgnoreCase(answer.getJobId())){
+                 } else if (!getJobId().equalsIgnoreCase(answer.getJobId())) {
 -                    return false;//TODO
 -                }
 -                transition(UploadEvent.UPLOAD_ANSWER, answer);
 -                processed = true;
 -            }
 -        }
 +    				return false;//TODO
 +    			}
 +    			transition(UploadEvent.UPLOAD_ANSWER, answer);
 +    			processed = true;
 +    		}
 +    	}
          return processed;
 -    }
 +	}
  
- 
 -    @Override
 -    public boolean processCommands(long agentId, long seq, Command[] commands) {
 -        return false;
 -    }
 +	@Override
 +	public boolean processCommands(long agentId, long seq, Command[] commands) {
 +		return false;
 +	}
  
 -    @Override
 +	@Override
- 	public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) {
+     public void processConnect(Host agent, StartupCommand cmd, boolean forRebalance) {
 -        if (!(cmd instanceof StartupStorageCommand)) {
 -            return;
 -        }
 +		if (!(cmd instanceof StartupStorageCommand)) {
 +	        return;
 +	    }
  
 -        long agentId = agent.getId();
 +	    long agentId = agent.getId();
  
 -        StartupStorageCommand storage = (StartupStorageCommand)cmd;
 -        if (storage.getResourceType() == Storage.StorageResourceType.STORAGE_HOST ||
 +	    StartupStorageCommand storage = (StartupStorageCommand)cmd;
 +	    if (storage.getResourceType() == Storage.StorageResourceType.STORAGE_HOST ||
- 	    storage.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE )
+                 storage.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE)
 -        {
 -            uploadMonitor.handleUploadSync(agentId);
 -        }
 -    }
 -
 -    @Override
 -    public AgentControlAnswer processControlCommand(long agentId,
 -            AgentControlCommand cmd) {
 -        return null;
 -    }
 -
 -    public void setUploadInactive(Status reason) {
 +	    {
 +	    	uploadMonitor.handleUploadSync(agentId);
 +	    }
 +	}
 +
 +	@Override
 +	public AgentControlAnswer processControlCommand(long agentId,
 +			AgentControlCommand cmd) {
 +		return null;
 +	}
 +
 +	public void setUploadInactive(Status reason) {
- 		uploadActive=false;
- 		uploadMonitor.handleUploadEvent(sserver, accountId, typeName, type, uploadId, reason, eventId);
+         uploadActive = false;
+         uploadMonitor.handleUploadEvent(accountId, typeName, type, uploadId, reason, eventId);
 -    }
 +	}
  
 -    public void logUploadStart() {
 -        //uploadMonitor.logEvent(accountId, event, "Storage server " + sserver.getName() + " started upload of " +type.toString() + " " + typeName, EventVO.LEVEL_INFO, eventId);
 -    }
 +	public void logUploadStart() {
 +		//uploadMonitor.logEvent(accountId, event, "Storage server " + sserver.getName() + " started upload of " +type.toString() + " " + typeName, EventVO.LEVEL_INFO, eventId);
 +	}
  
 -    public void cancelTimeoutTask() {
 +	public void cancelTimeoutTask() {
- 		if (timeoutTask != null) timeoutTask.cancel();
+         if (timeoutTask != null)
+             timeoutTask.cancel();
 -    }
 +	}
  
 -    public void cancelStatusTask() {
 +	public void cancelStatusTask() {
- 		if (statusTask != null) statusTask.cancel();
+         if (statusTask != null)
+             statusTask.cancel();
 -    }
 -
 -    @Override
 -    public boolean processDisconnect(long agentId, com.cloud.host.Status state) {
 -        setDisconnected();
 -        return true;
 -    }
 -
 -    @Override
 -    public boolean processTimeout(long agentId, long seq) {
 -        return true;
 -    }
 -
 -    private void initStateMachine() {
 -        stateMap.put(Status.NOT_UPLOADED.toString(), new NotUploadedState(this));
 -        stateMap.put(Status.UPLOADED.toString(), new UploadCompleteState(this));
 -        stateMap.put(Status.UPLOAD_ERROR.toString(), new UploadErrorState(this));
 -        stateMap.put(Status.UPLOAD_IN_PROGRESS.toString(), new UploadInProgressState(this));
 -        stateMap.put(Status.ABANDONED.toString(), new UploadAbandonedState(this));
 -    }
 -
 -    private UploadState getState(String stateName) {
 -        return stateMap.get(stateName);
 -    }
 -
 -    private synchronized void transition(UploadEvent event, Object evtObj) {
 -        if (currState == null) {
 -            return;
 -        }
 -        String prevName = currState.getName();
 -        String nextState = currState.handleEvent(event, evtObj);
 -        if (nextState != null) {
 -            currState = getState(nextState);
 -            if (currState != null) {
 -                currState.onEntry(prevName, event, evtObj);
 -            } else {
 +	}
 +
 +	@Override
 +	public boolean processDisconnect(long agentId, com.cloud.host.Status state) {
 +		setDisconnected();
 +		return true;
 +	}
 +
 +	@Override
 +	public boolean processTimeout(long agentId, long seq) {
 +		return true;
 +	}
 +
 +	private void initStateMachine() {
 +		stateMap.put(Status.NOT_UPLOADED.toString(), new NotUploadedState(this));
 +		stateMap.put(Status.UPLOADED.toString(), new UploadCompleteState(this));
 +		stateMap.put(Status.UPLOAD_ERROR.toString(), new UploadErrorState(this));
 +		stateMap.put(Status.UPLOAD_IN_PROGRESS.toString(), new UploadInProgressState(this));
 +		stateMap.put(Status.ABANDONED.toString(), new UploadAbandonedState(this));
 +	}
 +
 +	private UploadState getState(String stateName) {
 +		return stateMap.get(stateName);
 +	}
 +
 +	private synchronized void transition(UploadEvent event, Object evtObj) {
 +	    if (currState == null) {
 +	        return;
 +	    }
 +		String prevName = currState.getName();
 +		String nextState = currState.handleEvent(event, evtObj);
 +		if (nextState != null) {
 +			currState = getState(nextState);
 +			if (currState != null) {
 +				currState.onEntry(prevName, event, evtObj);
 +			} else {
- 				throw new CloudRuntimeException("Invalid next state: currState="+prevName+", evt="+event + ", next=" + nextState);
+                 throw new CloudRuntimeException("Invalid next state: currState=" + prevName + ", evt=" + event + ", next=" + nextState);
 -            }
 -        } else {
 +			}
 +		} else {
- 			throw new CloudRuntimeException("Unhandled event transition: currState="+prevName+", evt="+event);
+             throw new CloudRuntimeException("Unhandled event transition: currState=" + prevName + ", evt=" + event);
 -        }
 -    }
 +		}
 +	}
  
 -    public Date getLastUpdated() {
 -        return lastUpdated;
 -    }
 +	public Date getLastUpdated() {
 +		return lastUpdated;
 +	}
  
 -    public void setLastUpdated() {
 -        lastUpdated = new Date();
 -    }
 +	public void setLastUpdated() {
 +		lastUpdated  = new Date();
 +	}
  
 -    public void log(String message, Level level) {
 -        s_logger.log(level, message + ", " + type.toString() + " = " + typeName + " at host " + sserver.getName());
 -    }
 +	public void log(String message, Level level) {
 +		s_logger.log(level, message + ", " + type.toString() + " = " + typeName + " at host " + sserver.getName());
 +	}
  
 -    public void setDisconnected() {
 -        transition(UploadEvent.DISCONNECT, null);
 -    }
 +	public void setDisconnected() {
 +		transition(UploadEvent.DISCONNECT, null);
 +	}
  
 -    public void scheduleStatusCheck(com.cloud.agent.api.storage.UploadProgressCommand.RequestType getStatus) {
 +	public void scheduleStatusCheck(com.cloud.agent.api.storage.UploadProgressCommand.RequestType getStatus) {
- 		if (statusTask != null) statusTask.cancel();
+         if (statusTask != null)
+             statusTask.cancel();
  
 -        statusTask = new StatusTask(this, getStatus);
 -        timer.schedule(statusTask, STATUS_POLL_INTERVAL);
 -    }
 +		statusTask = new StatusTask(this, getStatus);
 +		timer.schedule(statusTask, STATUS_POLL_INTERVAL);
 +	}
  
 -    public void scheduleTimeoutTask(long delay) {
 +	public void scheduleTimeoutTask(long delay) {
- 		if (timeoutTask != null) timeoutTask.cancel();
+         if (timeoutTask != null)
+             timeoutTask.cancel();
  
 -        timeoutTask = new TimeoutTask(this);
 -        timer.schedule(timeoutTask, delay);
 -        if (s_logger.isDebugEnabled()) {
 -            log("Scheduling timeout at " + delay + " ms", Level.DEBUG);
 -        }
 -    }
 -
 -    public void updateDatabase(Status state, String uploadErrorString) {
 -        resultObj.setResultString(uploadErrorString);
 -        resultObj.setState(state.toString());
 -        asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 -        asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj);
 -
 -        UploadVO vo = uploadDao.createForUpdate();
 -        vo.setUploadState(state);
 -        vo.setLastUpdated(new Date());
 -        vo.setErrorString(uploadErrorString);
 -        uploadDao.update(getUploadId(), vo);
 -    }
 +		timeoutTask = new TimeoutTask(this);
 +		timer.schedule(timeoutTask, delay);
 +		if (s_logger.isDebugEnabled()) {
 +			log("Scheduling timeout at " + delay + " ms", Level.DEBUG);
 +		}
 +	}
 +
 +	public void updateDatabase(Status state, String uploadErrorString) {
 +		resultObj.setResultString(uploadErrorString);
 +		resultObj.setState(state.toString());
 +		asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 +        asyncMgr.updateAsyncJobStatus(asyncJobId, JobInfo.Status.IN_PROGRESS.ordinal(), ApiSerializerHelper.toSerializedString(resultObj));
 +
 +		UploadVO vo = uploadDao.createForUpdate();
 +		vo.setUploadState(state);
 +		vo.setLastUpdated(new Date());
 +		vo.setErrorString(uploadErrorString);
 +		uploadDao.update(getUploadId(), vo);
 +	}
  
- 	public void updateDatabase(Status state, String uploadUrl,String uploadErrorString) {
+     public void updateDatabase(Status state, String uploadUrl, String uploadErrorString) {
 -        resultObj.setResultString(uploadErrorString);
 -        resultObj.setState(state.toString());
 -        asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 -        asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj);
 -
 -        UploadVO vo = uploadDao.createForUpdate();
 -        vo.setUploadState(state);
 -        vo.setLastUpdated(new Date());
 -        vo.setUploadUrl(uploadUrl);
 -        vo.setJobId(null);
 -        vo.setUploadPercent(0);
 -        vo.setErrorString(uploadErrorString);
 -
 -        uploadDao.update(getUploadId(), vo);
 -    }
 +		resultObj.setResultString(uploadErrorString);
 +		resultObj.setState(state.toString());
 +		asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 +        asyncMgr.updateAsyncJobStatus(asyncJobId, JobInfo.Status.IN_PROGRESS.ordinal(), ApiSerializerHelper.toSerializedString(resultObj));
  
- 
 -    private Long getUploadId() {
 -        return uploadId;
 -    }
 +		UploadVO vo = uploadDao.createForUpdate();
 +		vo.setUploadState(state);
 +		vo.setLastUpdated(new Date());
 +		vo.setUploadUrl(uploadUrl);
 +		vo.setJobId(null);
 +		vo.setUploadPercent(0);
 +		vo.setErrorString(uploadErrorString);
 +
 +		uploadDao.update(getUploadId(), vo);
 +	}
 +
 +	private Long getUploadId() {
 +		return uploadId;
 +	}
  
 -    public synchronized void updateDatabase(UploadAnswer answer) {
 +	public synchronized void updateDatabase(UploadAnswer answer) {
  
- 	    if(answer.getErrorString().startsWith("553")){
+         if (answer.getErrorString().startsWith("553")) {
 -            answer.setErrorString(answer.getErrorString().concat("Please check if the file name already exists."));
 -        }
 -        resultObj.setResultString(answer.getErrorString());
 -        resultObj.setState(answer.getUploadStatus().toString());
 -        resultObj.setUploadPercent(answer.getUploadPct());
 +	        answer.setErrorString(answer.getErrorString().concat("Please check if the file name already exists."));
 +	    }
 +		resultObj.setResultString(answer.getErrorString());
 +		resultObj.setState(answer.getUploadStatus().toString());
 +		resultObj.setUploadPercent(answer.getUploadPct());
  
- 		if (answer.getUploadStatus() == Status.UPLOAD_IN_PROGRESS){
+         if (answer.getUploadStatus() == Status.UPLOAD_IN_PROGRESS) {
 -            asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 -            asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj);
 +			asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L);
 +            asyncMgr.updateAsyncJobStatus(asyncJobId, JobInfo.Status.IN_PROGRESS.ordinal(), ApiSerializerHelper.toSerializedString(resultObj));
- 		}else if(answer.getUploadStatus() == Status.UPLOADED){
- 		    resultObj.setResultString("Success");
+         } else if (answer.getUploadStatus() == Status.UPLOADED) {
+             resultObj.setResultString("Success");
 -            asyncMgr.completeAsyncJob(asyncJobId, AsyncJobResult.STATUS_SUCCEEDED, 1, resultObj);
 +            asyncMgr.completeAsyncJob(asyncJobId, JobInfo.Status.SUCCEEDED, 1, ApiSerializerHelper.toSerializedString(resultObj));
- 		}else{
+         } else {
 -            asyncMgr.completeAsyncJob(asyncJobId, AsyncJobResult.STATUS_FAILED, 2, resultObj);
 -        }
 +            asyncMgr.completeAsyncJob(asyncJobId, JobInfo.Status.FAILED, 2, ApiSerializerHelper.toSerializedString(resultObj));
 +		}
          UploadVO updateBuilder = uploadDao.createForUpdate();
 -        updateBuilder.setUploadPercent(answer.getUploadPct());
 -        updateBuilder.setUploadState(answer.getUploadStatus());
 -        updateBuilder.setLastUpdated(new Date());
 -        updateBuilder.setErrorString(answer.getErrorString());
 -        updateBuilder.setJobId(answer.getJobId());
 -
 -        uploadDao.update(getUploadId(), updateBuilder);
 -    }
 -
 -    public void sendCommand(RequestType reqType) {
 -        if (getJobId() != null) {
 -            if (s_logger.isTraceEnabled()) {
 -                log("Sending progress command ", Level.TRACE);
 -            }
 -            try {
 +		updateBuilder.setUploadPercent(answer.getUploadPct());
 +		updateBuilder.setUploadState(answer.getUploadStatus());
 +		updateBuilder.setLastUpdated(new Date());
 +		updateBuilder.setErrorString(answer.getErrorString());
 +		updateBuilder.setJobId(answer.getJobId());
 +
 +		uploadDao.update(getUploadId(), updateBuilder);
 +	}
 +
 +	public void sendCommand(RequestType reqType) {
 +		if (getJobId() != null) {
 +			if (s_logger.isTraceEnabled()) {
 +				log("Sending progress command ", Level.TRACE);
 +			}
 +			try {
- 	            uploadMonitor.send(sserver.getId(), new UploadProgressCommand(getCommand(), getJobId(), reqType), this);
-             } catch (AgentUnavailableException e) {
+                 EndPoint ep = _epSelector.select(sserver);
+                 ep.sendMessageAsync(new UploadProgressCommand(getCommand(), getJobId(), reqType), new Callback(ep.getId(), this));
+             } catch (Exception e) {
 -                s_logger.debug("Send command failed", e);
 -                setDisconnected();
 +            	s_logger.debug("Send command failed", e);
 +				setDisconnected();
              }
 -        }
 +		}
  
 -    }
 +	}
  
 -    private UploadCommand getCommand() {
 -        return cmd;
 -    }
 +	private UploadCommand getCommand() {
 +		return cmd;
 +	}
  
 -    public void logDisconnect() {
 -        s_logger.warn("Unable to monitor upload progress of " + typeName + " at host " + sserver.getName());
 -    }
 +	public void logDisconnect() {
 +		s_logger.warn("Unable to monitor upload progress of " + typeName + " at host " + sserver.getName());
 +	}
  
 -    public void scheduleImmediateStatusCheck(RequestType request) {
 +	public void scheduleImmediateStatusCheck(RequestType request) {
- 		if (statusTask != null) statusTask.cancel();
+         if (statusTask != null)
+             statusTask.cancel();
 -        statusTask = new StatusTask(this, request);
 -        timer.schedule(statusTask, SMALL_DELAY);
 -    }
 +		statusTask = new StatusTask(this, request);
 +		timer.schedule(statusTask, SMALL_DELAY);
 +	}
  
 -    public void setCurrState(Status uploadState) {
 -        this.currState = getState(currState.toString());
 -    }
 +	public void setCurrState(Status uploadState) {
 +		currState = getState(currState.toString());
 +	}
+ 
+     public static class Callback implements AsyncCompletionCallback<Answer> {
+         long id;
+         Listener listener;
+ 
+         public Callback(long id, Listener listener) {
+             this.id = id;
+             this.listener = listener;
+         }
+ 
+         @Override
+         public void complete(Answer answer) {
+             listener.processAnswers(id, -1, new Answer[] {answer});
+         }
+     }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/upload/UploadMonitor.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/upload/UploadMonitor.java
index d4f5762,b4ba531..c660299
--- a/server/src/com/cloud/storage/upload/UploadMonitor.java
+++ b/server/src/com/cloud/storage/upload/UploadMonitor.java
@@@ -17,14 -17,17 +17,15 @@@
  package com.cloud.storage.upload;
  
  
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
  
- import com.cloud.host.HostVO;
 -import com.cloud.async.AsyncJobManager;
 -import com.cloud.host.HostVO;
+ import com.cloud.storage.Storage.ImageFormat;
  import com.cloud.storage.Upload.Mode;
  import com.cloud.storage.Upload.Status;
  import com.cloud.storage.Upload.Type;
  import com.cloud.storage.UploadVO;
--import com.cloud.storage.VMTemplateHostVO;
  import com.cloud.storage.VMTemplateVO;
  import com.cloud.storage.VolumeVO;
  import com.cloud.utils.component.Manager;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/storage/upload/UploadMonitorImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/upload/UploadMonitorImpl.java
index 01eabad,d46db0c..f7cf88d
--- a/server/src/com/cloud/storage/upload/UploadMonitorImpl.java
+++ b/server/src/com/cloud/storage/upload/UploadMonitorImpl.java
@@@ -35,19 -42,15 +42,16 @@@ import org.apache.cloudstack.storage.im
  import org.apache.log4j.Logger;
  import org.springframework.stereotype.Component;
  
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 +
  import com.cloud.agent.AgentManager;
- import com.cloud.agent.Listener;
- import com.cloud.agent.api.Command;
+ import com.cloud.agent.api.Answer;
  import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
  import com.cloud.agent.api.storage.DeleteEntityDownloadURLCommand;
  import com.cloud.agent.api.storage.UploadCommand;
  import com.cloud.agent.api.storage.UploadProgressCommand.RequestType;
- import com.cloud.agent.manager.Commands;
  import com.cloud.api.ApiDBUtils;
 -import com.cloud.async.AsyncJobManager;
  import com.cloud.configuration.dao.ConfigurationDao;
- import com.cloud.exception.AgentUnavailableException;
  import com.cloud.host.Host;
  import com.cloud.host.HostVO;
  import com.cloud.host.dao.HostDao;
@@@ -83,10 -85,8 +86,8 @@@ import com.cloud.vm.dao.SecondaryStorag
  public class UploadMonitorImpl extends ManagerBase implements UploadMonitor {
  
  	static final Logger s_logger = Logger.getLogger(UploadMonitorImpl.class);
 -
 -    @Inject
 +	
 +    @Inject 
-     VMTemplateHostDao _vmTemplateHostDao;
-     @Inject 
      UploadDao _uploadDao;
      @Inject
      SecondaryStorageVmDao _secStorageVmDao;
@@@ -140,91 -144,89 +145,89 @@@
  	@Override
  	public UploadVO createNewUploadEntry(Long hostId, Long typeId, UploadVO.Status  uploadState,
  	                                        Type  type, String uploadUrl, Upload.Mode mode){
 -
 -        UploadVO uploadObj = new UploadVO(hostId, typeId, new Date(),
 +	       
 +        UploadVO uploadObj = new UploadVO(hostId, typeId, new Date(), 
                                            uploadState, type, uploadUrl, mode);
          _uploadDao.persist(uploadObj);
 -
 +        
          return uploadObj;
 -
 +	    
  	}
 -
 +	
  	@Override
- 	public void extractVolume(UploadVO uploadVolumeObj, HostVO sserver, VolumeVO volume, String url, Long dataCenterId, String installPath, long eventId, long asyncJobId, AsyncJobManager asyncMgr){				
+ 	public void extractVolume(UploadVO uploadVolumeObj, DataStore secStore, VolumeVO volume, String url, Long dataCenterId, String installPath, long eventId, long asyncJobId, AsyncJobManager asyncMgr){
 -
 +						
  		uploadVolumeObj.setUploadState(Upload.Status.NOT_UPLOADED);
  		_uploadDao.update(uploadVolumeObj.getId(), uploadVolumeObj);
 -
 -	    start();
 +				
 +	    start();		
  		UploadCommand ucmd = new UploadCommand(url, volume.getId(), volume.getSize(), installPath, Type.VOLUME);
- 		UploadListener ul = new UploadListener(sserver, _timer, _uploadDao, uploadVolumeObj, this, ucmd, volume.getAccountId(), volume.getName(), Type.VOLUME, eventId, asyncJobId, asyncMgr);
+ 		UploadListener ul = new UploadListener(secStore, _timer, _uploadDao, uploadVolumeObj, this, ucmd, volume.getAccountId(), volume.getName(), Type.VOLUME, eventId, asyncJobId, asyncMgr);
  		_listenerMap.put(uploadVolumeObj, ul);
  
  		try {
- 	        send(sserver.getId(), ucmd, ul);
-         } catch (AgentUnavailableException e) {
- 			s_logger.warn("Unable to start upload of volume " + volume.getName() + " from " + sserver.getName() + " to " +url, e);
+ 		    EndPoint ep = _epSelector.select(secStore);
+             ep.sendMessageAsync(ucmd, new UploadListener.Callback(ep.getId(), ul));
+         } catch (Exception e) {
+ 			s_logger.warn("Unable to start upload of volume " + volume.getName() + " from " + secStore.getName() + " to " +url, e);
  			ul.setDisconnected();
  			ul.scheduleStatusCheck(RequestType.GET_OR_RESTART);
 -        }
 +        }		
  	}
  
  	@Override
  	public Long extractTemplate( VMTemplateVO template, String url,
- 			VMTemplateHostVO vmTemplateHost,Long dataCenterId, long eventId, long asyncJobId, AsyncJobManager asyncMgr){
+ 			TemplateDataStoreVO vmTemplateHost,Long dataCenterId, long eventId, long asyncJobId, AsyncJobManager asyncMgr){
  
  		Type type = (template.getFormat() == ImageFormat.ISO) ? Type.ISO : Type.TEMPLATE ;
 -
 +				
- 		List<HostVO> storageServers = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.SecondaryStorage, dataCenterId);
- 		HostVO sserver = storageServers.get(0);			
+ 		DataStore secStore = this.storeMgr.getImageStore(dataCenterId);
 -
 +		
- 		UploadVO uploadTemplateObj = new UploadVO(sserver.getId(), template.getId(), new Date(), 
+ 		UploadVO uploadTemplateObj = new UploadVO(secStore.getId(), template.getId(), new Date(),
  													Upload.Status.NOT_UPLOADED, type, url, Mode.FTP_UPLOAD);
 -		_uploadDao.persist(uploadTemplateObj);
 -
 +		_uploadDao.persist(uploadTemplateObj);        		               
 +        		
  		if(vmTemplateHost != null) {
  		    start();
 -			UploadCommand ucmd = new UploadCommand(template, url, vmTemplateHost.getInstallPath(), vmTemplateHost.getSize());
 +			UploadCommand ucmd = new UploadCommand(template, url, vmTemplateHost.getInstallPath(), vmTemplateHost.getSize());	
- 			UploadListener ul = new UploadListener(sserver, _timer, _uploadDao, uploadTemplateObj, this, ucmd, template.getAccountId(), template.getName(), type, eventId, asyncJobId, asyncMgr);			
+ 			UploadListener ul = new UploadListener(secStore, _timer, _uploadDao, uploadTemplateObj, this, ucmd, template.getAccountId(), template.getName(), type, eventId, asyncJobId, asyncMgr);
  			_listenerMap.put(uploadTemplateObj, ul);
- 
- 			try {
- 	            send(sserver.getId(), ucmd, ul);
-             } catch (AgentUnavailableException e) {
- 				s_logger.warn("Unable to start upload of " + template.getUniqueName() + " from " + sserver.getName() + " to " +url, e);
+ 			try{
+ 			    EndPoint ep = _epSelector.select(secStore);
+                 ep.sendMessageAsync(ucmd, new UploadListener.Callback(ep.getId(), ul));
+             } catch (Exception e) {
+ 				s_logger.warn("Unable to start upload of " + template.getUniqueName() + " from " + secStore.getName() + " to " +url, e);
  				ul.setDisconnected();
  				ul.scheduleStatusCheck(RequestType.GET_OR_RESTART);
              }
  			return uploadTemplateObj.getId();
 -		}
 -		return null;
 -	}
 -
 +		}		
 +		return null;		
 +	}	
 +	
  	@Override
- 	public UploadVO createEntityDownloadURL(VMTemplateVO template, VMTemplateHostVO vmTemplateHost, Long dataCenterId, long eventId) {
+ 	public UploadVO createEntityDownloadURL(VMTemplateVO template, TemplateDataStoreVO vmTemplateHost, Long dataCenterId, long eventId) {
 -
 +	    
  	    String errorString = "";
  	    boolean success = false;
- 	    Host secStorage = ApiDBUtils.findHostById(vmTemplateHost.getHostId());	    
  	    Type type = (template.getFormat() == ImageFormat.ISO) ? Type.ISO : Type.TEMPLATE ;
 -
 -
 +	    
-         //Check if ssvm is up
-         HostVO ssvm = _ssvmMgr.pickSsvmHost(ApiDBUtils.findHostById(vmTemplateHost.getHostId()));
-         if( ssvm == null ) {
-             throw new CloudRuntimeException("There is no secondary storage VM for secondary storage host " + secStorage.getId());
-         }
 +	    
  	    //Check if it already exists.
 -	    List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(template.getId(), type, UploadVO.Status.DOWNLOAD_URL_CREATED);
 +	    List<UploadVO> extractURLList = _uploadDao.listByTypeUploadStatus(template.getId(), type, UploadVO.Status.DOWNLOAD_URL_CREATED);	    
  	    if (extractURLList.size() > 0) {
              return extractURLList.get(0);
          }
 -
 -	    // It doesn't exist so create a DB entry.
 +	    
 +	    // It doesn't exist so create a DB entry.	    
- 	    UploadVO uploadTemplateObj = new UploadVO(vmTemplateHost.getHostId(), template.getId(), new Date(), 
+ 	    UploadVO uploadTemplateObj = new UploadVO(vmTemplateHost.getDataStoreId(), template.getId(), new Date(),
 -	                                                Status.DOWNLOAD_URL_NOT_CREATED, 0, type, Mode.HTTP_DOWNLOAD);
 -	    uploadTemplateObj.setInstallPath(vmTemplateHost.getInstallPath());
 +	                                                Status.DOWNLOAD_URL_NOT_CREATED, 0, type, Mode.HTTP_DOWNLOAD); 
 +	    uploadTemplateObj.setInstallPath(vmTemplateHost.getInstallPath());	                                                
  	    _uploadDao.persist(uploadTemplateObj);
+ 
+ 	    // find an endpoint to send command
+ 	    DataStore store = this.storeMgr.getDataStore(vmTemplateHost.getDataStoreId(), DataStoreRole.Image);
+ 	    EndPoint ep = _epSelector.select(store);
  	    try{
      	    // Create Symlink at ssvm
  	    	String path = vmTemplateHost.getInstallPath();
@@@ -256,12 -257,12 +258,12 @@@
                  _uploadDao.update(uploadTemplateObj.getId(), uploadJob);
              }
  	    }
 -
 +	    
  	}
 -
 +	
  	@Override
-     public void createVolumeDownloadURL(Long entityId, String path, Type type, Long dataCenterId, Long uploadId) {
+     public void createVolumeDownloadURL(Long entityId, String path, Type type, Long dataCenterId, Long uploadId, ImageFormat format) {
 -
 +        
  	    String errorString = "";
  	    boolean success = false;
  	    try{
@@@ -278,20 -279,19 +280,19 @@@
              _uploadDao.update(uploadJob.getId(), uploadJob);
  
              // Create Symlink at ssvm
-             String uuid = UUID.randomUUID().toString() + path.substring(path.length() - 4) ; // last 4 characters of the path specify the format like .vhd
-             HostVO secStorage = ApiDBUtils.findHostById(ApiDBUtils.findUploadById(uploadId).getHostId());
-             HostVO ssvm = _ssvmMgr.pickSsvmHost(secStorage);
-             if( ssvm == null ) {
-             	errorString = "There is no secondary storage VM for secondary storage host " + secStorage.getName();
+             String uuid = UUID.randomUUID().toString() + "." + format.toString().toLowerCase() ;
+             DataStore secStore = this.storeMgr.getDataStore(ApiDBUtils.findUploadById(uploadId).getDataStoreId(), DataStoreRole.Image);
+             EndPoint ep = _epSelector.select(secStore);
+             if( ep == null ) {
+             	errorString = "There is no secondary storage VM for secondary storage host " + secStore.getName();
              	throw new CloudRuntimeException(errorString);
              }
 -
 +            
-             CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(secStorage.getParent(), path, uuid);
-             try {
- 	            send(ssvm.getId(), cmd, null);
-             } catch (AgentUnavailableException e) {
-                 errorString = "Unable to create a link for " +type+ " id:"+entityId + "," + e.getMessage();
-                 s_logger.warn(errorString, e);
+             CreateEntityDownloadURLCommand cmd = new CreateEntityDownloadURLCommand(((ImageStoreEntity)secStore).getMountPoint(), path, uuid);
+             Answer ans = ep.sendMessage(cmd);
+             if (ans == null || !ans.getResult()) {
+                 errorString = "Unable to create a link for " +type+ " id:"+entityId + "," + ans.getDetails();
+                 s_logger.warn(errorString);
                  throw new CloudRuntimeException(errorString);
              }
  
@@@ -340,21 -340,23 +341,23 @@@
  	            	hostname = hostname + ".realhostip.com";
  	            }	            
  	        }
 -	        return scheme + "://" + hostname + "/userdata/" + uuid;
 +	        return scheme + "://" + hostname + "/userdata/" + uuid; 
  	    }
 -
 +	
  
  
- 	public void send(Long hostId, Command cmd, Listener listener) throws AgentUnavailableException {
- 		_agentMgr.send(hostId, new Commands(cmd), listener);
- 	}
  
  	@Override
  	public boolean configure(String name, Map<String, Object> params)
  			throws ConfigurationException {
          final Map<String, String> configs = _configDao.getConfiguration("ManagementServer", params);
          _sslCopy = Boolean.parseBoolean(configs.get("secstorage.encrypt.copy"));
 -
 +        
+         String cert = configs.get("secstorage.secure.copy.cert");
+         if ("realhostip.com".equalsIgnoreCase(cert)) {
+         	s_logger.warn("Only realhostip.com ssl cert is supported, ignoring self-signed and other certs");
+         }
+ 
          _ssvmUrlDomain = configs.get("secstorage.ssl.cert.domain");      
          
          _agentMgr.registerForHostEvents(new UploadListener(this), true, false, false);
@@@ -378,12 -380,12 +381,12 @@@
  	}
  
  	@Override
 -	public boolean stop() {
 +	public boolean stop() {		
  		return true;
  	}
 -
 +	
- 	public void handleUploadEvent(HostVO host, Long accountId, String typeName, Type type, Long uploadId, com.cloud.storage.Upload.Status reason, long eventId) {
+ 	public void handleUploadEvent(Long accountId, String typeName, Type type, Long uploadId, com.cloud.storage.Upload.Status reason, long eventId) {
 -
 +		
  		if ((reason == Upload.Status.UPLOADED) || (reason==Upload.Status.ABANDONED)){
  			UploadVO uploadObj = new UploadVO(uploadId);
  			UploadListener oldListener = _listenerMap.get(uploadObj);
@@@ -459,17 -461,18 +462,18 @@@
  
          final int EXTRACT_URL_LIFE_LIMIT_IN_SECONDS = _urlExpirationInterval;
          List<UploadVO> extractJobs= _uploadDao.listByModeAndStatus(Mode.HTTP_DOWNLOAD, Status.DOWNLOAD_URL_CREATED);
 -
 +        
          for (UploadVO extractJob : extractJobs){
 -            if( getTimeDiff(extractJob.getLastUpdated()) > EXTRACT_URL_LIFE_LIMIT_IN_SECONDS ){
 +            if( getTimeDiff(extractJob.getLastUpdated()) > EXTRACT_URL_LIFE_LIMIT_IN_SECONDS ){                           
                  String path = extractJob.getInstallPath();
-                 HostVO secStorage = ApiDBUtils.findHostById(extractJob.getHostId());
+                 DataStore secStore = this.storeMgr.getDataStore(extractJob.getDataStoreId(), DataStoreRole.Image);
+ 
 -
 +                
                  // Would delete the symlink for the Type and if Type == VOLUME then also the volume
-                 DeleteEntityDownloadURLCommand cmd = new DeleteEntityDownloadURLCommand(path, extractJob.getType(),extractJob.getUploadUrl(), secStorage.getParent());
-                 HostVO ssvm = _ssvmMgr.pickSsvmHost(secStorage);
-                 if( ssvm == null ) {
-                 	s_logger.warn("UploadMonitor cleanup: There is no secondary storage VM for secondary storage host " + extractJob.getHostId());
+                 DeleteEntityDownloadURLCommand cmd = new DeleteEntityDownloadURLCommand(path, extractJob.getType(),extractJob.getUploadUrl(), ((ImageStoreVO)secStore).getParent());
+                 EndPoint ep = _epSelector.select(secStore);
+                  if( ep == null ) {
+                 	s_logger.warn("UploadMonitor cleanup: There is no secondary storage VM for secondary storage host " + extractJob.getDataStoreId());
                  	continue; //TODO: why continue? why not break?
                  }
                  if (s_logger.isDebugEnabled()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/template/TemplateAdapterBase.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/template/TemplateAdapterBase.java
index 9b6487b,c1f0604..8e01063
--- a/server/src/com/cloud/template/TemplateAdapterBase.java
+++ b/server/src/com/cloud/template/TemplateAdapterBase.java
@@@ -27,10 -27,9 +27,10 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
  import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
  import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
 +import org.apache.cloudstack.context.CallContext;
  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.cloudstack.storage.datastore.db.TemplateDataStoreDao;
  import org.apache.log4j.Logger;
  
  import com.cloud.api.ApiDBUtils;
@@@ -99,31 -100,24 +100,24 @@@ public abstract class TemplateAdapterBa
  	            (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
  	}
  
+ 	@Override
 -    public TemplateProfile prepare(boolean isIso, Long userId, String name, String displayText, Integer bits,
 +	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 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, null);
+ 	            chksum, bootable, null, null, details, false, null, false);
  	}
 -
 +	
+ 	@Override
 -    public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits,
 +	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,
- 			String imageStoreUuid) throws ResourceAllocationException {
+ 			String imageStoreUuid, Boolean isDynamicallyScalable) 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;
  		}
@@@ -216,57 -211,54 +211,54 @@@
                  throw new IllegalArgumentException("Cannot use reserved names for templates");
              }
          }
 -
 +        
-         DataStore imageStore = this.templateMgr.getImageStore(imageStoreUuid, zoneId);
-         if (imageStore == null) {
-             throw new IllegalArgumentException("Cann't find an image store");
-         }
-         Long imageStoreId = imageStore.getId();
-         
          Long id = _tmpltDao.getNextInSequence(Long.class, "id");
 -        UserContext.current().setEventDetails("Id: " +id+ " name: " + name);
 +        CallContext.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, imageStoreId);
+ 				featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, null, isDynamicallyScalable);
+ 
  	}
 -
 +	
  	@Override
  	public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
  	    //check if the caller can operate with the template owner
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
          _accountMgr.checkAccess(caller, null, true, owner);
 +	    
  
 -
 -
 -		return prepare(false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(),
 +        
 +		return prepare(false, CallContext.current().getCallingUserId(), 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.getImageStoreUuid());
+ 				cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails(), cmd.isSshKeyEnabled(), null, cmd.isDynamicallyScalable());
+ 
  	}
  
+ 	@Override
 -    public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
 +	public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
  	    //check if the caller can operate with the template owner
 -	    Account caller = UserContext.current().getCaller();
 +	    Account caller = CallContext.current().getCallingAccount();
  	    Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId());
  	    _accountMgr.checkAccess(caller, null, true, owner);
 -
 -		return prepare(true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false,
 +	   
 +		return prepare(true, CallContext.current().getCallingUserId(), 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.getImageStoreUuid());
+ 					cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null, false, cmd.getImageStoreUuid(), cmd.isDynamicallyScalable());
  	}
 -
 +	
  	protected VMTemplateVO persistTemplate(TemplateProfile profile) {
  		Long zoneId = profile.getZoneId();
  		VMTemplateVO template = new VMTemplateVO(profile.getTemplateId(), profile.getName(), profile.getFormat(), profile.getIsPublic(),
  				profile.getFeatured(), profile.getIsExtractable(), TemplateType.USER, profile.getUrl(), profile.getRequiresHVM(),
  				profile.getBits(), profile.getAccountId(), profile.getCheckSum(), profile.getDisplayText(),
 -				profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(),
 +				profile.getPasswordEnabled(), profile.getGuestOsId(), profile.getBootable(), profile.getHypervisorType(), profile.getTemplateTag(), 
  				profile.getDetails(), profile.getSshKeyEnabled());
  
- 		template.setImageDataStoreId(profile.getImageStoreId());
+ 
  		if (zoneId == null || zoneId.longValue() == -1) {
              List<DataCenterVO> dcs = _dcDao.listAll();
 -
 +            
              if (dcs.isEmpty()) {
              	throw new CloudRuntimeException("No zones are present in the system, can't add template");
              }
@@@ -315,11 -307,12 +307,12 @@@
  
  		return userId;
  	}
 -
 +	
+ 	@Override
 -    public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
 +	public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
  		Long templateId = cmd.getId();
 -		Long userId = UserContext.current().getCallerUserId();
 -		Account account = UserContext.current().getCaller();
 +		Long userId = CallContext.current().getCallingUserId();
 +		Account account = CallContext.current().getCallingAccount();
  		Long zoneId = cmd.getZoneId();
  
  		VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
@@@ -378,6 -371,8 +371,8 @@@
      	return new TemplateProfile(userId, template, zoneId);
  	}
  
+ 	@Override
 -    abstract public VMTemplateVO create(TemplateProfile profile);
 +	abstract public VMTemplateVO create(TemplateProfile profile);
+ 	@Override
 -    abstract public boolean delete(TemplateProfile profile);
 +	abstract public boolean delete(TemplateProfile profile);
  }


[47/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --cc engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index 97a3990,0000000..f378f4f
mode 100755,000000..100755
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@@ -1,3771 -1,0 +1,3771 @@@
 +// 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.vm;
 +
 +import java.net.URI;
 +import java.sql.PreparedStatement;
 +import java.sql.ResultSet;
 +import java.sql.SQLException;
 +import java.util.ArrayList;
 +import java.util.Collection;
 +import java.util.Date;
 +import java.util.HashMap;
 +import java.util.List;
 +import java.util.Map;
 +import java.util.TimeZone;
 +import java.util.concurrent.Executors;
 +import java.util.concurrent.ScheduledExecutorService;
 +import java.util.concurrent.TimeUnit;
 +import java.util.concurrent.TimeoutException;
 +
 +import javax.ejb.Local;
 +import javax.inject.Inject;
 +import javax.naming.ConfigurationException;
 +
 +import org.apache.log4j.Logger;
 +
 +import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
 +import org.apache.cloudstack.config.ConfigDepot;
 +import org.apache.cloudstack.config.ConfigKey;
 +import org.apache.cloudstack.config.ConfigValue;
 +import org.apache.cloudstack.config.Configurable;
 +import org.apache.cloudstack.context.CallContext;
 +import org.apache.cloudstack.engine.service.api.OrchestrationService;
 +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 +import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
 +import org.apache.cloudstack.framework.jobs.AsyncJob;
 +import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 +import org.apache.cloudstack.framework.jobs.Outcome;
 +import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
 +import org.apache.cloudstack.framework.messagebus.MessageBus;
 +import org.apache.cloudstack.framework.messagebus.MessageDispatcher;
 +import org.apache.cloudstack.framework.messagebus.MessageHandler;
 +import org.apache.cloudstack.jobs.JobInfo;
 +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 +import org.apache.cloudstack.vm.jobs.VmWorkJobDao;
 +import org.apache.cloudstack.vm.jobs.VmWorkJobVO;
 +import org.apache.cloudstack.vm.jobs.VmWorkJobVO.Step;
 +
 +import com.cloud.agent.AgentManager;
 +import com.cloud.agent.AgentManager.OnError;
 +import com.cloud.agent.Listener;
 +import com.cloud.agent.api.AgentControlAnswer;
 +import com.cloud.agent.api.AgentControlCommand;
 +import com.cloud.agent.api.Answer;
 +import com.cloud.agent.api.CheckVirtualMachineAnswer;
 +import com.cloud.agent.api.CheckVirtualMachineCommand;
 +import com.cloud.agent.api.ClusterSyncAnswer;
 +import com.cloud.agent.api.Command;
 +import com.cloud.agent.api.MigrateAnswer;
 +import com.cloud.agent.api.MigrateCommand;
 +import com.cloud.agent.api.PingRoutingCommand;
 +import com.cloud.agent.api.PlugNicAnswer;
 +import com.cloud.agent.api.PlugNicCommand;
 +import com.cloud.agent.api.PrepareForMigrationAnswer;
 +import com.cloud.agent.api.PrepareForMigrationCommand;
 +import com.cloud.agent.api.RebootAnswer;
 +import com.cloud.agent.api.RebootCommand;
 +import com.cloud.agent.api.StartAnswer;
 +import com.cloud.agent.api.StartCommand;
 +import com.cloud.agent.api.StartupCommand;
 +import com.cloud.agent.api.StartupRoutingCommand;
 +import com.cloud.agent.api.StopAnswer;
 +import com.cloud.agent.api.StopCommand;
 +import com.cloud.agent.api.UnPlugNicAnswer;
 +import com.cloud.agent.api.UnPlugNicCommand;
 +import com.cloud.agent.api.to.NicTO;
 +import com.cloud.agent.api.to.VirtualMachineTO;
 +import com.cloud.agent.manager.Commands;
 +import com.cloud.agent.manager.allocator.HostAllocator;
 +import com.cloud.alert.AlertManager;
 +import com.cloud.dc.ClusterDetailsDao;
 +import com.cloud.dc.ClusterDetailsVO;
 +import com.cloud.dc.ClusterVO;
 +import com.cloud.dc.DataCenter;
 +import com.cloud.dc.DataCenterVO;
 +import com.cloud.dc.HostPodVO;
 +import com.cloud.deploy.DataCenterDeployment;
 +import com.cloud.deploy.DeployDestination;
 +import com.cloud.deploy.DeploymentPlan;
 +import com.cloud.deploy.DeploymentPlanner;
 +import com.cloud.deploy.DeploymentPlanner.ExcludeList;
 +import com.cloud.deploy.DeploymentPlanningManager;
 +import com.cloud.exception.AffinityConflictException;
 +import com.cloud.exception.AgentUnavailableException;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.ConnectionException;
 +import com.cloud.exception.InsufficientAddressCapacityException;
 +import com.cloud.exception.InsufficientCapacityException;
 +import com.cloud.exception.InsufficientServerCapacityException;
 +import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
 +import com.cloud.exception.InvalidParameterValueException;
 +import com.cloud.exception.ManagementServerException;
 +import com.cloud.exception.OperationTimedoutException;
 +import com.cloud.exception.ResourceUnavailableException;
 +import com.cloud.exception.VirtualMachineMigrationException;
 +import com.cloud.ha.HighAvailabilityManager;
 +import com.cloud.ha.HighAvailabilityManager.WorkType;
 +import com.cloud.host.Host;
 +import com.cloud.host.HostVO;
 +import com.cloud.host.Status;
 +import com.cloud.host.dao.HostDao;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.hypervisor.HypervisorGuru;
 +import com.cloud.hypervisor.HypervisorGuruManager;
 +import com.cloud.network.Network;
 +import com.cloud.network.NetworkManager;
 +import com.cloud.network.NetworkModel;
 +import com.cloud.network.dao.NetworkVO;
 +import com.cloud.network.rules.RulesManager;
 +import com.cloud.offering.ServiceOffering;
 +import com.cloud.org.Cluster;
 +import com.cloud.resource.ResourceManager;
 +import com.cloud.service.ServiceOfferingVO;
 +import com.cloud.storage.DiskOfferingVO;
 +import com.cloud.storage.GuestOSVO;
 +import com.cloud.storage.GuestOsCategory;
 +import com.cloud.storage.Storage.ImageFormat;
 +import com.cloud.storage.StoragePool;
 +import com.cloud.storage.VMTemplateVO;
 +import com.cloud.storage.Volume;
 +import com.cloud.storage.Volume.Type;
 +import com.cloud.storage.VolumeManager;
 +import com.cloud.storage.VolumeVO;
 +import com.cloud.storage.dao.StoragePoolHostDao;
 +import com.cloud.storage.dao.VolumeDao;
 +import com.cloud.user.Account;
 +import com.cloud.user.User;
 +import com.cloud.utils.DateUtil;
 +import com.cloud.utils.Journal;
 +import com.cloud.utils.Pair;
 +import com.cloud.utils.Predicate;
 +import com.cloud.utils.StringUtils;
 +import com.cloud.utils.Ternary;
 +import com.cloud.utils.component.ManagerBase;
 +import com.cloud.utils.concurrency.NamedThreadFactory;
 +import com.cloud.utils.db.DB;
 +import com.cloud.utils.db.EntityManager;
 +import com.cloud.utils.db.GlobalLock;
 +import com.cloud.utils.db.SearchBuilder;
 +import com.cloud.utils.db.SearchCriteria;
 +import com.cloud.utils.db.Transaction;
 +import com.cloud.utils.exception.CloudRuntimeException;
 +import com.cloud.utils.exception.ExecutionException;
 +import com.cloud.utils.fsm.NoTransitionException;
 +import com.cloud.utils.fsm.StateMachine;
 +import com.cloud.utils.fsm.StateMachine2;
 +import com.cloud.vm.VirtualMachine.Event;
 +import com.cloud.vm.VirtualMachine.PowerState;
 +import com.cloud.vm.VirtualMachine.State;
 +import com.cloud.vm.dao.NicDao;
 +import com.cloud.vm.dao.UserVmDetailsDao;
 +import com.cloud.vm.dao.VMInstanceDao;
 +import com.cloud.vm.snapshot.VMSnapshotManager;
 +
 +@Local(value = VirtualMachineManager.class)
 +public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, Listener, Configurable {
 +    private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
 +
 +    private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert";
 +    
 +    protected static final ConfigKey<Integer> StartRetry = new ConfigKey<Integer>(
 +            Integer.class, "start.retry", "Advanced", OrchestrationService.class, "10", "Number of times to retry create and start commands", true, null);
 +    protected static final ConfigKey<Long> VmOpWaitInterval = new ConfigKey<Long>(
 +            Long.class, "vm.op.wait.interval", "Advanced", OrchestrationService.class, "120", "Time (in seconds) to wait before checking if a previous operation has succeeded",
 +            true, null);
 +    protected static final ConfigKey<Integer> VmOpLockStateRetry = new ConfigKey<Integer>(
 +            Integer.class, "vm.op.lock.state.retry", "Advanced", OrchestrationService.class, "5", "Times to retry locking the state of a VM for operations",
 +            true, "-1 means try forever");
 +    protected static final ConfigKey<Long> VmOpCleanupInterval = new ConfigKey<Long>(
 +            Long.class, "vm.op.cleanup.interval", "Advanced", OrchestrationService.class, "86400", "Interval to run the thread that cleans up the vm operations (in seconds)",
 +            false, "Seconds");
 +    protected static final ConfigKey<Long> VmOpCleanupWait = new ConfigKey<Long>(
 +            Long.class, "vm.op.cleanup.wait", "Advanced", OrchestrationService.class, "3600", "Time (in seconds) to wait before cleanuping up any vm work items", false, "Seconds");
 +    protected static final ConfigKey<Integer> VmOpCancelInterval = new ConfigKey<Integer>(
 +            Integer.class, "vm.op.cancel.interval", "Advanced", OrchestrationService.class, "3600", "Time (in seconds) to wait before cancelling a operation", false, "Seconds");
 +    protected static final ConfigKey<Integer> Wait = new ConfigKey<Integer>(
 +            Integer.class, "wait", "Advanced", OrchestrationService.class, "1800", "Time in seconds to wait for control commands to return", false, null);
 +    protected static final ConfigKey<Boolean> VmDestroyForceStop = new ConfigKey<Boolean>(
 +            Boolean.class, "vm.destroy.forcestop", "Advanced", OrchestrationService.class, "false", "On destroy, force-stop takes this value ", true, null);
 +
 +    // New
 +    protected static final ConfigKey<Long> VmJobCheckInterval = new ConfigKey<Long>(
 +            Long.class, "vm.job.check.interval", "VM Orchestration", OrchestrationService.class, "3000", "Interval in milliseconds to check if the job is complete", true,
 +            "Milliseconds");
 +    protected static final ConfigKey<Long> VmJobTimeout = new ConfigKey<Long>(
 +            Long.class, "vm.job.timeout", "VM Orchestration", OrchestrationService.class, "600000", "Time in milliseconds to wait before attempting to cancel a job", true,
 +            "Milliseconds");
 +    protected static final ConfigKey<Long> PingInterval = new ConfigKey<Long>(
 +            Long.class, "ping.interval", "Advanced", OrchestrationService.class, "60", "Ping interval in seconds", false, null);
 +
 +    protected static final StateMachine<Step, VirtualMachine.Event> MigrationStateMachine = new StateMachine<Step, VirtualMachine.Event>();
 +    static {
 +        MigrationStateMachine.addTransition(null, VirtualMachine.Event.MigrationRequested, Step.Prepare);
 +        MigrationStateMachine.addTransition(Step.Prepare, VirtualMachine.Event.OperationSucceeded, Step.Migrating);
 +        MigrationStateMachine.addTransition(Step.Prepare, VirtualMachine.Event.OperationFailed, Step.Error);
 +        MigrationStateMachine.addTransition(Step.Migrating, VirtualMachine.Event.OperationSucceeded, Step.Started);
 +        MigrationStateMachine.addTransition(Step.Migrating, VirtualMachine.Event.OperationFailed, Step.Error);
 +        MigrationStateMachine.addTransition(Step.Started, VirtualMachine.Event.OperationSucceeded, Step.Done);
 +        MigrationStateMachine.addTransition(Step.Started, VirtualMachine.Event.OperationFailed, Step.Error);
 +    }
 +
 +    @Inject
 +    protected EntityManager _entityMgr;
 +    @Inject
 +    ConfigDepot _configDepot;
 +    @Inject
 +    DataStoreManager _dataStoreMgr;
 +    @Inject
 +    protected NetworkManager _networkMgr;
 +    @Inject
 +    protected NetworkModel _networkModel;
 +    @Inject
 +    protected AgentManager _agentMgr;
 +    @Inject
 +    protected VMInstanceDao _vmDao;
 +    @Inject
 +    protected NicDao _nicsDao;
 +    @Inject
 +    protected HostDao _hostDao;
 +    @Inject
 +    protected AlertManager _alertMgr;
 +    @Inject
 +    protected VolumeDao _volsDao;
 +    @Inject
 +    protected HighAvailabilityManager _haMgr;
 +    @Inject
 +    protected HypervisorGuruManager _hvGuruMgr;
 +    @Inject
 +    protected StoragePoolHostDao _poolHostDao;
 +    @Inject
 +    protected RulesManager _rulesMgr;
 +    @Inject
 +    protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
 +
 +    @Inject
 +    protected List<DeploymentPlanner> _planners;
 +
 +    protected List<HostAllocator> _hostAllocators;
 +
 +    public List<HostAllocator> getHostAllocators() {
 +        return _hostAllocators;
 +    }
 +
 +    public void setHostAllocators(List<HostAllocator> hostAllocators) {
 +        _hostAllocators = hostAllocators;
 +    }
 +
 +	@Inject
 +    protected List<StoragePoolAllocator> _storagePoolAllocators;
 +
 +    @Inject
 +    protected ResourceManager _resourceMgr;
 +    
 +    @Inject
 +    protected VMSnapshotManager _vmSnapshotMgr = null;
 +    @Inject
 +    protected ClusterDetailsDao  _clusterDetailsDao;
 +    @Inject
 +    protected UserVmDetailsDao _uservmDetailsDao;
 +    
 +    @Inject
 +    VolumeManager _volumeMgr;
 +    
 +    @Inject protected MessageBus _messageBus;
 +    @Inject protected VirtualMachinePowerStateSync _syncMgr;
 +    @Inject protected VmWorkJobDao _workJobDao;
 +    @Inject protected AsyncJobManager _jobMgr;
 +    @Inject
 +    DeploymentPlanningManager _dpMgr;
 +
 +    Map<VirtualMachine.Type, VirtualMachineGuru> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
 +    protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
 +
 +    ScheduledExecutorService _executor = null;
 +
 +    protected ConfigValue<Integer> _retry;
 +    protected ConfigValue<Integer> _cancelWait;
 +    protected ConfigValue<Long> _cleanupWait;
 +    protected ConfigValue<Long> _cleanupInterval;
 +    protected ConfigValue<Long> _opWaitInterval;
 +    protected ConfigValue<Integer> _lockStateRetry;
 +    protected ConfigValue<Integer> _operationTimeout;
 +    protected ConfigValue<Boolean> _forceStop;
 +    protected ConfigValue<Long> _pingInterval;
 +    protected ConfigValue<Long> _jobCheckInterval;
 +    protected ConfigValue<Long> _jobTimeout;
 +
 +    protected long _nodeId;
 +
 +    SearchBuilder<VolumeVO> RootVolumeSearch;
 +
 +    @Override
 +    public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru) {
 +        synchronized (_vmGurus) {
 +            _vmGurus.put(type, guru);
 +        }
 +    }
 +    
 +    private VirtualMachineGuru getVmGuru(VirtualMachine vm) {
 +        return _vmGurus.get(vm.getType());
 +    }
 +
 +    @Override
 +    @DB
 +    public boolean allocate(String vmInstanceName, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering,
 +            List<Pair<DiskOfferingVO, Long>> dataDiskOfferings, List<Pair<NetworkVO, NicProfile>> networks, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan plan,
 +            HypervisorType hyperType, Account owner) {
 +        assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
 +
 +        VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Allocating entries for VM: " + vm);
 +        }
 +
 +        VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, serviceOffering, owner, params);
 +
 +        vm.setDataCenterId(plan.getDataCenterId());
 +        if (plan.getPodId() != null) {
 +            vm.setPodId(plan.getPodId());
 +        }
 +
 +        Transaction txn = Transaction.currentTxn();
 +        txn.start();
 +        _vmDao.update(vm.getId(), vm);
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Allocating nics for " + vm);
 +        }
 +
 +        try {
 +            _networkMgr.allocate(vmProfile, networks);
 +        } catch (ConcurrentOperationException e) {
 +            throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
 +        } catch (InsufficientCapacityException e) {
 +            throw new CloudRuntimeException("Insufficient Capacity to create a vm ", e);
 +        }
 +
 +        if (dataDiskOfferings == null) {
 +            dataDiskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(0);
 +        }
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Allocating disks for " + vm);
 +        }
 +
 +        if (template.getFormat() == ImageFormat.ISO) {
 +            _volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vm, owner);
 +        } else if (template.getFormat() == ImageFormat.BAREMETAL) {
 +            // Do nothing
 +        } else {
 +            _volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vm.getId(), rootDiskOffering.first(), template, vm, owner);
 +        }
 +
 +        for (Pair<DiskOfferingVO, Long> offering : dataDiskOfferings) {
 +            _volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vm.getId(), offering.first(), offering.second(), vm, owner);
 +        }
 +
 +        txn.commit();
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Allocation completed for VM: " + vm);
 +        }
 +
 +        return true;
 +    }
 +
 +    @Override
 +    public boolean allocate(String vmInstanceName, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks,
 +            DeploymentPlan plan, HypervisorType hyperType, Account owner) {
 +        return allocate(vmInstanceName, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner);
 +    }
 +
 +    @Override
 +    public void expunge(String vmUuid) {
 +        try {
 +            advanceExpunge(vmUuid);
 +        } catch (OperationTimedoutException e) {
 +            throw new CloudRuntimeException("Operation timed out", e);
 +        } catch (ConcurrentOperationException e) {
 +            throw new CloudRuntimeException("Concurrent operation ", e);
 +        } catch (ResourceUnavailableException e) {
 +            throw new CloudRuntimeException("Resource is unavailable ", e);
 +        }
 +    }
 +
 +    @Override
 +    public void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException,
 +            ConcurrentOperationException {
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        if (vm == null || vm.getRemoved() != null) {
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
 +            }
 +            return;
 +        }
 +
 +        stop(vmUuid, false);
 +
 +        vm = _vmDao.findByUuid(vmUuid);
 +        try {
 +            if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
 +                throw new CloudRuntimeException("Unable to detroy the VM because it is not in the correct state: " + vm);
 +            }
 +        } catch (NoTransitionException e) {
 +            throw new CloudRuntimeException("Unable to destroy the vm because it is not in the correct state: " + vm);
 +        }
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Destroying vm " + vm);
 +        }
 +
 +        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 +        s_logger.debug("Cleaning up NICS");
 +        _networkMgr.cleanupNics(profile);
 +        // Clean up volumes based on the vm's instance id
 +        _volumeMgr.cleanupVolumes(vm.getId());
 +
 +        VirtualMachineGuru guru = getVmGuru(vm);
 +        guru.finalizeExpunge(vm);
 +        //remove the overcommit detials from the uservm details
 +        _uservmDetailsDao.deleteDetails(vm.getId());
 +
 +        // send hypervisor-dependent commands before removing
 +        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
 +        List<Command> finalizeExpungeCommands = hvGuru.finalizeExpunge(vm);
 +        if(finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0){
 +            Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
 +            if(hostId != null){
 +                Commands cmds = new Commands(OnError.Stop);
 +                for (Command command : finalizeExpungeCommands) {
 +                    cmds.addCommand(command);
 +                }
 +                _agentMgr.send(hostId, cmds);
 +                if(!cmds.isSuccessful()){
 +                    for (Answer answer : cmds.getAnswers()){
 +                        if(answer != null && !answer.getResult()){
 +                            s_logger.warn("Failed to expunge vm due to: " + answer.getDetails());
 +                            break;
 +                        }
 +                    }
 +                    throw new CloudRuntimeException("Failed the expunge the vm on the hypervisor");
 +                }
 +            }
 +        }
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Expunged " + vm);
 +        }
 +        
 +        _vmDao.remove(vm.getId());
 +    }
 +    
 +    @Override
 +    public boolean start() {
 +        _executor.scheduleAtFixedRate(new TransitionTask(), _pingInterval.value(), _pingInterval.value(), TimeUnit.SECONDS);
 +        _executor.scheduleAtFixedRate(new CleanupTask(), _pingInterval.value()*2, _pingInterval.value()*2, TimeUnit.SECONDS);
 +
 +        // cancel jobs left-over from last run
 +        cancelWorkItems(_nodeId);
 +        
 +        return true;
 +    }
 + 
 +    @Override
 +    public boolean stop() {
 +        return true;
 +    }
 +
 +    @Override
 +    public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
 +        _retry = _configDepot.get(StartRetry);
 +
 +        _pingInterval = _configDepot.get(PingInterval).setMultiplier(1000);
 +        _cancelWait = _configDepot.get(VmOpCancelInterval);
 +        _cleanupWait = _configDepot.get(VmOpCleanupWait);
 +        _cleanupInterval = _configDepot.get(VmOpCleanupInterval).setMultiplier(1000);
 +        _opWaitInterval = _configDepot.get(VmOpWaitInterval).setMultiplier(1000);
 +        _lockStateRetry = _configDepot.get(VmOpLockStateRetry);
 +        _operationTimeout = _configDepot.get(Wait).setMultiplier(2);
 +        _forceStop = _configDepot.get(VmDestroyForceStop);
 +        _jobCheckInterval = _configDepot.get(VmJobCheckInterval);
 +        _jobTimeout = _configDepot.get(VmJobTimeout);
 +
 +        ReservationContextImpl.setComponents(_entityMgr);
 +        VirtualMachineProfileImpl.setComponents(_entityMgr);
 +        VmWorkMigrate.init(_entityMgr);
 +
 +        _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
 +
 +        _agentMgr.registerForHostEvents(this, true, true, true);
 +        
 +        RootVolumeSearch = _entityMgr.createSearchBuilder(VolumeVO.class);
 +        VolumeVO rvsEntity = RootVolumeSearch.entity();
 +        RootVolumeSearch.and(rvsEntity.getVolumeType(), SearchCriteria.Op.EQ).values(Volume.Type.ROOT)
 +                .and(rvsEntity.getState(), SearchCriteria.Op.EQ).values(Volume.State.Ready)
 +                .and(rvsEntity.getInstanceId(), SearchCriteria.Op.EQ, "instance")
 +                .and(rvsEntity.getDeviceId(), SearchCriteria.Op.EQ).values(0)
 +                .done();
 +
 +        
 +        _messageBus.subscribe(Topics.VM_POWER_STATE, MessageDispatcher.getDispatcher(this));
 +
 +        return true;
 +    }
 +
 +    protected VirtualMachineManagerImpl() {
 +        setStateMachine();
 +    }
 +
 +    @Override
 +    public void easyStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) {
 +        easyStart(vmUuid, params, null);
 +    }
 +
 +    @Override
 +    public void easyStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy) {
 +        Outcome<VirtualMachine> outcome = start(vmUuid, params, planToDeploy);
 +        try {
 +            outcome.get(_jobTimeout.value(), TimeUnit.MILLISECONDS);
 +        } catch (InterruptedException e) {
 +            // FIXME: What to do
 +        } catch (java.util.concurrent.ExecutionException e) {
 +            // FIXME: What to do
 +        } catch (TimeoutException e) {
 +            // FIXME: What to do
 +        }
 +    }
 +
 +    /*
 +        protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException {
 +            while (true) {
 +                VmWorkJobVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
 +                if (vo == null) {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state);
 +                    }
 +                    return true;
 +                }
 +
 +                if (vo.getStep() == Step.Done) {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Work for " + vm + " is " + vo.getStep());
 +                    }
 +                    return true;
 +                }
 +
 +                if (vo.getSecondsTaskIsInactive() > _cancelWait) {
 +                    s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
 +                    return false;
 +                }
 +
 +                try {
 +                    Thread.sleep(_opWaitInterval);
 +                } catch (InterruptedException e) {
 +                    s_logger.info("Waiting for " + vm + " but is interrupted");
 +                    throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
 +                }
 +                s_logger.debug("Waiting some more to make sure there's no activity on " + vm);
 +            }
 +        }
 +    */
 +    
 +    /*
 +        @DB
 +        protected VirtualMachineernary<T, ReservationContext, VmWorkJobVO> changeToStartState(VirtualMachineGuru<T> vmGuru, String vmUuid, User caller, Account account)
 +                throws ConcurrentOperationException {
 +            long vmId = vm.getId();
 +
 +            VmWorkJobVO work = new VmWorkJobVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
 +            int retry = _lockStateRetry;
 +            while (retry-- != 0) {
 +                Transaction txn = Transaction.currentTxn();
 +                Ternary<T, ReservationContext, VmWorkJobVO> result = null;
 +                txn.start();
 +                try {
 +                    Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
 +                    work = _workDao.persist(work);
 +                    ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
 +
 +                    if (stateTransitTo(vm, VirtualMachine.Event.StartRequested, null, work.getId())) {
 +                        if (s_logger.isDebugEnabled()) {
 +                            s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
 +                        }
 +                        result = new Ternary<T, ReservationContext, VmWorkJobVO>(vmGuru.findById(vmId), context, work);
 +                        txn.commit();
 +                        return result;
 +                    }
 +                } catch (NoTransitionException e) {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
 +                    }
 +                } finally {
 +                    if (result == null) {
 +                        txn.rollback();
 +                    }
 +                }
 +
 +                VMInstanceVO instance = _vmDao.findById(vmId);
 +                if (instance == null) {
 +                    throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
 +                }
 +
 +                if (s_logger.isDebugEnabled()) {
 +                    s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ".  Retry=" + retry);
 +                }
 +
 +                State state = instance.getState();
 +                if (state == State.Running) {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("VM is already started: " + vm);
 +                    }
 +                    return null;
 +                }
 +
 +                if (state.isTransitional()) {
 +                    if (!checkWorkItems(vm, state)) {
 +                        throw new ConcurrentOperationException("There are concurrent operations on " + vm);
 +                    } else {
 +                        continue;
 +                    }
 +                }
 +
 +                if (state != State.Stopped) {
 +                    s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
 +                    return null;
 +                }
 +            }
 +
 +            throw new ConcurrentOperationException("Unable to change the state of " + vm);
 +        }
 +    */
 +
 +    @DB
 +    protected Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO> changeToStartState(VirtualMachineGuru vmGuru, VMInstanceVO vm, User caller, Account account)
 +        throws ConcurrentOperationException {
 +    	
 +        Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO> result = null;
 +        Transaction txn = Transaction.currentTxn();
 +        txn.start();
 +        try {
 +	        VmWorkJobVO work = _workJobDao.findById(AsyncJobExecutionContext.getCurrentExecutionContext().getJob().getId());
 +	        
 +	        Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
 +	        ReservationContextImpl context = new ReservationContextImpl(work.getUuid(), journal, caller, account);
 +            if (stateTransitTo(vm, VirtualMachine.Event.StartRequested, null, work.getUuid())) {
 +	            if (s_logger.isDebugEnabled()) {
 +	                s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
 +	            }
 +                result = new Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO>(_vmDao.findById(vm.getId()), context, work);
 +	            txn.commit();
 +	            return result;
 +	        }
 +        } catch (NoTransitionException e) {
 +            s_logger.warn("Unable to transition into Starting state due to " + e.getMessage());
 +        } finally {
 +        	if(result == null)
 +        		txn.rollback();
 +        }
 +        
 +        throw new ConcurrentOperationException("Unable to change the state of " + vm);
 +    }
 +    
 +    @DB
 +    protected boolean changeState(VMInstanceVO vm, Event event, Long hostId, VmWorkJobVO work, Step step) throws NoTransitionException {
 +        VmWorkJobVO.Step previousStep = work.getStep();
 +        
 +        Transaction txn = Transaction.currentTxn();
 +
 +        txn.start();
 +        work.setStep(step);
 +        boolean result = stateTransitTo(vm, event, hostId);
 +        if (!result) {
 +            work.setStep(previousStep);
 +        }
 +        _workJobDao.update(work.getId(), work);
 +        txn.commit();
 +        return result;
 +    }
 +    
 +    @DB
 +    protected void changeState2(VMInstanceVO vm, VirtualMachine.Event vmEvent, Long hostId, VmWorkJobVO work, VirtualMachine.Event workEvent) throws NoTransitionException {
 +        VmWorkJobVO.Step currentStep = work.getStep();
 +        StateMachine<Step, Event> sm = work.getCmd() == VmWorkJobDispatcher.Migrate ? MigrationStateMachine : null;
 +
 +        Transaction txn = Transaction.currentTxn();
 +
 +        txn.start();
 +        if (vmEvent != null) {
 +            if (!stateTransitTo(vm, vmEvent, hostId)) {
 +                throw new NoTransitionException("Unable to transit the vm state");
 +            }
 +        }
 +        work.setStep(sm.getNextState(currentStep, workEvent));
 +        _workJobDao.update(work.getId(), work);
 +        txn.commit();
 +        return;
 +    }
 +
 +    protected boolean areAffinityGroupsAssociated(VirtualMachineProfile vmProfile) {
 +        VirtualMachine vm = vmProfile.getVirtualMachine();
 +        long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
 +
 +        if (vmGroupCount > 0) {
 +            return true;
 +        }
 +        return false;
 +    }
 +
 +    @Override
 +    @DB
 +    public Outcome<VirtualMachine> start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy) {
 +        CallContext context = CallContext.current();
 +        User callingUser = context.getCallingUser();
 +        Account callingAccount = context.getCallingAccount();
 +
 +        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +    	
 +    	VmWorkJobVO workJob = null;
 +    	Transaction txn = Transaction.currentTxn();
 +        txn.start();
 +
 +        _vmDao.lockRow(vm.getId(), true);
 +
 +        List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
 +
 +        if (pendingWorkJobs.size() > 0) {
 +            assert (pendingWorkJobs.size() == 1);
 +            workJob = pendingWorkJobs.get(0);
 +        } else {
 +            workJob = new VmWorkJobVO(context.getContextId());
 +
 +            workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
 +            workJob.setCmd(VmWorkJobDispatcher.Start);
 +
 +            workJob.setAccountId(callingAccount.getId());
 +            workJob.setUserId(callingUser.getId());
 +            workJob.setStep(VmWorkJobVO.Step.Starting);
 +            workJob.setVmType(vm.getType());
 +            workJob.setVmInstanceId(vm.getId());
 +
 +            // save work context info (there are some duplications)
 +            VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId());
 +            workInfo.setPlan(planToDeploy);
 +            workInfo.setParams(params);
 +            workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
 +
 +            _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
 +    	}
 +
 +        txn.commit();
 +    	final long jobId = workJob.getId();
 +    	AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
 +        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId(), null);
 +    }
 +
 +    private Pair<DeploymentPlan, DeployDestination> findDestination(VirtualMachineProfileImpl profile, DeploymentPlan planRequested, boolean reuseVolume,
 +            ReservationContext reservation, AsyncJobExecutionContext job) throws InsufficientCapacityException, ResourceUnavailableException {
 +        VirtualMachine vm = profile.getVirtualMachine();
 +
 +        DataCenterDeployment plan = null;
 +        if (planRequested != null) {
 +            plan = new DataCenterDeployment(planRequested);
 +        } else {
 +            plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null, reservation);
 +        }
 +        
 +        job.log(s_logger, "Starting " + vm + " with requested " + plan);
 +
 +        boolean planChangedByVolume = false;
 +        List<VolumeVO> vols = _entityMgr.search(VolumeVO.class, RootVolumeSearch.create("instance", vm.getId()));
 +        
 +        if (vols.size() > 0 && reuseVolume) {
 +            // edit plan if this vm's ROOT volume is in READY state already
 +            
 +            VolumeVO vol = vols.get(0);
 +            // make sure if the templateId is unchanged. If it is changed,
 +            // let planner reassign pool for the volume even if it ready.
 +            Long volTemplateId = vol.getTemplateId();
 +            if (vol.isRecreatable() && volTemplateId != null &&
 +                    vm.getTemplateId() != -1 && volTemplateId.longValue() != vm.getTemplateId()) {
 +                job.log(s_logger, "Recreating" + vol + " of " + vm + " because its template has changed.");
 +                plan.setPoolId(null);
 +            } else {
 +                StoragePool pool = (StoragePool)_dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
 +                Long rootVolPodId = pool.getPodId();
 +                Long rootVolClusterId = pool.getClusterId();
 +                Long clusterIdSpecified = plan.getClusterId();
 +                if (clusterIdSpecified != null && rootVolClusterId != null &&
 +                    clusterIdSpecified.longValue() != rootVolClusterId.longValue()) {
 +                    job.log(s_logger, "Unable to satisfy the deployment plan because it is requesting cluster " + clusterIdSpecified + " but the root volume is in cluster " + rootVolClusterId);
 +                    throw new ResourceUnavailableException("Unable to satisfy the deployment plan because it is requesting cluster " + clusterIdSpecified
 +                            + " but the root volume is in cluster " + rootVolClusterId, Cluster.class, clusterIdSpecified);
 +                }
 +                plan.setPoolId(vol.getPoolId());
 +                plan.setClusterId(rootVolClusterId);
 +                plan.setPodId(rootVolPodId);
 +                planChangedByVolume = true;
 +                job.log(s_logger, "Deployment plan has been adjusted to " + plan);
 +            }
 +        }
 +
 +        DeployDestination dest = null;
 +        try {
 +            dest = _dpMgr.planDeployment(profile, plan, plan.getAvoids());
 +        } catch (AffinityConflictException e2) {
 +            throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict", e2);
 +        }
 +
 +        if (dest == null && planChangedByVolume) {
 +            job.log(s_logger, "Unable to find a deploy destination using the adjusted deployment plan.  Replanning with ");
 +            return findDestination(profile, planRequested, false, reservation, job);
 +        }
 +
 +        if (dest == null) {
 +            throw new InsufficientServerCapacityException("Unable to create a deployment for " + vm,
 +                    DataCenter.class, plan.getDataCenterId(), areAffinityGroupsAssociated(profile));
 +        }
 +
 +        plan.getAvoids().addHost(dest.getHost().getId());
 +        job.log(s_logger, "Final deploy destination: " + dest);
 +        return new Pair<DeploymentPlan, DeployDestination>(plan, dest);
 +    }
 +
 +    /**
 +     * orchestrateStart orchestrates the vm start process.  Note that this
 +     * method is not in the interface.
 +     * 
 +     * @param vmUuid uuid for the vm
 +     * @param params additional parameters passed
 +     * @param planRequested deployment requested
 +     * @throws InsufficientCapacityException when there's not enough infrastructure capacity to ensure successful start of a vm.
 +     * @throws ConcurrentOperationException when there are multiple operations on the vm.
 +     * @throws ResourceUnavailableException when the resource being used to start the vm is not available.
 +     */
 +    public void orchestrateStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planRequested)
 +            throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
 +        CallContext context = CallContext.current();
 +        User caller = context.getCallingUser();
 +        Account account = context.getCallingAccount();
 +        AsyncJobExecutionContext job = AsyncJobExecutionContext.getCurrentExecutionContext();
 +
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        if (vm == null) {
 +            throw new ConcurrentOperationException("Unable to find vm by " + vmUuid);
 +        }
 +
 +        VirtualMachineGuru vmGuru = getVmGuru(vm);
 +  
 +        Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO> start = changeToStartState(vmGuru, vm, caller, account);
 +        assert(start != null);
 +
 +        ReservationContext reservation = start.second();
 +        VmWorkJobVO work = start.third();
 +
 +        VMInstanceVO startedVm = null;
 +        ServiceOfferingVO offering = _entityMgr.findById(ServiceOfferingVO.class, vm.getServiceOfferingId());
 +        VMTemplateVO template = _entityMgr.findById(VMTemplateVO.class, vm.getTemplateId());
 +
 +        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
 +
 +        boolean canRetry = true;
 +        try {
 +
 +            boolean reuseVolume = true;
 +            DeploymentPlan plan = planRequested;
 +
 +            int retry = _retry.value();
 +            while (retry-- != 0) { // It's != so that it can match -1.
 +
 +                VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, account, params);
 +                Pair<DeploymentPlan, DeployDestination> result = findDestination(vmProfile, plan, reuseVolume, reservation, job);
 +                plan = result.first();
 +                DeployDestination dest = result.second();
 +
 +                long destHostId = dest.getHost().getId();
 +                vm.setPodId(dest.getPod().getId());
 +                Long cluster_id = dest.getCluster().getId();
 +                ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
 +                ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
 +                vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
 +                vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
 +
 +                if (!changeState(vm, VirtualMachine.Event.OperationRetry, destHostId, work, Step.Prepare)) {
 +                    throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
 +                }
 +
 +                try {
 +                    _networkMgr.prepare(vmProfile, dest, reservation);
 +                    _volumeMgr.prepare(vmProfile, dest);
 +
 +                    reuseVolume = true;
 +
 +                    Commands cmds = null;
 +                    vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, reservation);
 +
 +                    VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
 +
 +                    cmds = new Commands(OnError.Stop);
-                     cmds.addCommand(new StartCommand(vmTO, dest.getHost()));
++                    cmds.addCommand(new StartCommand(vmTO, dest.getHost(), true));
 +
 +                    vmGuru.finalizeDeployment(cmds, vmProfile, dest, reservation);
 +
 +                    work.setStep(VmWorkJobVO.Step.Starting);
 +                    _workJobDao.update(work.getId(), work);
 +
 +                    _agentMgr.send(destHostId, cmds);
 +
 +                    work.setStep(VmWorkJobVO.Step.Started);
 +                    _workJobDao.update(work.getId(), work);
 +
 +                    StartAnswer startAnswer = cmds.getAnswer(StartAnswer.class);
 +                    if (startAnswer != null && startAnswer.getResult()) {
 +                        String host_guid = startAnswer.getHost_guid();
 +                        if( host_guid != null ) {
 +                            HostVO finalHost = _resourceMgr.findHostByGuid(host_guid);
 +                            if (finalHost == null ) {
 +                                throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something wrong here");
 +                            }
 +                            destHostId = finalHost.getId();
 +                        }
 +                        if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, reservation)) {
 +                            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, destHostId, work, Step.Done)) {
 +                                throw new ConcurrentOperationException("Unable to transition to a new state.");
 +                            }
 +                            startedVm = vm;
 +                            if (s_logger.isDebugEnabled()) {
 +                                s_logger.debug("Start completed for VM " + vm);
 +                            }
 +                            return;
 +                        } else {
 +                            if (s_logger.isDebugEnabled()) {
 +                                s_logger.info("The guru did not like the answers so stopping " + vm);
 +                            }
 +
-                             StopCommand cmd = new StopCommand(vm);
++                            StopCommand cmd = new StopCommand(vm, true);
 +                            StopAnswer answer = (StopAnswer) _agentMgr.easySend(destHostId, cmd);
 +                            if (answer == null || !answer.getResult()) {
 +                                s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
 +                                _haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop);
 +                                throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation");
 +                            }
 +                            throw new ExecutionException("Unable to start " + vm + " due to error in finalizeStart, not retrying");
 +                        }
 +                    }
 +                    s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
 +
 +                } catch (OperationTimedoutException e) {
 +                    s_logger.debug("Unable to send the start command to host " + dest.getHost());
 +                    if (e.isActive()) {
 +                        _haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop);
 +                    }
 +                    canRetry = false;
 +                    throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
 +                } catch (ResourceUnavailableException e) {
 +                    s_logger.info("Unable to contact resource.", e);
 +                    if (!plan.getAvoids().add(e)) {
 +                        if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
 +                            throw e;
 +                        } else {
 +                            s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
 +                            throw e;
 +                        }
 +                    }
 +                } catch (InsufficientCapacityException e) {
 +                    s_logger.info("Insufficient capacity ", e);
 +                    if (!plan.getAvoids().add(e)) {
 +                        if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
 +                            throw e;
 +                        } else {
 +                            s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
 +                        }
 +                    }
 +                } catch (Exception e) {
 +                    s_logger.error("Failed to start instance " + vm, e);
 +                    throw new CloudRuntimeException("Unable to start instance due to " + e.getMessage(), e);
 +                } finally {
 +                    if (startedVm == null && canRetry) {
 +                        VmWorkJobVO.Step prevStep = work.getStep();
 +                        _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Release);
 +                        if (prevStep == VmWorkJobVO.Step.Started || prevStep == VmWorkJobVO.Step.Starting) {
 +                            cleanup(vmGuru, vmProfile, work, false);
 +                        } else {
 +                            //if step is not starting/started, send cleanup command with force=true
 +                            cleanup(vmGuru, vmProfile, work, true);
 +                        }
 +                    }
 +                }
 +            }
 +        } catch (NoTransitionException e1) {
 +            throw new CloudRuntimeException(e1.getMessage());
 +        } finally {
 +            if (startedVm == null) {
 +                try {
 +                    changeState(vm, VirtualMachine.Event.OperationFailed, null, work, Step.Done);
 +                } catch (NoTransitionException e) {
 +                    throw new ConcurrentOperationException(e.getMessage());
 +                }
 +            }
 +        }
 +
 +        if (startedVm == null) {
 +            throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName()
 +                            + "' (" + vm.getUuid() + "), see management server log for details");
 +        }
 +    }
 +    
 +    @Override
 +    public void easyStop(String vmUuid) {
 +        Outcome<VirtualMachine> outcome = stop(vmUuid, false);
 +        try {
 +            outcome.get(_jobTimeout.value(), TimeUnit.MILLISECONDS);
 +        } catch (InterruptedException e) {
 +            throw new CloudRuntimeException("Interrupted while stopping vm " + vmUuid, e);
 +        } catch (java.util.concurrent.ExecutionException e) {
 +            throw new CloudRuntimeException("Unable to stop the VM", e);
 +        } catch (TimeoutException e) {
 +            throw new CloudRuntimeException("Unable to stop the VM due to timeout", e);
 +        }
 +    }
 +
 +    protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile profile, boolean force) {
 +        VirtualMachine vm = profile.getVirtualMachine();
-         StopCommand stop = new StopCommand(vm);
++        StopCommand stop = new StopCommand(vm, true);
 +        try {
 +            Answer answer = _agentMgr.send(vm.getHostId(), stop);
 +            if (!answer.getResult()) {
 +                s_logger.debug("Unable to stop VM due to " + answer.getDetails());
 +                return false;
 +            }
 +
 +            guru.finalizeStop(profile, (StopAnswer) answer);
 +        } catch (AgentUnavailableException e) {
 +            if (!force) {
 +                return false;
 +            }
 +        } catch (OperationTimedoutException e) {
 +            if (!force) {
 +                return false;
 +            }
 +        }
 +
 +        return true;
 +    }
 +
 +    protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, VmWorkJobVO work, boolean force) {
 +        VirtualMachine vm = profile.getVirtualMachine();
 +        State state = vm.getState();
 +        s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
 +        if (state == State.Starting) {
 +            VmWorkJobVO.Step step = work.getStep();
 +            if (step == VmWorkJobVO.Step.Starting && !force) {
 +                s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
 +                return false;
 +            }
 +
 +            if (step == VmWorkJobVO.Step.Started || step == VmWorkJobVO.Step.Starting || step == VmWorkJobVO.Step.Release) {
 +                if (vm.getHostId() != null) {
 +                    if (!sendStop(guru, profile, force)) {
 +                        s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
 +                        return false;
 +                    }
 +                }
 +            }
 +
 +            if (step != VmWorkJobVO.Step.Release && step != VmWorkJobVO.Step.Prepare && step != VmWorkJobVO.Step.Started && step != VmWorkJobVO.Step.Starting) {
 +                s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
 +                return true;
 +            }
 +        } else if (state == State.Stopping) {
 +            if (vm.getHostId() != null) {
 +                if (!sendStop(guru, profile, force)) {
 +                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
 +                    return false;
 +                }
 +            }
 +        } else if (state == State.Migrating) {
 +            if (vm.getHostId() != null) {
 +                if (!sendStop(guru, profile, force)) {
 +                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
 +                    return false;
 +                }
 +            }
 +            if (vm.getLastHostId() != null) {
 +                if (!sendStop(guru, profile, force)) {
 +                    s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
 +                    return false;
 +                }
 +            }
 +        } else if (state == State.Running) {
 +            if (!sendStop(guru, profile, force)) {
 +                s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
 +                return false;
 +            }
 +        }
 +
 +        try {
 +            _networkMgr.release(profile, force);
 +            s_logger.debug("Successfully released network resources for the vm " + vm);
 +        } catch (Exception e) {
 +            s_logger.warn("Unable to release some network resources.", e);
 +        }
 +
 +        _volumeMgr.release(profile);
 +        s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state");
 +        return true;
 +    }
 +    
 +    @Override
 +    @DB
 +    public Outcome<VirtualMachine> stop(final String vmUuid, boolean cleanup) {
 +        CallContext cc = CallContext.current();
 +        Account account = cc.getCallingAccount();
 +        User user = cc.getCallingUser();
 +
 +        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +    	VmWorkJobVO workJob = null;
 +    	Transaction txn = Transaction.currentTxn();
 +        txn.start();
 +
 +        _vmDao.lockRow(vm.getId(), true);
 +
 +        List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
 +
 +        if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
 +            assert (pendingWorkJobs.size() == 1);
 +            workJob = pendingWorkJobs.get(0);
 +        } else {
 +            workJob = new VmWorkJobVO(cc.getContextId());
 +
 +            workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
 +            workJob.setCmd(VmWorkJobDispatcher.Stop);
 +
 +            workJob.setAccountId(account.getId());
 +            workJob.setUserId(user.getId());
 +            workJob.setStep(VmWorkJobVO.Step.Prepare);
 +            workJob.setVmType(vm.getType());
 +            workJob.setVmInstanceId(vm.getId());
 +
 +            // save work context info (there are some duplications)
 +            VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), cleanup);
 +            workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
 +
 +            _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
 +    	}
 +
 +        txn.commit();
 +
 +    	final long jobId = workJob.getId();
 +    	AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
 +    	
 +        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOff, vm.getId(), null);
 +    }
 +
 +    public void orchestrateStop(String vmUuid, boolean forced) throws AgentUnavailableException,
 +            OperationTimedoutException, ConcurrentOperationException {
 +        CallContext context = CallContext.current();
 +
 +        VmWorkJobVO work = _workJobDao.findById(AsyncJobExecutionContext.getCurrentExecutionContext().getJob().getId());
 +
 +        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        Long hostId = vm.getHostId();
 +        if (hostId == null) {
 +            if (!forced) {
 +                if (s_logger.isDebugEnabled()) {
 +                    s_logger.debug("HostId is null but this is not a forced stop, cannot stop vm " + vm + " with state:" + vm.getState());
 +                }
 +                return;
 +            }
 +            
 +            try {
 +                stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null, null);
 +            } catch (NoTransitionException e) {
 +                s_logger.warn(e.getMessage());
 +            }
 +  
 +            _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Done);
 +            return;
 +        }
 +
 +        VirtualMachineGuru vmGuru = getVmGuru(vm);
 +        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 +
 +        try {
 +            if (!stateTransitTo(vm, VirtualMachine.Event.StopRequested, vm.getHostId())) {
 +                throw new ConcurrentOperationException("VM is being operated on.");
 +            }
 +        } catch (NoTransitionException e1) {
 +            if (!forced) {
 +                throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
 +            }
 +            
 +            State state = vm.getState();
 +            boolean doCleanup = false;
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Unable to transition the state but we're moving on because it's forced stop");
 +            }
 +            if (state == State.Starting || state == State.Migrating) {
 +                doCleanup = true;
 +            } else if (state == State.Stopping) {
 +                doCleanup = true;
 +            }
 +
 +            if (doCleanup) {
 +                if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, forced)) {
 +                    try {
 +                        if (s_logger.isDebugEnabled()) {
 +                            s_logger.debug("Updating work item to Done, id:" + work.getId());
 +                        }
 +                        changeState(vm, VirtualMachine.Event.AgentReportStopped, null, work, Step.Done);
 +                        return;
 +                    } catch (NoTransitionException e) {
 +                        s_logger.warn("Unable to cleanup " + vm);
 +                        return;
 +                    }
 +                } else {
 +                    if (s_logger.isDebugEnabled()) {
 +                        s_logger.debug("Failed to cleanup VM: " + vm);
 +                    }
 +                    throw new CloudRuntimeException("Failed to cleanup " + vm + " , current state " + vm.getState());
 +                }
 +            }
 +        }
 +
 +        vmGuru.prepareStop(profile);
 +        
-         StopCommand stop = new StopCommand(vm);
++        StopCommand stop = new StopCommand(vm, true);
 +        boolean stopped = false;
 +        StopAnswer answer = null;
 +        try {
 +            answer = (StopAnswer) _agentMgr.send(vm.getHostId(), stop);
 +            stopped = answer.getResult();
 +            if (!stopped) {
 +                throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
 +            }
 +            vmGuru.finalizeStop(profile, answer);
 +
 +        } catch (AgentUnavailableException e) {
 +        } catch (OperationTimedoutException e) {
 +        } finally {
 +            if (!stopped) {
 +                if (!forced) {
 +                    s_logger.warn("Unable to stop vm " + vm);
 +                    try {
 +                        stateTransitTo(vm, VirtualMachine.Event.OperationFailed, vm.getHostId());
 +                    } catch (NoTransitionException e) {
 +                        s_logger.warn("Unable to transition the state " + vm);
 +                    }
 +                    return;
 +                } else {
 +                    s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
 +                    vmGuru.finalizeStop(profile, answer);
 +                }
 +            }
 +        }
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug(vm + " is stopped on the host.  Proceeding to release resource held.");
 +        }
 +
 +        try {
 +            _networkMgr.release(profile, forced);
 +            s_logger.debug("Successfully released network resources for the vm " + vm);
 +        } catch (Exception e) {
 +            s_logger.warn("Unable to release some network resources.", e);
 +        }
 +
 +        try {
 +            if (vm.getHypervisorType() != HypervisorType.BareMetal) {
 +                _volumeMgr.release(profile);
 +                s_logger.debug("Successfully released storage resources for the vm " + vm);
 +            }
 +        } catch (Exception e) {
 +            s_logger.warn("Unable to release storage resources.", e);
 +        }
 +
 +        try {
 +            if (work != null) {
 +                if (s_logger.isDebugEnabled()) {
 +                    s_logger.debug("Updating the outstanding work item to Done, id:" + work.getId());
 +                }
 +                _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Done);
 +            }
 +
 +            stateTransitTo(vm, VirtualMachine.Event.OperationSucceeded, null, null);
 +            return;
 +        } catch (NoTransitionException e) {
 +            s_logger.warn(e.getMessage());
 +            return;
 +        }
 +    }
 +
 +    private void setStateMachine() {
 +        _stateMachine = VirtualMachine.State.getStateMachine();
 +    }
 +
 +    protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException {
 +        vm.setReservationId(reservationId);
 +        return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
 +    }
 +
 +    @Override
 +    public boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
 +        State oldState = vm.getState();
 +        if (oldState == State.Starting) {
 +            if (e == VirtualMachine.Event.OperationSucceeded) {
 +                vm.setLastHostId(hostId);
 +            }
 +        } else if (oldState == State.Stopping) {
 +            if (e == VirtualMachine.Event.OperationSucceeded) {
 +                vm.setLastHostId(vm.getHostId());
 +            }
 +        }
 +        return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
 +    }
 +
 +    @Override
 +    public boolean destroy(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException,
 +            ConcurrentOperationException {
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Destroying vm " + vm);
 +        }
 +        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
 +            }
 +            return true;
 +        }
 +
 +        stop(vmUuid, _forceStop.value());
 +        
 +        vm = _vmDao.findById(vm.getId());
 +
 +        if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(),null)){
 +            s_logger.debug("Unable to delete all snapshots for " + vm);
 +            return false;
 +        }
 +        
 +        try {
 +            if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
 +                s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
 +                return false;
 +            }
 +        } catch (NoTransitionException e) {
 +            s_logger.debug(e.getMessage());
 +            return false;
 +        }
 +
 +        return true;
 +    }
 +
 +    protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException {
 +        CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer) _agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName()));
 +        if (!answer.getResult() || answer.getState() == PowerState.PowerOff) {
 +            return false;
 +        }
 +
 +        return true;
 +    }
 +
 +    @Override
 +    public VirtualMachine storageMigration(String vmUuid, StoragePool destPool) {
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +
 +        try {
 +            stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
 +        } catch (NoTransitionException e) {
 +            s_logger.debug("Unable to migrate vm: " + e.toString());
 +            throw new CloudRuntimeException("Unable to migrate vm: " + e.toString());
 +        }
 +
 +        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 +        boolean migrationResult = false;
 +        try {
 +            migrationResult = _volumeMgr.storageMigration(profile, destPool);
 +
 +            if (migrationResult) {
 +                //if the vm is migrated to different pod in basic mode, need to reallocate ip
 +
 +                if (!vm.getPodIdToDeployIn().equals(destPool.getPodId())) {
 +                    DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null);
 +                    VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null);
 +                    _networkMgr.reallocate(vmProfile, plan);
 +                }
 +
 +                //when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool
 +                vm.setLastHostId(null);
 +                vm.setPodId(destPool.getPodId());
 +            } else {
 +                s_logger.debug("Storage migration failed");
 +            }
 +        } catch (ConcurrentOperationException e) {
 +            s_logger.debug("Failed to migration: " + e.toString());
 +            throw new CloudRuntimeException("Failed to migration: " + e.toString());
 +        } catch (InsufficientVirtualNetworkCapcityException e) {
 +            s_logger.debug("Failed to migration: " + e.toString());
 +            throw new CloudRuntimeException("Failed to migration: " + e.toString());
 +        } catch (InsufficientAddressCapacityException e) {
 +            s_logger.debug("Failed to migration: " + e.toString());
 +            throw new CloudRuntimeException("Failed to migration: " + e.toString());
 +        } catch (InsufficientCapacityException e) {
 +            s_logger.debug("Failed to migration: " + e.toString());
 +            throw new CloudRuntimeException("Failed to migration: " + e.toString());
 +        } finally {
 +            try {
 +                stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
 +            } catch (NoTransitionException e) {
 +                s_logger.debug("Failed to change vm state: " + e.toString());
 +                throw new CloudRuntimeException("Failed to change vm state: " + e.toString());
 +            }
 +        }
 +
 +        return vm;
 +    }
 +
 +    @Override
 +    public Outcome<VirtualMachine> migrate(String vmUuid, long srcHostId, DeployDestination dest) {
 +        CallContext context = CallContext.current();
 +        User user = context.getCallingUser();
 +        Account account = context.getCallingAccount();
 +
 +        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +
 +        VmWorkJobVO workJob = null;
 +        Transaction txn = Transaction.currentTxn();
 +        txn.start();
 +
 +        _vmDao.lockRow(vm.getId(), true);
 +
 +        List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
 +
 +        if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
 +            assert (pendingWorkJobs.size() == 1);
 +            workJob = pendingWorkJobs.get(0);
 +        } else {
 +                    
 +            workJob = new VmWorkJobVO(context.getContextId());
 +
 +            workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
 +            workJob.setCmd(VmWorkJobDispatcher.Start);
 +
 +            workJob.setAccountId(account.getId());
 +            workJob.setUserId(user.getId());
 +            workJob.setStep(VmWorkJobVO.Step.Migrating);
 +            workJob.setVmType(vm.getType());
 +            workJob.setVmInstanceId(vm.getId());
 +
 +            // save work context info (there are some duplications)
 +            VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), dest);
 +            workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
 +
 +            _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
 +        }
 +
 +        txn.commit();
 +        final long jobId = workJob.getId();
 +        AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
 +        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId());
 +
 +    }
 +
 +    public void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws AgentUnavailableException, OperationTimedoutException {
 +        AsyncJobExecutionContext jc = AsyncJobExecutionContext.getCurrentExecutionContext();
 +
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        if (vm == null) {
 +            throw new CloudRuntimeException("Unable to find the vm " + vm);
 +        }
 +
 +        if (vm.getState() != State.Running || vm.getHostId() == null || vm.getHostId() != srcHostId ) {
 +            if (s_logger.isDebugEnabled()) {
 +                s_logger.debug("Proper conditions to migrate " + vm + " is not met.");
 +            }
 +            return;
 +        }
 +        
 +        Host fromHost = _entityMgr.findById(Host.class, srcHostId);
 +        if (fromHost == null) {
 +            throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
 +        }
 +        long dstHostId = dest.getHost().getId();
 +
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Migrating " + vm + " to " + dest);
 +        }
 +
 +        short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
 +        if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
 +            alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
 +        } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
 +            alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
 +        }
 +
 +        VirtualMachineProfile srcVm = new VirtualMachineProfileImpl(vm);
 +        for (NicProfile nic : _networkMgr.getNicProfiles(vm)) {
 +            srcVm.addNic(nic);
 +        }
 +        
 +        VirtualMachineProfile dstVm = new VirtualMachineProfileImpl(vm);
 +        _networkMgr.prepareNicForMigration(dstVm, dest);
 +        _volumeMgr.prepareForMigration(dstVm, dest);
 +
 +        VirtualMachineTO to = toVmTO(dstVm);
 +
 +        VmWorkJobVO work = _workJobDao.findById(jc.getJob().getId());
 +        work.setStep(MigrationStateMachine.getNextState(null, VirtualMachine.Event.MigrationRequested));
 +        work = _workJobDao.persist(work);
 +
 +        PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
 +        PrepareForMigrationAnswer pfma = null;
 +        try {
 +            try {
 +                pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
 +                if (!pfma.getResult()) {
 +                    String msg = "Unable to prepare for migration due to " + pfma.getDetails();
 +                    throw new AgentUnavailableException(msg, dstHostId);
 +                }
 +            } catch (OperationTimedoutException e) {
 +                throw new AgentUnavailableException("Unable to prepare host " + dstHostId, dstHostId);
 +            }
 +    
 +            vm.setLastHostId(srcHostId);
 +            changeState2(vm, VirtualMachine.Event.MigrationRequested, dstHostId, work, VirtualMachine.Event.OperationSucceeded);
 +    
 +            boolean isWindows = _entityMgr.findById(GuestOsCategory.class, _entityMgr.findById(GuestOSVO.class, vm.getGuestOSId()).getCategoryId()).getName()
 +                    .equalsIgnoreCase("Windows");
 +            MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows);
 +            mc.setHostGuid(dest.getHost().getGuid());
 +
 +            try {
 +                MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
 +                if (!ma.getResult()) {
 +                    throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
 +                }
 +            } catch (OperationTimedoutException e) {
 +                if (!e.isActive()) {
 +                    s_logger.warn("Active migration command so scheduling a restart for " + vm);
 +                    _haMgr.scheduleRestart(vm, true);
 +                }
 +                throw new CloudRuntimeException("Operation timed out on migrating " + vm);
 +            }
 +
 +            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
 +                throw new CloudRuntimeException("Unable to change the state for " + vm);
 +            }
 +
 +            try {
 +                if (!checkVmOnHost(vm, dstHostId)) {
 +                    throw new CloudRuntimeException("Unable to complete migration for " + vm);
 +                }
 +            } catch (OperationTimedoutException e) {
 +                s_logger.warn("Unable to verify that " + vm + " has migrated but since the migrate command worked, it is assumed to have worked");
 +            }
 +            
 +            _networkMgr.commitNicForMigration(srcVm, dstVm);
 +            changeState2(vm, null, dstHostId, work, VirtualMachine.Event.OperationSucceeded);
 +
 +        } catch (NoTransitionException e) {
 +            throw new CloudRuntimeException("Unable to change state", e);
 +        } finally {
 +            Step step = work.getStep();
 +            
 +            if (step != Step.Done) {
 +                s_logger.debug("Migration was unsuccessful.  Cleaning up: " + vm + " Step was at " + step);
 +
 +                _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName()
 +                        + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed.  Please check logs.");
 +
 +                boolean cleanup = false;
 +                try {
 +                    cleanupMigration(work, dstVm, vm, false);
 +                    cleanup = true;
 +                } catch (Exception ae) {
 +                    s_logger.warn("Unable to cleanup migration for " + vm);
 +                }
 +
 +                if (cleanup) {
 +                    _networkMgr.rollbackNicForMigration(srcVm, dstVm);
 +
 +                    work.setStep(Step.Done);
 +                    _workJobDao.update(work.getId(), work);
 +                }
 +            }
 +        }
 +    }
 +
 +    private void determineVmLocation(VirtualMachineProfile vm, VMInstanceVO vo, boolean confirmedStopped) {
 +        try {
 +            if (checkVmOnHost(vo, vo.getLastHostId())) {
 +                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getLastHostId());
 +            } else if (checkVmOnHost(vo, vo.getHostId())) {
 +                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId());
 +            } else {
 +                s_logger.warn("Unable to find " + vo + " on source " + vo.getLastHostId() + " or on destination " + vo.getHostId()
 +                        + (!confirmedStopped ? ".  Either call Stop with cleanup option or wait for vmsync to check where the VM is." : "."));
 +                stateTransitTo(vo, VirtualMachine.Event.AgentReportStopped, null);
 +            }
 +        } catch (AgentUnavailableException e) {
 +            if (confirmedStopped) {
 +                s_logger.debug("Agent is unavailable to determine state for " + vo + " but continuing with confirmed stopped option");
 +            } else {
 +                throw new CloudRuntimeException("Unable to determine the state for " + vo).add(VirtualMachine.class, vo.getUuid());
 +            }
 +        } catch (OperationTimedoutException e) {
 +            if (confirmedStopped) {
 +                s_logger.debug("Operation timedout while determining state for " + vo + " but continuing with confirmed stopped option");
 +            } else {
 +                throw new CloudRuntimeException("Unable to determine the state for " + vo).add(VirtualMachine.class, vo.getUuid());
 +            }
 +        } catch (NoTransitionException e) {
 +            throw new CloudRuntimeException("Unable to change VM state ", e).add(VirtualMachine.class, vo.getUuid());
 +        }
 +
 +        if (confirmedStopped) {
 +            s_logger.info("Cleanup was requested on " + vo);
 +            cleanup(getVmGuru(vo), vm, null, true);
 +        }
 +    }
 +    /**
 +     * Migration goes through the following steps.
 +     *   Prepare - nics and storage are prepared
 +     *   Migrating - migrating command was issued
 +     *   Started - migrating command returned and was successful
 +     *   Done - the vm was verified on the destination host.
 +     * 
 +     * In order to cleanup, we have to go through the above steps in reverse.
 +     * 
 +     * @param job - job that was recording the status
 +     * @param vm - vm profile that needs to be cleaned up.
 +     * @param vo - vo object representing the VM.
 +     */
 +    private void cleanupMigration(VmWorkJobVO job, VirtualMachineProfile vm, VMInstanceVO vo, boolean confirmedStopped) {
 +        if (job == null) {
 +            s_logger.info("Cleaning up " + vo + " with no job to track progress");
 +            if (vo.getState() != VirtualMachine.State.Migrating) {
 +                if (s_logger.isDebugEnabled()) {
 +                    s_logger.debug("Requesting to clean up a vm that's not migrating: " + vo);
 +                }
 +                return;
 +            }
 +            determineVmLocation(vm, vo, confirmedStopped);
 +            return;
 +        }
 +        
 +        Step step = job.getStep();
 +        
 +        if (s_logger.isDebugEnabled()) {
 +            s_logger.debug("Migration operation was at " + step + " for " + vo);
 +        }
 +        if (step == Step.Started) {
 +            determineVmLocation(vm, vo, confirmedStopped);
 +        } else if (step == Step.Migrating) {
 +            determineVmLocation(vm, vo, confirmedStopped);
 +        }
 +    }
 +
 +
 +    private void filterPoolListForVolumesForMigration(VirtualMachineProfile profile, Host host, Map<Volume, StoragePool> volumeToPool) {
 +        List<VolumeVO> allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId());
 +        for (VolumeVO volume : allVolumes) {
 +            StoragePool dstPool = volumeToPool.get(volume);
 +            DiskOfferingVO diskOffering = _entityMgr.findById(DiskOfferingVO.class, volume.getDiskOfferingId());
 +            StoragePoolVO srcPool = _entityMgr.findById(StoragePoolVO.class, volume.getPoolId());
 +            if (dstPool != null) {
 +                // Check if pool is accessible from the destination host and disk offering with which the volume was
 +                // created is compliant with the pool type.
 +                if (_poolHostDao.findByPoolHost(dstPool.getId(), host.getId()) == null ||
 +                        dstPool.isLocal() != diskOffering.getUseLocalStorage()) {
 +                    // Cannot find a pool for the volume. Throw an exception.
 +                    throw new CloudRuntimeException("Cannot migrate volume " + volume + " to storage pool " + dstPool +
 +                            " while migrating vm to host " + host + ". Either the pool is not accessible from the " +
 +                            "host or because of the offering with which the volume is created it cannot be placed on " +
 +                            "the given pool.");
 +                } else if (dstPool.getId() == srcPool.getId()){
 +                    // If the pool to migrate too is the same as current pool, remove the volume from the list of
 +                    // volumes to be migrated.
 +                    volumeToPool.remove(volume);
 +                }
 +            } else {
 +                // Find a suitable pool for the volume. Call the storage pool allocator to find the list of pools.
 +                DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType());
 +                DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(),
 +                        host.getClusterId(), host.getId(), null, null);
 +                ExcludeList avoid = new ExcludeList();
 +                boolean currentPoolAvailable = false;
 +
 +                for (StoragePoolAllocator allocator : _storagePoolAllocators) {
 +                    List<StoragePool> poolList = allocator.allocateToPool(diskProfile, profile, plan, avoid,
 +                            StoragePoolAllocator.RETURN_UPTO_ALL);
 +                    if (poolList != null && !poolList.isEmpty()) {
 +                        // Volume needs to be migrated. Pick the first pool from the list. Add a mapping to migrate the
 +                        // volume to a pool only if it is required; that is the current pool on which the volume resides
 +                        // is not available on the destination host.
 +                        if (poolList.contains(srcPool)) {
 +                            currentPoolAvailable = true;
 +                        } else {
 +                            volumeToPool.put(volume, poolList.get(0));
 +                        }
 +
 +                        break;
 +                    }
 +                }
 +
 +                if (!currentPoolAvailable && !volumeToPool.containsKey(volume)) {
 +                    // Cannot find a pool for the volume. Throw an exception.
 +                    throw new CloudRuntimeException("Cannot find a storage pool which is available for volume " +
 +                            volume + " while migrating virtual machine " + profile.getVirtualMachine() + " to host " +
 +                            host);
 +                }
 +            }
 +        }
 +    }
 +
 +    private void moveVmToMigratingState(VMInstanceVO vm, Long hostId, VmWorkJobVO work)
 +            throws ConcurrentOperationException {
 +        // Put the vm in migrating state.
 +        try {
 +            if (!changeState(vm, VirtualMachine.Event.MigrationRequested, hostId, work, Step.Migrating)) {
 +                s_logger.info("Migration cancelled because state has changed: " + vm);
 +                throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
 +            }
 +        } catch (NoTransitionException e) {
 +            s_logger.info("Migration cancelled because " + e.getMessage());
 +            throw new ConcurrentOperationException("Migration cancelled because " + e.getMessage());
 +        }
 +    }
 +
 +    private void moveVmOutofMigratingStateOnSuccess(VMInstanceVO vm, Long hostId, VmWorkJobVO work)
 +            throws ConcurrentOperationException {
 +        // Put the vm in running state.
 +        try {
 +            if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, hostId, work, Step.Started)) {
 +                s_logger.error("Unable to change the state for " + vm);
 +                throw new ConcurrentOperationException("Unable to change the state for " + vm);
 +            }
 +        } catch (NoTransitionException e) {
 +            s_logger.error("Unable to change state due to " + e.getMessage());
 +            throw new ConcurrentOperationException("Unable to change state due to " + e.getMessage());
 +        }
 +    }
 +
 +    @Override
 +    public VirtualMachine migrateWithStorage(String vmUuid, long srcHostId, long destHostId,
 +            Map<Volume, StoragePool> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException,
 +            ManagementServerException, VirtualMachineMigrationException {
 +        CallContext context = CallContext.current();
 +
 +        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 +        HostVO srcHost = _entityMgr.findById(HostVO.class, srcHostId);
 +        HostVO destHost = _entityMgr.findById(HostVO.class, destHostId);
 +        VirtualMachineGuru vmGuru = getVmGuru(vm);
 +
 +        DataCenterVO dc = _entityMgr.findById(DataCenterVO.class, destHost.getDataCenterId());
 +        HostPodVO pod = _entityMgr.findById(HostPodVO.class, destHost.getPodId());
 +        Cluster cluster = _entityMgr.findById(ClusterVO.class, destHost.getClusterId());
 +        DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost);
 +
 +        // Create a map of which volume should go in which storage pool.
 +        VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 +        filterPoolListForVolumesForMigration(profile, destHost, volumeToPool);
 +
 +        // If none of the volumes have to be migrated, fail the call. Administrator needs to make a call for migrating
 +        // a vm and not migrating a vm with storage.
 +        if (volumeToPool.isEmpty()) {
 +            throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost +
 +                    " to destination host " + destHost + " doesn't involve migrating the volumes.");
 +        }
 +
 +        short alertType = AlertManager.ALERT_TYPE_USERVM_MIGRATE;
 +        if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
 +            alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
 +        } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
 +            alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
 +        }
 +
 +        _networkMgr.prepareNicForMigration(profile, destination);
 +        _volumeMgr.prepareForMigration(profile, destination);
 +        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
 +        VirtualMachineTO to = hvGuru.implement(profile);
 +
 +        VmWorkJobVO work = new VmWorkJobVO(context.getContextId());
 +//        VmWorkJobVO work = new VmWorkJobVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
 +//        work.setStep(Step.Prepare);
 +//        work.setResourceType(ItWorkVO.ResourceType.Host);
 +//        work.setResourceId(destHostId);
 +//        work = _workDao.persist(work);
 +
 +        // Put the vm in migrating state.
 +        vm.setLastHostId(srcHostId);
 +        moveVmToMigratingState(vm, destHostId, work);
 +
 +        boolean migrated = false;
 +        try {
 +            // Migrate the vm and its volume.
 +            _volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPool);
 +
 +            // Put the vm back to running state.
 +            moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
 +
 +            try {
 +                if (!checkVmOnHost(vm, destHostId)) {
 +                    s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
 +                    try {
 +                        _age

<TRUNCATED>

[22/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-1578 kvm:Egress default policy configurable using network offering on kvm


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

Branch: refs/heads/vmsync
Commit: 0cd8f9e7316759f7634a7057cb4b40c98c27b8ae
Parents: 9121191
Author: Jayapal <ja...@apache.org>
Authored: Thu Jun 20 16:32:11 2013 +0530
Committer: Jayapal <ja...@apache.org>
Committed: Mon Jun 24 13:37:01 2013 +0530

----------------------------------------------------------------------
 .../resource/virtualnetwork/VirtualRoutingResource.java      | 8 ++++++++
 1 file changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cd8f9e7/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index dae1c85..4f0ccec 100755
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@ -224,6 +224,7 @@ public class VirtualRoutingResource implements Manager {
             results[i] = "Failed";
         }
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
 
         if (routerIp == null) {
             return new SetFirewallRulesAnswer(cmd, false, results);
@@ -239,6 +240,13 @@ public class VirtualRoutingResource implements Manager {
         
         if (trafficType == FirewallRule.TrafficType.Egress){
             command.add("-E");
+            if (egressDefault.equals("true")) {
+                command.add("-P ", "1");
+            } else if (egressDefault.equals("System")) {
+                command.add("-P ", "2");
+            } else {
+                command.add("-P ", "0");
+            }
         }
 
         StringBuilder sb = new StringBuilder();


[32/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
finished up the conversion to using outcome


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

Branch: refs/heads/vmsync
Commit: c0febea950e52acbba9035a85b8641da83416c43
Parents: 4254cb8
Author: Alex Huang <al...@gmail.com>
Authored: Mon Jun 17 20:32:19 2013 -0700
Committer: Alex Huang <al...@gmail.com>
Committed: Mon Jun 24 10:16:35 2013 -0700

----------------------------------------------------------------------
 .../src/com/cloud/vm/VirtualMachineManager.java |   2 +-
 .../com/cloud/vm/VirtualMachineManagerImpl.java | 134 ++++++++-----------
 .../lb/ElasticLoadBalancerManagerImpl.java      |   2 +-
 .../lb/InternalLoadBalancerVMManagerImpl.java   |   2 +-
 .../cloud/ha/HighAvailabilityManagerImpl.java   |  14 +-
 .../VirtualNetworkApplianceManagerImpl.java     |   2 +-
 .../com/cloud/server/ManagementServerImpl.java  |   4 +-
 .../storage/StoragePoolAutomationImpl.java      |   2 +-
 .../vm/snapshot/VMSnapshotManagerImpl.java      |   2 +-
 .../vm/VmWorkMockVirtualMachineManagerImpl.java |   5 +-
 10 files changed, 71 insertions(+), 98 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
----------------------------------------------------------------------
diff --git a/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java b/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
index e1365e2..92f05f0 100644
--- a/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
+++ b/engine/components-api/src/com/cloud/vm/VirtualMachineManager.java
@@ -126,7 +126,7 @@ public interface VirtualMachineManager extends Manager {
      */
     Outcome<VirtualMachine> start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy);
 
-    void advanceStop(String vmUuid, boolean cleanup) throws ResourceUnavailableException, OperationTimedoutException,
+    Outcome<VirtualMachine> stop(String vmUuid, boolean cleanup) throws ResourceUnavailableException, OperationTimedoutException,
             ConcurrentOperationException;
 
     void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index 141fcb4..3a308a9 100755
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -401,7 +401,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             return;
         }
 
-        advanceStop(vmUuid, false);
+        stop(vmUuid, false);
 
         vm = _vmDao.findByUuid(vmUuid);
         try {
@@ -995,14 +995,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     
     @Override
     public void easyStop(String vmUuid) {
+        Outcome<VirtualMachine> outcome = stop(vmUuid, false);
         try {
-            advanceStop(vmUuid, false);
-        } catch (OperationTimedoutException e) {
-            throw new CloudRuntimeException(e).add(VirtualMachine.class, vmUuid);
-        } catch (ConcurrentOperationException e) {
-            throw new CloudRuntimeException(e).add(VirtualMachine.class, vmUuid);
-        } catch (ResourceUnavailableException e) {
-            throw new CloudRuntimeException(e).add(VirtualMachine.class, vmUuid);
+            outcome.get(_jobTimeout.value(), TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+            throw new CloudRuntimeException("Interrupted while stopping vm " + vmUuid, e);
+        } catch (java.util.concurrent.ExecutionException e) {
+            throw new CloudRuntimeException("Unable to stop the VM", e);
+        } catch (TimeoutException e) {
+            throw new CloudRuntimeException("Unable to stop the VM due to timeout", e);
         }
     }
 
@@ -1094,8 +1095,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
     
     @Override
-    public void advanceStop(final String vmUuid, boolean forced) throws ResourceUnavailableException,
-            OperationTimedoutException, ConcurrentOperationException {
+    @DB
+    public Outcome<VirtualMachine> stop(final String vmUuid, boolean forced) {
         CallContext cc = CallContext.current();
         Account account = cc.getCallingAccount();
         User user = cc.getCallingUser();
@@ -1103,73 +1104,44 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
     	VmWorkJobVO workJob = null;
     	Transaction txn = Transaction.currentTxn();
-    	try {
-        	txn.start();
-        	
-        	_vmDao.lockRow(vm.getId(), true);
-        	
-        	List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
-                    VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
-        	
-        	if(pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
-        		assert(pendingWorkJobs.size() == 1);
-        		workJob = pendingWorkJobs.get(0);
-        	} else {
-                workJob = new VmWorkJobVO(cc.getContextId());
-        	
-                workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
-                workJob.setCmd(VmWorkJobDispatcher.Stop);
-        		
-        		workJob.setAccountId(account.getId());
-        		workJob.setUserId(user.getId());
-        		workJob.setStep(VmWorkJobVO.Step.Prepare);
-        		workJob.setVmType(vm.getType());
-        		workJob.setVmInstanceId(vm.getId());
-
-        		// save work context info (there are some duplications)
-        		VmWorkStop workInfo = new VmWorkStop();
-        		workInfo.setAccountId(account.getId());
-        		workInfo.setUserId(user.getId());
-        		workInfo.setVmId(vm.getId());
-        		workInfo.setForceStop(forced);
-                workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
-        		
-                _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
-        	}
-    	
-        	txn.commit();
-    	} catch(Throwable e) {
-    		s_logger.error("Unexpected exception", e);
-    		txn.rollback();
-    		throw new ConcurrentOperationException("Unhandled exception, converted to ConcurrentOperationException");
+        txn.start();
+
+        _vmDao.lockRow(vm.getId(), true);
+
+        List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkJobDispatcher.Start);
+
+        if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
+            assert (pendingWorkJobs.size() == 1);
+            workJob = pendingWorkJobs.get(0);
+        } else {
+            workJob = new VmWorkJobVO(cc.getContextId());
+
+            workJob.setDispatcher(VmWorkJobDispatcher.VM_WORK_JOB_DISPATCHER);
+            workJob.setCmd(VmWorkJobDispatcher.Stop);
+
+            workJob.setAccountId(account.getId());
+            workJob.setUserId(user.getId());
+            workJob.setStep(VmWorkJobVO.Step.Prepare);
+            workJob.setVmType(vm.getType());
+            workJob.setVmInstanceId(vm.getId());
+
+            // save work context info (there are some duplications)
+            VmWorkStop workInfo = new VmWorkStop();
+            workInfo.setAccountId(account.getId());
+            workInfo.setUserId(user.getId());
+            workInfo.setVmId(vm.getId());
+            workInfo.setForceStop(forced);
+            workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
+
+            _jobMgr.submitAsyncJob(workJob, VmWorkJobDispatcher.VM_WORK_QUEUE, vm.getId());
     	}
 
+        txn.commit();
+
     	final long jobId = workJob.getId();
     	AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
     	
-    	_jobMgr.waitAndCheck(
-                new String[] {Topics.VM_POWER_STATE, AsyncJob.Topics.JOB_STATE},
-    		3000L, 600000L, new Predicate() {
-
-				@Override
-				public boolean checkCondition() {
-					VMInstanceVO instance = _vmDao.findById(vm.getId());
-					if(instance.getPowerState() == VirtualMachine.PowerState.PowerOff)
-						return true;
-			
-					VmWorkJobVO workJob = _workJobDao.findById(jobId);
-					if(workJob.getStatus() != JobInfo.Status.IN_PROGRESS)
-						return true;
-					
-					return false;
-				}
-    		});
-    	
-        try {
-            AsyncJobExecutionContext.getCurrentExecutionContext().disjoinJob(jobId);
-        } catch (InsufficientCapacityException e) {
-            throw new CloudRuntimeException("Should never ever happen on a stop.  Who threw this?", e);
-        }
+        return new VmOutcome(workJob, VirtualMachine.PowerState.PowerOff, vm.getId());
     }
 
     public void orchestrateStop(String vmUuid, boolean forced) throws AgentUnavailableException,
@@ -1358,7 +1330,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             return true;
         }
 
-        advanceStop(vmUuid, _forceStop.value());
+        stop(vmUuid, _forceStop.value());
         
         vm = _vmDao.findById(vm.getId());
 
@@ -1907,16 +1879,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             if (vmInstance != null) {
                 return true;
             }
+            Outcome<VirtualMachine> outcome = stop(vm.getUuid(), true);
             try {
-                advanceStop(vm.getUuid(), true);
+                outcome.get(_jobTimeout.value(), TimeUnit.MILLISECONDS);
                 return true;
-            } catch (ResourceUnavailableException e) {
-                s_logger.debug("Unable to stop VM due to " + e.getMessage());
-            } catch (ConcurrentOperationException e) {
-                s_logger.debug("Unable to stop VM due to " + e.getMessage());
-            } catch (OperationTimedoutException e) {
-                s_logger.debug("Unable to stop VM due to " + e.getMessage());
+            } catch (InterruptedException e) {
+                s_logger.warn("Unable to migrate the VM", e);
+            } catch (java.util.concurrent.ExecutionException e) {
+                s_logger.warn("Unable to migrate the VM", e);
+            } catch (TimeoutException e) {
+                s_logger.warn("Unable to migrate the VM", e);
             }
+
             return false;
         }
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
index 2bb3ba3..297eea0 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
@@ -557,7 +557,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements
     private DomainRouterVO stop(DomainRouterVO elbVm, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException {
         s_logger.debug("Stopping ELB vm " + elbVm);
         try {
-            _itMgr.advanceStop(elbVm.getUuid(), forced);
+            _itMgr.stop(elbVm.getUuid(), forced);
             return _routerDao.findById(elbVm.getId());
         } catch (OperationTimedoutException e) {
             throw new CloudRuntimeException("Unable to stop " + elbVm, e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index 2a91c95..b0ac526 100644
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@ -552,7 +552,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements
     protected VirtualRouter stopInternalLbVm(DomainRouterVO internalLbVm, boolean forced, Account caller, long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException {
         s_logger.debug("Stopping internal lb vm " + internalLbVm);
         try {
-            _itMgr.advanceStop(internalLbVm.getUuid(), forced);
+            _itMgr.stop(internalLbVm.getUuid(), forced);
             return _internalLbVmDao.findById(internalLbVm.getId());
         } catch (OperationTimedoutException e) {
             throw new CloudRuntimeException("Unable to stop " + internalLbVm, e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
index fb20711..da61257 100755
--- a/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
+++ b/server/src/com/cloud/ha/HighAvailabilityManagerImpl.java
@@ -292,7 +292,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
         if (hostId == null) {
             try {
                 s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm);
-                _itMgr.advanceStop(vm.getUuid(), true);
+                _itMgr.stop(vm.getUuid(), true);
             } catch (ResourceUnavailableException e) {
                 assert false : "How do we hit this when force is true?";
                 throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
@@ -337,7 +337,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
             }
 
             try {
-                _itMgr.advanceStop(vm.getUuid(), true);
+                _itMgr.stop(vm.getUuid(), true);
             } catch (ResourceUnavailableException e) {
                 assert false : "How do we hit this when force is true?";
                 throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
@@ -485,7 +485,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
                 }
 
                 try {
-                    _itMgr.advanceStop(vm.getUuid(), true);
+                    _itMgr.stop(vm.getUuid(), true);
                 } catch (ResourceUnavailableException e) {
                     assert false : "How do we hit this when force is true?";
                     throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
@@ -502,7 +502,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
             } else {
                 s_logger.debug("How come that HA step is Investigating and the host is removed? Calling forced Stop on Vm anyways");
                 try {
-                    _itMgr.advanceStop(vm.getUuid(), true);
+                    _itMgr.stop(vm.getUuid(), true);
                 } catch (ResourceUnavailableException e) {
                     assert false : "How do we hit this when force is true?";
                     throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
@@ -671,7 +671,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
         s_logger.info("Stopping " + vm);
         try {
             if (work.getWorkType() == WorkType.Stop) {
-                _itMgr.advanceStop(vm.getUuid(), false);
+                _itMgr.stop(vm.getUuid(), false);
                 s_logger.info("Successfully stopped " + vm);
                 return null;
             } else if (work.getWorkType() == WorkType.CheckStop) {
@@ -681,7 +681,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
                             + " State: " + vm.getState());
                     return null;
                 }
-                _itMgr.advanceStop(vm.getUuid(), false);
+                _itMgr.stop(vm.getUuid(), false);
                 s_logger.info("Stop for " + vm + " was successful");
                 return null;
             } else if (work.getWorkType() == WorkType.ForceStop) {
@@ -691,7 +691,7 @@ public class HighAvailabilityManagerImpl extends ManagerBase implements HighAvai
                             + " State: " + vm.getState());
                     return null;
                 }
-                _itMgr.advanceStop(vm.getUuid(), true);
+                _itMgr.stop(vm.getUuid(), true);
                 s_logger.info("Stop for " + vm + " was successful");
                 return null;
             } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index 81eebe4..efd247b 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -2741,7 +2741,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
     public DomainRouterVO stop(VirtualRouter router, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException {
         s_logger.debug("Stopping router " + router);
         try {
-            _itMgr.advanceStop(router.getUuid(), forced);
+            _itMgr.stop(router.getUuid(), forced);
             return _routerDao.findById(router.getId());
         } catch (OperationTimedoutException e) {
             throw new CloudRuntimeException("Unable to stop " + router, e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java
index 2c20bc6..362b8e0 100755
--- a/server/src/com/cloud/server/ManagementServerImpl.java
+++ b/server/src/com/cloud/server/ManagementServerImpl.java
@@ -2131,7 +2131,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         User caller = _userDao.findById(CallContext.current().getCallingUserId());
 
-        _itMgr.advanceStop(systemVm.getUuid(), isForced);
+        _itMgr.stop(systemVm.getUuid(), isForced);
         return _consoleProxyDao.findById(systemVm.getId());
     }
 
@@ -3013,7 +3013,7 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe
 
         User caller = _userDao.findById(CallContext.current().getCallingUserId());
 
-        _itMgr.advanceStop(systemVm.getUuid(), isForced);
+        _itMgr.stop(systemVm.getUuid(), isForced);
         return _secStorageVmDao.findById(systemVm.getId());
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/StoragePoolAutomationImpl.java b/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
index e1550b8..cb085cc 100644
--- a/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
+++ b/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
@@ -234,7 +234,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                     }
                 } else if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
                     DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
-                    vmMgr.advanceStop(domR.getUuid(), false);
+                    vmMgr.stop(domR.getUuid(), false);
                     work.setStoppedForMaintenance(true);
                     _storagePoolWorkDao.update(work.getId(), work);
                     if (restart) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
index 64adc92..fd2d06f 100644
--- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
+++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
@@ -683,7 +683,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         }else {
             if(userVm.getState() == VirtualMachine.State.Running && vmSnapshotVo.getType() == VMSnapshot.Type.Disk){
                 try {
-                    _itMgr.advanceStop(userVm.getUuid(), false);
+                    _itMgr.stop(userVm.getUuid(), false);
                 } catch (Exception e) {
                     s_logger.error("Stop VM " + userVm.getInstanceName() + " before reverting failed due to " + e.getMessage());
     			    throw new CloudRuntimeException(e.getMessage());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c0febea9/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java b/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
index 0c23220..d4ded07 100644
--- a/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
+++ b/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
@@ -179,9 +179,8 @@ public class VmWorkMockVirtualMachineManagerImpl implements VirtualMachineManage
 	}
 
 	@Override
-    public void advanceStop(String vmUuid, boolean forced) throws ResourceUnavailableException,
-			OperationTimedoutException, ConcurrentOperationException {
-		// TODO Auto-generated method stub
+    public Outcome<VirtualMachine> stop(String vmUuid, boolean forced) {
+        return null;
 	}
 
 	@Override


[41/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index ac80383,704162e..560a673
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@@ -68,12 -66,8 +68,14 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd;
  import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd;
  import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd;
 +import org.apache.cloudstack.config.ConfigDepot;
 +import org.apache.cloudstack.config.ConfigKey;
 +import org.apache.cloudstack.config.ConfigValue;
 +import org.apache.cloudstack.config.Configurable;
 +import org.apache.cloudstack.config.Configuration;
 +import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
  import org.apache.cloudstack.region.PortableIp;
  import org.apache.cloudstack.region.PortableIpDao;
  import org.apache.cloudstack.region.PortableIpRange;
@@@ -321,14 -316,10 +321,15 @@@ public class ConfigurationManagerImpl e
      public ManagementService _mgr;
      @Inject
      DedicatedResourceDao _dedicatedDao;
 +    @Inject
 +    EntityManager _entityMgr;
 +
 +    @Inject
 +    List<Configurable> _configurables;
  
      // FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao?
-     @Inject protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao;
+     @Inject
+     protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao;
  
      private int _maxVolumeSizeInGb = Integer.parseInt(Config.MaxVolumeSize.getDefaultValue());
      private long _defaultPageSize = Long.parseLong(Config.DefaultPageSize.getDefaultValue());
@@@ -342,9 -334,10 +344,10 @@@
  
          String defaultPageSizeString = _configDao.getValue(Config.DefaultPageSize.key());
          _defaultPageSize = NumbersUtil.parseLong(defaultPageSizeString,
 -                Long.parseLong(Config.DefaultPageSize.getDefaultValue()));
 +        	Long.parseLong(Config.DefaultPageSize.getDefaultValue()));
  
          populateConfigValuesForValidationSet();
+         weightBasedParametersForValidation();
          return true;
      }
  
@@@ -413,62 -438,74 +448,74 @@@
              throw new InvalidParameterValueException(validationMsg);
          }
  
-         // If scope of the parameter is given then it needs to be updated in the corresponding details table,
-         // if scope is mentioned as global or not mentioned then it is normal global parameter updation
-         if (scope != null && !scope.isEmpty() && !Config.ConfigurationParameterScope.global.toString().equalsIgnoreCase(scope)) {
+         // If scope of the parameter is given then it needs to be updated in the
+         // corresponding details table,
+         // if scope is mentioned as global or not mentioned then it is normal
+         // global parameter updation
+         if (scope != null && !scope.isEmpty()
+                 && !Config.ConfigurationParameterScope.global.toString().equalsIgnoreCase(scope)) {
              switch (Config.ConfigurationParameterScope.valueOf(scope)) {
-                 case zone:      DataCenterVO zone = _zoneDao.findById(resourceId);
+             case zone:
+                 DataCenterVO zone = _zoneDao.findById(resourceId);
 -                if (zone == null) {
 -                    throw new InvalidParameterValueException("unable to find zone by id " + resourceId);
 -                }
 -                DcDetailVO dcDetailVO = _dcDetailsDao.findDetail(resourceId, name.toLowerCase());
 -                if (dcDetailVO == null) {
 -                    dcDetailVO = new DcDetailVO(resourceId, name, value);
 -                    _dcDetailsDao.persist(dcDetailVO);
 -                } else {
 -                    dcDetailVO.setValue(value);
 -                    _dcDetailsDao.update(dcDetailVO.getId(), dcDetailVO);
 +                                if (zone == null) {
 +                                    throw new InvalidParameterValueException("unable to find zone by id " + resourceId);
 +                                }
 +                                DcDetailVO dcDetailVO = _dcDetailsDao.findDetail(resourceId, name.toLowerCase());
 +                                if (dcDetailVO == null) {
 +                                    dcDetailVO = new DcDetailVO(resourceId, name, value);
 +                                    _dcDetailsDao.persist(dcDetailVO);
 +                                } else {
 +                                    dcDetailVO.setValue(value);
 +                                    _dcDetailsDao.update(dcDetailVO.getId(), dcDetailVO);
-                                 } break;
-                 case cluster:   ClusterVO cluster = _clusterDao.findById(resourceId);
+                 }
+                 break;
+             case cluster:
+                 ClusterVO cluster = _clusterDao.findById(resourceId);
 -                if (cluster == null) {
 -                    throw new InvalidParameterValueException("unable to find cluster by id " + resourceId);
 -                }
 -                ClusterDetailsVO clusterDetailsVO = _clusterDetailsDao.findDetail(resourceId, name);
 -                if (clusterDetailsVO == null) {
 -                    clusterDetailsVO = new ClusterDetailsVO(resourceId, name, value);
 -                    _clusterDetailsDao.persist(clusterDetailsVO);
 -                } else {
 -                    clusterDetailsVO.setValue(value);
 -                    _clusterDetailsDao.update(clusterDetailsVO.getId(), clusterDetailsVO);
 +                                if (cluster == null) {
 +                                    throw new InvalidParameterValueException("unable to find cluster by id " + resourceId);
 +                                }
 +                                ClusterDetailsVO clusterDetailsVO = _clusterDetailsDao.findDetail(resourceId, name);
 +                                if (clusterDetailsVO == null) {
 +                                    clusterDetailsVO = new ClusterDetailsVO(resourceId, name, value);
 +                                    _clusterDetailsDao.persist(clusterDetailsVO);
 +                                } else {
 +                                    clusterDetailsVO.setValue(value);
 +                                    _clusterDetailsDao.update(clusterDetailsVO.getId(), clusterDetailsVO);
-                                 } break;
+                 }
+                 break;
  
-                 case storagepool:      StoragePoolVO pool = _storagePoolDao.findById(resourceId);
+             case storagepool:
+                 StoragePoolVO pool = _storagePoolDao.findById(resourceId);
 -                if (pool == null) {
 -                    throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
 -                }
 -                StoragePoolDetailVO storagePoolDetailVO = _storagePoolDetailsDao.findDetail(resourceId, name);
 -                if (storagePoolDetailVO == null) {
 -                    storagePoolDetailVO = new StoragePoolDetailVO(resourceId, name, value);
 -                    _storagePoolDetailsDao.persist(storagePoolDetailVO);
 -
 -                } else {
 -                    storagePoolDetailVO.setValue(value);
 -                    _storagePoolDetailsDao.update(storagePoolDetailVO.getId(), storagePoolDetailVO);
 +                                if (pool == null) {
 +                                    throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
 +                                }
 +                                StoragePoolDetailVO storagePoolDetailVO = _storagePoolDetailsDao.findDetail(resourceId, name);
 +                                if (storagePoolDetailVO == null) {
 +                                    storagePoolDetailVO = new StoragePoolDetailVO(resourceId, name, value);
 +                                    _storagePoolDetailsDao.persist(storagePoolDetailVO);
 +
 +                                } else {
 +                                    storagePoolDetailVO.setValue(value);
 +                                    _storagePoolDetailsDao.update(storagePoolDetailVO.getId(), storagePoolDetailVO);
-                                 } break;
+                 }
+                 break;
  
-                 case account:   AccountVO account = _accountDao.findById(resourceId);
+             case account:
+                 AccountVO account = _accountDao.findById(resourceId);
 -                if (account == null) {
 -                    throw new InvalidParameterValueException("unable to find account by id " + resourceId);
 -                }
 -                AccountDetailVO accountDetailVO = _accountDetailsDao.findDetail(resourceId, name);
 -                if (accountDetailVO == null) {
 -                    accountDetailVO = new AccountDetailVO(resourceId, name, value);
 -                    _accountDetailsDao.persist(accountDetailVO);
 -                } else {
 -                    accountDetailVO.setValue(value);
 -                    _accountDetailsDao.update(accountDetailVO.getId(), accountDetailVO);
 +                                if (account == null) {
 +                                    throw new InvalidParameterValueException("unable to find account by id " + resourceId);
 +                                }
 +                                AccountDetailVO accountDetailVO = _accountDetailsDao.findDetail(resourceId, name);
 +                                if (accountDetailVO == null) {
 +                                    accountDetailVO = new AccountDetailVO(resourceId, name, value);
 +                                    _accountDetailsDao.persist(accountDetailVO);
 +                                } else {
 +                                    accountDetailVO.setValue(value);
 +                                    _accountDetailsDao.update(accountDetailVO.getId(), accountDetailVO);
-                                 } break;
-                 default:        throw new InvalidParameterValueException("Scope provided is invalid");
+                 }
+                 break;
+             default:
+                 throw new InvalidParameterValueException("Scope provided is invalid");
              }
              return value;
          }
@@@ -670,8 -723,8 +732,8 @@@
                  return "Please enter either 'true' or 'false'.";
              }
              if (Config.SwiftEnable.key().equals(name)) {
-                 List<HostVO> hosts = _ssvmMgr.listSecondaryStorageHostsInAllZones();
-                 if (hosts != null && hosts.size() > 0) {
 -                List<DataStore> stores = this._dataStoreMgr.listImageStores();
++                List<DataStore> stores = _dataStoreMgr.listImageStores();
+                 if (stores != null && stores.size() > 0) {
                      return " can not change " + Config.SwiftEnable.key() + " after you have added secondary storage";
                  }
                  SwiftVO swift = _swiftDao.findById(1L);
@@@ -1126,9 -1212,10 +1221,10 @@@
      }
  
      @Override
-     public Pod createPod(long zoneId, String name, String startIp, String endIp, String gateway, String netmask, String allocationState) {
+     public Pod createPod(long zoneId, String name, String startIp, String endIp, String gateway, String netmask,
+             String allocationState) {
          String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
 -        Long userId = UserContext.current().getCallerUserId();
 +        Long userId = CallContext.current().getCallingUserId();
  
          if (allocationState == null) {
              allocationState = Grouping.AllocationState.Enabled.toString();
@@@ -2159,10 -2320,20 +2328,20 @@@
          DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize, tags, isCustomized);
          newDiskOffering.setUseLocalStorage(localStorageRequired);
          newDiskOffering.setDisplayOffering(isDisplayOfferingEnabled);
 +        CallContext.current().setEventDetails("Disk offering id=" + newDiskOffering.getId());
+ 
+         if (bytesReadRate != null && (bytesReadRate > 0))
+             newDiskOffering.setBytesReadRate(bytesReadRate);
+         if (bytesWriteRate != null && (bytesWriteRate > 0))
+             newDiskOffering.setBytesWriteRate(bytesWriteRate);
+         if (iopsReadRate != null && (iopsReadRate > 0))
+             newDiskOffering.setIopsReadRate(iopsReadRate);
+         if (iopsWriteRate != null && (iopsWriteRate > 0))
+             newDiskOffering.setIopsWriteRate(iopsWriteRate);
+ 
 -        UserContext.current().setEventDetails("Disk offering id=" + newDiskOffering.getId());
          DiskOfferingVO offering = _diskOfferingDao.persist(newDiskOffering);
          if (offering != null) {
 -            UserContext.current().setEventDetails("Disk offering id=" + newDiskOffering.getId());
 +            CallContext.current().setEventDetails("Disk offering id=" + newDiskOffering.getId());
              return offering;
          } else {
              return null;
@@@ -2405,9 -2583,10 +2591,10 @@@
          }
  
          if (ipv6) {
 -            if (network.getGuestType() != GuestType.Shared || zone.isSecurityGroupEnabled()) {
 +        	if (network.getGuestType() != GuestType.Shared || zone.isSecurityGroupEnabled()) {
-         		throw new InvalidParameterValueException("Only support IPv6 on extending existed share network without SG");
+                 throw new InvalidParameterValueException(
+                         "Only support IPv6 on extending existed share network without SG");
 -            }
 +        	}
          }
          // verify that physical network exists
          PhysicalNetworkVO pNtwk = null;
@@@ -2444,19 -2628,21 +2636,20 @@@
                  }
              }
          }
 -
 +        
-         
          // Check if zone is enabled
 -        Account caller = UserContext.current().getCaller();
 -        if (Grouping.AllocationState.Disabled == zone.getAllocationState()
 -                && !_accountMgr.isRootAdmin(caller.getType())) {
 +        Account caller = CallContext.current().getCallingAccount();
 +        if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getType())) {
              throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
          }
  
          if (zone.isSecurityGroupEnabled() && zone.getNetworkType() != DataCenter.NetworkType.Basic && forVirtualNetwork) {
-             throw new InvalidParameterValueException("Can't add virtual ip range into a zone with security group enabled");
+             throw new InvalidParameterValueException(
+                     "Can't add virtual ip range into a zone with security group enabled");
          }
 -
 +        
-         // If networkId is not specified, and vlan is Virtual or Direct Untagged, try to locate default networks
+         // If networkId is not specified, and vlan is Virtual or Direct
+         // Untagged, try to locate default networks
          if (forVirtualNetwork) {
              if (network == null) {
                  // find default public network in the zone
@@@ -2489,37 -2676,40 +2683,40 @@@
              throw new InvalidParameterValueException("Network " + network + " doesn't support adding ip ranges");
          }
  
-         if ( zone.getNetworkType() == DataCenter.NetworkType.Advanced ) {
+         if (zone.getNetworkType() == DataCenter.NetworkType.Advanced) {
              if (network.getTrafficType() == TrafficType.Guest) {
                  if (network.getGuestType() != GuestType.Shared) {
-                     throw new InvalidParameterValueException("Can execute createVLANIpRanges on shared guest network, but type of this guest network "
+                     throw new InvalidParameterValueException(
+                             "Can execute createVLANIpRanges on shared guest network, but type of this guest network "
 -                                    + network.getId() + " is " + network.getGuestType());
 +                            + network.getId() + " is " + network.getGuestType());
                  }
  
                  List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
 -                VlanVO vlan = vlans.get(0);
 +                    VlanVO vlan = vlans.get(0);
-                 if ( vlans != null && vlans.size() > 0 ) {
-                     if ( vlanId == null ) {
+                 if (vlans != null && vlans.size() > 0) {
+                     if (vlanId == null) {
                          vlanId = vlan.getVlanTag();
                      } else if (!vlan.getVlanTag().equals(vlanId)) {
-                         throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag() + " on network :" +
-                                 + network.getId() + ", only one vlan is allowed on guest network");
+                         throw new InvalidParameterValueException("there is already one vlan " + vlan.getVlanTag()
+                                 + " on network :" + +network.getId() + ", only one vlan is allowed on guest network");
                      }
 -                }
 +                    }
-                sameSubnet=validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr,startIPv6, endIPv6, network);
+                 sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6,
+                         ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
  
 -            }
 +                }
  
 -        } else if (network.getTrafficType() == TrafficType.Management) {
 -            throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
 +            } else if (network.getTrafficType() == TrafficType.Management) {
 +                throw new InvalidParameterValueException("Cannot execute createVLANIpRanges on management network");
-             }
-         else if (zone.getNetworkType() == NetworkType.Basic){
+         } else if (zone.getNetworkType() == NetworkType.Basic) {
 -            List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
 +                 List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(network.getId());
-                  sameSubnet=validateIpRange(startIP,endIP,newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway, ip6Cidr, startIPv6, endIPv6, network);
+             sameSubnet = validateIpRange(startIP, endIP, newVlanGateway, newVlanNetmask, vlans, ipv4, ipv6, ip6Gateway,
+                     ip6Cidr, startIPv6, endIPv6, network);
          }
  
 -        if (zoneId == null || (ipv6 && (ip6Gateway == null || ip6Cidr == null))) {
 +        if (zoneId == null  || (ipv6 && (ip6Gateway == null || ip6Cidr == null))) {
-             throw new InvalidParameterValueException("Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
+             throw new InvalidParameterValueException(
+                     "Gateway, netmask and zoneId have to be passed in for virtual and direct untagged networks");
          }
  
          if (forVirtualNetwork) {
@@@ -2582,14 -2773,16 +2780,16 @@@
          String cidrnew = NetUtils.getCidrFromGatewayAndNetmask(newVlanGateway, newVlanNetmask);
          String existing_cidr = NetUtils.getCidrFromGatewayAndNetmask(vlan.getVlanGateway(), vlan.getVlanNetmask());
  
 -        return (NetUtils.isNetowrkASubsetOrSupersetOfNetworkB(cidrnew, existing_cidr));
 +        return  (NetUtils.isNetowrkASubsetOrSupersetOfNetworkB(cidrnew, existing_cidr));
      }
  
-     public Pair<Boolean,Pair<String,String>> validateIpRange(String startIP, String endIP, String newVlanGateway, String newVlanNetmask, List<VlanVO> vlans, boolean ipv4, boolean ipv6, String ip6Gateway, String ip6Cidr, String startIPv6, String endIPv6, Network network) {
-         String vlanGateway=null;
-         String vlanNetmask=null;
+     public Pair<Boolean, Pair<String, String>> validateIpRange(String startIP, String endIP, String newVlanGateway,
+             String newVlanNetmask, List<VlanVO> vlans, boolean ipv4, boolean ipv6, String ip6Gateway, String ip6Cidr,
+             String startIPv6, String endIPv6, Network network) {
+         String vlanGateway = null;
+         String vlanNetmask = null;
          boolean sameSubnet = false;
-         if ( vlans != null && vlans.size() > 0 ) {
+         if (vlans != null && vlans.size() > 0) {
              for (VlanVO vlan : vlans) {
                  if (ipv4) {
                      vlanGateway = vlan.getVlanGateway();
@@@ -2625,63 -2823,65 +2830,65 @@@
                      _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
                  }
              }
 -        }
 +                }
-         if (newVlanGateway==null && newVlanNetmask ==null && sameSubnet == false) {
-             throw new InvalidParameterValueException("The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet");
+         if (newVlanGateway == null && newVlanNetmask == null && sameSubnet == false) {
+             throw new InvalidParameterValueException(
+                     "The ip range dose not belong to any of the existing subnets, Provide the netmask and gateway if you want to add new subnet");
          }
-         Pair<String,String> vlanDetails=null;
+         Pair<String, String> vlanDetails = null;
  
-         if (sameSubnet){
+         if (sameSubnet) {
 -            vlanDetails = new Pair<String, String>(vlanGateway, vlanNetmask);
 +             vlanDetails = new Pair<String, String>(vlanGateway, vlanNetmask);
-         }
-         else {
+         } else {
 -            vlanDetails = new Pair<String, String>(newVlanGateway, newVlanNetmask);
 -        }
 +             vlanDetails = new Pair<String, String>(newVlanGateway, newVlanNetmask);
 +            }
-         //check if the gatewayip is the part of the ip range being added.
+         // check if the gatewayip is the part of the ip range being added.
          if (NetUtils.ipRangesOverlap(startIP, endIP, vlanDetails.first(), vlanDetails.first())) {
-             throw new InvalidParameterValueException("The gateway ip should not be the part of the ip range being added.");
+             throw new InvalidParameterValueException(
+                     "The gateway ip should not be the part of the ip range being added.");
          }
  
-         Pair<Boolean,Pair<String,String>> result = new Pair<Boolean,Pair<String,String>>(sameSubnet, vlanDetails);
+         Pair<Boolean, Pair<String, String>> result = new Pair<Boolean, Pair<String, String>>(sameSubnet, vlanDetails);
 -        return result;
 +        return  result;
      }
  
      @Override
      @DB
-     public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId,
-             String startIP, String endIP, String vlanGateway, String vlanNetmask,
-             String vlanId, Account vlanOwner, String startIPv6, String endIPv6, String vlanIp6Gateway, String vlanIp6Cidr) {
+     public Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId,
+             boolean forVirtualNetwork, Long podId, String startIP, String endIP, String vlanGateway,
+             String vlanNetmask, String vlanId, Account vlanOwner, String startIPv6, String endIPv6,
+             String vlanIp6Gateway, String vlanIp6Cidr) {
          Network network = _networkModel.getNetwork(networkId);
 -
 +        
          boolean ipv4 = false, ipv6 = false;
 -
 +        
          if (startIP != null) {
 -            ipv4 = true;
 +        	ipv4 = true;
          }
 -
 +        
          if (startIPv6 != null) {
 -            ipv6 = true;
 +        	ipv6 = true;
          }
 -
 +        
          if (!ipv4 && !ipv6) {
              throw new InvalidParameterValueException("Please specify IPv4 or IPv6 address.");
          }
 -
 +        
-         //Validate the zone
+         // Validate the zone
          DataCenterVO zone = _zoneDao.findById(zoneId);
          if (zone == null) {
              throw new InvalidParameterValueException("Please specify a valid zone.");
          }
 -
 +        
          // ACL check
 -        checkZoneAccess(UserContext.current().getCaller(), zone);
 -
 +        checkZoneAccess(CallContext.current().getCallingAccount(), zone);
 +        
-         //Validate the physical network
+         // Validate the physical network
          if (_physicalNetworkDao.findById(physicalNetworkId) == null) {
              throw new InvalidParameterValueException("Please specify a valid physical network id");
          }
 -
 +        
-         //Validate the pod
+         // Validate the pod
          if (podId != null) {
              Pod pod = _podDao.findById(podId);
              if (pod == null) {
@@@ -2690,27 -2890,29 +2897,29 @@@
              if (pod.getDataCenterId() != zoneId) {
                  throw new InvalidParameterValueException("Pod id=" + podId + " doesn't belong to zone id=" + zoneId);
              }
-             //pod vlans can be created in basic zone only
+             // pod vlans can be created in basic zone only
              if (zone.getNetworkType() != NetworkType.Basic || network.getTrafficType() != TrafficType.Guest) {
                  throw new InvalidParameterValueException("Pod id can be specified only for the networks of type "
 -                        + TrafficType.Guest + " in zone of type " + NetworkType.Basic);
 +                                                        + TrafficType.Guest + " in zone of type " + NetworkType.Basic);
              }
          }
 -
 +        
-         //1) if vlan is specified for the guest network range, it should be the same as network's vlan
-         //2) if vlan is missing, default it to the guest network's vlan
+         // 1) if vlan is specified for the guest network range, it should be the
+         // same as network's vlan
+         // 2) if vlan is missing, default it to the guest network's vlan
          if (network.getTrafficType() == TrafficType.Guest) {
              String networkVlanId = null;
              URI uri = network.getBroadcastUri();
              if (uri != null) {
                  String[] vlan = uri.toString().split("vlan:\\/\\/");
                  networkVlanId = vlan[1];
-                 //For pvlan
+                 // For pvlan
                  networkVlanId = networkVlanId.split("-")[0];
              }
 -
 +            
              if (vlanId != null) {
-                 // if vlan is specified, throw an error if it's not equal to network's vlanId
+                 // if vlan is specified, throw an error if it's not equal to
+                 // network's vlanId
                  if (networkVlanId != null && !networkVlanId.equalsIgnoreCase(vlanId)) {
                      throw new InvalidParameterValueException("Vlan doesn't match vlan of the network");
                  }
@@@ -2718,19 -2920,19 +2927,19 @@@
                  vlanId = networkVlanId;
              }
          } else if (network.getTrafficType() == TrafficType.Public && vlanId == null) {
-             //vlan id is required for public network
+             // vlan id is required for public network
              throw new InvalidParameterValueException("Vlan id is required when add ip range to the public network");
          }
 -
 +        
          if (vlanId == null) {
              vlanId = Vlan.UNTAGGED;
          }
  
          VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached;
 -
 +        
-         
          if (vlanOwner != null && zone.getNetworkType() != NetworkType.Advanced) {
-             throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced);
+             throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type "
+                     + NetworkType.Advanced);
          }
  
          if (ipv4) {
@@@ -2755,111 -2957,126 +2964,126 @@@
          }
  
          if (ipv4) {
 -            String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask);
 +        	String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask);
  
-         	// Check if the new VLAN's subnet conflicts with the guest network in
+             // Check if the new VLAN's subnet conflicts with the guest network
+             // in
 -            // the specified zone (guestCidr is null for basic zone)
 -            String guestNetworkCidr = zone.getGuestNetworkCidr();
 -            if (guestNetworkCidr != null) {
 -                String[] cidrPair = guestNetworkCidr.split("\\/");
 -                String guestIpNetwork = NetUtils.getIpRangeStartIpFromCidr(cidrPair[0], Long.parseLong(cidrPair[1]));
 -                long guestCidrSize = Long.parseLong(cidrPair[1]);
 -                long vlanCidrSize = NetUtils.getCidrSize(vlanNetmask);
 -
 -                long cidrSizeToUse = -1;
 -                if (vlanCidrSize < guestCidrSize) {
 -                    cidrSizeToUse = vlanCidrSize;
 -                } else {
 -                    cidrSizeToUse = guestCidrSize;
 -                }
 -
 -                String guestSubnet = NetUtils.getCidrSubNet(guestIpNetwork, cidrSizeToUse);
 -
 -                if (newVlanSubnet.equals(guestSubnet)) {
 +        	// the specified zone (guestCidr is null for basic zone)
 +        	String guestNetworkCidr = zone.getGuestNetworkCidr();
 +        	if (guestNetworkCidr != null) {
 +        		String[] cidrPair = guestNetworkCidr.split("\\/");
 +        		String guestIpNetwork = NetUtils.getIpRangeStartIpFromCidr(cidrPair[0], Long.parseLong(cidrPair[1]));
 +        		long guestCidrSize = Long.parseLong(cidrPair[1]);
 +        		long vlanCidrSize = NetUtils.getCidrSize(vlanNetmask);
 +
 +        		long cidrSizeToUse = -1;
 +        		if (vlanCidrSize < guestCidrSize) {
 +        			cidrSizeToUse = vlanCidrSize;
 +        		} else {
 +        			cidrSizeToUse = guestCidrSize;
 +        		}
 +
 +        		String guestSubnet = NetUtils.getCidrSubNet(guestIpNetwork, cidrSizeToUse);
 +
 +        		if (newVlanSubnet.equals(guestSubnet)) {
-         			throw new InvalidParameterValueException("The new IP range you have specified has the same subnet as the guest network in zone: " + zone.getName()
-         					+ ". Please specify a different gateway/netmask.");
+                     throw new InvalidParameterValueException(
+                             "The new IP range you have specified has the same subnet as the guest network in zone: "
+                                     + zone.getName() + ". Please specify a different gateway/netmask.");
 -                }
 -            }
 +        		}
 +        	}
  
 -            // Check if there are any errors with the IP range
 -            checkPublicIpRangeErrors(zoneId, vlanId, vlanGateway, vlanNetmask, startIP, endIP);
 +        	// Check if there are any errors with the IP range
 +        	checkPublicIpRangeErrors(zoneId, vlanId, vlanGateway, vlanNetmask, startIP, endIP);
  
 -            // Throw an exception if any of the following is true:
 -            // 1. Another VLAN in the same zone has a different tag but the same
 -            // subnet as the new VLAN. Make an exception for the
 -            // case when both vlans are Direct.
 +        	// Throw an exception if any of the following is true:
 +        	// 1. Another VLAN in the same zone has a different tag but the same
 +        	// subnet as the new VLAN. Make an exception for the
 +        	// case when both vlans are Direct.
-         	// 2. Another VLAN in the same zone that has the same tag and subnet as
+             // 2. Another VLAN in the same zone that has the same tag and subnet
+             // as
 -            // the new VLAN has IPs that overlap with the IPs
 -            // being added
 +        	// the new VLAN has IPs that overlap with the IPs
 +        	// being added
-         	// 3. Another VLAN in the same zone that has the same tag and subnet as
+             // 3. Another VLAN in the same zone that has the same tag and subnet
+             // as
 -            // the new VLAN has a different gateway than the
 -            // new VLAN
 +        	// the new VLAN has a different gateway than the
 +        	// new VLAN
-         	// 4. If VLAN is untagged and Virtual, and there is existing UNTAGGED
+             // 4. If VLAN is untagged and Virtual, and there is existing
+             // UNTAGGED
 -            // vlan with different subnet
 -            List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
 -            for (VlanVO vlan : vlans) {
 -                String otherVlanGateway = vlan.getVlanGateway();
 -                // Continue if it's not IPv4
 -                if (otherVlanGateway == null) {
 -                    continue;
 -                }
 -                String otherVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
 -                String[] otherVlanIpRange = vlan.getIpRange().split("\\-");
 -                String otherVlanStartIP = otherVlanIpRange[0];
 -                String otherVlanEndIP = null;
 -                if (otherVlanIpRange.length > 1) {
 -                    otherVlanEndIP = otherVlanIpRange[1];
 -                }
 +        	// vlan with different subnet
 +        	List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
 +        	for (VlanVO vlan : vlans) {
 +        		String otherVlanGateway = vlan.getVlanGateway();
 +        		// Continue if it's not IPv4
 +        		if (otherVlanGateway == null) {
 +        			continue;
 +        		}
 +        		String otherVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
 +        		String[] otherVlanIpRange = vlan.getIpRange().split("\\-");
 +        		String otherVlanStartIP = otherVlanIpRange[0];
 +        		String otherVlanEndIP = null;
 +        		if (otherVlanIpRange.length > 1) {
 +        			otherVlanEndIP = otherVlanIpRange[1];
 +        		}
  
-         		if (forVirtualNetwork && !vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet) && !allowIpRangeOverlap(vlan, forVirtualNetwork, networkId)) {
-         			throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " in zone " + zone.getName()
+                 if (forVirtualNetwork && !vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet)
+                         && !allowIpRangeOverlap(vlan, forVirtualNetwork, networkId)) {
+                     throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag()
+                             + " in zone " + zone.getName()
 -                            + " has the same subnet. Please specify a different gateway/netmask.");
 -                }
 +        					+ " has the same subnet. Please specify a different gateway/netmask.");
 +        		}
  
-         		boolean vlansUntaggedAndVirtual = (vlanId.equals(Vlan.UNTAGGED) && vlanId.equals(vlan.getVlanTag()) && forVirtualNetwork && vlan.getVlanType() == VlanType.VirtualNetwork);
+                 boolean vlansUntaggedAndVirtual = (vlanId.equals(Vlan.UNTAGGED) && vlanId.equals(vlan.getVlanTag())
+                         && forVirtualNetwork && vlan.getVlanType() == VlanType.VirtualNetwork);
  
 -                if (vlansUntaggedAndVirtual && !newVlanSubnet.equals(otherVlanSubnet)) {
 +        		if (vlansUntaggedAndVirtual && !newVlanSubnet.equals(otherVlanSubnet)) {
-         			throw new InvalidParameterValueException("The Untagged ip range with different subnet already exists in zone " + zone.getId());
+                     throw new InvalidParameterValueException(
+                             "The Untagged ip range with different subnet already exists in zone " + zone.getId());
 -                }
 +        		}
  
 -                if (vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet)) {
 -                    if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) {
 +        		if (vlanId.equals(vlan.getVlanTag()) && newVlanSubnet.equals(otherVlanSubnet)) {
 +        			if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) {
-         				throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag()
+                         throw new InvalidParameterValueException(
+                                 "The IP range with tag: "
+                                         + vlan.getVlanTag()
 -                                        + " already has IPs that overlap with the new range. Please specify a different start IP/end IP.");
 -                    }
 +        						+ " already has IPs that overlap with the new range. Please specify a different start IP/end IP.");
 +        			}
  
 -                    if (!vlanGateway.equals(otherVlanGateway)) {
 +        			if (!vlanGateway.equals(otherVlanGateway)) {
-         				throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + otherVlanGateway
+                         throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag()
+                                 + " has already been added with gateway " + otherVlanGateway
 -                                + ". Please specify a different tag.");
 -                    }
 -                }
 -            }
 +        						+ ". Please specify a different tag.");
 +        			}
 +        		}
 +        	}
          }
 -
 +        
          String ipv6Range = null;
          if (ipv6) {
 -            ipv6Range = startIPv6;
 -            if (endIPv6 != null) {
 -                ipv6Range += "-" + endIPv6;
 -            }
 -
 -            List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
 -            for (VlanVO vlan : vlans) {
 -                if (vlan.getIp6Gateway() == null) {
 -                    continue;
 -                }
 -                if (vlanId.equals(vlan.getVlanTag())) {
 -                    if (NetUtils.isIp6RangeOverlap(ipv6Range, vlan.getIp6Range())) {
 +        	ipv6Range = startIPv6;
 +        	if (endIPv6 != null) {
 +        		ipv6Range += "-" + endIPv6;
 +        	}
 +        	
 +        	List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
 +        	for (VlanVO vlan : vlans) {
 +        		if (vlan.getIp6Gateway() == null) {
 +        			continue;
 +        		}
 +        		if (vlanId.equals(vlan.getVlanTag())) {
 +        			if (NetUtils.isIp6RangeOverlap(ipv6Range, vlan.getIp6Range())) {
-         				throw new InvalidParameterValueException("The IPv6 range with tag: " + vlan.getVlanTag()
+                         throw new InvalidParameterValueException(
+                                 "The IPv6 range with tag: "
+                                         + vlan.getVlanTag()
 -                                        + " already has IPs that overlap with the new range. Please specify a different start IP/end IP.");
 -                    }
 +        						+ " already has IPs that overlap with the new range. Please specify a different start IP/end IP.");
 +        			}
  
 -                    if (!vlanIp6Gateway.equals(vlan.getIp6Gateway())) {
 +        			if (!vlanIp6Gateway.equals(vlan.getIp6Gateway())) {
-         				throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + vlan.getIp6Gateway()
+                         throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag()
+                                 + " has already been added with gateway " + vlan.getIp6Gateway()
 -                                + ". Please specify a different tag.");
 -                    }
 -                }
 -            }
 +        						+ ". Please specify a different tag.");
 +        			}
 +        		}
 +        	}
          }
  
          // Check if a guest VLAN is using the same tag
@@@ -2884,11 -3103,12 +3110,12 @@@
          s_logger.debug("Saving vlan range " + vlan);
          vlan = _vlanDao.persist(vlan);
  
-         // IPv6 use a used ip map, is different from ipv4, no need to save public ip range
+         // IPv6 use a used ip map, is different from ipv4, no need to save
+         // public ip range
          if (ipv4) {
 -            if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) {
 -                throw new CloudRuntimeException("Failed to save IPv4 range. Please contact Cloud Support.");
 -            }
 +        	if (!savePublicIPRange(startIP, endIP, zoneId, vlan.getId(), networkId, physicalNetworkId)) {
 +        		throw new CloudRuntimeException("Failed to save IPv4 range. Please contact Cloud Support.");
 +        	}
          }
  
          if (vlanOwner != null) {
@@@ -2923,10 -3152,11 +3159,11 @@@
          if (vlanRange == null) {
              throw new InvalidParameterValueException("Please specify a valid IP range id.");
          }
 -
 +        
          boolean isAccountSpecific = false;
          List<AccountVlanMapVO> acctVln = _accountVlanMapDao.listAccountVlanMapsByVlan(vlanRange.getId());
-         // Check for account wide pool. It will have an entry for account_vlan_map.
+         // Check for account wide pool. It will have an entry for
+         // account_vlan_map.
          if (acctVln != null && !acctVln.isEmpty()) {
              isAccountSpecific = true;
          }
@@@ -2946,24 -3176,33 +3183,33 @@@
                      if (s_logger.isDebugEnabled()) {
                          s_logger.debug("lock vlan " + vlanDbId + " is acquired");
                      }
-                     
                      for (IPAddressVO ip : ips) {
                          if (ip.isOneToOneNat()) {
-                             throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId +
-                                     " as ip " + ip + " belonging to the range is used for static nat purposes. Cleanup the rules first");
+                             throw new InvalidParameterValueException(
+                                     "Can't delete account specific vlan "
+                                             + vlanDbId
+                                             + " as ip "
+                                             + ip
+                                             + " belonging to the range is used for static nat purposes. Cleanup the rules first");
                          }
 -
 +                        
                          if (ip.isSourceNat()) {
-                             throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId +
-                                     " as ip " + ip + " belonging to the range is a source nat ip for the network id=" + ip.getSourceNetworkId() +
-                                     ". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
+                             throw new InvalidParameterValueException(
+                                     "Can't delete account specific vlan "
+                                             + vlanDbId
+                                             + " as ip "
+                                             + ip
+                                             + " belonging to the range is a source nat ip for the network id="
+                                             + ip.getSourceNetworkId()
+                                             + ". IP range with the source nat ip address can be removed either as a part of Network, or account removal");
                          }
 -
 +                        
                          if (_firewallDao.countRulesByIpId(ip.getId()) > 0) {
-                             throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId +
-                                     " as ip " + ip + " belonging to the range has firewall rules applied. Cleanup the rules first");
+                             throw new InvalidParameterValueException("Can't delete account specific vlan " + vlanDbId
+                                     + " as ip " + ip
+                                     + " belonging to the range has firewall rules applied. Cleanup the rules first");
                          }
-                         //release public ip address here
+                         // release public ip address here
                          success = success && _networkMgr.disassociatePublicIpAddress(ip.getId(), userId, caller);
                      }
                      if (!success) {
@@@ -2989,120 -3230,126 +3237,126 @@@
                  Network network = _networkDao.findById(vlanRange.getNetworkId());
                  DhcpServiceProvider dhcpServiceProvider = _networkMgr.getDhcpServiceProvider(network);
                  if (!dhcpServiceProvider.getProvider().getName().equalsIgnoreCase(Provider.VirtualRouter.getName())) {
-                     if (!deletePublicIPRange(vlanDbId)) {
+                     Transaction txn = Transaction.currentTxn();
+                     txn.start();
+                     if (!removeFromDb(vlanDbId)) {
+                         txn.rollback();
+                         txn.close();
                          return false;
                      }
-                     _vlanDao.expunge(vlanDbId);
+ 
+                     else {
+                         txn.commit();
+                     }
+                     txn.close();
+                 }
+ 
+                 else {
+                   return  handleIpAliasDeletion(vlanRange, vlanDbId, dhcpServiceProvider, network);
+                 }
+             }
+         }
 -        return true;
 -    }
 +                    return  true;
 +                }
-                 //search if the vlan has any allocated ips.
-                 boolean aliasIpBelongsToThisVlan = false;
-                 long freeIpsInsubnet = 0;
+ 
+     private boolean handleIpAliasDeletion(VlanVO vlanRange, long vlanDbId, DhcpServiceProvider dhcpServiceProvider, Network network) {
+         boolean result_final = false;
+         Transaction txn = Transaction.currentTxn();
+         txn.start();
+         IPAddressVO ip = null;
 -        NicIpAliasVO ipAlias = null;
 +                NicIpAliasVO ipAlias = null;
+         try{
+             Integer allocIpCount=0;
+             //search if the vlan has any allocated ips.
 -            allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
 -            if (allocIpCount > 1) {
 -                throw  new InvalidParameterValueException ("cannot delete this range as some of the vlans are in use.");
 -            }
 -            if (allocIpCount == 0){
 +                allocIpCount = _publicIpAddressDao.countIPs(vlanRange.getDataCenterId(), vlanDbId, true);
 +                if (allocIpCount > 1) {
 +                    throw  new InvalidParameterValueException ("cannot delete this range as some of the vlans are in use.");
 +                }
 +                if (allocIpCount == 0){
-                     //remove the vlan range.
-                     if (!deletePublicIPRange(vlanDbId)) {
-                         return false;
-                     }
-                     _vlanDao.expunge(vlanDbId);
-                     return true;
+                 result_final=true;
 -            }
 +                }
-                 //check if this allocated ip is being used as an ipAlias on the router.
+             else {
                  ipAlias = _nicIpAliasDao.findByGatewayAndNetworkIdAndState(vlanRange.getVlanGateway(), vlanRange.getNetworkId(),  NicIpAlias.state.active);
+                 ipAlias.setState(NicIpAlias.state.revoked);
+                 _nicIpAliasDao.update(ipAlias.getId(), ipAlias);
                  //check if this ip belongs to this vlan and is allocated.
-                 IPAddressVO ip = _publicIpAddressDao.findByIpAndVlanId(ipAlias.getIp4Address(), vlanDbId);
+                 ip = _publicIpAddressDao.findByIpAndVlanId(ipAlias.getIp4Address(), vlanDbId);
                  if (ip != null && ip.getState() == IpAddress.State.Allocated) {
-                     aliasIpBelongsToThisVlan =true;
                      //check if there any other vlan ranges in the same subnet having free ips
                      List<VlanVO> vlanRanges = _vlanDao.listVlansByNetworkIdAndGateway(vlanRange.getNetworkId(), vlanRange.getVlanGateway());
                      //if there is no other vlanrage in this subnet. free the ip and delete the vlan.
                      if (vlanRanges.size() == 1){
                          boolean result = dhcpServiceProvider.removeDhcpSupportForSubnet(network);
                          if (result == false) {
+                             result_final = false;
                              s_logger.debug("Failed to delete the vlan range as we could not free the ip used to provide the dhcp service.");
-                         }
-                         else {
+                         } else {
                              _publicIpAddressDao.unassignIpAddress(ip.getId());
-                             if (!deletePublicIPRange(vlanDbId)) {
-                                 return false;
-                             }
-                             _vlanDao.expunge(vlanDbId);
-                             _nicIpAliasDao.expunge(ipAlias.getId());
+                             result_final = true;
                          }
 -                    } else {
 +        } else {
-                         // if there are more vlans in the subnet check if there are free ips.
+                         // if there are more vlans in the subnet check if there
+                         // are free ips.
                          List<Long> vlanDbIdList = new ArrayList<Long>();
                          for (VlanVO vlanrange : vlanRanges) {
                              if (vlanrange.getId() != vlanDbId) {
                                  vlanDbIdList.add(vlanrange.getId());
                              }
                          }
-                         s_logger.info("vlan Range"+vlanRange.getId()+" id being deleted, one of the Ips in this range is used to provide the dhcp service, trying to free this ip and allocate a new one.");
+                         s_logger.info("vlan Range"
+                                 + vlanRange.getId()
+                                 + " id being deleted, one of the Ips in this range is used to provide the dhcp service, trying to free this ip and allocate a new one.");
                          for (VlanVO vlanrange : vlanRanges) {
                              if (vlanrange.getId() != vlanDbId) {
-                                 freeIpsInsubnet =  _publicIpAddressDao.countFreeIpsInVlan(vlanrange.getId());
+ 
+                                 long freeIpsInsubnet =  _publicIpAddressDao.countFreeIpsInVlan(vlanrange.getId());
                                  if (freeIpsInsubnet > 0){
-                                     //assign one free ip to the router for creating ip Alias.
-                                     Transaction txn = Transaction.currentTxn();
-                                     //changing the state to revoked so that removeDhcpSupport for subnet sses it.
-                                     ipAlias.setState(NicIpAlias.state.revoked);
-                                     _nicIpAliasDao.update(ipAlias.getId(), ipAlias);
+                                     //assign one free ip to the router for creating ip Alias. The ipalias is system managed ip so we are using the system account to allocate the ip not the caller.
                                      boolean result = false;
-                                     try {
-                                         PublicIp routerPublicIP = _networkMgr.assignPublicIpAddressFromVlans(network.getDataCenterId(), null, caller, Vlan.VlanType.DirectAttached, vlanDbIdList, network.getId(), null, false);
+                                     PublicIp routerPublicIP = _networkMgr.assignPublicIpAddressFromVlans(network.getDataCenterId(), null, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), Vlan.VlanType.DirectAttached, vlanDbIdList, network.getId(), null, false);
 -                                    s_logger.info("creating a db entry for the new ip alias.");
 -                                    NicIpAliasVO newipAlias = new NicIpAliasVO(ipAlias.getNicId(), routerPublicIP.getAddress().addr(), ipAlias.getVmId(), ipAlias.getAccountId(), network.getDomainId(), network.getId(), ipAlias.getGateway(), ipAlias.getNetmask());
 -                                    newipAlias.setAliasCount(routerPublicIP.getIpMacAddress());
 -                                    _nicIpAliasDao.persist(newipAlias);
 -                                    //we revoke all the rules and apply all the rules as a part of the removedhcp config. so the new ip will get configured when we delete the old ip.
 +                                        s_logger.info("creating a db entry for the new ip alias.");
 +                                        NicIpAliasVO newipAlias = new NicIpAliasVO(ipAlias.getNicId(), routerPublicIP.getAddress().addr(), ipAlias.getVmId(), ipAlias.getAccountId(), network.getDomainId(), network.getId(), ipAlias.getGateway(), ipAlias.getNetmask());
 +                                        newipAlias.setAliasCount(routerPublicIP.getIpMacAddress());
 +                                        _nicIpAliasDao.persist(newipAlias);
 +                                        //we revoke all the rules and apply all the rules as a part of the removedhcp config. so the new ip will get configured when we delete the old ip.
- 
-                                     }
-                                     catch (InsufficientAddressCapacityException e) {
-                                         txn.rollback();
-                                         txn.close();
-                                         throw new InvalidParameterValueException("cannot delete  vlan range"+ vlanRange.getId()+"one of the ips in this range is benig used to provide dhcp service. Cannot use some other ip as there are no free ips in this subnet");
-                                     }
                                      s_logger.info("removing the old ip alias on router");
                                      result = dhcpServiceProvider.removeDhcpSupportForSubnet(network);
                                      if (result == false) {
                                          s_logger.debug("could't delete the ip alias on the router");
-                                         txn.rollback();
-                                         txn.close();
-                                         return false;
+                                         result_final = false;
                                      }
+                                     else {
 -                                        _publicIpAddressDao.unassignIpAddress(ip.getId());
 +                                    _publicIpAddressDao.unassignIpAddress(ip.getId());
-                                     if (!deletePublicIPRange(vlanDbId)) {
-             return false;
+                                         result_final=true;
+                                     }
 +        }
                                  }
                              }
                          }
 -                    }
 +    }
                  }
 -            }
  
-             } else {
-                 // when there is no dhcp support in the network.
-                 if (!deletePublicIPRange(vlanDbId)) {
-                     return false;
+         } catch (InsufficientAddressCapacityException e) {
+             throw new InvalidParameterValueException("cannot delete  vlan range"+ vlanRange.getId()+"one of the ips in this range is benig used to provide dhcp service. Cannot use some other ip as there are no free ips in this subnet");
 -        }
++                }
+         finally {
+             if (result_final) {
+                 if (!removeFromDb(vlanDbId)) {
+                     txn.rollback();
                  }
-                 _vlanDao.expunge(vlanDbId);
-                 return  true;
+                 else {
+                     txn.commit();
+                 }
+                 txn.close();
              }
          }
-         return false;
+         return result_final;
      }
  
- 
      @Override
      @DB
-     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DEDICATE, eventDescription = "dedicating vlan ip range", async = false)
+     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DEDICATE, eventDescription = "dedicating vlan ip range",
+             async = false)
      public Vlan dedicatePublicIpRange(DedicatePublicIpRangeCmd cmd) throws ResourceAllocationException {
          Long vlanDbId = cmd.getId();
          String accountName = cmd.getAccountName();
@@@ -3200,10 -3452,10 +3459,9 @@@
              throw new InvalidParameterValueException("Please specify a valid IP range id.");
          }
  
 -        return releasePublicIpRange(vlanDbId, UserContext.current().getCallerUserId(), UserContext.current()
 -                .getCaller());
 +        return releasePublicIpRange(vlanDbId, CallContext.current().getCallingUserId(), CallContext.current().getCallingAccount());
      }
  
- 
      @DB
      public boolean releasePublicIpRange(long vlanDbId, long userId, Account caller) {
          VlanVO vlan = _vlanDao.findById(vlanDbId);
@@@ -3294,10 -3579,10 +3556,10 @@@
  
          return true;
      }
 -
 +    
- 
      @DB
-     protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid, long physicalNetworkId) {
+     protected boolean savePublicIPRange(String startIP, String endIP, long zoneId, long vlanDbId, long sourceNetworkid,
+             long physicalNetworkId) {
          long startIPLong = NetUtils.ip2Long(startIP);
          long endIPLong = NetUtils.ip2Long(endIP);
          Transaction txn = Transaction.currentTxn();
@@@ -3410,10 -3698,15 +3675,15 @@@
                  // Check that cidrSubnet does not equal guestSubnet
                  if (cidrSubnet.equals(guestSubnet)) {
                      if (podName.equals("newPod")) {
-                         throw new InvalidParameterValueException("The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR.");
+                         throw new InvalidParameterValueException(
+                                 "The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR.");
                      } else {
-                         throw new InvalidParameterValueException("Warning: The subnet of pod " + podName + " in zone " + zoneName
+                         throw new InvalidParameterValueException(
+                                 "Warning: The subnet of pod "
+                                         + podName
+                                         + " in zone "
+                                         + zoneName
 -                                        + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management.");
 +                                + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management.");
                      }
                  }
              }
@@@ -3671,8 -3983,9 +3959,9 @@@
                          if (provider == Provider.JuniperSRX || provider == Provider.CiscoVnmc) {
                              firewallProvider = provider;
                          }
 -
 +                        
-                         if ((service == Service.PortForwarding || service == Service.StaticNat) && provider == Provider.VirtualRouter){
+                         if ((service == Service.PortForwarding || service == Service.StaticNat)
+                                 && provider == Provider.VirtualRouter) {
                              firewallProvider = Provider.VirtualRouter;
                          }
  
@@@ -3731,8 -4054,11 +4030,11 @@@
              Set<Provider> firewallProviderSet = new HashSet<Provider>();
              firewallProviderSet.add(firewallProvider);
              serviceProviderMap.put(Service.Firewall, firewallProviderSet);
+             if (!(firewallProvider.getName().equals(Provider.JuniperSRX.getName()) || firewallProvider.getName().equals(Provider.VirtualRouter.getName())) && egressDefaultPolicy == false) {
+                 throw new InvalidParameterValueException("Firewall egress with default policy " +  egressDefaultPolicy + "is not supported by the provider "+ firewallProvider.getName());
+             }
          }
 -
 +        
          Map<NetworkOffering.Detail, String> details = new HashMap<NetworkOffering.Detail, String>();
          if (detailsStr != null) {
              for (String detailStr : detailsStr.keySet()) {
@@@ -3871,9 -4223,10 +4199,10 @@@
          if (!specifyVlan && type == GuestType.Shared) {
              throw new InvalidParameterValueException("SpecifyVlan should be true if network offering's type is " + type);
          }
 -
 +        
-         //specifyIpRanges should always be true for Shared networks
-         //specifyIpRanges can only be true for Isolated networks with no Source Nat service
+         // specifyIpRanges should always be true for Shared networks
+         // specifyIpRanges can only be true for Isolated networks with no Source
+         // Nat service
          if (specifyIpRanges) {
              if (type == GuestType.Isolated) {
                  if (serviceProviderMap.containsKey(Service.SourceNat)) {
@@@ -3903,11 -4259,11 +4235,11 @@@
              // only one network offering in the system can be Required
              List<NetworkOfferingVO> offerings = _networkOfferingDao.listByAvailability(Availability.Required, false);
              if (!offerings.isEmpty()) {
-                 throw new InvalidParameterValueException("System already has network offering id=" + offerings.get(0).getId()
-                         + " with availability " + Availability.Required);
+                 throw new InvalidParameterValueException("System already has network offering id="
+                         + offerings.get(0).getId() + " with availability " + Availability.Required);
              }
          }
 -
 +        
          boolean dedicatedLb = false;
          boolean elasticLb = false;
          boolean sharedSourceNat = false;
@@@ -3933,10 -4290,11 +4266,11 @@@
                  if (param != null) {
                      elasticLb = param.contains("true");
                  }
 -
 +                
                  String inlineMode = lbServiceCapabilityMap.get(Capability.InlineMode);
                  if (inlineMode != null) {
-                     _networkModel.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode);
+                     _networkModel.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb,
+                             Capability.InlineMode, inlineMode);
                      inline = inlineMode.contains("true");
                  } else {
                      inline = false;
@@@ -3951,10 -4310,12 +4286,12 @@@
                      }
                  }
              }
 -
 +            
-             //in the current version of the code, publicLb and specificLb can't both be set to true for the same network offering
+             // in the current version of the code, publicLb and specificLb can't
+             // both be set to true for the same network offering
              if (publicLb && internalLb) {
-                 throw new InvalidParameterValueException("Public lb and internal lb can't be enabled at the same time on the offering");
+                 throw new InvalidParameterValueException(
+                         "Public lb and internal lb can't be enabled at the same time on the offering");
              }
  
              Map<Capability, String> sourceNatServiceCapabilityMap = serviceCapabilityMap.get(Service.SourceNat);
@@@ -3999,8 -4361,8 +4337,8 @@@
          if (serviceOfferingId != null) {
              offering.setServiceOfferingId(serviceOfferingId);
          }
 -
 +        
-         //validate the details
+         // validate the details
          if (details != null) {
              validateNtwkOffDetails(details, serviceProviderMap);
          }
@@@ -4020,11 -4382,13 +4358,13 @@@
                          if (provider == Provider.VPCVirtualRouter) {
                              vpcOff = true;
                          }
-                         NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(), service, provider);
+                         NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(offering.getId(),
+                                 service, provider);
                          _ntwkOffServiceMapDao.persist(offService);
-                         s_logger.trace("Added service for the network offering: " + offService + " with provider " + provider.getName());
+                         s_logger.trace("Added service for the network offering: " + offService + " with provider "
+                                 + provider.getName());
                      }
 -
 +                    
                      if (vpcOff) {
                          List<Service> supportedSvcs = new ArrayList<Service>();
                          supportedSvcs.addAll(serviceProviderMap.keySet());
@@@ -4046,13 -4411,16 +4387,16 @@@
  
      protected void validateNtwkOffDetails(Map<Detail, String> details, Map<Service, Set<Provider>> serviceProviderMap) {
          for (Detail detail : details.keySet()) {
 -
 +            
              Provider lbProvider = null;
-             if (detail == NetworkOffering.Detail.InternalLbProvider || detail == NetworkOffering.Detail.PublicLbProvider) {
-                 //1) Vaidate the detail values - have to match the lb provider name
+             if (detail == NetworkOffering.Detail.InternalLbProvider
+                     || detail == NetworkOffering.Detail.PublicLbProvider) {
+                 // 1) Vaidate the detail values - have to match the lb provider
+                 // name
                  String providerStr = details.get(detail);
                  if (Network.Provider.getProvider(providerStr) == null) {
-                     throw new InvalidParameterValueException("Invalid value " + providerStr + " for the detail " + detail);
+                     throw new InvalidParameterValueException("Invalid value " + providerStr + " for the detail "
+                             + detail);
                  }
                  if (serviceProviderMap.get(Service.Lb) != null) {
                      for (Provider provider : serviceProviderMap.get(Service.Lb)) {
@@@ -4067,8 -4435,8 +4411,8 @@@
                      throw new InvalidParameterValueException("Invalid value " + details.get(detail)
                              + " for the detail " + detail + ". The provider is not supported by the network offering");
                  }
 -
 +                
-                 //2) validate if the provider supports the scheme
+                 // 2) validate if the provider supports the scheme
                  Set<Provider> lbProviders = new HashSet<Provider>();
                  lbProviders.add(lbProvider);
                  if (detail == NetworkOffering.Detail.InternalLbProvider) {
@@@ -4283,12 -4658,14 +4633,14 @@@
                  }
  
                  if (sourceNatSupported != null) {
-                     addOffering = addOffering && (_networkModel.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported);
+                     addOffering = addOffering
+                             && (_networkModel.areServicesSupportedByNetworkOffering(offering.getId(),
+                                     Network.Service.SourceNat) == sourceNatSupported);
                  }
 -
 +                
                  if (forVpc != null) {
                      addOffering = addOffering && (isOfferingForVpc(offering) == forVpc.booleanValue());
-                 } else if (network != null){
+                 } else if (network != null) {
                      addOffering = addOffering && (isOfferingForVpc(offering) == (network.getVpcId() != null));
                  }
  
@@@ -4404,15 -4782,15 +4757,15 @@@
              }
              if (availability == null) {
                  throw new InvalidParameterValueException("Invalid value for Availability. Supported types: "
 -                        + Availability.Required + ", " + Availability.Optional);
 +            + Availability.Required + ", " + Availability.Optional);
              } else {
                  if (availability == NetworkOffering.Availability.Required) {
-                     boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated
-                             && _networkModel.areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat));
+                     boolean canOffBeRequired = (offeringToUpdate.getGuestType() == GuestType.Isolated && _networkModel
+                             .areServicesSupportedByNetworkOffering(offeringToUpdate.getId(), Service.SourceNat));
                      if (!canOffBeRequired) {
-                         throw new InvalidParameterValueException("Availability can be " +
-                     NetworkOffering.Availability.Required + " only for networkOfferings of type " + GuestType.Isolated + " and with "
-                                 + Service.SourceNat.getName() + " enabled");
+                         throw new InvalidParameterValueException("Availability can be "
+                                 + NetworkOffering.Availability.Required + " only for networkOfferings of type "
+                                 + GuestType.Isolated + " and with " + Service.SourceNat.getName() + " enabled");
                      }
  
                      // only one network offering in the system can be Required
@@@ -4434,15 -4813,16 +4788,16 @@@
      }
  
      @Override
-     @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE, eventDescription = "Marking account with the " +
-     		"default zone", async=true)
+     @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE, eventDescription = "Marking account with the "
+             + "default zone", async = true)
      public AccountVO markDefaultZone(String accountName, long domainId, long defaultZoneId) {
 -
 -        // Check if the account exists
 -        Account account = _accountDao.findEnabledAccount(accountName, domainId);
 -        if (account == null) {
 +    	
 +    	// Check if the account exists
 +    	Account account = _accountDao.findEnabledAccount(accountName, domainId);
 +    	if (account == null) {
              s_logger.error("Unable to find account by name: " + accountName + " in domain " + domainId);
-             throw new InvalidParameterValueException("Account by name: " + accountName + " doesn't exist in domain " + domainId);
+             throw new InvalidParameterValueException("Account by name: " + accountName + " doesn't exist in domain "
+                     + domainId);
          }
  
          // Don't allow modification of system account
@@@ -4590,31 -4972,31 +4947,31 @@@
      public ClusterVO getCluster(long id) {
          return _clusterDao.findById(id);
      }
 -
 +    
      @Override
-     public AllocationState findClusterAllocationState(ClusterVO cluster){
+     public AllocationState findClusterAllocationState(ClusterVO cluster) {
 -
 +    	
-     	if(cluster.getAllocationState() == AllocationState.Disabled){
+         if (cluster.getAllocationState() == AllocationState.Disabled) {
 -            return AllocationState.Disabled;
 +    		return AllocationState.Disabled;
-     	}else if(ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled){
+         } else if (ApiDBUtils.findPodById(cluster.getPodId()).getAllocationState() == AllocationState.Disabled) {
 -            return AllocationState.Disabled;
 +    		return AllocationState.Disabled;
-     	}else {
+         } else {
 -            DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId());
 -            return zone.getAllocationState();
 -        }
 +    		DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId());
 +    		return zone.getAllocationState();
 +    	}
      }
  
      @Override
-     public AllocationState findPodAllocationState(HostPodVO pod){
+     public AllocationState findPodAllocationState(HostPodVO pod) {
 -
 +    	
-     	if(pod.getAllocationState() == AllocationState.Disabled){
+         if (pod.getAllocationState() == AllocationState.Disabled) {
 -            return AllocationState.Disabled;
 +    		return AllocationState.Disabled;
-     	}else {
+         } else {
 -            DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId());
 -            return zone.getAllocationState();
 -        }
 +    		DataCenterVO zone = ApiDBUtils.findZoneById(pod.getDataCenterId());
 +    		return zone.getAllocationState();
 +    	}
      }
 -
 +    
      private boolean allowIpRangeOverlap(VlanVO vlan, boolean forVirtualNetwork, long networkId) {
          // FIXME - delete restriction for virtual network in the future
          if (vlan.getVlanType() == VlanType.DirectAttached && !forVirtualNetwork) {
@@@ -4682,13 -5066,9 +5041,14 @@@
      }
  
      @Override
 +    public <T> ConfigValue<T> get(ConfigKey<T> config) {
 +        return new ConfigValue<T>(_entityMgr, config);
 +    }
 +    
 +    @Override
      @DB
-     @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_CREATE, eventDescription = "creating portable ip range", async = false)
+     @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_CREATE,
+             eventDescription = "creating portable ip range", async = false)
      public PortableIpRange createPortableIpRange(CreatePortableIpRangeCmd cmd) throws ConcurrentOperationException {
          Integer regionId = cmd.getRegionId();
          String startIP = cmd.getStartIp();
@@@ -4736,11 -5116,11 +5096,11 @@@
          PortableIpRangeVO portableIpRange = new PortableIpRangeVO(regionId, vlanId, gateway, netmask, startIP, endIP);
          portableIpRange = _portableIpRangeDao.persist(portableIpRange);
  
 -        long startIpLong = NetUtils.ip2Long(startIP);
 +        long startIpLong =  NetUtils.ip2Long(startIP);
          long endIpLong = NetUtils.ip2Long(endIP);
-         while(startIpLong <= endIpLong) {
-             PortableIpVO portableIP = new PortableIpVO(regionId, portableIpRange.getId(), vlanId,
-                     gateway, netmask,NetUtils.long2Ip(startIpLong));
+         while (startIpLong <= endIpLong) {
+             PortableIpVO portableIP = new PortableIpVO(regionId, portableIpRange.getId(), vlanId, gateway, netmask,
+                     NetUtils.long2Ip(startIpLong));
              _portableIpDao.persist(portableIP);
              startIpLong++;
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
index 07c3952,5983aa7..cfeecdc
--- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
+++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
@@@ -28,14 -28,11 +28,16 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
 +import org.apache.log4j.Logger;
 +
 +import com.google.gson.Gson;
 +import com.google.gson.GsonBuilder;
 +
 +import org.apache.cloudstack.context.CallContext;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
 -import org.apache.log4j.Logger;
  
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
@@@ -113,9 -115,8 +113,9 @@@ import com.cloud.utils.NumbersUtil
  import com.cloud.utils.Pair;
  import com.cloud.utils.component.ManagerBase;
  import com.cloud.utils.db.DB;
++import com.cloud.utils.db.EntityManager;
  import com.cloud.utils.db.GlobalLock;
  import com.cloud.utils.db.SearchCriteria.Op;
- import com.cloud.utils.db.EntityManager;
  import com.cloud.utils.db.SearchCriteria2;
  import com.cloud.utils.db.SearchCriteriaService;
  import com.cloud.utils.db.Transaction;
@@@ -939,22 -938,10 +934,10 @@@ public class ConsoleProxyManagerImpl ex
          ZoneHostInfo zoneHostInfo = zoneHostInfoMap.get(dataCenterId);
          if (zoneHostInfo != null && isZoneHostReady(zoneHostInfo)) {
              VMTemplateVO template = _templateDao.findSystemVMTemplate(dataCenterId);
-             HostVO secondaryStorageHost = templateMgr.getSecondaryStorageHost(dataCenterId);
-             boolean templateReady = false;
- 
-             if (secondaryStorageHost == null) {
-                 if (s_logger.isDebugEnabled()) {
-                     s_logger.debug("No secondary storage available in zone " + dataCenterId + ", wait until it is ready to launch secondary storage vm");
-                 }
-                 return false;
-             }
- 
-             if (template != null && secondaryStorageHost != null) {
-                 VMTemplateHostVO templateHostRef = _vmTemplateHostDao.findByHostTemplate(secondaryStorageHost.getId(), template.getId());
-                 templateReady = (templateHostRef != null) && (templateHostRef.getDownloadState() == Status.DOWNLOADED);
-             }
 -            TemplateDataStoreVO templateHostRef = this._vmTemplateStoreDao.findByTemplateZoneDownloadStatus(template.getId(), dataCenterId,
++            TemplateDataStoreVO templateHostRef = _vmTemplateStoreDao.findByTemplateZoneDownloadStatus(template.getId(), dataCenterId,
+                     Status.DOWNLOADED);
  
-             if (templateReady) {
+             if (templateHostRef != null) {
                  List<Pair<Long, Integer>> l = _consoleProxyDao.getDatacenterStoragePoolHostInfo(dataCenterId, _use_lvm);
                  if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
                      return true;
@@@ -967,11 -954,9 +950,9 @@@
                  if (s_logger.isDebugEnabled()) {
                      if (template == null) {
                          s_logger.debug("Zone host is ready, but console proxy template is null");
-                     } else if (secondaryStorageHost != null) {
- 			s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() +  " is not ready on secondary storage: " + secondaryStorageHost.getId());
 -                    } else {
 -                        s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() + " is not ready on secondary storage.");
 -                    }
 +		    } else {
 +			s_logger.debug("Zone host is ready, but console proxy template: " + template.getId() +  " is not ready on secondary storage.");
 +		    }
                  }
              }
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/hypervisor/HypervisorGuruBase.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkManagerImpl.java
index dc26380,674a35f..0c2f7a9
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@@ -3093,10 -3090,22 +3093,22 @@@ public class NetworkManagerImpl extend
          }
  
          List<FirewallRuleVO> firewallEgressRulesToApply = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Egress);
+         if (firewallEgressRulesToApply.size() == 0) {
+             NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
+             //there are no egress rules then apply the default egress rule
+             DataCenter zone = _dcDao.findById(network.getDataCenterId());
+             if (offering.getEgressDefaultPolicy() && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall)
+                     && (network.getGuestType() == Network.GuestType.Isolated ||
+                     (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) {
+                 // add default egress rule to accept the traffic
+                 _firewallMgr.applyDefaultEgressFirewallRule(network.getId(), true);
+             }
+         } else {
 -            if (!_firewallMgr.applyFirewallRules(firewallEgressRulesToApply, false, caller)) {
 -                s_logger.warn("Failed to reapply firewall Egress rule(s) as a part of network id=" + networkId + " restart");
 -                success = false;
 -            }
 +        if (!_firewallMgr.applyFirewallRules(firewallEgressRulesToApply, false, caller)) {
 +            s_logger.warn("Failed to reapply firewall Egress rule(s) as a part of network id=" + networkId + " restart");
 +            success = false;
 +        }
+         }
  
          // apply port forwarding rules
          if (!_rulesMgr.applyPortForwardingRulesForNetwork(networkId, false, caller)) {
@@@ -3782,21 -3791,21 +3794,21 @@@
          }
  
          if(network.getVpcId() != null){
 -            if (s_logger.isDebugEnabled()) {
 +        if (s_logger.isDebugEnabled()) {
                  s_logger.debug("Releasing Network ACL Items for network id=" + networkId +
 -                        " as a part of shutdownNetworkRules");
 -            }
 +                    " as a part of shutdownNetworkRules");
 +        }
  
 -            try {
 +        try {
                  //revoke all Network ACLs for the network w/o applying them in the DB
-                 if (!_networkACLMgr.revokeACLItemsForNetwork(networkId, callerUserId, caller)) {
+                 if (!_networkACLMgr.revokeACLItemsForNetwork(networkId)) {
 -                    s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules");
 -                    success = false;
 -                }
 -            } catch (ResourceUnavailableException ex) {
 -                s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex);
 +                s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules");
                  success = false;
              }
 +        } catch (ResourceUnavailableException ex) {
 +            s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex);
 +            success = false;
 +        }
  
          }
  
@@@ -4359,13 -4368,12 +4371,12 @@@
  
          @Override
      public NicVO savePlaceholderNic(Network network, String ip4Address, String ip6Address, Type vmType) {
 -            NicVO nic = new NicVO(null, null, network.getId(), null); 
 +            NicVO nic = new NicVO(null, null, network.getId(), null);
              nic.setIp4Address(ip4Address);
          nic.setIp6Address(ip6Address);
 -        nic.setReservationStrategy(ReservationStrategy.PlaceHolder);
 -        nic.setState(Nic.State.Reserved);
 -        nic.setVmType(vmType);
 -        return _nicDao.persist(nic);
 -    }
 +            nic.setReservationStrategy(ReservationStrategy.PlaceHolder);
 +            nic.setState(Nic.State.Reserved);
 +            nic.setVmType(vmType);
 +            return _nicDao.persist(nic);
 +        }
-         
   }


[46/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java
----------------------------------------------------------------------
diff --cc engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java
index 192f99a,0000000..ae9aab7
mode 100644,000000..100644
--- a/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java
+++ b/engine/orchestration/test/com/cloud/vm/VirtualMachineManagerImplTest.java
@@@ -1,430 -1,0 +1,444 @@@
 +// 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.vm;
 +
 +import static org.mockito.Matchers.any;
 +import static org.mockito.Matchers.anyLong;
 +import static org.mockito.Matchers.isA;
 +import static org.mockito.Mockito.doNothing;
 +import static org.mockito.Mockito.mock;
 +import static org.mockito.Mockito.when;
 +
 +import java.util.HashMap;
 +import java.util.Iterator;
 +import java.util.List;
 +import java.util.Map;
 +
 +import org.junit.Before;
 +import org.junit.Test;
 +import org.mockito.Mock;
 +import org.mockito.MockitoAnnotations;
 +import org.mockito.Spy;
 +
 +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
 +import org.apache.cloudstack.config.ConfigDepot;
 +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 +
 +import com.cloud.agent.AgentManager;
 +import com.cloud.agent.api.Answer;
 +import com.cloud.agent.api.CheckVirtualMachineAnswer;
 +import com.cloud.agent.api.CheckVirtualMachineCommand;
 +import com.cloud.agent.api.MigrateWithStorageAnswer;
 +import com.cloud.agent.api.MigrateWithStorageCommand;
 +import com.cloud.agent.api.MigrateWithStorageCompleteAnswer;
 +import com.cloud.agent.api.MigrateWithStorageCompleteCommand;
 +import com.cloud.agent.api.MigrateWithStorageReceiveAnswer;
 +import com.cloud.agent.api.MigrateWithStorageReceiveCommand;
 +import com.cloud.agent.api.MigrateWithStorageSendAnswer;
 +import com.cloud.agent.api.MigrateWithStorageSendCommand;
 +import com.cloud.agent.api.PrepareForMigrationAnswer;
 +import com.cloud.agent.api.PrepareForMigrationCommand;
 +import com.cloud.agent.api.ScaleVmAnswer;
 +import com.cloud.agent.api.ScaleVmCommand;
 +import com.cloud.configuration.dao.ConfigurationDao;
 +import com.cloud.dc.dao.ClusterDao;
 +import com.cloud.dc.dao.DataCenterDao;
 +import com.cloud.dc.dao.HostPodDao;
 +import com.cloud.deploy.DeployDestination;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.ManagementServerException;
 +import com.cloud.exception.OperationTimedoutException;
 +import com.cloud.exception.ResourceUnavailableException;
 +import com.cloud.exception.VirtualMachineMigrationException;
 +import com.cloud.host.HostVO;
 +import com.cloud.host.dao.HostDao;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.hypervisor.HypervisorGuru;
 +import com.cloud.hypervisor.HypervisorGuruManager;
 +import com.cloud.network.NetworkManager;
 +import com.cloud.offering.ServiceOffering;
 +import com.cloud.service.ServiceOfferingVO;
 +import com.cloud.storage.DiskOfferingVO;
 +import com.cloud.storage.StoragePool;
 +import com.cloud.storage.StoragePoolHostVO;
 +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.StoragePoolHostDao;
 +import com.cloud.storage.dao.VMTemplateDao;
 +import com.cloud.storage.dao.VolumeDao;
 +import com.cloud.user.Account;
 +import com.cloud.user.AccountVO;
 +import com.cloud.user.UserVO;
 +import com.cloud.user.dao.AccountDao;
 +import com.cloud.user.dao.UserDao;
 +import com.cloud.utils.Pair;
 +import com.cloud.utils.db.EntityManager;
 +import com.cloud.utils.exception.CloudRuntimeException;
 +import com.cloud.vm.VirtualMachine.Event;
 +import com.cloud.vm.VirtualMachine.PowerState;
 +import com.cloud.vm.VirtualMachine.State;
 +import com.cloud.vm.dao.UserVmDao;
++import com.cloud.vm.dao.UserVmDetailsDao;
 +import com.cloud.vm.dao.VMInstanceDao;
 +import com.cloud.vm.snapshot.VMSnapshotManager;
 +
 +public class VirtualMachineManagerImplTest {
 +
 +        @Spy VirtualMachineManagerImpl _vmMgr = new VirtualMachineManagerImpl();
 +        @Mock
 +        VolumeManager _storageMgr;
 +        @Mock
 +        Account _account;
 +        @Mock
 +        AgentManager _agentMgr;
 +        @Mock
 +        AccountDao _accountDao;
 +        @Mock
 +        ConfigurationDao _configDao;
 +        @Mock
 +        HostDao _hostDao;
 +        @Mock
 +        UserDao _userDao;
 +        @Mock
 +        UserVmDao _vmDao;
 +        @Mock
 +        ItWorkDao _workDao;
 +        @Mock
 +        VMInstanceDao _vmInstanceDao;
 +        @Mock
 +        VMTemplateDao _templateDao;
 +        @Mock
 +        VolumeDao _volsDao;
 +        @Mock
 +        RestoreVMCmd _restoreVMCmd;
 +        @Mock
 +        AccountVO _accountMock;
 +        @Mock
 +        UserVO _userMock;
 +        @Mock
 +        UserVmVO _vmMock;
 +        @Mock
 +        VMInstanceVO _vmInstance;
 +        @Mock
 +        HostVO _host;
 +        @Mock
 +        VMTemplateVO _templateMock;
 +        @Mock
 +        VolumeVO _volumeMock;
 +        @Mock
 +        List<VolumeVO> _rootVols;
 +        @Mock
 +        ItWorkVO _work;
 +        @Mock
 +    ConfigDepot _configDepot;
 +        @Mock
 +        HostVO hostVO;
++        @Mock
++        UserVmDetailVO _vmDetailVO;
 +
 +    @Mock
 +    EntityManager _entityMgr;
 +
 +        @Mock ClusterDao _clusterDao;
 +        @Mock HostPodDao _podDao;
 +        @Mock DataCenterDao _dcDao;
 +        @Mock DiskOfferingDao _diskOfferingDao;
 +        @Mock PrimaryDataStoreDao _storagePoolDao;
++        @Mock UserVmDetailsDao _vmDetailsDao;
 +        @Mock StoragePoolHostDao _poolHostDao;
 +        @Mock NetworkManager _networkMgr;
 +        @Mock HypervisorGuruManager _hvGuruMgr;
 +        @Mock VMSnapshotManager _vmSnapshotMgr;
 +
 +        // Mock objects for vm migration with storage test.
 +        @Mock DiskOfferingVO _diskOfferingMock;
 +        @Mock StoragePoolVO _srcStoragePoolMock;
 +        @Mock StoragePoolVO _destStoragePoolMock;
 +        @Mock HostVO _srcHostMock;
 +        @Mock HostVO _destHostMock;
 +    @Mock
 +    Map<Volume, StoragePool> _volumeToPoolMock;
 +
 +        @Before
 +        public void setup(){
 +            MockitoAnnotations.initMocks(this);
 +
 +        _vmMgr._entityMgr = _entityMgr;
 +            _vmMgr._volsDao = _volsDao;
 +            _vmMgr._volumeMgr = _storageMgr;
 +            _vmMgr._hostDao = _hostDao;
 +            _vmMgr._nodeId = 1L;
 +/*
 +            _vmMgr._workDao = _workDao;
 +*/
 +            _vmMgr._agentMgr = _agentMgr;
 +            _vmMgr._poolHostDao= _poolHostDao;
 +            _vmMgr._networkMgr = _networkMgr;
 +            _vmMgr._hvGuruMgr = _hvGuruMgr;
 +            _vmMgr._vmSnapshotMgr = _vmSnapshotMgr;
 +            _vmMgr._vmDao = _vmInstanceDao;
 +        _vmMgr._configDepot = _configDepot;
 +
 +            when(_vmMock.getId()).thenReturn(314l);
 +            when(_vmInstance.getId()).thenReturn(1L);
 +            when(_vmInstance.getServiceOfferingId()).thenReturn(2L);
 +            when(_vmInstance.getInstanceName()).thenReturn("myVm");
 +            when(_vmInstance.getHostId()).thenReturn(2L);
 +            when(_vmInstance.getType()).thenReturn(VirtualMachine.Type.User);
 +            when(_host.getId()).thenReturn(1L);
 +            when(_hostDao.findById(anyLong())).thenReturn(null);
 +        when(_entityMgr.findById(ServiceOffering.class, anyLong())).thenReturn(getSvcoffering(512));
 +            when(_workDao.persist(_work)).thenReturn(_work);
 +            when(_workDao.update("1", _work)).thenReturn(true);
 +            when(_work.getId()).thenReturn("1");
 +            doNothing().when(_work).setStep(ItWorkVO.Step.Done);
 +            //doNothing().when(_volsDao).detachVolume(anyLong());
 +            //when(_work.setStep(ItWorkVO.Step.Done)).thenReturn("1");
 +
 +        }
 +
 +
 +    @Test(expected=CloudRuntimeException.class)
 +    public void testScaleVM1()  throws Exception {
 +
 +
 +        DeployDestination dest = new DeployDestination(null, null, null, _host);
 +        long l = 1L;
 +
 +        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
 +        _vmMgr.migrateForScale(_vmInstance.getUuid(), l, dest, l);
 +
 +    }
 +
 +    @Test (expected=CloudRuntimeException.class)
 +    public void testScaleVM2()  throws Exception {
 +
 +        DeployDestination dest = new DeployDestination(null, null, null, _host);
 +        long l = 1L;
 +
++        when(_vmInstance.getId()).thenReturn(3L);
++        when(_vmDetailsDao.findDetail(3L, VirtualMachine.IsDynamicScalingEnabled)).thenReturn(_vmDetailVO);
++        when(_vmDetailVO.getValue()).thenReturn("true");
 +        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
 +        ServiceOfferingVO newServiceOffering = getSvcoffering(512);
 +        when(_hostDao.findById(_vmInstance.hostId)).thenReturn(hostVO);
 +        when(hostVO.getClusterId()).thenReturn(1L);
 +//        when(_configDepot.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
 +//        when(_configServer.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
++        when(_vmInstance.getHostId()).thenReturn(1L);
++        when(_hostDao.findById(1L)).thenReturn(hostVO);
++        when(_vmInstance.getDataCenterId()).thenReturn(1L);
++        when(hostVO.getClusterId()).thenReturn(1L);
++//        when(_configServer.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.ConfigurationParameterScope.zone.toString(), 1L)).thenReturn("true");
++//        when(_configServer.getConfigValue(Config.MemOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
++//        when(_configServer.getConfigValue(Config.CPUOverprovisioningFactor.key(), Config.ConfigurationParameterScope.cluster.toString(), 1L)).thenReturn("1.0");
 +        ScaleVmCommand reconfigureCmd = new ScaleVmCommand("myVmName", newServiceOffering.getCpu(),
-                 newServiceOffering.getSpeed(), newServiceOffering.getSpeed(), newServiceOffering.getRamSize(), newServiceOffering.getRamSize(), newServiceOffering.getLimitCpuUse());
++                newServiceOffering.getSpeed(), newServiceOffering.getSpeed(), newServiceOffering.getRamSize(), newServiceOffering.getRamSize(), newServiceOffering.getLimitCpuUse(), true);
 +        Answer answer = new ScaleVmAnswer(reconfigureCmd, true, "details");
 +        when(_agentMgr.send(2l, reconfigureCmd)).thenReturn(null);
 +        _vmMgr.reConfigureVm(_vmInstance, getSvcoffering(256), false);
 +
 +    }
 +
 +    @Test (expected=CloudRuntimeException.class)
 +    public void testScaleVM3()  throws Exception {
 +
 +        /*VirtualMachineProfile<VMInstanceVO> profile = new VirtualMachineProfileImpl<VMInstanceVO>(vm);
 +
 +        Long srcHostId = vm.getHostId();
 +        Long oldSvcOfferingId = vm.getServiceOfferingId();
 +        if (srcHostId == null) {
 +            throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id");
 +        }*/
 +
 +        when(_vmInstance.getHostId()).thenReturn(null);
 +        when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
 +        _vmMgr.findHostAndMigrate(_vmInstance.getUuid(), 2l);
 +
 +    }
 +
 +
 +    private ServiceOfferingVO getSvcoffering(int ramSize){
 +
 +        long id  = 4L;
 +        String name = "name";
 +        String displayText = "displayText";
 +        int cpu = 1;
 +        //int ramSize = 256;
 +        int speed = 128;
 +
 +        boolean ha = false;
 +        boolean useLocalStorage = false;
 +
 +        ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, useLocalStorage, false, null, false, null, false);
 +        return serviceOffering;
 +    }
 +
 +    private void initializeMockConfigForMigratingVmWithVolumes() throws OperationTimedoutException,
 +        ResourceUnavailableException {
 +
 +        // Mock the source and destination hosts.
 +        when(_srcHostMock.getId()).thenReturn(5L);
 +        when(_destHostMock.getId()).thenReturn(6L);
 +        when(_hostDao.findById(5L)).thenReturn(_srcHostMock);
 +        when(_hostDao.findById(6L)).thenReturn(_destHostMock);
 +
 +        // Mock the vm being migrated.
 +        when(_vmMock.getId()).thenReturn(1L);
 +        when(_vmMock.getHypervisorType()).thenReturn(HypervisorType.XenServer);
 +        when(_vmMock.getState()).thenReturn(State.Running).thenReturn(State.Running).thenReturn(State.Migrating)
 +            .thenReturn(State.Migrating);
 +        when(_vmMock.getHostId()).thenReturn(5L);
 +        when(_vmInstance.getId()).thenReturn(1L);
 +        when(_vmInstance.getServiceOfferingId()).thenReturn(2L);
 +        when(_vmInstance.getInstanceName()).thenReturn("myVm");
 +        when(_vmInstance.getHostId()).thenReturn(5L);
 +        when(_vmInstance.getType()).thenReturn(VirtualMachine.Type.User);
 +        when(_vmInstance.getState()).thenReturn(State.Running).thenReturn(State.Running).thenReturn(State.Migrating)
 +            .thenReturn(State.Migrating);
 +
 +        // Mock the work item.
 +        when(_workDao.persist(any(ItWorkVO.class))).thenReturn(_work);
 +        when(_workDao.update("1", _work)).thenReturn(true);
 +        when(_work.getId()).thenReturn("1");
 +        doNothing().when(_work).setStep(ItWorkVO.Step.Done);
 +
 +        // Mock the vm guru and the user vm object that gets returned.
 +        _vmMgr._vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
 +
 +        // Mock the iteration over all the volumes of an instance.
 +        Iterator<VolumeVO> volumeIterator = mock(Iterator.class);
 +        when(_volsDao.findUsableVolumesForInstance(anyLong())).thenReturn(_rootVols);
 +        when(_rootVols.iterator()).thenReturn(volumeIterator);
 +        when(volumeIterator.hasNext()).thenReturn(true, false);
 +        when(volumeIterator.next()).thenReturn(_volumeMock);
 +
 +        // Mock the disk offering and pool objects for a volume.
 +        when(_volumeMock.getDiskOfferingId()).thenReturn(5L);
 +        when(_volumeMock.getPoolId()).thenReturn(200L);
 +        when(_diskOfferingDao.findById(anyLong())).thenReturn(_diskOfferingMock);
 +        when(_storagePoolDao.findById(anyLong())).thenReturn(_srcStoragePoolMock);
 +
 +        // Mock the volume to pool mapping.
 +        when(_volumeToPoolMock.get(_volumeMock)).thenReturn(_destStoragePoolMock);
 +        when(_destStoragePoolMock.getId()).thenReturn(201L);
 +        when(_srcStoragePoolMock.getId()).thenReturn(200L);
 +        when(_destStoragePoolMock.isLocal()).thenReturn(false);
 +        when(_diskOfferingMock.getUseLocalStorage()).thenReturn(false);
 +        when(_poolHostDao.findByPoolHost(anyLong(), anyLong())).thenReturn(mock(StoragePoolHostVO.class));
 +
 +        // Mock hypervisor guru.
 +        HypervisorGuru guruMock = mock(HypervisorGuru.class);
 +        when(_hvGuruMgr.getGuru(HypervisorType.XenServer)).thenReturn(guruMock);
 +
 +        when(_srcHostMock.getClusterId()).thenReturn(3L);
 +        when(_destHostMock.getClusterId()).thenReturn(3L);
 +
 +        // Mock the commands and answers to the agent.
 +        PrepareForMigrationAnswer prepAnswerMock = mock(PrepareForMigrationAnswer.class);
 +        when(prepAnswerMock.getResult()).thenReturn(true);
 +        when(_agentMgr.send(anyLong(), isA(PrepareForMigrationCommand.class))).thenReturn(prepAnswerMock);
 +
 +        MigrateWithStorageAnswer migAnswerMock = mock(MigrateWithStorageAnswer.class);
 +        when(migAnswerMock.getResult()).thenReturn(true);
 +        when(_agentMgr.send(anyLong(), isA(MigrateWithStorageCommand.class))).thenReturn(migAnswerMock);
 +
 +        MigrateWithStorageReceiveAnswer migRecAnswerMock = mock(MigrateWithStorageReceiveAnswer.class);
 +        when(migRecAnswerMock.getResult()).thenReturn(true);
 +        when(_agentMgr.send(anyLong(), isA(MigrateWithStorageReceiveCommand.class))).thenReturn(migRecAnswerMock);
 +
 +        MigrateWithStorageSendAnswer migSendAnswerMock = mock(MigrateWithStorageSendAnswer.class);
 +        when(migSendAnswerMock.getResult()).thenReturn(true);
 +        when(_agentMgr.send(anyLong(), isA(MigrateWithStorageSendCommand.class))).thenReturn(migSendAnswerMock);
 +
 +        MigrateWithStorageCompleteAnswer migCompleteAnswerMock = mock(MigrateWithStorageCompleteAnswer.class);
 +        when(migCompleteAnswerMock.getResult()).thenReturn(true);
 +        when(_agentMgr.send(anyLong(), isA(MigrateWithStorageCompleteCommand.class))).thenReturn(migCompleteAnswerMock);
 +
 +        CheckVirtualMachineAnswer checkVmAnswerMock = mock(CheckVirtualMachineAnswer.class);
 +        when(checkVmAnswerMock.getResult()).thenReturn(true);
 +        when(checkVmAnswerMock.getState()).thenReturn(PowerState.PowerOn);
 +        when(_agentMgr.send(anyLong(), isA(CheckVirtualMachineCommand.class))).thenReturn(checkVmAnswerMock);
 +
 +        // Mock the state transitions of vm.
 +        Pair<Long, Long> opaqueMock = new Pair<Long, Long> (_vmMock.getHostId(), _destHostMock.getId());
 +        when(_vmSnapshotMgr.hasActiveVMSnapshotTasks(anyLong())).thenReturn(false);
 +        when(_vmInstanceDao.updateState(State.Running, Event.MigrationRequested, State.Migrating, _vmMock, opaqueMock))
 +            .thenReturn(true);
 +        when(_vmInstanceDao.updateState(State.Migrating, Event.OperationSucceeded, State.Running, _vmMock, opaqueMock))
 +            .thenReturn(true);
 +    }
 +
 +    // Check migration of a vm with its volumes within a cluster.
 +    @Test
 +    public void testMigrateWithVolumeWithinCluster() throws ResourceUnavailableException, ConcurrentOperationException,
 +        ManagementServerException, VirtualMachineMigrationException, OperationTimedoutException {
 +
 +        initializeMockConfigForMigratingVmWithVolumes();
 +        when(_srcHostMock.getClusterId()).thenReturn(3L);
 +        when(_destHostMock.getClusterId()).thenReturn(3L);
 +
 +        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
 +    }
 +
 +    // Check migration of a vm with its volumes across a cluster.
 +    @Test
 +    public void testMigrateWithVolumeAcrossCluster() throws ResourceUnavailableException, ConcurrentOperationException,
 +        ManagementServerException, VirtualMachineMigrationException, OperationTimedoutException {
 +
 +        initializeMockConfigForMigratingVmWithVolumes();
 +        when(_srcHostMock.getClusterId()).thenReturn(3L);
 +        when(_destHostMock.getClusterId()).thenReturn(4L);
 +
 +        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
 +    }
 +
 +    // Check migration of a vm fails when src and destination pool are not of same type; that is, one is shared and
 +    // other is local.
 +    @Test(expected=CloudRuntimeException.class)
 +    public void testMigrateWithVolumeFail1() throws ResourceUnavailableException, ConcurrentOperationException,
 +        ManagementServerException, VirtualMachineMigrationException, OperationTimedoutException {
 +
 +        initializeMockConfigForMigratingVmWithVolumes();
 +        when(_srcHostMock.getClusterId()).thenReturn(3L);
 +        when(_destHostMock.getClusterId()).thenReturn(3L);
 +
 +        when(_destStoragePoolMock.isLocal()).thenReturn(true);
 +        when(_diskOfferingMock.getUseLocalStorage()).thenReturn(false);
 +
 +        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
 +    }
 +
 +    // Check migration of a vm fails when vm is not in Running state.
 +    @Test(expected=ConcurrentOperationException.class)
 +    public void testMigrateWithVolumeFail2() throws ResourceUnavailableException, ConcurrentOperationException,
 +        ManagementServerException, VirtualMachineMigrationException, OperationTimedoutException {
 +
 +        initializeMockConfigForMigratingVmWithVolumes();
 +        when(_srcHostMock.getClusterId()).thenReturn(3L);
 +        when(_destHostMock.getClusterId()).thenReturn(3L);
 +
 +        when(_vmMock.getState()).thenReturn(State.Stopped);
 +
 +        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/schema/src/com/cloud/vm/VMInstanceVO.java
----------------------------------------------------------------------
diff --cc engine/schema/src/com/cloud/vm/VMInstanceVO.java
index 973feb6,e1d2892..cffdb34
--- a/engine/schema/src/com/cloud/vm/VMInstanceVO.java
+++ b/engine/schema/src/com/cloud/vm/VMInstanceVO.java
@@@ -185,24 -173,21 +185,24 @@@ public class VMInstanceVO implements Vi
              long accountId,
              boolean haEnabled) {
          this.id = id;
--        this.hostName = name != null ? name : this.uuid;
++        hostName = name != null ? name : uuid;
          if (vmTemplateId != null) {
--            this.templateId = vmTemplateId;
++            templateId = vmTemplateId;
          }
          this.instanceName = instanceName;
          this.type = type;
          this.guestOSId = guestOSId;
          this.haEnabled = haEnabled;
--        this.vncPassword = Long.toHexString(new Random().nextLong());
--        this.state = State.Stopped;
++        vncPassword = Long.toHexString(new Random().nextLong());
++        state = State.Stopped;
          this.accountId = accountId;
          this.domainId = domainId;
          this.serviceOfferingId = serviceOfferingId;
          this.hypervisorType = hypervisorType;
--        this.limitCpuUse = false;
++        limitCpuUse = false;
 +        
-         this.powerState = PowerState.PowerUnknown;
-         this.powerStateUpdateTime = DateUtil.currentGMTTime();
++        powerState = PowerState.PowerUnknown;
++        powerStateUpdateTime = DateUtil.currentGMTTime();
      }
  
      public VMInstanceVO(long id,
@@@ -218,11 -203,8 +218,11 @@@
              boolean haEnabled,
              boolean limitResourceUse, Long diskOfferingId) {
          this(id, serviceOfferingId, name, instanceName, type, vmTemplateId, hypervisorType, guestOSId, domainId, accountId, haEnabled);
--        this.limitCpuUse = limitResourceUse;
++        limitCpuUse = limitResourceUse;
          this.diskOfferingId = diskOfferingId;
 +
-         this.powerState = PowerState.PowerUnknown;
-         this.powerStateUpdateTime = DateUtil.currentGMTTime();
++        powerState = PowerState.PowerUnknown;
++        powerStateUpdateTime = DateUtil.currentGMTTime();
      }
  
      protected VMInstanceVO() {
@@@ -337,11 -319,11 +337,11 @@@
      }
  
      public Date getProxyAssignTime() {
--        return this.proxyAssignTime;
++        return proxyAssignTime;
      }
  
      public void setProxyAssignTime(Date time) {
--        this.proxyAssignTime = time;
++        proxyAssignTime = time;
      }
  
      @Override
@@@ -425,7 -407,7 +425,7 @@@
      }
  
      public void setPodId(long podId) {
--        this.podIdToDeployIn = podId;
++        podIdToDeployIn = podId;
      }
  
      public void setPrivateMacAddress(String privateMacAddress) {
@@@ -449,7 -431,7 +449,7 @@@
      }
  
      public String getReservationId() {
--        return this.reservationId;
++        return reservationId;
      }
  
      @Override
@@@ -507,36 -490,5 +507,36 @@@
  	public Long getDiskOfferingId() {
  		return diskOfferingId;
  	}
 -
 +	
 +	public VirtualMachine.PowerState getPowerState() {
- 		return this.powerState;
++		return powerState;
 +	}
 +	
 +	public void setPowerState(PowerState powerState) {
 +		this.powerState = powerState;
 +	}
 +	
 +	public Date getPowerStateUpdateTime() {
- 		return this.powerStateUpdateTime;
++		return powerStateUpdateTime;
 +	}
 +    
 +	public void setPowerStateUpdateTime(Date updateTime) {
- 		this.powerStateUpdateTime = updateTime;
++		powerStateUpdateTime = updateTime;
 +	}
 +	
 +	public int getPowerStateUpdateCount() {
- 		return this.powerStateUpdateCount;
++		return powerStateUpdateCount;
 +	}
 +	
 +	public void setPowerStateUpdateCount(int count) {
- 		this.powerStateUpdateCount = count;
++		powerStateUpdateCount = count;
 +	}
 +	
 +	public Long getPowerHostId() {
- 		return this.powerHostId;
++		return powerHostId;
 +	}
 +	
 +	public void setPowerHostId(Long hostId) {
- 		this.powerHostId = hostId;
++		powerHostId = hostId;
 +	}
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/schema/src/com/cloud/vm/VirtualMachineProfileImpl.java
----------------------------------------------------------------------
diff --cc engine/schema/src/com/cloud/vm/VirtualMachineProfileImpl.java
index 9e9e342,0000000..46bdfd7
mode 100644,000000..100644
--- a/engine/schema/src/com/cloud/vm/VirtualMachineProfileImpl.java
+++ b/engine/schema/src/com/cloud/vm/VirtualMachineProfileImpl.java
@@@ -1,255 -1,0 +1,255 @@@
 +// 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.vm;
 +
 +import java.util.ArrayList;
 +import java.util.HashMap;
 +import java.util.List;
 +import java.util.Map;
 +
- import com.cloud.agent.api.to.VolumeTO;
++import com.cloud.agent.api.to.DiskTO;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.offering.ServiceOffering;
 +import com.cloud.service.ServiceOfferingVO;
 +import com.cloud.storage.VMTemplateVO;
 +import com.cloud.template.VirtualMachineTemplate;
 +import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 +import com.cloud.user.Account;
 +import com.cloud.user.AccountVO;
 +import com.cloud.utils.db.EntityManager;
 +
 +/**
 + * Implementation of VirtualMachineProfile.
 + *
 + */
 +public class VirtualMachineProfileImpl implements VirtualMachineProfile {
 +    
 +    VMInstanceVO _vm;
 +    ServiceOfferingVO _offering;
 +    VMTemplateVO _template;
 +    Map<Param, Object> _params;
 +    List<NicProfile> _nics = new ArrayList<NicProfile>();
-     List<VolumeTO> _disks = new ArrayList<VolumeTO>();
++    List<DiskTO> _disks = new ArrayList<DiskTO>();
 +    StringBuilder _bootArgs = new StringBuilder();
 +    Account _owner;
 +    BootloaderType _bootloader;
 +    Float cpuOvercommitRatio = 1.0f;
 +    Float memoryOvercommitRatio = 1.0f;
 +
 +    VirtualMachine.Type _type;
 +    
 +    public VirtualMachineProfileImpl(VMInstanceVO vm, VMTemplateVO template, ServiceOfferingVO offering, Account owner, Map<Param, Object> params) {
 +        _vm = vm;
 +        _template = template;
 +        _offering = offering;
 +        _params = params;
 +        _owner = owner;
 +        if (_owner == null) {
 +            _owner = s_entityMgr.findById(AccountVO.class, vm.getAccountId());
 +        }
 +        if (_params == null) {
 +            _params = new HashMap<Param, Object>();
 +        }
 +        if (vm != null)
 +        	_type = vm.getType();
 +    }
 +    
 +    public VirtualMachineProfileImpl(VMInstanceVO vm) {
 +        this(vm, null, null, null, null);
 +    }
 +    
 +    @Override
 +    public String toString() {
 +        return _vm.toString();
 +    }
 +    
 +    @Override
 +    public VirtualMachine getVirtualMachine() {
 +        return _vm;
 +    }
 +    
 +    @Override
 +    public ServiceOffering getServiceOffering() {
 +        if (_offering == null) {
 +            _offering = s_entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, _vm.getServiceOfferingId());
 +        }
 +        return _offering;
 +    }
 +    
 +    @Override
 +    public void setParameter(Param name, Object value) {
 +        _params.put(name, value);
 +    }
 +    
 +    @Override
 +    public void setBootLoaderType(BootloaderType bootLoader) {
 +    	_bootloader = bootLoader;
 +    }
 +    
 +    @Override
 +    public VirtualMachineTemplate getTemplate() {
 +        if (_template == null && _vm != null) {
 +            _template = s_entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, _vm.getTemplateId());
 +        }
 +        return _template;
 +    }
 +    
 +    @Override
 +    public HypervisorType getHypervisorType() {
 +        return _vm.getHypervisorType();
 +    }
 +
 +    @Override
 +    public long getTemplateId() {
 +        return _vm.getTemplateId();
 +    }
 +
 +    @Override
 +    public long getServiceOfferingId() {
 +        return _vm.getServiceOfferingId();
 +    }
 +
 +    @Override
 +    public long getId() {
 +        return _vm.getId();
 +    }
 +    
 +    @Override
 +    public String getUuid() {
 +	return _vm.getUuid();
 +    }
 +
 +    public void setNics(List<NicProfile> nics) {
 +        _nics = nics;
 +    }
 +    
-     public void setDisks(List<VolumeTO> disks) {
++    public void setDisks(List<DiskTO> disks) {
 +        _disks = disks;
 +    }
 +    
 +    @Override
 +    public List<NicProfile> getNics() {
 +        return _nics;
 +    }
 +    
 +    @Override
-     public List<VolumeTO> getDisks() {
++    public List<DiskTO> getDisks() {
 +        return _disks;
 +    }
 +    
 +    @Override
 +    public void addNic(int index, NicProfile nic) {
 +        _nics.add(index, nic);
 +    }
 +    
 +    @Override
-     public void addDisk(int index, VolumeTO disk) {
++    public void addDisk(int index, DiskTO disk) {
 +        _disks.add(index, disk);
 +    }
 +    
 +    @Override
 +    public StringBuilder getBootArgsBuilder() {
 +        return _bootArgs;
 +    }
 +    
 +    @Override
 +    public void addBootArgs(String... args) {
 +        for (String arg : args) {
 +            _bootArgs.append(arg).append(" ");
 +        }
 +    }
 +    
 +    @Override
 +    public VirtualMachine.Type getType() {
 +        return _type;
 +    }
 +    
 +    @Override
 +    public Account getOwner() {
 +        return _owner;
 +    }
 +    
 +    @Override
 +    public String getBootArgs() {
 +        return _bootArgs.toString();
 +    }
 +    
 +    static EntityManager s_entityMgr;
 +
 +    public static void setComponents(EntityManager entityMgr) {
 +        s_entityMgr = entityMgr;
 +    }
 +
 +    @Override
 +    public void addNic(NicProfile nic) {
 +        _nics.add(nic);
 +    }
 +
 +    @Override
-     public void addDisk(VolumeTO disk) {
++    public void addDisk(DiskTO disk) {
 +        _disks.add(disk);
 +    }
 +
 +    @Override
 +    public Object getParameter(Param name) {
 +        return _params.get(name);
 +    }
 +    
 +    @Override
 +    public String getHostName() {
 +        return _vm.getHostName();
 +    }
 +    
 +    @Override
 +    public String getInstanceName() {
 +        return _vm.getInstanceName();
 +    }
 +
 +	@Override
 +	public BootloaderType getBootLoaderType() {
 +		return _bootloader;
 +	}
 +	
 +	@Override
 +	public Map<Param, Object> getParameters() {
 +	    return _params;
 +	}
 +
 +	public void setServiceOffering(ServiceOfferingVO offering) {
 +		_offering = offering;
 +	}
 +
 +    public void setCpuOvercommitRatio(Float cpuOvercommitRatio) {
 +        this.cpuOvercommitRatio = cpuOvercommitRatio;
 +
 +    }
 +
 +    public void setMemoryOvercommitRatio(Float memoryOvercommitRatio) {
 +        this.memoryOvercommitRatio = memoryOvercommitRatio;
 +
 +    }
 +
 +    @Override
 +    public Float getCpuOvercommitRatio() {
 +        return cpuOvercommitRatio;
 +    }
 +
 +    @Override
 +    public Float getMemoryOvercommitRatio() {
 +        return memoryOvercommitRatio;
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java
----------------------------------------------------------------------
diff --cc engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java
index f4a970b,ac50e9b..8c4571f
--- a/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java
+++ b/engine/storage/integration-test/test/org/apache/cloudstack/storage/test/DirectAgentManagerSimpleImpl.java
@@@ -46,9 -58,14 +58,14 @@@ import com.cloud.utils.exception.CloudR
  
  public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentManager {
      private static final Logger logger = Logger.getLogger(DirectAgentManagerSimpleImpl.class);
 -    private Map<Long, ServerResource> hostResourcesMap = new HashMap<Long, ServerResource>();
 +    private final Map<Long, ServerResource> hostResourcesMap = new HashMap<Long, ServerResource>();
      @Inject
      HostDao hostDao;
+     @Inject
+     ClusterDao clusterDao;
+     @Inject
+     ClusterDetailsDao clusterDetailsDao;
+ 
      @Override
      public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
          // TODO Auto-generated method stub
@@@ -88,18 -113,54 +113,54 @@@
          params.put("password", "password");
          params.put("zone", String.valueOf(host.getDataCenterId()));
          params.put("pod", String.valueOf(host.getPodId()));
 -
 +        
          ServerResource resource = null;
          if (host.getHypervisorType() == HypervisorType.XenServer) {
 -            resource = new XcpOssResource();
 -            try {
 -                resource.configure(host.getName(), params);
 +             resource = new XcpOssResource();
-         }
-         
 +        try {
 +            resource.configure(host.getName(), params);
-             hostResourcesMap.put(hostId, resource);
+ 
 -            } catch (ConfigurationException e) {
 -                logger.debug("Failed to load resource:" + e.toString());
 -            }
 +        } catch (ConfigurationException e) {
 +            logger.debug("Failed to load resource:" + e.toString());
 +        }
+         } else if (host.getHypervisorType() == HypervisorType.KVM) {
+             resource = new LibvirtComputingResource();
+             try {
+                 params.put("public.network.device", "cloudbr0");
+                 params.put("private.network.device", "cloudbr0");
+                 resource.configure(host.getName(), params);
+             } catch (ConfigurationException e) {
+                 // TODO Auto-generated catch block
+                 e.printStackTrace();
+             }
+         } else if (host.getHypervisorType() == HypervisorType.VMware) {
+             ClusterVO cluster = clusterDao.findById(host.getClusterId());
+             String url = clusterDetailsDao.findDetail(cluster.getId(), "url").getValue();
+             URI uri;
+             try {
+                 uri = new URI(url);
+                 String userName = clusterDetailsDao.findDetail(cluster.getId(), "username").getValue();
+                 String password = clusterDetailsDao.findDetail(cluster.getId(), "password").getValue();
+                 VmwareServerDiscoverer discover = new VmwareServerDiscoverer();
+ 
+                 Map<? extends ServerResource, Map<String, String>> resources = discover.find(host.getDataCenterId(),
+                         host.getPodId(), host.getClusterId(), uri, userName, password, null);
+                 for (Map.Entry<? extends ServerResource, Map<String, String>> entry : resources.entrySet()) {
+                     resource = entry.getKey();
+                 }
+                 if (resource == null) {
+                     throw new CloudRuntimeException("can't find resource");
+                 }
+             } catch (DiscoveryException e) {
+                 // TODO Auto-generated catch block
+                 e.printStackTrace();
+             } catch (URISyntaxException e) {
+                 // TODO Auto-generated catch block
+                 e.printStackTrace();
+             }
+         }
+ 
+         hostResourcesMap.put(hostId, resource);
          HostEnvironment env = new HostEnvironment();
          SetupCommand cmd = new SetupCommand(env);
          cmd.setNeedSetup(true);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java
index f959939,e16703e..dd6a6a2
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java
@@@ -27,10 -27,10 +27,11 @@@ import java.util.Random
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
++import org.apache.log4j.Logger;
++
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
  import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
--import org.apache.log4j.Logger;
  
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.dc.ClusterVO;
@@@ -49,18 -49,24 +50,23 @@@ import com.cloud.user.Account
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.component.AdapterBase;
  import com.cloud.vm.DiskProfile;
  import com.cloud.vm.VirtualMachineProfile;
  
  public abstract class AbstractStoragePoolAllocator extends AdapterBase implements StoragePoolAllocator {
 -    private static final Logger s_logger = Logger.getLogger(AbstractStoragePoolAllocator.class);
 +	private static final Logger s_logger = Logger.getLogger(AbstractStoragePoolAllocator.class);
-     @Inject StorageManager storageMgr;
-     protected @Inject PrimaryDataStoreDao _storagePoolDao;
-     @Inject VolumeDao _volumeDao;
-     @Inject ConfigurationDao _configDao;
-     @Inject ClusterDao _clusterDao;
-     protected @Inject DataStoreManager dataStoreMgr;
-     protected BigDecimal _storageOverprovisioningFactor = new BigDecimal(1);    
+     @Inject
+     StorageManager storageMgr;
+     protected @Inject
+     PrimaryDataStoreDao _storagePoolDao;
+     @Inject
+     VolumeDao _volumeDao;
+     @Inject
+     ConfigurationDao _configDao;
+     @Inject
+     ClusterDao _clusterDao;
+     protected @Inject
+     DataStoreManager dataStoreMgr;
+     protected BigDecimal _storageOverprovisioningFactor = new BigDecimal(1);
      long _extraBytesPerVolume = 0;
      Random _rand;
      boolean _dontMatter;
@@@ -71,14 -77,15 +77,15 @@@
      @Override
      public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
          super.configure(name, params);
 -
 +        
          Map<String, String> configs = _configDao.getConfiguration(null, params);
 -
 +        
          String globalStorageOverprovisioningFactor = configs.get("storage.overprovisioning.factor");
-         _storageOverprovisioningFactor = new BigDecimal(NumbersUtil.parseFloat(globalStorageOverprovisioningFactor, 2.0f));
+         _storageOverprovisioningFactor = new BigDecimal(NumbersUtil.parseFloat(globalStorageOverprovisioningFactor,
+                 2.0f));
 -
 +        
          _extraBytesPerVolume = 0;
 -
 +        
          _rand = new Random(System.currentTimeMillis());
  
          _dontMatter = Boolean.parseBoolean(configs.get("storage.overwrite.provisioning"));
@@@ -90,95 -97,108 +97,107 @@@
  
          return true;
      }
 -
 +	
- 	protected abstract List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo);
-     
+     protected abstract List<StoragePool> select(DiskProfile dskCh,
 -            VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid,
++            VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid,
+             int returnUpTo);
+ 
      @Override
- 	public
-     List<StoragePool> allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
+     public List<StoragePool> allocateToPool(DiskProfile dskCh,
 -            VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid,
++            VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid,
+             int returnUpTo) {
 -        List<StoragePool> pools = select(dskCh, vmProfile, plan, avoid, returnUpTo);
 -        return reOrder(pools, vmProfile, plan);
 +    	List<StoragePool> pools = select(dskCh, vmProfile, plan, avoid, returnUpTo);
 +    	return reOrder(pools, vmProfile, plan);
      }
 -
 +    
-     protected List<StoragePool> reorderPoolsByNumberOfVolumes(DeploymentPlan plan, List<StoragePool> pools, Account account) {
-         if(account == null){
+     protected List<StoragePool> reorderPoolsByNumberOfVolumes(DeploymentPlan plan, List<StoragePool> pools,
+             Account account) {
+         if (account == null) {
              return pools;
          }
          long dcId = plan.getDataCenterId();
          Long podId = plan.getPodId();
          Long clusterId = plan.getClusterId();
 -
 +            
-         List<Long> poolIdsByVolCount = _volumeDao.listPoolIdsByVolumeCount(dcId, podId, clusterId, account.getAccountId());
+         List<Long> poolIdsByVolCount = _volumeDao.listPoolIdsByVolumeCount(dcId, podId, clusterId,
+                 account.getAccountId());
          if (s_logger.isDebugEnabled()) {
-             s_logger.debug("List of pools in ascending order of number of volumes for account id: "+ account.getAccountId() + " is: "+ poolIdsByVolCount);
+             s_logger.debug("List of pools in ascending order of number of volumes for account id: "
+                     + account.getAccountId() + " is: " + poolIdsByVolCount);
          }
 -
 +            
-         //now filter the given list of Pools by this ordered list
-         Map<Long, StoragePool> poolMap = new HashMap<Long, StoragePool>();        
+         // now filter the given list of Pools by this ordered list
+         Map<Long, StoragePool> poolMap = new HashMap<Long, StoragePool>();
          for (StoragePool pool : pools) {
              poolMap.put(pool.getId(), pool);
          }
          List<Long> matchingPoolIds = new ArrayList<Long>(poolMap.keySet());
 -
 +        
          poolIdsByVolCount.retainAll(matchingPoolIds);
 -
 +        
          List<StoragePool> reorderedPools = new ArrayList<StoragePool>();
-         for(Long id: poolIdsByVolCount){
+         for (Long id : poolIdsByVolCount) {
              reorderedPools.add(poolMap.get(id));
          }
 -
 +        
          return reorderedPools;
      }
 -
 -    protected List<StoragePool> reOrder(List<StoragePool> pools,
 -            VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan) {
 -        Account account = null;
 +    
-     protected List<StoragePool> reOrder(List<StoragePool> pools, 
-     		VirtualMachineProfile vmProfile,
-     		DeploymentPlan plan) {
++    protected List<StoragePool> reOrder(List<StoragePool> pools, VirtualMachineProfile vmProfile, DeploymentPlan plan) {
 +    	Account account = null;
-     	if(vmProfile.getVirtualMachine() != null){
+         if (vmProfile.getVirtualMachine() != null) {
 -            account = vmProfile.getOwner();
 -        }
 -
 +    		account = vmProfile.getOwner();
 +    	}
 +    	
-     	if(_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random") || (account == null)) {
+         if (_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random")
+                 || (account == null)) {
 -            // Shuffle this so that we don't check the pools in the same order.
 -            Collections.shuffle(pools);
 +    		// Shuffle this so that we don't check the pools in the same order.
 +    		Collections.shuffle(pools);
-     	}else if(_allocationAlgorithm.equals("userdispersing")){
+         } else if (_allocationAlgorithm.equals("userdispersing")) {
 -            pools = reorderPoolsByNumberOfVolumes(plan, pools, account);
 -        }
 -        return pools;
 +    		pools = reorderPoolsByNumberOfVolumes(plan, pools, account);
 +    	}
 +    	return pools;
      }
 -
 +	
- 	protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, 
- 		 DeploymentPlan plan) {
+     protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, DeploymentPlan plan) {
 -
 -        if (s_logger.isDebugEnabled()) {
 +		
 +		if (s_logger.isDebugEnabled()) {
-             s_logger.debug("Checking if storage pool is suitable, name: " + pool.getName()+ " ,poolId: "+ pool.getId());
+             s_logger.debug("Checking if storage pool is suitable, name: " + pool.getName() + " ,poolId: "
+                     + pool.getId());
          }
 -        if (avoid.shouldAvoid(pool)) {
 -            if (s_logger.isDebugEnabled()) {
 +		if (avoid.shouldAvoid(pool)) {
 +			if (s_logger.isDebugEnabled()) {
                  s_logger.debug("StoragePool is in avoid set, skipping this pool");
-             }			
+             }
 -            return false;
 -        }
 -
 +			return false;
 +		}
 +		
-         if(dskCh.getType().equals(Type.ROOT) && pool.getPoolType().equals(StoragePoolType.Iscsi)){
+         if (dskCh.getType().equals(Type.ROOT) && pool.getPoolType().equals(StoragePoolType.Iscsi)) {
 -            if (s_logger.isDebugEnabled()) {
 +    		if (s_logger.isDebugEnabled()) {
                  s_logger.debug("Disk needed for ROOT volume, but StoragePoolType is Iscsi, skipping this and trying other available pools");
-             }	
+             }
              return false;
          }
 -
 -
 +        
 +        
+         DiskOfferingVO diskOffering = _diskOfferingDao.findById(dskCh.getDiskOfferingId());
+         if (diskOffering.getSystemUse() && pool.getPoolType() == StoragePoolType.RBD) {
+             s_logger.debug("Skipping RBD pool " + pool.getName()
+                     + " as a suitable pool. RBD is not supported for System VM's");
+             return false;
+         }
+ 
 -        Long clusterId = pool.getClusterId();
 -        ClusterVO cluster = _clusterDao.findById(clusterId);
 -        if (!(cluster.getHypervisorType() == dskCh.getHypervisorType())) {
 -            if (s_logger.isDebugEnabled()) {
 +		Long clusterId = pool.getClusterId();
 +		ClusterVO cluster = _clusterDao.findById(clusterId);
 +		if (!(cluster.getHypervisorType() == dskCh.getHypervisorType())) {
 +    		if (s_logger.isDebugEnabled()) {
                  s_logger.debug("StoragePool's Cluster does not have required hypervisorType, skipping this pool");
              }
 -            return false;
 -        }
 +			return false;
 +		}
  
-         // check capacity  
+         // check capacity
 -        Volume volume = _volumeDao.findById(dskCh.getVolumeId());
 +        Volume volume =  _volumeDao.findById(dskCh.getVolumeId());
          List<Volume> requestVolumes = new ArrayList<Volume>();
          requestVolumes.add(volume);
          return storageMgr.storagePoolHasEnoughSpace(requestVolumes, pool);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
index 4288e5e,0933adc..146c2e2
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
@@@ -25,18 -25,18 +25,18 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
  import org.apache.log4j.Logger;
  import org.springframework.stereotype.Component;
  
++import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
++import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
++
  import com.cloud.deploy.DeploymentPlan;
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
  import com.cloud.offering.ServiceOffering;
  import com.cloud.storage.StoragePool;
  import com.cloud.storage.dao.DiskOfferingDao;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
  @Component
@@@ -49,19 -49,21 +49,20 @@@ public class ClusterScopeStoragePoolAll
      DiskOfferingDao _diskOfferingDao;
  
      @Override
 -    protected List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
 -            DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 -
 +	protected List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 +	    
          s_logger.debug("ClusterScopeStoragePoolAllocator looking for storage pool");
 -        List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 +    	List<StoragePool> suitablePools = new ArrayList<StoragePool>();
  
 -        long dcId = plan.getDataCenterId();
 -        Long podId = plan.getPodId();
 -        Long clusterId = plan.getClusterId();
 +		long dcId = plan.getDataCenterId();
 +		Long podId = plan.getPodId();
 +		Long clusterId = plan.getClusterId();
  
-         if(dskCh.getTags() != null && dskCh.getTags().length != 0){
-         	s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId + " having tags:" + Arrays.toString(dskCh.getTags()));
-         }else{
+         if (dskCh.getTags() != null && dskCh.getTags().length != 0) {
+             s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId
+                     + " having tags:" + Arrays.toString(dskCh.getTags()));
+         } else {
 -            s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
 +        	s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
          }
  
          List<StoragePoolVO> pools = _storagePoolDao.findPoolsByTags(dcId, podId, clusterId, dskCh.getTags());
@@@ -80,25 -83,25 +82,25 @@@
              }
              return suitablePools;
          }
 -
 +    	
-         for (StoragePoolVO pool: pools) {
-         	if(suitablePools.size() == returnUpTo){
+         for (StoragePoolVO pool : pools) {
+             if (suitablePools.size() == returnUpTo) {
 -                break;
 -            }
 -            StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -            if (filter(avoid, pol, dskCh, plan)) {
 -                suitablePools.add(pol);
 +        		break;
 +        	}
-         	StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
++            StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(pool.getId());
 +        	if (filter(avoid, pol, dskCh, plan)) {
 +        		suitablePools.add(pol);
              } else {
                  avoid.addPool(pool.getId());
 -            }
 +        	}
          }
 -
 +        
          if (s_logger.isDebugEnabled()) {
-             s_logger.debug("FirstFitStoragePoolAllocator returning "+suitablePools.size() +" suitable storage pools");
+             s_logger.debug("FirstFitStoragePoolAllocator returning " + suitablePools.size() + " suitable storage pools");
          }
 -
 +        
          return suitablePools;
 -    }
 +	}
  
      @Override
      public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java
index 78cc1b7,979ea73..cae4d2a
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/GarbageCollectingStoragePoolAllocator.java
@@@ -23,9 -23,9 +23,10 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
--import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
  import org.apache.log4j.Logger;
  
++import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
++
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.deploy.DeploymentPlan;
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
@@@ -33,10 -33,10 +34,9 @@@ import com.cloud.storage.StorageManager
  import com.cloud.storage.StoragePool;
  import com.cloud.utils.component.ComponentContext;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
- @Local(value=StoragePoolAllocator.class)
+ @Local(value = StoragePoolAllocator.class)
  public class GarbageCollectingStoragePoolAllocator extends AbstractStoragePoolAllocator {
      private static final Logger s_logger = Logger.getLogger(GarbageCollectingStoragePoolAllocator.class);
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
index 6d3b22d,ef9e84e..7198a28
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
@@@ -25,11 -25,11 +25,12 @@@ import javax.ejb.Local
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
  import org.apache.log4j.Logger;
  import org.springframework.stereotype.Component;
  
++import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
++import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
++
  import com.cloud.capacity.dao.CapacityDao;
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.deploy.DeploymentPlan;
@@@ -41,7 -41,7 +42,6 @@@ import com.cloud.storage.Volume
  import com.cloud.storage.dao.StoragePoolHostDao;
  import com.cloud.utils.NumbersUtil;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  import com.cloud.vm.dao.UserVmDao;
  import com.cloud.vm.dao.VMInstanceDao;
@@@ -78,16 -79,16 +78,16 @@@ public class LocalStoragePoolAllocator 
          // data disk and host identified from deploying vm (attach volume case)
          if (dskCh.getType() == Volume.Type.DATADISK && plan.getHostId() != null) {
              List<StoragePoolHostVO> hostPools = _poolHostDao.listByHostId(plan.getHostId());
-             for (StoragePoolHostVO hostPool: hostPools) {
+             for (StoragePoolHostVO hostPool : hostPools) {
                  StoragePoolVO pool = _storagePoolDao.findById(hostPool.getPoolId());
                  if (pool != null && pool.isLocal()) {
-                 	StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -                    StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -                    if (filter(avoid, pol, dskCh, plan)) {
 -                        s_logger.debug("Found suitable local storage pool " + pool.getId() + ", adding to list");
 -                        suitablePools.add(pol);
++                    StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(pool.getId());
 +                	if (filter(avoid, pol, dskCh, plan)) {
 +                		s_logger.debug("Found suitable local storage pool " + pool.getId() + ", adding to list");
 +                		suitablePools.add(pol);
                      } else {
                          avoid.addPool(pool.getId());
 -                    }
 +                	}
                  }
  
                  if (suitablePools.size() == returnUpTo) {
@@@ -95,18 -96,19 +95,19 @@@
                  }
              }
          } else {
-         	List<StoragePoolVO> availablePools = _storagePoolDao.findLocalStoragePoolsByTags(plan.getDataCenterId(), plan.getPodId(), plan.getClusterId(), dskCh.getTags());
+             List<StoragePoolVO> availablePools = _storagePoolDao.findLocalStoragePoolsByTags(plan.getDataCenterId(),
+                     plan.getPodId(), plan.getClusterId(), dskCh.getTags());
 -            for (StoragePoolVO pool : availablePools) {
 -                if (suitablePools.size() == returnUpTo) {
 -                    break;
 -                }
 -                StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -                if (filter(avoid, pol, dskCh, plan)) {
 -                    suitablePools.add(pol);
 +        	for (StoragePoolVO pool : availablePools) {
 +        		if (suitablePools.size() == returnUpTo) {
 +            		break;
 +            	}
-         		StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
++                StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(pool.getId());
 +        		if (filter(avoid, pol, dskCh, plan)) {
 +        			suitablePools.add(pol);
                  } else {
                      avoid.addPool(pool.getId());
 -                }
 -            }
 +        		}
 +        	}
  
              // add remaining pools in cluster, that did not match tags, to avoid
              // set

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java
index b9a88bb,d057138..c3c9015
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/UseLocalForRootAllocator.java
@@@ -31,17 -31,19 +31,18 @@@ import com.cloud.deploy.DeploymentPlan
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
  import com.cloud.storage.StoragePool;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
- @Local(value=StoragePoolAllocator.class)
+ @Local(value = StoragePoolAllocator.class)
  public class UseLocalForRootAllocator extends LocalStoragePoolAllocator implements StoragePoolAllocator {
  
      @Inject
      DataCenterDao _dcDao;
  
      @Override
-     public List<StoragePool> allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
+     public List<StoragePool> allocateToPool(DiskProfile dskCh,
 -            VirtualMachineProfile<? extends VirtualMachine> vmProfile, DeploymentPlan plan, ExcludeList avoid,
++            VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid,
+             int returnUpTo) {
          DataCenterVO dc = _dcDao.findById(plan.getDataCenterId());
          if (!dc.isLocalStorageEnabled()) {
              return null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
index 9da3475,29b3400..e916a5c
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
@@@ -21,11 -21,11 +21,12 @@@ import java.util.List
  
  import javax.inject.Inject;
  
++import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
++
  import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
--import org.apache.log4j.Logger;
--import org.springframework.stereotype.Component;
  
  import com.cloud.deploy.DeploymentPlan;
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
@@@ -33,42 -33,42 +34,41 @@@ import com.cloud.hypervisor.Hypervisor.
  import com.cloud.storage.StoragePool;
  import com.cloud.storage.Volume;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
  @Component
  public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator {
 -    private static final Logger s_logger = Logger.getLogger(ZoneWideStoragePoolAllocator.class);
 +	private static final Logger s_logger = Logger.getLogger(ZoneWideStoragePoolAllocator.class);
- 	@Inject PrimaryDataStoreDao _storagePoolDao; 
- 	@Inject DataStoreManager dataStoreMgr; 
+     @Inject
+     PrimaryDataStoreDao _storagePoolDao;
+     @Inject
+     DataStoreManager dataStoreMgr;
 -
 -    @Override
 +	
 +	@Override
- 	protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, 
- 			 DeploymentPlan plan) {
+     protected boolean filter(ExcludeList avoid, StoragePool pool, DiskProfile dskCh, DeploymentPlan plan) {
 -        Volume volume = _volumeDao.findById(dskCh.getVolumeId());
 +        Volume volume =  _volumeDao.findById(dskCh.getVolumeId());
          List<Volume> requestVolumes = new ArrayList<Volume>();
          requestVolumes.add(volume);
          return storageMgr.storagePoolHasEnoughSpace(requestVolumes, pool);
 -    }
 -
 -    @Override
 -    protected List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
 -            DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 -        s_logger.debug("ZoneWideStoragePoolAllocator to find storage pool");
 -        List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 -        HypervisorType hypervisor = dskCh.getHypervisorType();
 -        if (hypervisor != null) {
 +	}
 +	
 +	@Override
- 	protected List<StoragePool> select(DiskProfile dskCh,
- 			VirtualMachineProfile vmProfile,
++    protected List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile,
 +			DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 +	    s_logger.debug("ZoneWideStoragePoolAllocator to find storage pool");
 +		List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 +		HypervisorType hypervisor = dskCh.getHypervisorType();
 +		if (hypervisor != null) {
              if (hypervisor != HypervisorType.KVM && hypervisor != HypervisorType.VMware) {
                  s_logger.debug("Only kvm, VMware hypervisors are enabled to support zone wide storage");
 -                return suitablePools;
 -            }
 -        }
 -
 -        List<StoragePoolVO> storagePools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), dskCh.getTags());
 +				return suitablePools;
 +			}
 +		}
 +		
 +		List<StoragePoolVO> storagePools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), dskCh.getTags());
          List<StoragePoolVO> storagePoolsByHypervisor = _storagePoolDao.findZoneWideStoragePoolsByHypervisor(plan.getDataCenterId(), dskCh.getHypervisorType());
          storagePools.retainAll(storagePoolsByHypervisor);
 -
 +	
          // add remaining pools in zone, that did not match tags, to avoid set
          List<StoragePoolVO> allPools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), null);
          allPools.removeAll(storagePools);
@@@ -76,17 -76,17 +76,17 @@@
              avoid.addPool(pool.getId());
          }
  
 -        for (StoragePoolVO storage : storagePools) {
 -            if (suitablePools.size() == returnUpTo) {
 -                break;
 -            }
 -            StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(storage.getId());
 -            if (filter(avoid, pol, dskCh, plan)) {
 -                suitablePools.add(pol);
 +		for (StoragePoolVO storage : storagePools) {
 +			if (suitablePools.size() == returnUpTo) {
 +        		break;
 +        	}
- 			StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(storage.getId());
++            StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(storage.getId());
 +			if (filter(avoid, pol, dskCh, plan)) {
 +				suitablePools.add(pol);
              } else {
                  avoid.addPool(pol.getId());
 -            }
 -        }
 -        return suitablePools;
 -    }
 +			}
 +		}
 +		return suitablePools;
 +	}
  }


[13/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
ntier apps


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

Branch: refs/heads/vmsync
Commit: f3fa54e732fc24013f551089805fd9900a9b0797
Parents: 1a50e2f
Author: Radhika PC <ra...@citrix.com>
Authored: Mon Jun 24 09:50:00 2013 +0530
Committer: Radhika PC <ra...@citrix.com>
Committed: Mon Jun 24 09:51:32 2013 +0530

----------------------------------------------------------------------
 docs/en-US/add-gateway-vpc.xml | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f3fa54e7/docs/en-US/add-gateway-vpc.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/add-gateway-vpc.xml b/docs/en-US/add-gateway-vpc.xml
index a081faf..5ef8b63 100644
--- a/docs/en-US/add-gateway-vpc.xml
+++ b/docs/en-US/add-gateway-vpc.xml
@@ -22,7 +22,8 @@
   <title>Adding a Private Gateway to a VPC</title>
   <para>A private gateway can be added by the root admin only. The VPC private network has 1:1
     relationship with the NIC of the physical network. You can configure multiple private gateways
-    to a single VPC. No gateways with duplicated VLAN and IP are allowed in the same data center.</para>
+    to a single VPC. No gateways with duplicated VLAN and IP are allowed in the same data
+    center.</para>
   <orderedlist>
     <listitem>
       <para>Log in to the &PRODUCT; UI as an administrator or end user.</para>
@@ -148,4 +149,13 @@
       private gateway interface are blocked. You can change this default behaviour while creating a
       private gateway.</para>
   </section>
+  <section id="static-route">
+    <title>Creating a Static Route</title>
+    <para>&PRODUCT; enables you to specify routing for the VPN connection you create. You can enter
+      one or CIDR addresses to indicate which traffic is to be routed back to the gateway.</para>
+  </section>
+  <section id="blacklist-route">
+    <title>Blacklisting Routes</title>
+    <para/>
+  </section>
 </section>


[50/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
merge from head


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

Branch: refs/heads/vmsync
Commit: 049dd7242e7778eaa4a5ac9b68dc3d2f7a3fb1e6
Parents: 7b7db05 e7c3479
Author: Alex Huang <al...@gmail.com>
Authored: Mon Jun 24 16:51:59 2013 -0700
Committer: Alex Huang <al...@gmail.com>
Committed: Mon Jun 24 16:51:59 2013 -0700

----------------------------------------------------------------------
 client/pom.xml                                                    | 2 ++
 .../com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java  | 3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/049dd724/client/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/049dd724/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java
----------------------------------------------------------------------


[43/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
index 17fc568,18ac13b..f5c1fcd
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java
@@@ -202,12 -179,23 +179,23 @@@ public class InternalLoadBalancerElemen
          }
          
          if (vm.getType() == VirtualMachine.Type.User) {
+             return implementInternalLbVms(network, dest);
+         }
+         return true;
+     }
+ 
+ 
+     protected boolean implementInternalLbVms(Network network, DeployDestination dest) throws ResourceUnavailableException {
 -        //1) Get all the Ips from the network having LB rules assigned
 -        List<String> ips = _appLbDao.listLbIpsBySourceIpNetworkIdAndScheme(network.getId(), Scheme.Internal);
 -        
 +          //1) Get all the Ips from the network having LB rules assigned
 +            List<String> ips = _appLbDao.listLbIpsBySourceIpNetworkIdAndScheme(network.getId(), Scheme.Internal);
 +            
-             //2) Start those vms
+         //2) Start internal lb vms for the ips having active rules
 -        for (String ip : ips) {
 -            Ip sourceIp = new Ip(ip);
 +            for (String ip : ips) {
 +                Ip sourceIp = new Ip(ip);
+             long active = _appLbDao.countActiveBySourceIp(sourceIp, network.getId());
+             if (active > 0) {
+                 s_logger.debug("Have to implement internal lb vm for source ip " + sourceIp + " as a part of network " + network
+                         + " implement as there are " + active + " internal lb rules exist for this ip");
                  List<? extends VirtualRouter> internalLbVms;
                  try {
                      internalLbVms = _internalLbMgr.deployInternalLbVm(network, sourceIp, dest, _accountMgr.getAccount(network.getAccountId()), null);
@@@ -410,17 -398,21 +398,21 @@@
      protected Map<Ip, List<LoadBalancingRule>> groupBySourceIp(List<LoadBalancingRule> rules) {
          Map<Ip, List<LoadBalancingRule>> groupedRules = new HashMap<Ip, List<LoadBalancingRule>>();
          for (LoadBalancingRule rule : rules) {
+             if (rule.getDestinations() != null && !rule.getDestinations().isEmpty()) {
 -                Ip sourceIp = rule.getSourceIp();
 -                if (!groupedRules.containsKey(sourceIp)) {
 -                    groupedRules.put(sourceIp, null);
 -                }
 -                
 -                List<LoadBalancingRule> rulesToApply = groupedRules.get(sourceIp);
 -                if (rulesToApply == null) {
 -                    rulesToApply = new ArrayList<LoadBalancingRule>();
 -                }
 -                rulesToApply.add(rule);
 -                groupedRules.put(sourceIp, rulesToApply);
 +            Ip sourceIp = rule.getSourceIp();
 +            if (!groupedRules.containsKey(sourceIp)) {
 +                groupedRules.put(sourceIp, null);
 +            }
 +            
 +            List<LoadBalancingRule> rulesToApply = groupedRules.get(sourceIp);
 +            if (rulesToApply == null) {
 +                rulesToApply = new ArrayList<LoadBalancingRule>();
 +            }
 +            rulesToApply.add(rule);
 +            groupedRules.put(sourceIp, rulesToApply);
+             } else {
+                 s_logger.debug("Internal lb rule " + rule + " doesn't have any vms assigned, skipping");
+             }
          }
          return groupedRules;
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --cc plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index b0ac526,c633d57..f49ea69
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@@ -381,10 -394,19 +381,19 @@@ public class InternalLoadBalancerVMMana
          _mgmtHost = configs.get("host");
          _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
          
-         String offIdStr = configs.get(Config.InternalLbVmServiceOfferingId.key());
-         if (offIdStr != null && !offIdStr.isEmpty()) {
-             _internalLbVmOfferingId = Long.parseLong(offIdStr);
+         String offUUID = configs.get(Config.InternalLbVmServiceOfferingId.key());
+         if (offUUID != null && !offUUID.isEmpty()) {
+             //get the id by offering UUID
+             ServiceOfferingVO off = _serviceOfferingDao.findByUuid(offUUID);
+             if (off != null) {
+                 _internalLbVmOfferingId = off.getId();
 -            } else {
 +        } else {
+                 s_logger.warn("Invalid offering UUID is passed in " + Config.InternalLbVmServiceOfferingId.key() + "; the default offering will be used instead");
+             }
+         }
+         
+         //if offering wasn't set, try to get the default one
+         if (_internalLbVmOfferingId == 0L) {
              boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
              ServiceOfferingVO newOff = new ServiceOfferingVO("System Offering For Internal LB VM", 1, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_RAMSIZE, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_CPU_MHZ, null,
                      null, true, null, useLocalStorage, true, null, true, VirtualMachine.Type.InternalLoadBalancerVm, true);
@@@ -749,46 -765,44 +755,49 @@@
          DomainRouterVO internalLbVm = null;
          for (Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext();) {
              HypervisorType hType = iter.next();
-             s_logger.debug("Allocating the Internal lb with the hypervisor type " + hType);
 -            try {
 -                long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Creating the internal lb vm " + id + " in datacenter "  + dest.getDataCenter() + " with hypervisor type " + hType);
 -                }                String templateName = null;
 -                switch (hType) {
 -                    case XenServer:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case KVM:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case VMware:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case Hyperv:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    case LXC:
 -                        templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 -                        break;
 -                    default: break;
 -                }
 -                VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
++            long id = _internalLbVmDao.getNextInSequence(Long.class, "id");
++            if (s_logger.isDebugEnabled()) {
++                s_logger.debug("Creating the internal lb vm " + id + " in datacenter " + dest.getDataCenter() + " with hypervisor type " + hType);
++            }
 +            String templateName = null;
 +            switch (hType) {
 +            case XenServer:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateXen.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case KVM:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateKVM.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case VMware:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateVmware.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case Hyperv:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateHyperv.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            case LXC:
 +                templateName = _configServer.getConfigValue(Config.RouterTemplateLXC.key(), Config.ConfigurationParameterScope.zone.toString(), dest.getDataCenter().getId());
 +                break;
 +            default:
 +                break;
 +            }
 +            VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
  
 -                if (template == null) {
 -                    s_logger.debug(hType + " won't support system vm, skip it");
 -                    continue;
 -                }
 +            if (template == null) {
 +                s_logger.debug(hType + " won't support system vm, skip it");
 +                continue;
 +            }
  
 -                internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId, 
 -                VirtualMachineName.getSystemVmName(id, _instance, _internalLbVmNamePrefix), template.getId(), template.getHypervisorType(),
 -                template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false, 
 -                RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
 -                internalLbVm.setRole(Role.INTERNAL_LB_VM);
 -                internalLbVm = _itMgr.allocate(internalLbVm, template, routerOffering, networks, plan, null, owner);
 -            } catch (InsufficientCapacityException ex) {
 +            internalLbVm = new DomainRouterVO(id, routerOffering.getId(), internalLbProviderId,
 +                    VirtualMachineName.getSystemVmName(id, _instance, _internalLbVmNamePrefix), template.getId(), template.getHypervisorType(),
 +                    template.getGuestOSId(), owner.getDomainId(), owner.getId(), false, 0, false,
 +                    RedundantState.UNKNOWN, false, false, VirtualMachine.Type.InternalLoadBalancerVm, vpcId);
 +            internalLbVm.setRole(Role.INTERNAL_LB_VM);
 +            internalLbVm = _internalLbVmDao.persist(internalLbVm);
 +            try {
 +                _itMgr.allocate(internalLbVm.getInstanceName(), template, routerOffering, networks, plan, null, owner);
 +            } catch (CloudRuntimeException e) {
                  if (allocateRetry < 2 && iter.hasNext()) {
 +                    allocateRetry++;
 +                    _internalLbVmDao.remove(internalLbVm.getId());
                      s_logger.debug("Failed to allocate the Internal lb vm with hypervisor type " + hType + ", retrying one more time");
                      continue;
                  } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
index 0be2dba,76ce663..73f308b
--- a/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
+++ b/plugins/storage-allocators/random/src/org/apache/cloudstack/storage/allocator/RandomStoragePoolAllocator.java
@@@ -21,52 -21,53 +21,53 @@@ import java.util.List
  
  import javax.ejb.Local;
  
- import org.apache.cloudstack.engine.subsystem.api.storage.ScopeType;
++import org.apache.log4j.Logger;
++
  import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
  
  import com.cloud.deploy.DeploymentPlan;
  import com.cloud.deploy.DeploymentPlanner.ExcludeList;
+ import com.cloud.storage.ScopeType;
  import com.cloud.storage.StoragePool;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
- @Local(value=StoragePoolAllocator.class)
+ @Local(value = StoragePoolAllocator.class)
  public class RandomStoragePoolAllocator extends AbstractStoragePoolAllocator {
      private static final Logger s_logger = Logger.getLogger(RandomStoragePoolAllocator.class);
 -
 +    
      @Override
-     public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
 -    public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
++    public List<StoragePool> select(DiskProfile dskCh, VirtualMachineProfile vmProfile,
+             DeploymentPlan plan, ExcludeList avoid, int returnUpTo) {
  
 -        List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 -
 -        long dcId = plan.getDataCenterId();
 -        Long podId = plan.getPodId();
 -        Long clusterId = plan.getClusterId();
 +    	List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 +    	
 +		long dcId = plan.getDataCenterId();
 +		Long podId = plan.getPodId();
 +		Long clusterId = plan.getClusterId();
          s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
 -        List<StoragePoolVO> pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER);
 +    	List<StoragePoolVO> pools = _storagePoolDao.listBy(dcId, podId, clusterId, ScopeType.CLUSTER);
          if (pools.size() == 0) {
 -            if (s_logger.isDebugEnabled()) {
 -                s_logger.debug("No storage pools available for allocation, returning");
 -            }
 +        	if (s_logger.isDebugEnabled()) {
 +        		s_logger.debug("No storage pools available for allocation, returning");
 +    		}
              return suitablePools;
          }
 -
 +        
          Collections.shuffle(pools);
 -        if (s_logger.isDebugEnabled()) {
 +    	if (s_logger.isDebugEnabled()) {
              s_logger.debug("RandomStoragePoolAllocator has " + pools.size() + " pools to check for allocation");
          }
-         for (StoragePoolVO pool: pools) {
-         	if(suitablePools.size() == returnUpTo){
+         for (StoragePoolVO pool : pools) {
+             if (suitablePools.size() == returnUpTo) {
 -                break;
 -            }
 -            StoragePool pol = (StoragePool) this.dataStoreMgr.getPrimaryDataStore(pool.getId());
 -
 -            if (filter(avoid, pol, dskCh, plan)) {
 -                suitablePools.add(pol);
 -            }
 +        		break;
-         	}        	
-         	StoragePool pol = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(pool.getId());
++        	}
++            StoragePool pol = (StoragePool) dataStoreMgr.getPrimaryDataStore(pool.getId());
 +            
 +        	if (filter(avoid, pol, dskCh, plan)) {
 +        		suitablePools.add(pol);
 +        	}
          }
  
          if (s_logger.isDebugEnabled()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/agent/manager/AgentManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/ApiDBUtils.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index caef5e9,b56aa4a..9fd101e
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -74,6 -70,6 +71,7 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.HostResponse;
  import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse;
  import org.apache.cloudstack.api.response.IPAddressResponse;
++import org.apache.cloudstack.api.response.ImageStoreResponse;
  import org.apache.cloudstack.api.response.InstanceGroupResponse;
  import org.apache.cloudstack.api.response.InternalLoadBalancerElementResponse;
  import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
@@@ -175,9 -176,9 +176,8 @@@ import com.cloud.configuration.Resource
  import com.cloud.configuration.Resource.ResourceType;
  import com.cloud.configuration.ResourceCount;
  import com.cloud.configuration.ResourceLimit;
 -import com.cloud.dao.EntityManager;
  import com.cloud.dc.ClusterVO;
  import com.cloud.dc.DataCenter;
- import com.cloud.dc.DataCenterVO;
  import com.cloud.dc.HostPodVO;
  import com.cloud.dc.Pod;
  import com.cloud.dc.StorageNetworkIpRange;
@@@ -261,15 -262,11 +263,11 @@@ import com.cloud.storage.ImageStore
  import com.cloud.storage.S3;
  import com.cloud.storage.Snapshot;
  import com.cloud.storage.SnapshotVO;
- import com.cloud.storage.Storage.ImageFormat;
- import com.cloud.storage.Storage.TemplateType;
 -import com.cloud.storage.Upload;
+ import com.cloud.storage.Storage.StoragePoolType;
  import com.cloud.storage.StoragePool;
  import com.cloud.storage.Swift;
++import com.cloud.storage.Upload;
  import com.cloud.storage.UploadVO;
- import com.cloud.storage.VMTemplateHostVO;
- import com.cloud.storage.VMTemplateS3VO;
- import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
- import com.cloud.storage.VMTemplateSwiftVO;
  import com.cloud.storage.VMTemplateVO;
  import com.cloud.storage.Volume;
  import com.cloud.storage.VolumeVO;
@@@ -302,13 -299,11 +300,15 @@@ public class ApiResponseHelper implemen
  
      public final Logger s_logger = Logger.getLogger(ApiResponseHelper.class);
      private static final DecimalFormat s_percentFormat = new DecimalFormat("##.##");
-     @Inject private final EntityManager _entityMgr = null;
-     @Inject private final UsageService _usageSvc = null;
+     @Inject
 -    private EntityManager _entityMgr = null;
++    private final EntityManager _entityMgr = null;
+     @Inject
 -    private UsageService _usageSvc = null;
++    private final UsageService _usageSvc = null;
      @Inject NetworkModel _ntwkModel;
 +    @Inject
 +    AccountManager _accountMgr;
 +    @Inject
 +    AsyncJobManager _jobMgr;
  
      @Override
      public UserResponse createUserResponse(User user) {
@@@ -1142,15 -1136,15 +1141,15 @@@
              vmResponse.setSystemVmType(vm.getType().toString().toLowerCase());
  
              vmResponse.setName(vm.getHostName());
-             if ( vm.getPodIdToDeployIn() != null ){
+             if (vm.getPodIdToDeployIn() != null) {
                  HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn());
-                 if ( pod != null ){
+                 if (pod != null) {
 -                    vmResponse.setPodId(pod.getUuid());
 +            vmResponse.setPodId(pod.getUuid());
                  }
              }
              VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId());
-             if (template != null){
+             if (template != null) {
 -                vmResponse.setTemplateId(template.getUuid());
 +            vmResponse.setTemplateId(template.getUuid());
              }
              vmResponse.setCreated(vm.getCreated());
  
@@@ -1417,126 -1288,25 +1293,24 @@@
      }
  
      @Override
-     public List<TemplateResponse> createTemplateResponses(long templateId, long zoneId, boolean readyOnly) {
+     public List<TemplateResponse> createTemplateResponses(long templateId, Long zoneId, boolean readyOnly) {
          VirtualMachineTemplate template = findTemplateById(templateId);
-         List<TemplateResponse> responses = new ArrayList<TemplateResponse>();
-         VMTemplateHostVO templateHostRef = ApiDBUtils.findTemplateHostRef(templateId, zoneId, readyOnly);
-         if (templateHostRef == null) {
-             return responses;
-         }
- 
-         HostVO host = ApiDBUtils.findHostById(templateHostRef.getHostId());
-         if (host.getType() == Host.Type.LocalSecondaryStorage && host.getStatus() != com.cloud.host.Status.Up) {
-             return responses;
-         }
- 
-         TemplateResponse templateResponse = new TemplateResponse();
-         templateResponse.setId(template.getUuid());
-         templateResponse.setName(template.getName());
-         templateResponse.setDisplayText(template.getDisplayText());
-         templateResponse.setPublic(template.isPublicTemplate());
-         templateResponse.setCreated(templateHostRef.getCreated());
- 
-         templateResponse.setReady(templateHostRef.getDownloadState() == Status.DOWNLOADED);
-         templateResponse.setFeatured(template.isFeatured());
-         templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
-         templateResponse.setPasswordEnabled(template.getEnablePassword());
-         templateResponse.setSshKeyEnabled(template.getEnableSshKey());
-         templateResponse.setCrossZones(template.isCrossZones());
-         templateResponse.setFormat(template.getFormat());
-         if (template.getTemplateType() != null) {
-             templateResponse.setTemplateType(template.getTemplateType().toString());
-         }
- 
-         templateResponse.setHypervisor(template.getHypervisorType().toString());
-         templateResponse.setDetails(template.getDetails());
- 
-         GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId());
-         if (os != null) {
-             templateResponse.setOsTypeId(os.getUuid());
-             templateResponse.setOsTypeName(os.getDisplayName());
-         } else {
-             templateResponse.setOsTypeId("-1");
-             templateResponse.setOsTypeName("");
-         }
- 
-         Account account = ApiDBUtils.findAccountByIdIncludingRemoved(template.getAccountId());
-         populateAccount(templateResponse, account.getId());
-         populateDomain(templateResponse, account.getDomainId());
- 
-         DataCenter datacenter = ApiDBUtils.findZoneById(zoneId);
- 
-         if (datacenter != null) {
-             // Add the zone ID
-             templateResponse.setZoneId(datacenter.getUuid());
-             templateResponse.setZoneName(datacenter.getName());
-             templateResponse.setZoneType(datacenter.getNetworkType().toString());
-         }
- 
-         boolean isAdmin = false;
-         Account caller = CallContext.current().getCallingAccount();
-         if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
-             isAdmin = true;
-         }
- 
-         // If the user is an Admin, add the template download status
-         if (isAdmin || caller.getId() == template.getAccountId()) {
-             // add download status
-             if (templateHostRef.getDownloadState() != Status.DOWNLOADED) {
-                 String templateStatus = "Processing";
-                 if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
-                     if (templateHostRef.getDownloadPercent() == 100) {
-                         templateStatus = "Installing Template";
-                     } else {
-                         templateStatus = templateHostRef.getDownloadPercent() + "% Downloaded";
-                     }
-                 } else {
-                     templateStatus = templateHostRef.getErrorString();
-                 }
-                 templateResponse.setStatus(templateStatus);
-             } else if (templateHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
-                 templateResponse.setStatus("Download Complete");
-             } else {
-                 templateResponse.setStatus("Successfully Installed");
-             }
-         }
- 
-         Long templateSize = templateHostRef.getSize();
-         if (templateSize > 0) {
-             templateResponse.setSize(templateSize);
-         }
- 
-         templateResponse.setChecksum(template.getChecksum());
-         if (template.getSourceTemplateId() != null) {
-             VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId());
-             if (tmpl != null) {
-                 templateResponse.setSourceTemplateId(tmpl.getUuid());
-             }
-         }
- 
-         templateResponse.setChecksum(template.getChecksum());
- 
-         templateResponse.setTemplateTag(template.getTemplateTag());
+         return createTemplateResponses(template, zoneId, readyOnly);
+     }
  
-         //set tag information
-         List<? extends ResourceTag> tags = null;
-         if (template.getFormat() == ImageFormat.ISO) {
-             tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, template.getId());
 -
+     @Override
+     public List<TemplateResponse> createIsoResponses(VirtualMachineTemplate result, Long zoneId, boolean readyOnly) {
+         List<TemplateJoinVO> tvo = null;
+         if (zoneId == null || zoneId == -1) {
+             tvo = ApiDBUtils.newTemplateView(result);
          } else {
-             tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Template, template.getId());
-         }
-         List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
-         for (ResourceTag tag : tags) {
-             ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
-             tagResponses.add(tagResponse);
+             tvo = ApiDBUtils.newTemplateView(result, zoneId, readyOnly);
          }
-         templateResponse.setTags(tagResponses);
  
-         templateResponse.setObjectName("template");
-         responses.add(templateResponse);
-         return responses;
+         return ViewResponseHelper.createIsoResponse(tvo.toArray(new TemplateJoinVO[tvo.size()]));
      }
  
+     /*
      @Override
      public List<TemplateResponse> createIsoResponses(long isoId, Long zoneId, boolean readyOnly) {
  
@@@ -1564,8 -1334,8 +1338,8 @@@
              populateAccount(isoResponse, owner.getId());
              populateDomain(isoResponse, owner.getDomainId());
  
-             //set tag information
+             // set tag information
 -            List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
 +            List<? extends ResourceTag> tags =  ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
              List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
              for (ResourceTag tag : tags) {
                  ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
@@@ -1789,8 -1558,8 +1562,8 @@@
              isoResponse.setSize(isoSize);
          }
  
-         //set tag information
+         // set tag information
 -        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
 +        List<? extends ResourceTag> tags =  ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId());
  
          List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
          for (ResourceTag tag : tags) {
@@@ -1828,11 -1597,41 +1601,41 @@@
              response.setZoneName(zone.getName());
          }
          response.setMode(mode);
+         response.setUrl(url);
+         response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString());
+         Account account = ApiDBUtils.findAccountById(accountId);
+         response.setAccountId(account.getUuid());
+ 
+         return response;
+     }
+ 
+     @Override
+     public ExtractResponse createExtractResponse(Long uploadId, Long id, Long zoneId, Long accountId, String mode, String url) {
+ 
+         ExtractResponse response = new ExtractResponse();
+         response.setObjectName("template");
+         VMTemplateVO template = ApiDBUtils.findTemplateById(id);
+         response.setId(template.getUuid());
+         response.setName(template.getName());
+         if (zoneId != null) {
+             DataCenter zone = ApiDBUtils.findZoneById(zoneId);
+             response.setZoneId(zone.getUuid());
+             response.setZoneName(zone.getName());
+         }
+         response.setMode(mode);
+         if (uploadId == null) {
+             // region-wide image store
+             response.setUrl(url);
+             response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString());
+         } else {
+             UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId);
 -            response.setUploadId(uploadInfo.getUuid());
 -            response.setState(uploadInfo.getUploadState().toString());
 +        response.setUploadId(uploadInfo.getUuid());
 +        response.setState(uploadInfo.getUploadState().toString());
+             response.setUrl(uploadInfo.getUploadUrl());
+         }
          Account account = ApiDBUtils.findAccountById(accountId);
          response.setAccountId(account.getUuid());
-         response.setUrl(uploadInfo.getUploadUrl());
+ 
          return response;
  
      }
@@@ -2214,40 -2151,41 +2168,41 @@@
          response.setIp6Gateway(network.getIp6Gateway());
          response.setIp6Cidr(network.getIp6Cidr());
  
-         // create response for reserved IP ranges that can be used for non-cloudstack purposes
+         // create response for reserved IP ranges that can be used for
+         // non-cloudstack purposes
 -        String reservation = null;
 +        String  reservation = null;
          if ((network.getCidr() != null) && (NetUtils.isNetworkAWithinNetworkB(network.getCidr(), network.getNetworkCidr()))) {
 -            String[] guestVmCidrPair = network.getCidr().split("\\/");
 -            String[] guestCidrPair = network.getNetworkCidr().split("\\/");
 +                String[] guestVmCidrPair = network.getCidr().split("\\/");
 +                String[] guestCidrPair = network.getNetworkCidr().split("\\/");
  
 -            Long guestVmCidrSize = Long.valueOf(guestVmCidrPair[1]);
 -            Long guestCidrSize = Long.valueOf(guestCidrPair[1]);
 +                Long guestVmCidrSize = Long.valueOf(guestVmCidrPair[1]);
 +                Long guestCidrSize = Long.valueOf(guestCidrPair[1]);
  
 -            String[] guestVmIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], guestVmCidrSize);
 -            String[] guestIpRange = NetUtils.getIpRangeFromCidr(guestCidrPair[0], guestCidrSize);
 -            long startGuestIp = NetUtils.ip2Long(guestIpRange[0]);
 -            long endGuestIp = NetUtils.ip2Long(guestIpRange[1]);
 -            long startVmIp = NetUtils.ip2Long(guestVmIpRange[0]);
 -            long endVmIp = NetUtils.ip2Long(guestVmIpRange[1]);
 +                String[] guestVmIpRange = NetUtils.getIpRangeFromCidr(guestVmCidrPair[0], guestVmCidrSize);
 +                String[] guestIpRange = NetUtils.getIpRangeFromCidr(guestCidrPair[0], guestCidrSize);
 +                long startGuestIp = NetUtils.ip2Long(guestIpRange[0]);
 +                long endGuestIp = NetUtils.ip2Long(guestIpRange[1]);
 +                long startVmIp = NetUtils.ip2Long(guestVmIpRange[0]);
 +                long endVmIp = NetUtils.ip2Long(guestVmIpRange[1]);
  
-                 if (startVmIp == startGuestIp && endVmIp < endGuestIp -1) {
+             if (startVmIp == startGuestIp && endVmIp < endGuestIp - 1) {
 -                reservation = (NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp));
 -            }
 -            if (endVmIp == endGuestIp && startVmIp > startGuestIp + 1) {
 +                    reservation = (NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils.long2Ip(endGuestIp));
 +                }
 +                if (endVmIp == endGuestIp && startVmIp > startGuestIp + 1) {
-                     reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp-1));
+                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1));
 -            }
 +                }
-                 if(startVmIp > startGuestIp + 1 && endVmIp < endGuestIp - 1) {
-                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" +  NetUtils.long2Ip(startVmIp-1) + " ,  " +
-                         NetUtils.long2Ip(endVmIp + 1) + "-"+  NetUtils.long2Ip(endGuestIp));
+             if (startVmIp > startGuestIp + 1 && endVmIp < endGuestIp - 1) {
+                 reservation = (NetUtils.long2Ip(startGuestIp) + "-" + NetUtils.long2Ip(startVmIp - 1) + " ,  " + NetUtils.long2Ip(endVmIp + 1) + "-" + NetUtils
+                         .long2Ip(endGuestIp));
              }
          }
          response.setReservedIpRange(reservation);
  
-         //return vlan information only to Root admin
+         // return vlan information only to Root admin
 -        if (network.getBroadcastUri() != null && UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
 +        if (network.getBroadcastUri() != null && CallContext.current().getCallingAccount().getType() == Account.ACCOUNT_TYPE_ADMIN) {
              String broadcastUri = network.getBroadcastUri().toString();
              response.setBroadcastUri(broadcastUri);
-             String vlan="N/A";
+             String vlan = "N/A";
              if (broadcastUri.startsWith("vlan")) {
                  vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length());
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/QueryManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/QueryManagerImpl.java
index de39793,9a80082..a7217ce
--- a/server/src/com/cloud/api/query/QueryManagerImpl.java
+++ b/server/src/com/cloud/api/query/QueryManagerImpl.java
@@@ -54,28 -56,11 +58,31 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd;
  import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd;
  import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd;
 -import org.apache.cloudstack.api.response.*;
 +import org.apache.cloudstack.api.response.AccountResponse;
 +import org.apache.cloudstack.api.response.AsyncJobResponse;
 +import org.apache.cloudstack.api.response.DiskOfferingResponse;
 +import org.apache.cloudstack.api.response.DomainRouterResponse;
 +import org.apache.cloudstack.api.response.EventResponse;
 +import org.apache.cloudstack.api.response.HostResponse;
++import org.apache.cloudstack.api.response.ImageStoreResponse;
 +import org.apache.cloudstack.api.response.InstanceGroupResponse;
 +import org.apache.cloudstack.api.response.ListResponse;
 +import org.apache.cloudstack.api.response.ProjectAccountResponse;
 +import org.apache.cloudstack.api.response.ProjectInvitationResponse;
 +import org.apache.cloudstack.api.response.ProjectResponse;
 +import org.apache.cloudstack.api.response.ResourceDetailResponse;
 +import org.apache.cloudstack.api.response.ResourceTagResponse;
 +import org.apache.cloudstack.api.response.SecurityGroupResponse;
 +import org.apache.cloudstack.api.response.ServiceOfferingResponse;
 +import org.apache.cloudstack.api.response.StoragePoolResponse;
++import org.apache.cloudstack.api.response.TemplateResponse;
 +import org.apache.cloudstack.api.response.UserResponse;
 +import org.apache.cloudstack.api.response.UserVmResponse;
 +import org.apache.cloudstack.api.response.VolumeResponse;
 +import org.apache.cloudstack.api.response.ZoneResponse;
 +import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
  import org.apache.cloudstack.query.QueryService;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
  import com.cloud.api.query.dao.AccountJoinDao;
  import com.cloud.api.query.dao.AffinityGroupJoinDao;
@@@ -141,9 -132,11 +154,17 @@@ import com.cloud.server.ResourceTag.Tag
  import com.cloud.server.TaggedResourceService;
  import com.cloud.service.ServiceOfferingVO;
  import com.cloud.service.dao.ServiceOfferingDao;
++import com.cloud.storage.DataStoreRole;
++import com.cloud.storage.ScopeType;
++import com.cloud.storage.Storage;
+ import com.cloud.storage.Storage.ImageFormat;
+ import com.cloud.storage.Storage.TemplateType;
++import com.cloud.storage.VMTemplateVO;
 +import com.cloud.storage.Volume;
 +import com.cloud.storage.VolumeDetailVO;
+ import com.cloud.storage.dao.VMTemplateDao;
  import com.cloud.storage.dao.VolumeDetailsDao;
+ import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
  import com.cloud.user.Account;
  import com.cloud.user.AccountManager;
  import com.cloud.user.AccountVO;
@@@ -295,10 -306,11 +333,10 @@@ public class QueryManagerImpl extends M
          return response;
      }
  
 -    private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd)
 -            throws PermissionDeniedException {
 -        Account caller = UserContext.current().getCaller();
 +    private Pair<List<UserAccountJoinVO>, Integer> searchForUsersInternal(ListUsersCmd cmd) throws PermissionDeniedException {
 +        Account caller = CallContext.current().getCallingAccount();
  
-         //TODO: Integrate with ACL checkAccess refactoring
+         // TODO: Integrate with ACL checkAccess refactoring
          Long domainId = cmd.getDomainId();
          if (domainId != null) {
              Domain domain = _domainDao.findById(domainId);
@@@ -871,9 -894,9 +920,9 @@@
          }
  
          // search vm details by ids
 -        Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<UserVmJoinVO>, Integer> uniqueVmPair =  _userVmJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueVmPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueVmPair;
          }
@@@ -965,9 -990,9 +1015,9 @@@
          }
  
          // search security group together with rules
 -        Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair =  _securityGroupJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueSgPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueSgPair;
          }
@@@ -1026,12 -1051,10 +1076,10 @@@
          return response;
      }
  
- 
      private Pair<List<DomainRouterJoinVO>, Integer> searchForRoutersInternal(BaseListProjectAndAccountResourcesCmd cmd, Long id,
-             String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role, String zoneType) {
-        
+             String name, String state, Long zoneId, Long podId, Long hostId, String keyword, Long networkId, Long vpcId, Boolean forVpc, String role) {
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          List<Long> permittedAccounts = new ArrayList<Long>();
  
          Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
@@@ -1323,11 -1332,13 +1357,13 @@@
          boolean isRecursive = cmd.isRecursive();
          boolean listAll = cmd.listAll();
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          List<Long> permittedAccounts = new ArrayList<Long>();
  
-         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
-         _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true);
+         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                 domainId, isRecursive, null);
+         _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts,
+                 domainIdRecursiveListProject, listAll, true);
          domainId = domainIdRecursiveListProject.first();
          isRecursive = domainIdRecursiveListProject.second();
          ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
@@@ -1384,10 -1396,11 +1421,10 @@@
          Long startIndex = cmd.getStartIndex();
          Long pageSizeVal = cmd.getPageSizeVal();
  
 -        // long projectId, String accountName, String role, Long startIndex,
 -        // Long pageSizeVal) {
 -        Account caller = UserContext.current().getCaller();
 +        //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) {
 +        Account caller = CallContext.current().getCallingAccount();
  
-         //check that the project exists
+         // check that the project exists
          Project project = _projectDao.findById(projectId);
  
          if (project == null) {
@@@ -1521,9 -1539,9 +1563,9 @@@
          }
  
          // search host details by ids
 -        Pair<List<HostJoinVO>, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter);
 +        Pair<List<HostJoinVO>, Integer> uniqueHostPair =  _hostJoinDao.searchAndCount(sc, searchFilter);
          Integer count = uniqueHostPair.second();
-         if ( count.intValue() == 0 ){
+         if (count.intValue() == 0) {
              // handle empty result cases
              return uniqueHostPair;
          }
@@@ -1548,10 -1567,9 +1591,9 @@@
          return response;
      }
  
- 
      private Pair<List<VolumeJoinVO>, Integer> searchForVolumesInternal(ListVolumesCmd cmd) {
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          List<Long> permittedAccounts = new ArrayList<Long>();
  
          Long id = cmd.getId();
@@@ -1684,9 -1703,8 +1727,8 @@@
          return response;
      }
  
- 
      private Pair<List<AccountJoinVO>, Integer> searchForAccountsInternal(ListAccountsCmd cmd) {
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Long domainId = cmd.getDomainId();
          Long accountId = cmd.getId();
          String accountName = cmd.getSearchName();
@@@ -1811,10 -1830,9 +1854,9 @@@
          return response;
      }
  
- 
      private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
  
          List<Long> permittedAccounts = new ArrayList<Long>();
  
@@@ -1892,8 -1911,16 +1935,16 @@@
      }
  
      private Pair<List<StoragePoolJoinVO>, Integer> searchForStoragePoolsInternal(ListStoragePoolsCmd cmd) {
+         ScopeType scopeType = null;
+         if (cmd.getScope() != null) {
+             try {
+                 scopeType = Enum.valueOf(ScopeType.class, cmd.getScope().toUpperCase());
+             } catch (Exception e) {
+                 throw new InvalidParameterValueException("Invalid scope type: " + cmd.getScope());
+             }
+         }
  
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
 +        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
          Object id = cmd.getId();
          Object name = cmd.getStoragePoolName();
          Object path = cmd.getPath();
@@@ -1972,6 -2000,166 +2024,166 @@@
      }
  
      @Override
+     public ListResponse<ImageStoreResponse> searchForImageStores(ListImageStoresCmd cmd) {
+         Pair<List<ImageStoreJoinVO>, Integer> result = searchForImageStoresInternal(cmd);
+         ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
+ 
+         List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
+                 new ImageStoreJoinVO[result.first().size()]));
+         response.setResponses(poolResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<ImageStoreJoinVO>, Integer> searchForImageStoresInternal(ListImageStoresCmd cmd) {
+ 
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
++        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
+         Object id = cmd.getId();
+         Object name = cmd.getStoreName();
+         String provider = cmd.getProvider();
+         String protocol = cmd.getProtocol();
+         Object keyword = cmd.getKeyword();
+         Long startIndex = cmd.getStartIndex();
+         Long pageSize = cmd.getPageSizeVal();
+ 
+         Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
+ 
+         SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
+         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
+                                                              // ids
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+         sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
+         sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
+         sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
+         sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<ImageStoreJoinVO> sc = sb.create();
+         sc.setParameters("role", DataStoreRole.Image);
+ 
+         if (keyword != null) {
+             SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
+             ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             sc.addAnd("name", SearchCriteria.Op.SC, ssc);
+         }
+ 
+         if (id != null) {
+             sc.setParameters("id", id);
+         }
+ 
+         if (name != null) {
+             sc.setParameters("name", name);
+         }
+ 
+         if (zoneId != null) {
+             sc.setParameters("dataCenterId", zoneId);
+         }
+         if (provider != null) {
+             sc.setParameters("provider", provider);
+         }
+         if (protocol != null) {
+             sc.setParameters("protocol", protocol);
+         }
+ 
+         // search Store details by ids
+         Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueStorePair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueStorePair;
+         }
+         List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
+         Long[] vrIds = new Long[uniqueStores.size()];
+         int i = 0;
+         for (ImageStoreJoinVO v : uniqueStores) {
+             vrIds[i++] = v.getId();
+         }
+         List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
+         return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
+ 
+     }
+ 
+     @Override
+     public ListResponse<ImageStoreResponse> searchForCacheStores(ListCacheStoresCmd cmd) {
+         Pair<List<ImageStoreJoinVO>, Integer> result = searchForCacheStoresInternal(cmd);
+         ListResponse<ImageStoreResponse> response = new ListResponse<ImageStoreResponse>();
+ 
+         List<ImageStoreResponse> poolResponses = ViewResponseHelper.createImageStoreResponse(result.first().toArray(
+                 new ImageStoreJoinVO[result.first().size()]));
+         response.setResponses(poolResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<ImageStoreJoinVO>, Integer> searchForCacheStoresInternal(ListCacheStoresCmd cmd) {
+ 
 -        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId());
++        Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), cmd.getZoneId());
+         Object id = cmd.getId();
+         Object name = cmd.getStoreName();
+         String provider = cmd.getProvider();
+         String protocol = cmd.getProtocol();
+         Object keyword = cmd.getKeyword();
+         Long startIndex = cmd.getStartIndex();
+         Long pageSize = cmd.getPageSizeVal();
+ 
+         Filter searchFilter = new Filter(ImageStoreJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize);
+ 
+         SearchBuilder<ImageStoreJoinVO> sb = _imageStoreJoinDao.createSearchBuilder();
+         sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct
+                                                              // ids
+         sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+         sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
+         sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
+         sb.and("protocol", sb.entity().getProtocol(), SearchCriteria.Op.EQ);
+         sb.and("provider", sb.entity().getProviderName(), SearchCriteria.Op.EQ);
+         sb.and("role", sb.entity().getRole(), SearchCriteria.Op.EQ);
+ 
+         SearchCriteria<ImageStoreJoinVO> sc = sb.create();
+         sc.setParameters("role", DataStoreRole.ImageCache);
+ 
+         if (keyword != null) {
+             SearchCriteria<ImageStoreJoinVO> ssc = _imageStoreJoinDao.createSearchCriteria();
+             ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             ssc.addOr("provider", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             sc.addAnd("name", SearchCriteria.Op.SC, ssc);
+         }
+ 
+         if (id != null) {
+             sc.setParameters("id", id);
+         }
+ 
+         if (name != null) {
+             sc.setParameters("name", name);
+         }
+ 
+         if (zoneId != null) {
+             sc.setParameters("dataCenterId", zoneId);
+         }
+         if (provider != null) {
+             sc.setParameters("provider", provider);
+         }
+         if (protocol != null) {
+             sc.setParameters("protocol", protocol);
+         }
+ 
+         // search Store details by ids
+         Pair<List<ImageStoreJoinVO>, Integer> uniqueStorePair = _imageStoreJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueStorePair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueStorePair;
+         }
+         List<ImageStoreJoinVO> uniqueStores = uniqueStorePair.first();
+         Long[] vrIds = new Long[uniqueStores.size()];
+         int i = 0;
+         for (ImageStoreJoinVO v : uniqueStores) {
+             vrIds[i++] = v.getId();
+         }
+         List<ImageStoreJoinVO> vrs = _imageStoreJoinDao.searchByIds(vrIds);
+         return new Pair<List<ImageStoreJoinVO>, Integer>(vrs, count);
+ 
+     }
+ 
+     @Override
      public ListResponse<DiskOfferingResponse> searchForDiskOfferings(ListDiskOfferingsCmd cmd) {
          Pair<List<DiskOfferingJoinVO>, Integer> result = searchForDiskOfferingsInternal(cmd);
          ListResponse<DiskOfferingResponse> response = new ListResponse<DiskOfferingResponse>();
@@@ -1993,11 -2182,11 +2206,12 @@@
  
          Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
          isAscending = (isAscending == null ? true : isAscending);
-         Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
+         Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
+                 cmd.getPageSizeVal());
          SearchCriteria<DiskOfferingJoinVO> sc = _diskOfferingJoinDao.createSearchCriteria();
  
 -        Account account = UserContext.current().getCaller();
 +
 +        Account account = CallContext.current().getCallingAccount();
          Object name = cmd.getDiskOfferingName();
          Object id = cmd.getId();
          Object keyword = cmd.getKeyword();
@@@ -2108,10 -2303,11 +2328,11 @@@
          // root
          Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
          isAscending = (isAscending == null ? true : isAscending);
-         Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
+         Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(),
+                 cmd.getPageSizeVal());
          SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
  
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Object name = cmd.getServiceOfferingName();
          Object id = cmd.getId();
          Object keyword = cmd.getKeyword();
@@@ -2231,9 -2428,8 +2453,8 @@@
          return response;
      }
  
- 
      private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesByCmd cmd) {
 -        Account account = UserContext.current().getCaller();
 +        Account account = CallContext.current().getCallingAccount();
          Long domainId = cmd.getDomainId();
          Long id = cmd.getId();
          String keyword = cmd.getKeyword();
@@@ -2243,9 -2439,9 +2464,9 @@@
          Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
          SearchCriteria<DataCenterJoinVO> sc = _dcJoinDao.createSearchCriteria();
  
-         if(networkType != null)
+         if (networkType != null)
 -            sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
 -
 +          sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
 +        
          if (id != null) {
              sc.addAnd("id", SearchCriteria.Op.EQ, id);
          } else if (name != null) {
@@@ -2402,6 -2610,322 +2635,323 @@@
      }
  
      @Override
+     public ListResponse<TemplateResponse> listTemplates(ListTemplatesCmd cmd) {
+         Pair<List<TemplateJoinVO>, Integer> result = searchForTemplatesInternal(cmd);
+         ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
+ 
+         List<TemplateResponse> templateResponses = ViewResponseHelper.createTemplateResponse(result.first().toArray(
+                 new TemplateJoinVO[result.first().size()]));
+         response.setResponses(templateResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(ListTemplatesCmd cmd) {
+         TemplateFilter templateFilter = TemplateFilter.valueOf(cmd.getTemplateFilter());
+         Long id = cmd.getId();
+         Map<String, String> tags = cmd.getTags();
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+ 
+         boolean listAll = false;
+         if (templateFilter != null && templateFilter == TemplateFilter.all) {
+             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+                         + " can be specified by admin only");
+             }
+             listAll = true;
+         }
+ 
+         List<Long> permittedAccountIds = new ArrayList<Long>();
+         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                 cmd.getDomainId(), cmd.isRecursive(), null);
+         _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
+                 domainIdRecursiveListProject, listAll, false);
+         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+         List<Account> permittedAccounts = new ArrayList<Account>();
+         for (Long accountId : permittedAccountIds) {
+             permittedAccounts.add(_accountMgr.getAccount(accountId));
+         }
+ 
+         boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured));
+         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
+ 
+         return searchForTemplatesInternal(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null,
+                 cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr,
+                 cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name,
+             String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize,
+             Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady,
+             List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria,
+             Map<String, String> tags) {
+         VMTemplateVO template = null;
+ 
+         Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
+         isAscending = (isAscending == null ? true : isAscending);
+         Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
+         SearchCriteria<TemplateJoinVO> sc = _templateJoinDao.createSearchCriteria();
+ 
+         // verify templateId parameter and specially handle it
+         if (templateId != null) {
+             template = _templateDao.findById(templateId);
+             if (template == null) {
+                 throw new InvalidParameterValueException("Please specify a valid template ID.");
+             }// If ISO requested then it should be ISO.
+             if (isIso && template.getFormat() != ImageFormat.ISO) {
+                 s_logger.error("Template Id " + templateId + " is not an ISO");
+                 InvalidParameterValueException ex = new InvalidParameterValueException(
+                         "Specified Template Id is not an ISO");
+                 ex.addProxyObject(template.getUuid(), "templateId");
+                 throw ex;
+             }// If ISO not requested then it shouldn't be an ISO.
+             if (!isIso && template.getFormat() == ImageFormat.ISO) {
+                 s_logger.error("Incorrect format of the template id " + templateId);
+                 InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format "
+                         + template.getFormat() + " of the specified template id");
+                 ex.addProxyObject(template.getUuid(), "templateId");
+                 throw ex;
+             }
+ 
+             // if template is not public, perform permission check here
+             if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
+                 Account owner = _accountMgr.getAccount(template.getAccountId());
+                 _accountMgr.checkAccess(caller, null, true, owner);
+             }
+ 
+             // if templateId is specified, then we will just use the id to
+             // search and ignore other query parameters
+             sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
+         } else {
+ 
+             DomainVO domain = null;
+             if (!permittedAccounts.isEmpty()) {
+                 domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
+             } else {
+                 domain = _domainDao.findById(DomainVO.ROOT_DOMAIN);
+             }
+ 
+             List<HypervisorType> hypers = null;
+             if (!isIso) {
+                 hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
+             }
+ 
+             // add criteria for project or not
+             if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
+                 sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
+             } else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
+                 sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
+             }
+ 
+             // add criteria for domain path in case of domain admin
+             if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable)
+                     && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
+                 sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
+             }
+ 
+             List<Long> relatedDomainIds = new ArrayList<Long>();
+             List<Long> permittedAccountIds = new ArrayList<Long>();
+             if (!permittedAccounts.isEmpty()) {
+                 for (Account account : permittedAccounts) {
+                     permittedAccountIds.add(account.getId());
+                     DomainVO accountDomain = _domainDao.findById(account.getDomainId());
+ 
+                     // get all parent domain ID's all the way till root domain
+                     DomainVO domainTreeNode = accountDomain;
+                     relatedDomainIds.add(domainTreeNode.getId());
+                     while (domainTreeNode.getParent() != null) {
+                         domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
+                         relatedDomainIds.add(domainTreeNode.getId());
+                     }
+ 
+                     // get all child domain ID's
+                     if (_accountMgr.isAdmin(account.getType())) {
+                         List<DomainVO> allChildDomains = _domainDao.findAllChildren(accountDomain.getPath(),
+                                 accountDomain.getId());
+                         for (DomainVO childDomain : allChildDomains) {
+                             relatedDomainIds.add(childDomain.getId());
+                         }
+                     }
+                 }
+             }
+ 
+             if (!isIso) {
+                 // add hypervisor criteria for template case
+                 if (hypers != null && !hypers.isEmpty()) {
+                     String[] relatedHypers = new String[hypers.size()];
+                     for (int i = 0; i < hypers.size(); i++) {
+                         relatedHypers[i] = hypers.get(i).toString();
+                     }
+                     sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
+                 }
+             }
+ 
+             // control different template filters
+             if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
+                 sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
+                 if (templateFilter == TemplateFilter.featured) {
+                     sc.addAnd("featured", SearchCriteria.Op.EQ, true);
+                 } else {
+                     sc.addAnd("featured", SearchCriteria.Op.EQ, false);
+                 }
+                 if (!permittedAccounts.isEmpty()) {
+                     SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                     scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
+                     scc.addOr("domainId", SearchCriteria.Op.NULL);
+                     sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
+                 }
+             } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
+                 if (!permittedAccounts.isEmpty()) {
+                     sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 }
+             } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 sc.addAnd("accountId", SearchCriteria.Op.SC, scc);
+             } else if (templateFilter == TemplateFilter.executable) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
+                 if (!permittedAccounts.isEmpty()) {
+                     scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
+                 }
+                 sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
+             }
+ 
+             // add tags criteria
+             if (tags != null && !tags.isEmpty()) {
+                 SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
+                 int count = 0;
+                 for (String key : tags.keySet()) {
+                     SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
+                     scTag.addAnd("tagKey", SearchCriteria.Op.EQ, key);
+                     scTag.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
+                     if (isIso) {
+                         scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.ISO);
+                     } else {
+                         scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, TaggedResourceType.Template);
+                     }
+                     scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
+                     count++;
+                 }
+                 sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
+             }
+ 
+             // other criteria
+ 
+             if (keyword != null) {
+                 sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
+             } else if (name != null) {
+                 sc.addAnd("name", SearchCriteria.Op.EQ, name);
+             }
+ 
+             if (isIso) {
+                 sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
+ 
+             } else {
+                 sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
+             }
+ 
+             if (!hyperType.equals(HypervisorType.None)) {
+                 sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
+             }
+ 
+             if (bootable != null) {
+                 sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
+             }
+ 
+             if (onlyReady) {
+                 SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
+                 readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
+                 readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
+                 SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
+                 isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
+                 isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
+                 readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
+                 sc.addAnd("state", SearchCriteria.Op.SC, readySc);
+             }
+ 
+             if (zoneId != null) {
+                 sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
+             }
+ 
+             if (!showDomr) {
+                 // excluding system template
+                 sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
+             }
+         }
+ 
+         // don't return removed template, this should not be needed since we
+         // changed annotation for removed field in TemplateJoinVO.
+         // sc.addAnd("removed", SearchCriteria.Op.NULL);
+ 
+         // search unique templates and find details by Ids
+         Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
+         Integer count = uniqueTmplPair.second();
+         if (count.intValue() == 0) {
+             // empty result
+             return uniqueTmplPair;
+         }
+         List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
+         Long[] vrIds = new Long[uniqueTmpls.size()];
+         int i = 0;
+         for (TemplateJoinVO v : uniqueTmpls) {
+             vrIds[i++] = v.getId();
+         }
+         List<TemplateJoinVO> vrs = _templateJoinDao.searchByIds(vrIds);
+         return new Pair<List<TemplateJoinVO>, Integer>(vrs, count);
+ 
+         // TODO: revisit the special logic for iso search in
+         // VMTemplateDaoImpl.searchForTemplates and understand why we need to
+         // specially handle ISO. The original logic is very twisted and no idea
+         // about what the code was doing.
+ 
+     }
+ 
+     @Override
+     public ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd) {
+         Pair<List<TemplateJoinVO>, Integer> result = searchForIsosInternal(cmd);
+         ListResponse<TemplateResponse> response = new ListResponse<TemplateResponse>();
+ 
+         List<TemplateResponse> templateResponses = ViewResponseHelper.createIsoResponse(result.first().toArray(
+                 new TemplateJoinVO[result.first().size()]));
+         response.setResponses(templateResponses, result.second());
+         return response;
+     }
+ 
+     private Pair<List<TemplateJoinVO>, Integer> searchForIsosInternal(ListIsosCmd cmd) {
+         TemplateFilter isoFilter = TemplateFilter.valueOf(cmd.getIsoFilter());
+         Long id = cmd.getId();
+         Map<String, String> tags = cmd.getTags();
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+ 
+         boolean listAll = false;
+         if (isoFilter != null && isoFilter == TemplateFilter.all) {
+             if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
+                 throw new InvalidParameterValueException("Filter " + TemplateFilter.all
+                         + " can be specified by admin only");
+             }
+             listAll = true;
+         }
+ 
+         List<Long> permittedAccountIds = new ArrayList<Long>();
+         Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(
+                 cmd.getDomainId(), cmd.isRecursive(), null);
+         _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds,
+                 domainIdRecursiveListProject, listAll, false);
+         ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+         List<Account> permittedAccounts = new ArrayList<Account>();
+         for (Long accountId : permittedAccountIds) {
+             permittedAccounts.add(_accountMgr.getAccount(accountId));
+         }
+ 
+         HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor());
+ 
+         return searchForTemplatesInternal(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true,
+                 cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true,
+                 cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags);
+     }
+ 
++    @Override
      public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName,
              String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive,
              boolean listAll, Long startIndex, Long pageSize) {
@@@ -2534,13 -3057,12 +3085,12 @@@
  
              return volumeDetailResponseList;
  
 -        } else {
 +        }  else {
  
- 
              List<NicDetailVO> nicDetailList;
-             if(key == null){
+             if (key == null) {
                  nicDetailList = _nicDetailDao.findDetails(id);
-             }else {
+             } else {
                  NicDetailVO nicDetail = _nicDetailDao.findDetail(id, key);
                  nicDetailList = new LinkedList<NicDetailVO>();
                  nicDetailList.add(nicDetail);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/ViewResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/ViewResponseHelper.java
index 3daa1c1,b98cea3..0e605a5
--- a/server/src/com/cloud/api/query/ViewResponseHelper.java
+++ b/server/src/com/cloud/api/query/ViewResponseHelper.java
@@@ -33,7 -48,8 +33,8 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.EventResponse;
  import org.apache.cloudstack.api.response.HostForMigrationResponse;
  import org.apache.cloudstack.api.response.HostResponse;
 -import org.apache.cloudstack.api.response.InstanceGroupResponse;
+ import org.apache.cloudstack.api.response.ImageStoreResponse;
 +import org.apache.cloudstack.api.response.InstanceGroupResponse;
  import org.apache.cloudstack.api.response.ProjectAccountResponse;
  import org.apache.cloudstack.api.response.ProjectInvitationResponse;
  import org.apache.cloudstack.api.response.ProjectResponse;
@@@ -45,29 -62,15 +47,31 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.UserVmResponse;
  import org.apache.cloudstack.api.response.VolumeResponse;
  import org.apache.cloudstack.api.response.ZoneResponse;
 -import org.apache.log4j.Logger;
 -
 +import org.apache.cloudstack.context.CallContext;
  
 +import com.cloud.api.ApiDBUtils;
 +import com.cloud.api.query.vo.AccountJoinVO;
 +import com.cloud.api.query.vo.AffinityGroupJoinVO;
 +import com.cloud.api.query.vo.AsyncJobJoinVO;
 +import com.cloud.api.query.vo.DataCenterJoinVO;
 +import com.cloud.api.query.vo.DiskOfferingJoinVO;
 +import com.cloud.api.query.vo.DomainRouterJoinVO;
 +import com.cloud.api.query.vo.EventJoinVO;
 +import com.cloud.api.query.vo.HostJoinVO;
+ import com.cloud.api.query.vo.ImageStoreJoinVO;
 +import com.cloud.api.query.vo.InstanceGroupJoinVO;
 +import com.cloud.api.query.vo.ProjectAccountJoinVO;
 +import com.cloud.api.query.vo.ProjectInvitationJoinVO;
 +import com.cloud.api.query.vo.ProjectJoinVO;
 +import com.cloud.api.query.vo.ResourceTagJoinVO;
 +import com.cloud.api.query.vo.SecurityGroupJoinVO;
 +import com.cloud.api.query.vo.ServiceOfferingJoinVO;
 +import com.cloud.api.query.vo.StoragePoolJoinVO;
+ import com.cloud.api.query.vo.TemplateJoinVO;
 -import java.util.ArrayList;
 -import java.util.EnumSet;
 -import java.util.Hashtable;
 -import java.util.List;
 +import com.cloud.api.query.vo.UserAccountJoinVO;
 +import com.cloud.api.query.vo.UserVmJoinVO;
 +import com.cloud.api.query.vo.VolumeJoinVO;
 +import com.cloud.user.Account;
  
  /**
   * Helper class to generate response from DB view VO objects.


[44/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 87b3df3,5040443..f6fd69d
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@@ -31,18 -31,23 +31,69 @@@ import java.util.Comparator
  import java.util.Date;
  import java.util.GregorianCalendar;
  import java.util.HashMap;
++import java.util.HashSet;
  import java.util.List;
  import java.util.Map;
++import java.util.Map.Entry;
  import java.util.Random;
++import java.util.Set;
  import java.util.TimeZone;
  import java.util.UUID;
  
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
 +import org.apache.log4j.Logger;
 +import org.apache.log4j.NDC;
 +
++import com.google.gson.Gson;
++import com.vmware.vim25.AboutInfo;
++import com.vmware.vim25.ClusterDasConfigInfo;
++import com.vmware.vim25.ComputeResourceSummary;
++import com.vmware.vim25.DatastoreSummary;
++import com.vmware.vim25.DynamicProperty;
++import com.vmware.vim25.GuestInfo;
++import com.vmware.vim25.HostCapability;
++import com.vmware.vim25.HostFirewallInfo;
++import com.vmware.vim25.HostFirewallRuleset;
++import com.vmware.vim25.HostNetworkTrafficShapingPolicy;
++import com.vmware.vim25.HostPortGroupSpec;
++import com.vmware.vim25.ManagedObjectReference;
++import com.vmware.vim25.ObjectContent;
++import com.vmware.vim25.OptionValue;
++import com.vmware.vim25.PerfCounterInfo;
++import com.vmware.vim25.PerfEntityMetric;
++import com.vmware.vim25.PerfEntityMetricBase;
++import com.vmware.vim25.PerfMetricId;
++import com.vmware.vim25.PerfMetricIntSeries;
++import com.vmware.vim25.PerfMetricSeries;
++import com.vmware.vim25.PerfQuerySpec;
++import com.vmware.vim25.PerfSampleInfo;
++import com.vmware.vim25.RuntimeFaultFaultMsg;
++import com.vmware.vim25.ToolsUnavailableFaultMsg;
++import com.vmware.vim25.VimPortType;
++import com.vmware.vim25.VirtualDevice;
++import com.vmware.vim25.VirtualDeviceConfigSpec;
++import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
++import com.vmware.vim25.VirtualDisk;
++import com.vmware.vim25.VirtualEthernetCard;
++import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo;
++import com.vmware.vim25.VirtualLsiLogicController;
++import com.vmware.vim25.VirtualMachineConfigSpec;
++import com.vmware.vim25.VirtualMachineFileInfo;
++import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
++import com.vmware.vim25.VirtualMachinePowerState;
++import com.vmware.vim25.VirtualMachineRelocateSpec;
++import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator;
++import com.vmware.vim25.VirtualMachineRuntimeInfo;
++import com.vmware.vim25.VirtualSCSISharing;
++
+ import org.apache.cloudstack.storage.command.DeleteCommand;
+ import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
+ import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
+ import org.apache.cloudstack.storage.to.TemplateObjectTO;
+ import org.apache.cloudstack.storage.to.VolumeObjectTO;
 -import org.apache.log4j.Logger;
 -import org.apache.log4j.NDC;
+ 
  import com.cloud.agent.IAgentControl;
  import com.cloud.agent.api.Answer;
  import com.cloud.agent.api.AttachIsoCommand;
@@@ -74,9 -79,9 +125,6 @@@ import com.cloud.agent.api.CreateVolume
  import com.cloud.agent.api.DeleteStoragePoolCommand;
  import com.cloud.agent.api.DeleteVMSnapshotAnswer;
  import com.cloud.agent.api.DeleteVMSnapshotCommand;
--import com.cloud.agent.api.MigrateWithStorageAnswer;
--import com.cloud.agent.api.MigrateWithStorageCommand;
--import com.cloud.agent.api.UnregisterVMCommand;
  import com.cloud.agent.api.GetDomRVersionAnswer;
  import com.cloud.agent.api.GetDomRVersionCmd;
  import com.cloud.agent.api.GetHostStatsAnswer;
@@@ -94,6 -99,6 +142,8 @@@ import com.cloud.agent.api.ManageSnapsh
  import com.cloud.agent.api.ManageSnapshotCommand;
  import com.cloud.agent.api.MigrateAnswer;
  import com.cloud.agent.api.MigrateCommand;
++import com.cloud.agent.api.MigrateWithStorageAnswer;
++import com.cloud.agent.api.MigrateWithStorageCommand;
  import com.cloud.agent.api.ModifySshKeysCommand;
  import com.cloud.agent.api.ModifyStoragePoolAnswer;
  import com.cloud.agent.api.ModifyStoragePoolCommand;
@@@ -131,6 -136,6 +181,7 @@@ import com.cloud.agent.api.StopCommand
  import com.cloud.agent.api.StoragePoolInfo;
  import com.cloud.agent.api.UnPlugNicAnswer;
  import com.cloud.agent.api.UnPlugNicCommand;
++import com.cloud.agent.api.UnregisterVMCommand;
  import com.cloud.agent.api.UpgradeSnapshotCommand;
  import com.cloud.agent.api.ValidateSnapshotAnswer;
  import com.cloud.agent.api.ValidateSnapshotCommand;
@@@ -165,16 -170,16 +216,16 @@@ import com.cloud.agent.api.routing.VmDa
  import com.cloud.agent.api.routing.VpnUsersCfgCommand;
  import com.cloud.agent.api.storage.CopyVolumeAnswer;
  import com.cloud.agent.api.storage.CopyVolumeCommand;
--import com.cloud.agent.api.storage.CreateVolumeOVACommand;
++import com.cloud.agent.api.storage.CreateAnswer;
++import com.cloud.agent.api.storage.CreateCommand;
++import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
  import com.cloud.agent.api.storage.CreateVolumeOVAAnswer;
++import com.cloud.agent.api.storage.CreateVolumeOVACommand;
++import com.cloud.agent.api.storage.DestroyCommand;
  import com.cloud.agent.api.storage.MigrateVolumeAnswer;
  import com.cloud.agent.api.storage.MigrateVolumeCommand;
  import com.cloud.agent.api.storage.PrepareOVAPackingAnswer;
  import com.cloud.agent.api.storage.PrepareOVAPackingCommand;
--import com.cloud.agent.api.storage.CreateAnswer;
--import com.cloud.agent.api.storage.CreateCommand;
--import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
--import com.cloud.agent.api.storage.DestroyCommand;
  import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
  import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
  import com.cloud.agent.api.storage.ResizeVolumeAnswer;
@@@ -247,51 -259,51 +306,6 @@@ import com.cloud.vm.VirtualMachine.Powe
  import com.cloud.vm.VirtualMachine.State;
  import com.cloud.vm.VirtualMachineName;
  import com.cloud.vm.VmDetailConstants;
--import com.google.gson.Gson;
--import com.vmware.vim25.AboutInfo;
--import com.vmware.vim25.ClusterDasConfigInfo;
--import com.vmware.vim25.ComputeResourceSummary;
--import com.vmware.vim25.DatastoreSummary;
--import com.vmware.vim25.DynamicProperty;
--import com.vmware.vim25.GuestInfo;
--import com.vmware.vim25.HostCapability;
--import com.vmware.vim25.HostFirewallInfo;
--import com.vmware.vim25.HostFirewallRuleset;
--import com.vmware.vim25.HostNetworkTrafficShapingPolicy;
--import com.vmware.vim25.HostPortGroupSpec;
--import com.vmware.vim25.ManagedObjectReference;
--import com.vmware.vim25.ObjectContent;
--import com.vmware.vim25.OptionValue;
--import com.vmware.vim25.PerfCounterInfo;
--import com.vmware.vim25.PerfEntityMetric;
--import com.vmware.vim25.PerfEntityMetricBase;
--import com.vmware.vim25.PerfMetricId;
--import com.vmware.vim25.PerfMetricIntSeries;
--import com.vmware.vim25.PerfMetricSeries;
--import com.vmware.vim25.PerfQuerySpec;
--import com.vmware.vim25.PerfSampleInfo;
--import com.vmware.vim25.RuntimeFaultFaultMsg;
--import com.vmware.vim25.ToolsUnavailableFaultMsg;
--import com.vmware.vim25.VimPortType;
--import com.vmware.vim25.VirtualDevice;
--import com.vmware.vim25.VirtualDeviceConfigSpec;
--import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
--import com.vmware.vim25.VirtualDisk;
--import com.vmware.vim25.VirtualEthernetCard;
--import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo;
--import com.vmware.vim25.VirtualLsiLogicController;
--import com.vmware.vim25.VirtualMachineConfigSpec;
--import com.vmware.vim25.VirtualMachineFileInfo;
--import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
--import com.vmware.vim25.VirtualMachinePowerState;
--import com.vmware.vim25.VirtualMachineRelocateSpec;
--import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator;
--import com.vmware.vim25.VirtualMachineRuntimeInfo;
--import com.vmware.vim25.VirtualSCSISharing;
--
--import java.util.HashSet;
--import java.util.Set;
--import java.util.Map.Entry;
  
  public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService {
      private static final Logger s_logger = Logger.getLogger(VmwareResource.class);
@@@ -343,14 -355,20 +357,20 @@@
  
      protected volatile long _cmdSequence = 1;
  
+     protected StorageSubsystemCommandHandler storageHandler;
+ 
 -    protected static HashMap<VirtualMachinePowerState, State> s_statesTable;
 +    protected static HashMap<VirtualMachinePowerState, PowerState> s_statesTable;
      static {
 -        s_statesTable = new HashMap<VirtualMachinePowerState, State>();
 -        s_statesTable.put(VirtualMachinePowerState.POWERED_ON, State.Running);
 -        s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, State.Stopped);
 -        s_statesTable.put(VirtualMachinePowerState.SUSPENDED, State.Stopped);
 +        s_statesTable = new HashMap<VirtualMachinePowerState, PowerState>();
 +        s_statesTable.put(VirtualMachinePowerState.POWERED_ON, PowerState.PowerOn);
 +        s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, PowerState.PowerOff);
 +        s_statesTable.put(VirtualMachinePowerState.SUSPENDED, PowerState.PowerOn);
      }
  
+     public Gson getGson() {
+     	return _gson;
+     }
+ 
      public VmwareResource() {
          _gson = GsonHelper.getGsonLogger();
      }
@@@ -1710,11 -1738,11 +1740,11 @@@
              vSwitchType = _publicTrafficInfo.getVirtualSwitchType();
          }
          if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) {
-             networkInfo = HypervisorHostHelper.prepareNetwork(this._publicTrafficInfo.getVirtualSwitchName(), "cloud.public",
-                     vmMo.getRunningHost(), vlanId, null, null, this._ops_timeout, true);
+             networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public",
+                     vmMo.getRunningHost(), vlanId, null, null, _ops_timeout, true);
          } else {
--            networkInfo = HypervisorHostHelper.prepareNetwork(this._publicTrafficInfo.getVirtualSwitchName(), "cloud.public",
--                    vmMo.getRunningHost(), vlanId, null, null, null, this._ops_timeout, vSwitchType, _portsPerDvPortGroup, null, false);
++            networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public",
++                    vmMo.getRunningHost(), vlanId, null, null, null, _ops_timeout, vSwitchType, _portsPerDvPortGroup, null, false);
          }
  
          int nicIndex = allocPublicNicIndex(vmMo);
@@@ -2305,14 -2333,21 +2335,21 @@@
          return new CheckSshAnswer(cmd);
      }
  
-     private VolumeTO[] validateDisks(VolumeTO[] disks) {
-         List<VolumeTO> validatedDisks = new ArrayList<VolumeTO>();
+     private DiskTO[] validateDisks(DiskTO[] disks) {
+         List<DiskTO> validatedDisks = new ArrayList<DiskTO>();
  
-         for (VolumeTO vol : disks) {
-             if (vol.getPoolUuid() != null && !vol.getPoolUuid().isEmpty()) {
+         for (DiskTO vol : disks) {
+             if (vol.getType() != Volume.Type.ISO) {
+             	VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData();
+             	PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore();
+             	if (primaryStore.getUuid() != null && !primaryStore.getUuid().isEmpty()) {
 -            		validatedDisks.add(vol);
 +                validatedDisks.add(vol);
-             } else if (vol.getPoolType() == StoragePoolType.ISO && (vol.getPath() != null && !vol.getPath().isEmpty())) {
+             	}
+             } else if (vol.getType() == Volume.Type.ISO) {
+             	TemplateObjectTO templateTO = (TemplateObjectTO)vol.getData();
+             	if (templateTO.getPath() != null && !templateTO.getPath().isEmpty()) {
 -            		validatedDisks.add(vol);
 +                validatedDisks.add(vol);
+             	}
              } else {
                  if (s_logger.isDebugEnabled()) {
                      s_logger.debug("Drop invalid disk option, volumeTO: " + _gson.toJson(vol));
@@@ -2511,23 -2547,35 +2549,35 @@@
                  }
              } else {
                  // we will always plugin a CDROM device
-                 if (volIso != null && volIso.getPath() != null && !volIso.getPath().isEmpty()) {
-                     Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, volIso.getPath());
+ 
+                 if (volIso != null) {
+                 	TemplateObjectTO iso = (TemplateObjectTO)volIso.getData();
+ 
+                 	if (iso.getPath() != null && !iso.getPath().isEmpty()) {
+                 		DataStoreTO imageStore = iso.getDataStore();
+                 		if (!(imageStore instanceof NfsTO)) {
+                 			s_logger.debug("unsupported protocol");
+                 			throw new Exception("unsupported protocol");
+                 		}
+                 		NfsTO nfsImageStore = (NfsTO)imageStore;
+                 		String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath();
+                 		Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, isoPath);
 -                		assert (isoDatastoreInfo != null);
 -                		assert (isoDatastoreInfo.second() != null);
 +                    assert (isoDatastoreInfo != null);
 +                    assert (isoDatastoreInfo.second() != null);
  
 -                		deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
 +                    deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                      Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1);
 -                		deviceConfigSpecArray[i].setDevice(isoInfo.first());
 -                		if (isoInfo.second()) {
 -                			if(s_logger.isDebugEnabled())
 -                				s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
 -                			deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
 -                		} else {
 -                			if(s_logger.isDebugEnabled())
 -                				s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
 -                			deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
 -                		}
 +                    deviceConfigSpecArray[i].setDevice(isoInfo.first());
 +                    if (isoInfo.second()) {
 +                        if(s_logger.isDebugEnabled())
 +                            s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
 +                        deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
 +                    } else {
 +                        if(s_logger.isDebugEnabled())
 +                            s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
 +                        deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
 +                    }
+                 	}
                  } else {
                      deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
                      Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, ideUnitNumber++, i + 1);
@@@ -5019,16 -5070,7 +5071,16 @@@
              details.put("NativeHA", "true");
          }
      }
 +    
 +    protected HashMap<String, PowerState> sync() {
 +    	try {
-     		return this.getVmStates();
++    		return getVmStates();
 +    	} catch(Exception e) {
 +    		return new HashMap<String, PowerState>();
 +    	}
 +    }
  
 +/*
      protected HashMap<String, State> sync() {
          HashMap<String, State> changes = new HashMap<String, State>();
          HashMap<String, State> oldStates = null;
@@@ -5543,7 -5589,7 +5595,7 @@@
          return s_statesTable.get(powerState);
      }
  
-     private static PowerState getVmState(VirtualMachineMO vmMo) throws Exception {
 -    public static State getVmState(VirtualMachineMO vmMo) throws Exception {
++    public static PowerState getVmState(VirtualMachineMO vmMo) throws Exception {
          VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo();
          return convertState(runtimeInfo.getPowerState());
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
index 0000000,d3df0f5..cc83998
mode 000000,100644..100644
--- a/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/storage/resource/VmwareStorageProcessor.java
@@@ -1,0 -1,1288 +1,1283 @@@
+ // 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 
++// KIND, either express or implied.  See the License for the
+ // specific language governing permissions and limitations
+ // under the License.
+ package com.cloud.storage.resource;
+ 
+ import java.io.BufferedWriter;
+ import java.io.File;
+ import java.io.FileOutputStream;
+ import java.io.OutputStreamWriter;
+ import java.net.URI;
+ import java.rmi.RemoteException;
+ import java.util.HashMap;
+ import java.util.List;
+ import java.util.Map;
+ import java.util.UUID;
+ 
++import org.apache.log4j.Logger;
++
++import com.google.gson.Gson;
++import com.vmware.vim25.ManagedObjectReference;
++import com.vmware.vim25.VirtualDeviceConfigSpec;
++import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
++import com.vmware.vim25.VirtualDisk;
++import com.vmware.vim25.VirtualEthernetCard;
++import com.vmware.vim25.VirtualLsiLogicController;
++import com.vmware.vim25.VirtualMachineConfigSpec;
++import com.vmware.vim25.VirtualMachineFileInfo;
++import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
++import com.vmware.vim25.VirtualSCSISharing;
++
+ import org.apache.cloudstack.storage.command.AttachAnswer;
+ import org.apache.cloudstack.storage.command.AttachCommand;
+ import org.apache.cloudstack.storage.command.CopyCmdAnswer;
+ import org.apache.cloudstack.storage.command.CopyCommand;
+ import org.apache.cloudstack.storage.command.CreateObjectAnswer;
+ import org.apache.cloudstack.storage.command.CreateObjectCommand;
+ import org.apache.cloudstack.storage.command.DeleteCommand;
+ import org.apache.cloudstack.storage.command.DettachCommand;
+ import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
+ import org.apache.cloudstack.storage.to.SnapshotObjectTO;
+ import org.apache.cloudstack.storage.to.TemplateObjectTO;
+ import org.apache.cloudstack.storage.to.VolumeObjectTO;
 -import org.apache.log4j.Logger;
+ 
+ import com.cloud.agent.api.Answer;
 -import com.cloud.agent.api.BackupSnapshotAnswer;
+ import com.cloud.agent.api.Command;
 -import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
 -import com.cloud.agent.api.ManageSnapshotAnswer;
 -import com.cloud.agent.api.ManageSnapshotCommand;
 -import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
 -import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
+ import com.cloud.agent.api.to.DataStoreTO;
+ import com.cloud.agent.api.to.DataTO;
+ import com.cloud.agent.api.to.DiskTO;
+ import com.cloud.agent.api.to.NfsTO;
 -import com.cloud.agent.api.to.VolumeTO;
+ import com.cloud.hypervisor.vmware.manager.VmwareHostService;
+ import com.cloud.hypervisor.vmware.manager.VmwareStorageMount;
+ import com.cloud.hypervisor.vmware.mo.ClusterMO;
+ import com.cloud.hypervisor.vmware.mo.CustomFieldConstants;
+ import com.cloud.hypervisor.vmware.mo.DatacenterMO;
+ import com.cloud.hypervisor.vmware.mo.DatastoreMO;
+ import com.cloud.hypervisor.vmware.mo.HostMO;
+ import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper;
+ import com.cloud.hypervisor.vmware.mo.NetworkDetails;
+ import com.cloud.hypervisor.vmware.mo.VirtualMachineMO;
+ import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost;
+ import com.cloud.hypervisor.vmware.resource.VmwareResource;
+ import com.cloud.hypervisor.vmware.util.VmwareContext;
+ import com.cloud.hypervisor.vmware.util.VmwareHelper;
+ import com.cloud.serializer.GsonHelper;
+ import com.cloud.storage.DataStoreRole;
+ import com.cloud.storage.JavaStorageLayer;
++import com.cloud.storage.Storage.ImageFormat;
+ import com.cloud.storage.StorageLayer;
+ import com.cloud.storage.Volume;
 -import com.cloud.storage.Storage.ImageFormat;
+ import com.cloud.storage.template.VmdkProcessor;
+ import com.cloud.utils.Pair;
+ import com.cloud.utils.StringUtils;
+ import com.cloud.utils.Ternary;
+ import com.cloud.utils.script.Script;
 -import com.cloud.vm.VirtualMachine.State;
 -import com.google.gson.Gson;
 -import com.vmware.vim25.ManagedObjectReference;
 -import com.vmware.vim25.VirtualDeviceConfigSpec;
 -import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
 -import com.vmware.vim25.VirtualDisk;
 -import com.vmware.vim25.VirtualEthernetCard;
 -import com.vmware.vim25.VirtualLsiLogicController;
 -import com.vmware.vim25.VirtualMachineConfigSpec;
 -import com.vmware.vim25.VirtualMachineFileInfo;
 -import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
 -import com.vmware.vim25.VirtualSCSISharing;
++import com.cloud.vm.VirtualMachine.PowerState;
+ 
+ public class VmwareStorageProcessor implements StorageProcessor {
+ 	private static final Logger s_logger = Logger.getLogger(VmwareStorageProcessor.class);
 -	private VmwareHostService hostService;
 -	private boolean _fullCloneFlag;
 -	private VmwareStorageMount mountService;
 -	private VmwareResource resource;
 -	private Integer _timeout;
++	private final VmwareHostService hostService;
++	private final boolean _fullCloneFlag;
++	private final VmwareStorageMount mountService;
++	private final VmwareResource resource;
++	private final Integer _timeout;
+ 	protected Integer _shutdown_waitMs;
+ 	private final Gson _gson;
+ 	private final StorageLayer _storage = new JavaStorageLayer();
+ 	public VmwareStorageProcessor(VmwareHostService hostService, boolean fullCloneFlag, VmwareStorageMount mountService,
+ 			Integer timeout,
+ 			VmwareResource resource,
+ 			Integer shutdownWaitMs) {
+ 		this.hostService = hostService;
 -		this._fullCloneFlag = fullCloneFlag;
++		_fullCloneFlag = fullCloneFlag;
+ 		this.mountService = mountService;
 -		this._timeout = timeout;
++		_timeout = timeout;
+ 		this.resource = resource;
 -		this._shutdown_waitMs = shutdownWaitMs;
++		_shutdown_waitMs = shutdownWaitMs;
+ 		_gson = GsonHelper.getGsonLogger();
+ 	}
+ 	
+ 	private String getOVFFilePath(String srcOVAFileName) {
+         File file = new File(srcOVAFileName);
+         assert(_storage != null);
+         String[] files = _storage.listFiles(file.getParent());
+         if(files != null) {
+             for(String fileName : files) {
+                 if(fileName.toLowerCase().endsWith(".ovf")) {
+                     File ovfFile = new File(fileName);
+                     return file.getParent() + File.separator + ovfFile.getName();
+                 }
+             }
+         }
+         return null;
+     }
+ 	 private void copyTemplateFromSecondaryToPrimary(VmwareHypervisorHost hyperHost, DatastoreMO datastoreMo, String secondaryStorageUrl,
+ 		        String templatePathAtSecondaryStorage, String templateName, String templateUuid) throws Exception {
+ 
+ 		        s_logger.info("Executing copyTemplateFromSecondaryToPrimary. secondaryStorage: "
+ 		            + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
+ 		            + ", templateName: " + templateName);
+ 
+ 		        String secondaryMountPoint = mountService.getMountPoint(secondaryStorageUrl);
+ 		        s_logger.info("Secondary storage mount point: " + secondaryMountPoint);
+ 
+ 		        String srcOVAFileName = secondaryMountPoint + "/" +  templatePathAtSecondaryStorage +
+ 		            templateName + "." + ImageFormat.OVA.getFileExtension();
+ 
+ 		        String srcFileName = getOVFFilePath(srcOVAFileName);
+ 		        if(srcFileName == null) {
+ 		            Script command = new Script("tar", 0, s_logger);
+ 		            command.add("--no-same-owner");
+ 		            command.add("-xf", srcOVAFileName);
+ 		            command.setWorkDir(secondaryMountPoint + "/" +  templatePathAtSecondaryStorage);
+ 		            s_logger.info("Executing command: " + command.toString());
+ 		            String result = command.execute();
+ 		            if(result != null) {
+ 		                String msg = "Unable to unpack snapshot OVA file at: " + srcOVAFileName;
+ 		                s_logger.error(msg);
+ 		                throw new Exception(msg);
+ 		            }
+ 		        }
+ 
+ 		        srcFileName = getOVFFilePath(srcOVAFileName);
+ 		        if(srcFileName == null) {
+ 		            String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
+ 		            s_logger.error(msg);
+ 		            throw new Exception(msg);
+ 		        }
+ 
+ 		        String vmName = templateUuid;
+ 		        hyperHost.importVmFromOVF(srcFileName, vmName, datastoreMo, "thin");
+ 
+ 		        VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
+ 		        if(vmMo == null) {
+ 		            String msg = "Failed to import OVA template. secondaryStorage: "
+ 		                + secondaryStorageUrl + ", templatePathAtSecondaryStorage: " + templatePathAtSecondaryStorage
+ 		                + ", templateName: " + templateName + ", templateUuid: " + templateUuid;
+ 		            s_logger.error(msg);
+ 		            throw new Exception(msg);
+ 		        }
+ 
+ 		        if(vmMo.createSnapshot("cloud.template.base", "Base snapshot", false, false)) {
+ 		            vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, templateUuid);
+ 		            vmMo.markAsTemplate();
+ 		        } else {
+ 		            vmMo.destroy();
+ 		            String msg = "Unable to create base snapshot for template, templateName: " + templateName + ", templateUuid: " + templateUuid;
+ 		            s_logger.error(msg);
+ 		            throw new Exception(msg);
+ 		        }
+ 		    }
+ 	
+ 	@Override
+ 	public Answer copyTemplateToPrimaryStorage(CopyCommand cmd) {
+ 		DataTO srcData = cmd.getSrcTO();
+ 		TemplateObjectTO template = (TemplateObjectTO)srcData;
+ 		DataStoreTO srcStore = srcData.getDataStore();
+ 		if (!(srcStore instanceof NfsTO)) {
+ 			return new CopyCmdAnswer("unsupported protocol");
+ 		}
+ 		NfsTO nfsImageStore = (NfsTO)srcStore;
+ 		DataTO destData = cmd.getDestTO();
+ 		DataStoreTO destStore = destData.getDataStore();
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)destStore;
+ 		String secondaryStorageUrl = nfsImageStore.getUrl();
+ 		assert (secondaryStorageUrl != null);
+ 
+ 		String templateUrl = secondaryStorageUrl + File.separator + srcData.getPath();
+ 
+ 		String templateName = null;
+ 		String mountPoint = null;
+ 		if (templateUrl.endsWith(".ova")) {
+ 			int index = templateUrl.lastIndexOf("/");
+ 			mountPoint = templateUrl.substring(0, index);
+ 			mountPoint = mountPoint.substring(secondaryStorageUrl.length() + 1);
+ 			if (!mountPoint.endsWith("/")) {
+ 				mountPoint = mountPoint + "/";
+ 			}
+ 
+ 			templateName = templateUrl.substring(index + 1).replace("." + ImageFormat.OVA.getFileExtension(), "");
+ 
+ 			if (templateName == null || templateName.isEmpty()) {
+ 				templateName = template.getName();
+ 			}
+ 		} else {
+ 			mountPoint = templateUrl.substring(secondaryStorageUrl.length() + 1);
+ 			if (!mountPoint.endsWith("/")) {
+ 				mountPoint = mountPoint + "/";
+ 			}
+ 			templateName = template.getName();
+ 		}
+ 
+ 		VmwareContext context = hostService.getServiceContext(cmd);
+ 		try {
+ 			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
+ 
+ 			String templateUuidName = UUID.nameUUIDFromBytes((templateName + "@" + primaryStore.getUuid() + "-" + hyperHost.getMor().getValue()).getBytes()).toString();
+ 			// truncate template name to 32 chars to ensure they work well with vSphere API's.
+ 			templateUuidName = templateUuidName.replace("-", "");
+ 
+ 			DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
+ 			VirtualMachineMO templateMo = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templateUuidName), true);
+ 
+ 			if (templateMo == null) {
+ 			    if(s_logger.isInfoEnabled())
+ 			        s_logger.info("Template " + templateName + " is not setup yet, setup template from secondary storage with uuid name: " + templateUuidName);
+ 				ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
+ 				assert (morDs != null);
+ 				DatastoreMO primaryStorageDatastoreMo = new DatastoreMO(context, morDs);
+ 
+ 				copyTemplateFromSecondaryToPrimary(hyperHost,
+ 					primaryStorageDatastoreMo, secondaryStorageUrl,
+ 					mountPoint, templateName, templateUuidName);
+ 			} else {
+ 				s_logger.info("Template " + templateName + " has already been setup, skip the template setup process in primary storage");
+ 			}
+ 
+ 			TemplateObjectTO newTemplate = new TemplateObjectTO();
+ 			newTemplate.setPath(templateUuidName);
+ 			return new CopyCmdAnswer(newTemplate);
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				hostService.invalidateServiceContext(context);
+ 			}
+ 
+ 			String msg = "Unable to execute PrimaryStorageDownloadCommand due to exception";
+ 			s_logger.error(msg, e);
+ 			return new CopyCmdAnswer(msg);
+ 		}
+ 	}
+ 	private boolean createVMLinkedClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo,
+             String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception {
+ 
+         ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base");
+         if (morBaseSnapshot == null) {
+             String msg = "Unable to find template base snapshot, invalid template";
+             s_logger.error(msg);
+             throw new Exception(msg);
+         }
+ 
+         if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName))
+             dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false);
+ 
+         s_logger.info("creating linked clone from template");
+         if (!vmTemplate.createLinkedClone(vmdkName, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) {
+             String msg = "Unable to clone from the template";
+             s_logger.error(msg);
+             throw new Exception(msg);
+         }
+ 
+         // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know
+         // to move files
+         s_logger.info("Move volume out of volume-wrapper VM ");
+         dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName),
+                 dcMo.getMor(), dsMo.getMor(),
+                 String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true);
+ 
+         dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName),
+                 dcMo.getMor(), dsMo.getMor(),
+                 String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true);
+ 
+         return true;
+     }
+ 
+ 	private boolean createVMFullClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo,
+             String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception {
+ 
+         if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName))
+             dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false);
+ 
+         s_logger.info("creating full clone from template");
+         if (!vmTemplate.createFullClone(vmdkName, dcMo.getVmFolder(), morPool, morDatastore)) {
+             String msg = "Unable to create full clone from the template";
+             s_logger.error(msg);
+             throw new Exception(msg);
+         }
+ 
+         // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know
+         // to move files
+         s_logger.info("Move volume out of volume-wrapper VM ");
+         dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName),
+                 dcMo.getMor(), dsMo.getMor(),
+                 String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true);
+ 
+         dsMo.moveDatastoreFile(String.format("[%s] %s/%s-flat.vmdk", dsMo.getName(), vmdkName, vmdkName),
+                 dcMo.getMor(), dsMo.getMor(),
+                 String.format("[%s] %s-flat.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true);
+ 
+         return true;
+     }
+ 
+ 	@Override
+ 	public Answer cloneVolumeFromBaseTemplate(CopyCommand cmd) {
+ 		DataTO srcData = cmd.getSrcTO();
+ 		TemplateObjectTO template = (TemplateObjectTO)srcData;
+ 		DataTO destData = cmd.getDestTO();
+ 		VolumeObjectTO volume = (VolumeObjectTO)destData;
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volume.getDataStore();
+ 		PrimaryDataStoreTO srcStore = (PrimaryDataStoreTO)template.getDataStore();
+ 
+ 		
+ 		try {
 -			VmwareContext context = this.hostService.getServiceContext(null);
 -			VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(context, null);
++			VmwareContext context = hostService.getServiceContext(null);
++			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
+ 			DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
+ 			VirtualMachineMO vmMo = null;
+ 			ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
+ 			if (morDatastore == null)
+ 				throw new Exception("Unable to find datastore in vSphere");
+ 
+ 			DatastoreMO dsMo = new DatastoreMO(context, morDatastore);
+ 
+ 
+ 			// attach volume id to make the name unique
+ 			String vmdkName = volume.getName() + "-" + volume.getId();
+ 			if (srcStore == null) {
+ 				// create a root volume for blank VM
 -				String dummyVmName = this.hostService.getWorkerName(context, cmd, 0);
++				String dummyVmName = hostService.getWorkerName(context, cmd, 0);
+ 
+ 				try {
+ 					vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName);
+ 					if (vmMo == null) {
+ 						throw new Exception("Unable to create a dummy VM for volume creation");
+ 					}
+ 
+ 					String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName);
+ 					synchronized (this) {
+ 						s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath);
+ 						VmwareHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo);
+ 						vmMo.createDisk(volumeDatastorePath, (int) (volume.getSize() / (1024L * 1024L)), morDatastore, -1);
+ 						vmMo.detachDisk(volumeDatastorePath, false);
+ 					}
+ 
+ 					VolumeObjectTO newVol = new VolumeObjectTO();
+ 					newVol.setPath(vmdkName);
+ 					return new CopyCmdAnswer(newVol);
+ 				} finally {
+ 					vmMo.detachAllDisks();
+ 
+ 					s_logger.info("Destroy dummy VM after volume creation");
+ 					vmMo.destroy();
+ 				}
+ 			} else {
+ 				String templatePath = template.getPath();
+ 				VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(templatePath), true);
+ 				if (vmTemplate == null) {
+ 					s_logger.warn("Template host in vSphere is not in connected state, request template reload");
+ 					return new CopyCmdAnswer("Template host in vSphere is not in connected state, request template reload");
+ 				}
+ 
+ 				ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool();
+ 				ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
+ 				//createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool);
+ 				if (!_fullCloneFlag) {
+ 					createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool);
+ 				} else {
+ 					createVMFullClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool);
+ 				}
+ 
+ 				vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName);
+ 				assert (vmMo != null);
+ 
+ 				s_logger.info("detach disks from volume-wrapper VM " + vmdkName);
+ 				vmMo.detachAllDisks();
+ 
+ 				s_logger.info("destroy volume-wrapper VM " + vmdkName);
+ 				vmMo.destroy();
+ 
+ 				String srcFile = String.format("[%s] %s/", dsMo.getName(), vmdkName);
+ 				dsMo.deleteFile(srcFile, dcMo.getMor(), true);
+ 				VolumeObjectTO newVol = new VolumeObjectTO();
+ 				newVol.setPath(vmdkName);
+ 				return new CopyCmdAnswer(newVol);
+ 			}
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
 -				this.hostService.invalidateServiceContext(null);
++				hostService.invalidateServiceContext(null);
+ 			}
+ 
+ 			String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e);
+ 			s_logger.error(msg, e);
+ 			return new CopyCmdAnswer(e.toString());
+ 		}
+ 	}
+ 	
+ 
+ 	@Override
+ 	public Answer copyVolumeFromImageCacheToPrimary(CopyCommand cmd) {
+ 		// TODO Auto-generated method stub
+ 		return null;
+ 	}
+ 
+ 	@Override
+ 	public Answer copyVolumeFromPrimaryToSecondary(CopyCommand cmd) {
+ 		// TODO Auto-generated method stub
+ 		return null;
+ 	}
+ 	
+ 	private void postCreatePrivateTemplate(String installFullPath, long templateId,
+ 	        String templateName, long size, long virtualSize) throws Exception {
+ 
+ 	        // TODO a bit ugly here
+ 	        BufferedWriter out = null;
+ 	        try {
+ 	            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(installFullPath + "/template.properties")));
+ 	            out.write("filename=" + templateName + ".ova");
+ 	            out.newLine();
+ 	            out.write("description=");
+ 	            out.newLine();
+ 	            out.write("checksum=");
+ 	            out.newLine();
+ 	            out.write("hvm=false");
+ 	            out.newLine();
+ 	            out.write("size=" + size);
+ 	            out.newLine();
+ 	            out.write("ova=true");
+ 	            out.newLine();
+ 	            out.write("id=" + templateId);
+ 	            out.newLine();
+ 	            out.write("public=false");
+ 	            out.newLine();
+ 	            out.write("ova.filename=" + templateName + ".ova");
+ 	            out.newLine();
+ 	            out.write("uniquename=" + templateName);
+ 	            out.newLine();
+ 	            out.write("ova.virtualsize=" + virtualSize);
+ 	            out.newLine();
+ 	            out.write("virtualsize=" + virtualSize);
+ 	            out.newLine();
+ 	            out.write("ova.size=" + size);
+ 	            out.newLine();
+ 	        } finally {
+ 	            if(out != null)
+ 	                out.close();
+ 	        }
+ 	    }
+ 
+ 	private Ternary<String, Long, Long> createTemplateFromVolume(VirtualMachineMO vmMo, String installPath, long templateId, String templateUniqueName,
+ 	        String secStorageUrl, String volumePath, String workerVmName) throws Exception {
+ 
+ 	        String secondaryMountPoint = mountService.getMountPoint(secStorageUrl);
+ 	        String installFullPath = secondaryMountPoint + "/" + installPath;
+ 	        synchronized(installPath.intern()) {
+ 	            Script command = new Script(false, "mkdir", _timeout, s_logger);
+ 	            command.add("-p");
+ 	            command.add(installFullPath);
+ 
+ 	            String result = command.execute();
+ 	            if(result != null) {
+ 	                String msg = "unable to prepare template directory: "
+ 	                    + installPath + ", storage: " + secStorageUrl + ", error msg: " + result;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 	        }
+ 
+ 	        VirtualMachineMO clonedVm = null;
+ 	        try {
+ 	            Pair<VirtualDisk, String> volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
+ 	            if(volumeDeviceInfo == null) {
+ 	                String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            if(!vmMo.createSnapshot(templateUniqueName, "Temporary snapshot for template creation", false, false)) {
+ 	                String msg = "Unable to take snapshot for creating template from volume. volume path: " + volumePath;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            // 4 MB is the minimum requirement for VM memory in VMware
+ 	            vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
+ 	                VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
+ 	            clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
+ 	            if(clonedVm == null) {
+ 	                String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            clonedVm.exportVm(secondaryMountPoint + "/" + installPath, templateUniqueName, true, false);
+ 
+ 	            long physicalSize = new File(installFullPath + "/" + templateUniqueName + ".ova").length();
+ 	            VmdkProcessor processor = new VmdkProcessor();
+ 	            Map<String, Object> params = new HashMap<String, Object>();
+ 	            params.put(StorageLayer.InstanceConfigKey, _storage);
+ 	            processor.configure("VMDK Processor", params);
+ 	            long virtualSize = processor.getTemplateVirtualSize(installFullPath, templateUniqueName);
+ 
+ 	            postCreatePrivateTemplate(installFullPath, templateId, templateUniqueName, physicalSize, virtualSize);
+ 	            return new Ternary<String, Long, Long>(installPath + "/" + templateUniqueName + ".ova", physicalSize, virtualSize);
+ 
+ 	        } finally {
+ 	            if(clonedVm != null) {
+ 	                clonedVm.detachAllDisks();
+ 	                clonedVm.destroy();
+ 	            }
+ 
+ 	            vmMo.removeSnapshot(templateUniqueName, false);
+ 	        }
+ 	    }
+ 
+ 	@Override
+ 	public Answer createTemplateFromVolume(CopyCommand cmd) {
+ 		VolumeObjectTO volume = (VolumeObjectTO)cmd.getSrcTO();
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volume.getDataStore();
+ 		TemplateObjectTO template = (TemplateObjectTO)cmd.getDestTO();
+ 		DataStoreTO imageStore = template.getDataStore();
+ 		
+ 		if (!(imageStore instanceof NfsTO)) {
+ 			return new CopyCmdAnswer("unsupported protocol");
+ 		}
+ 		NfsTO nfsImageStore = (NfsTO)imageStore;
+ 		String secondaryStoragePoolURL = nfsImageStore.getUrl();
+ 		String volumePath = volume.getPath();
+ 
+ 		String details = null;
+ 
+ 		VmwareContext context = hostService.getServiceContext(cmd);
+ 		try {
+ 			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
+ 
+ 			VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(volume.getVmName());
+ 			if (vmMo == null) {
+ 				if(s_logger.isDebugEnabled())
+ 					s_logger.debug("Unable to find the owner VM for CreatePrivateTemplateFromVolumeCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter");
+ 				vmMo = hyperHost.findVmOnPeerHyperHost(volume.getVmName());
+ 
+ 				if(vmMo == null) {
+ 					String msg = "Unable to find the owner VM for volume operation. vm: " + volume.getVmName();
+ 					s_logger.error(msg);
+ 					throw new Exception(msg);
+ 				}
+ 			}
+ 
+ 			Ternary<String, Long, Long> result = createTemplateFromVolume(vmMo,
+ 					template.getPath(), template.getId(), template.getName(),
+ 					secondaryStoragePoolURL, volumePath,
+ 					hostService.getWorkerName(context, cmd, 0));
+ 
+ 			TemplateObjectTO newTemplate = new TemplateObjectTO();
+ 			newTemplate.setPath(template.getName());
+ 			newTemplate.setFormat(ImageFormat.OVA);
+ 			newTemplate.setSize(result.third());
+ 			return new CopyCmdAnswer(newTemplate);
+ 
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				hostService.invalidateServiceContext(context);
+ 			}
+ 
+ 			s_logger.error("Unexpecpted exception ", e);
+ 
+ 			details = "CreatePrivateTemplateFromVolumeCommand exception: " + StringUtils.getExceptionStackInfo(e);
+ 			return new CopyCmdAnswer(details);
+ 		}
+ 	}
+ 	
+ 	private void exportVolumeToSecondaryStroage(VirtualMachineMO vmMo, String volumePath,
+ 	        String secStorageUrl, String secStorageDir, String exportName,
+ 	        String workerVmName) throws Exception {
+ 
+ 	        String secondaryMountPoint = mountService.getMountPoint(secStorageUrl);
+ 	        String exportPath =  secondaryMountPoint + "/" + secStorageDir + "/" + exportName;
+ 	        
+ 	        synchronized(exportPath.intern()) {
+ 	            if(!new File(exportPath).exists()) {
+ 	                Script command = new Script(false, "mkdir", _timeout, s_logger);
+ 	                command.add("-p");
+ 	                command.add(exportPath);
+ 	                if(command.execute() != null)
+ 	                    throw new Exception("unable to prepare snapshot backup directory");
+ 	            }
+ 	        }
+ 
+ 	        VirtualMachineMO clonedVm = null;
+ 	        try {
+ 
+ 	            Pair<VirtualDisk, String> volumeDeviceInfo = vmMo.getDiskDevice(volumePath, false);
+ 	            if(volumeDeviceInfo == null) {
+ 	                String msg = "Unable to find related disk device for volume. volume path: " + volumePath;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            // 4 MB is the minimum requirement for VM memory in VMware
+ 	            vmMo.cloneFromCurrentSnapshot(workerVmName, 0, 4, volumeDeviceInfo.second(),
+ 	                VmwareHelper.getDiskDeviceDatastore(volumeDeviceInfo.first()));
+ 	            clonedVm = vmMo.getRunningHost().findVmOnHyperHost(workerVmName);
+ 	            if(clonedVm == null) {
+ 	                String msg = "Unable to create dummy VM to export volume. volume path: " + volumePath;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            clonedVm.exportVm(exportPath, exportName, true, true);
+ 	        } finally {
+ 	            if(clonedVm != null) {
+ 	                clonedVm.detachAllDisks();
+ 	                clonedVm.destroy();
+ 	            }
+ 	        }
+ 	    }
+ 
+ 	
+ 	private String backupSnapshotToSecondaryStorage(VirtualMachineMO vmMo, String installPath,
+ 	        String volumePath, String snapshotUuid, String secStorageUrl,
+ 	        String prevSnapshotUuid, String prevBackupUuid, String workerVmName) throws Exception {
+ 
+ 	        String backupUuid = UUID.randomUUID().toString();
+ 	        exportVolumeToSecondaryStroage(vmMo, volumePath, secStorageUrl,
+ 	        		installPath, backupUuid, workerVmName);
+ 	        return backupUuid + "/" + backupUuid;
+ 	    }
+ 	@Override
+ 	public Answer backupSnasphot(CopyCommand cmd) {
+ 		SnapshotObjectTO srcSnapshot = (SnapshotObjectTO)cmd.getSrcTO();
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)srcSnapshot.getDataStore();
+ 		SnapshotObjectTO destSnapshot = (SnapshotObjectTO)cmd.getDestTO();
+ 		DataStoreTO destStore = destSnapshot.getDataStore();
+ 		if (!(destStore instanceof NfsTO)) {
+ 			return new CopyCmdAnswer("unsupported protocol");
+ 		}
+ 
+ 		NfsTO destNfsStore = (NfsTO)destStore;
+ 
+ 
+ 		String secondaryStorageUrl = destNfsStore.getUrl();
+ 		String snapshotUuid = srcSnapshot.getPath();
+ 		String prevSnapshotUuid = srcSnapshot.getParentSnapshotPath();
+ 		String prevBackupUuid = destSnapshot.getParentSnapshotPath();
+ 		VirtualMachineMO workerVm=null;
+ 		String workerVMName = null;
+ 		String volumePath = srcSnapshot.getVolume().getPath();
+ 		ManagedObjectReference morDs = null;
+ 		DatastoreMO dsMo=null;
+ 
+ 		// By default assume failure
+ 		String details = null;
+ 		boolean success = false;
+ 		String snapshotBackupUuid = null;
+ 
+ 		VmwareContext context = hostService.getServiceContext(cmd);
+ 		VirtualMachineMO vmMo = null;
+ 		String vmName = srcSnapshot.getVmName();
+ 		try {
+ 			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
+ 			morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
+ 
+ 			try {
+ 				vmMo = hyperHost.findVmOnHyperHost(vmName);
+ 				if (vmMo == null) {
+ 					if(s_logger.isDebugEnabled())
+ 						s_logger.debug("Unable to find owner VM for BackupSnapshotCommand on host " + hyperHost.getHyperHostName() + ", will try within datacenter");
+ 
+ 					vmMo = hyperHost.findVmOnPeerHyperHost(vmName);
+ 					if(vmMo == null) {
+ 						dsMo = new DatastoreMO(hyperHost.getContext(), morDs);
+ 
+ 						workerVMName = hostService.getWorkerName(context, cmd, 0);
+ 
+ 						// attach a volume to dummay wrapper VM for taking snapshot and exporting the VM for backup
+ 						if (!hyperHost.createBlankVm(workerVMName, 1, 512, 0, false, 4, 0, VirtualMachineGuestOsIdentifier.OTHER_GUEST.value(), morDs, false)) {
+ 							String msg = "Unable to create worker VM to execute BackupSnapshotCommand";
+ 							s_logger.error(msg);
+ 							throw new Exception(msg);
+ 						}
+ 						vmMo = hyperHost.findVmOnHyperHost(workerVMName);
+ 						if (vmMo == null) {
+ 							throw new Exception("Failed to find the newly create or relocated VM. vmName: " + workerVMName);
+ 						}
+ 						workerVm = vmMo;
+ 
+ 						// attach volume to worker VM
+ 						String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumePath);
+ 						vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
+ 					}
+ 				}
+ 
+ 				if (!vmMo.createSnapshot(snapshotUuid, "Snapshot taken for " + srcSnapshot.getName(), false, false)) {
+ 					throw new Exception("Failed to take snapshot " + srcSnapshot.getName() + " on vm: " + vmName);
+ 				}
+ 
+ 				snapshotBackupUuid = backupSnapshotToSecondaryStorage(vmMo, destSnapshot.getPath(), srcSnapshot.getVolume().getPath(), snapshotUuid, secondaryStorageUrl, prevSnapshotUuid, prevBackupUuid,
+ 						hostService.getWorkerName(context, cmd, 1));
+ 
+ 				success = (snapshotBackupUuid != null);
+ 				if (success) {
+ 					details = "Successfully backedUp the snapshotUuid: " + snapshotUuid + " to secondary storage.";
+ 					return new CopyCmdAnswer(details);
+ 				} else {
+ 					SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
+ 					newSnapshot.setPath(snapshotBackupUuid);
+ 					return new CopyCmdAnswer(newSnapshot);
+ 				}
+ 			} finally {
+ 				if(vmMo != null){
+ 					ManagedObjectReference snapshotMor = vmMo.getSnapshotMor(snapshotUuid);
+ 					if (snapshotMor != null){
+ 						vmMo.removeSnapshot(snapshotUuid, false);
+ 					}
+ 				}
+ 
+ 				try {
+ 					if (workerVm != null) {
+ 						// detach volume and destroy worker vm
+ 						workerVm.detachAllDisks();
+ 						workerVm.destroy();
+ 					}
+ 				} catch (Throwable e) {
+ 					s_logger.warn("Failed to destroy worker VM: " + workerVMName);
+ 				}
+ 			}
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				hostService.invalidateServiceContext(context);
+ 			}
+ 
+ 			s_logger.error("Unexpecpted exception ", e);
+ 
+ 			details = "BackupSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e);
+ 			return new CopyCmdAnswer(details);
+ 		}
+ 	}
+ 
+ 	@Override
+ 	public Answer attachIso(AttachCommand cmd) {
+ 		return this.attachIso(cmd.getDisk(), true, cmd.getVmName());
+ 	}
+ 
+ 	@Override
+ 	public Answer attachVolume(AttachCommand cmd) {
+ 		return this.attachVolume(cmd, cmd.getDisk(), true, cmd.getVmName());
+ 	}
+ 	
+ 	private Answer attachVolume(Command cmd, DiskTO disk, boolean isAttach, String vmName) {
+ 
+ 		VolumeObjectTO volumeTO = (VolumeObjectTO)disk.getData();
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore();
+ 		try {
 -			VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(this.hostService.getServiceContext(null), null);
++			VmwareHypervisorHost hyperHost = hostService.getHyperHost(hostService.getServiceContext(null), null);
+ 			VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
+ 			if (vmMo == null) {
+ 				String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + vmName;
+ 				s_logger.error(msg);
+ 				throw new Exception(msg);
+ 			}
+ 
+ 			ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
+ 			if (morDs == null) {
+ 				String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + vmName;
+ 				s_logger.error(msg);
+ 				throw new Exception(msg);
+ 			}
+ 
 -			DatastoreMO dsMo = new DatastoreMO(this.hostService.getServiceContext(null), morDs);
++			DatastoreMO dsMo = new DatastoreMO(hostService.getServiceContext(null), morDs);
+ 			String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeTO.getPath());
+ 
+ 			AttachAnswer answer = new AttachAnswer(disk);
+ 			if (isAttach) {
+ 				vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs);
+ 			} else {
+ 				vmMo.removeAllSnapshots();
+ 				vmMo.detachDisk(datastoreVolumePath, false);
+ 			}
+ 
+ 			return answer;
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
 -				this.hostService.invalidateServiceContext(null);
++				hostService.invalidateServiceContext(null);
+ 			}
+ 
+ 			String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e);
+ 			s_logger.error(msg, e);
+ 			return new AttachAnswer(msg);
+ 		}
+ 	}
+ 	
+ 	  private static String getSecondaryDatastoreUUID(String storeUrl) {
+ 	        return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString();
+ 	    }
+ 
+ 	public synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception {
+         String storeName = getSecondaryDatastoreUUID(storeUrl);
+         URI uri = new URI(storeUrl);
+ 
 -        VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(this.hostService.getServiceContext(null), null);
++        VmwareHypervisorHost hyperHost = hostService.getHyperHost(hostService.getServiceContext(null), null);
+         ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName.replace("-", ""));
+ 
+         if (morDatastore == null)
+             throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl);
+ 
+         return morDatastore;
+     }
+ 	private Answer attachIso(DiskTO disk, boolean isAttach, String vmName) {
+ 		
+ 
+ 	        try {
 -	            VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(this.hostService.getServiceContext(null), null);
++	            VmwareHypervisorHost hyperHost = hostService.getHyperHost(hostService.getServiceContext(null), null);
+ 	            VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
+ 	            if (vmMo == null) {
+ 	                String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + vmName;
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 	            TemplateObjectTO iso = (TemplateObjectTO)disk.getData();
+ 	            NfsTO nfsImageStore = (NfsTO)iso.getDataStore();
+ 	            String storeUrl = nfsImageStore.getUrl();
+ 	            if (storeUrl == null) {
+ 	                if (!iso.getName().equalsIgnoreCase("vmware-tools.iso")) {
+ 	                    String msg = "ISO store root url is not found in AttachIsoCommand";
+ 	                    s_logger.error(msg);
+ 	                    throw new Exception(msg);
+ 	                } else {
+ 	                    if (isAttach) {
+ 	                        vmMo.mountToolsInstaller();
+ 	                    } else {
+ 	                        try{
+ 	                            vmMo.unmountToolsInstaller();
+ 	                        }catch(Throwable e){
+ 	                            vmMo.detachIso(null);
+ 	                        }
+ 	                    }
+ 
+ 	                    return new AttachAnswer(disk);
+ 	                }
+ 	            }
+ 
+ 	            ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl);
+ 	            String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath();
+ 	            if (!isoPath.startsWith(storeUrl)) {
+ 	                assert (false);
+ 	                String msg = "ISO path does not start with the secondary storage root";
+ 	                s_logger.error(msg);
+ 	                throw new Exception(msg);
+ 	            }
+ 
+ 	            int isoNameStartPos = isoPath.lastIndexOf('/');
+ 	            String isoFileName = isoPath.substring(isoNameStartPos + 1);
+ 	            String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos);
+ 
+ 	            // TODO, check if iso is already attached, or if there is a previous
+ 	            // attachment
 -	            DatastoreMO secondaryDsMo = new DatastoreMO(this.hostService.getServiceContext(null), morSecondaryDs);
++	            DatastoreMO secondaryDsMo = new DatastoreMO(hostService.getServiceContext(null), morSecondaryDs);
+ 	            String storeName = secondaryDsMo.getName();
+ 	            String isoDatastorePath = String.format("[%s] %s%s", storeName, isoStorePathFromRoot, isoFileName);
+ 
+ 	            if (isAttach) {
+ 	                vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false);
+ 	            } else {
+ 	                vmMo.detachIso(isoDatastorePath);
+ 	            }
+ 
+ 	            return new AttachAnswer(disk);
+ 	        } catch (Throwable e) {
+ 	            if (e instanceof RemoteException) {
+ 	                s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
 -	                this.hostService.invalidateServiceContext(null);
++	                hostService.invalidateServiceContext(null);
+ 	            }
+ 
+ 	            if(isAttach) {
+ 	                String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e);
+ 	                s_logger.error(msg, e);
+ 	                return new AttachAnswer(msg);
+ 	            } else {
+ 	                String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e);
+ 	                s_logger.warn(msg, e);
+ 	                return new AttachAnswer(msg);
+ 	            }
+ 	        }
+ 	}
+ 	@Override
+ 	public Answer dettachIso(DettachCommand cmd) {
+ 		return this.attachIso(cmd.getDisk(), false, cmd.getVmName());
+ 	}
+ 
+ 	@Override
+ 	public Answer dettachVolume(DettachCommand cmd) {
+ 		return this.attachVolume(cmd, cmd.getDisk(), false, cmd.getVmName());
+ 	}
+ 
+ 	protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception {
+         assert (hyperHost != null);
+ 
+         VirtualMachineMO vmMo = null;
+         VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec();
+         vmConfig.setName(vmName);
+         vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB
+         vmConfig.setNumCPUs(1);
+         vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value());
+         VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo();
+         fileInfo.setVmPathName(String.format("[%s]", dsMo.getName()));
+         vmConfig.setFiles(fileInfo);
+ 
+         // Scsi controller
+         VirtualLsiLogicController scsiController = new VirtualLsiLogicController();
+         scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING);
+         scsiController.setBusNumber(0);
+         scsiController.setKey(1);
+         VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec();
+         scsiControllerSpec.setDevice(scsiController);
+         scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
+ 
+         vmConfig.getDeviceChange().add(scsiControllerSpec );
+         hyperHost.createVm(vmConfig);
+         vmMo = hyperHost.findVmOnHyperHost(vmName);
+         return vmMo;
+     }
+ 	@Override
+ 	public Answer createVolume(CreateObjectCommand cmd) {
+ 
+ 		VolumeObjectTO volume = (VolumeObjectTO)cmd.getData();
+ 		PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volume.getDataStore();
+        
+ 		try {
 -			VmwareContext context = this.hostService.getServiceContext(null);
 -			VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(context, null);
++			VmwareContext context = hostService.getServiceContext(null);
++			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
+ 			DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter());
+ 
+ 			ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, primaryStore.getUuid());
+ 			if (morDatastore == null)
+ 				throw new Exception("Unable to find datastore in vSphere");
+ 
+ 			DatastoreMO dsMo = new DatastoreMO(context, morDatastore);
+ 			// create data volume
+ 			VirtualMachineMO vmMo = null;
+ 			String volumeUuid = UUID.randomUUID().toString().replace("-", "");
+ 			String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid);
 -			String dummyVmName = this.hostService.getWorkerName(context, cmd, 0);
++			String dummyVmName = hostService.getWorkerName(context, cmd, 0);
+ 			try {
+ 				vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName);
+ 				if (vmMo == null) {
+ 					throw new Exception("Unable to create a dummy VM for volume creation");
+ 				}
+ 
+ 				synchronized (this) {
+ 					// s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath);
+ 					VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo);
+ 
+ 					vmMo.createDisk(volumeDatastorePath, (int) (volume.getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey());
+ 					vmMo.detachDisk(volumeDatastorePath, false);
+ 				}
+ 
+ 				VolumeObjectTO newVol = new VolumeObjectTO();
+ 				newVol.setPath(volumeUuid);
+ 				newVol.setSize(volume.getSize() / (1024L * 1024L));
+ 				return new CreateObjectAnswer(newVol);
+ 			} finally {
+ 				s_logger.info("Destroy dummy VM after volume creation");
+ 				vmMo.detachAllDisks();
+ 				vmMo.destroy();
+ 			}
+ 
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
 -				this.hostService.invalidateServiceContext(null);
++				hostService.invalidateServiceContext(null);
+ 			}
+ 
+ 			String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e);
+ 			s_logger.error(msg, e);
+ 			return new CreateObjectAnswer(e.toString());
+ 		}
+ 	}
+ 
+ 	@Override
+ 	public Answer createSnapshot(CreateObjectCommand cmd) {
+ 		// snapshot operation (create or destroy) is handled inside BackupSnapshotCommand(), we just fake
+ 		// a success return here
+ 		String snapshotUUID = UUID.randomUUID().toString();
+ 		SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
+ 		newSnapshot.setPath(snapshotUUID);
+ 		return new CreateObjectAnswer(newSnapshot);
+ 	}
+ 
+ 	@Override
+ 	public Answer deleteVolume(DeleteCommand cmd) {
+ 		if (s_logger.isInfoEnabled()) {
+ 			s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd));
+ 		}
+ 
+ 		/*
+ 		 * DestroyCommand content example
+ 		 *
+ 		 * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary",
+ 		 * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType":
+ 		 * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } }
+ 		 *
+ 		 * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary",
+ 		 * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem",
+ 		 * "poolId":0,"deviceId":0 } }
+ 		 */
+ 
+ 		try {
 -			VmwareContext context = this.hostService.getServiceContext(null);
 -			VmwareHypervisorHost hyperHost = this.hostService.getHyperHost(context, null);
++			VmwareContext context = hostService.getServiceContext(null);
++			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, null);
+ 			VolumeObjectTO vol = (VolumeObjectTO)cmd.getData();
+ 			PrimaryDataStoreTO store = (PrimaryDataStoreTO)vol.getDataStore();
+ 
+ 			ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid());
+ 			if (morDs == null) {
+ 				String msg = "Unable to find datastore based on volume mount point " + store.getPath();
+ 				s_logger.error(msg);
+ 				throw new Exception(msg);
+ 			}
+ 
+ 			DatastoreMO dsMo = new DatastoreMO(context, morDs);
+ 
+ 			ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
+ 			ManagedObjectReference morCluster = hyperHost.getHyperHostCluster();
+ 			ClusterMO clusterMo = new ClusterMO(context, morCluster);
+ 
+ 			if (vol.getVolumeType() == Volume.Type.ROOT) {
+ 				String vmName = vol.getVmName();
+ 				if (vmName != null) {
+ 					VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName);
+ 					if (vmMo != null) {
+ 						if (s_logger.isInfoEnabled()) {
+ 							s_logger.info("Destroy root volume and VM itself. vmName " + vmName);
+ 						}
+ 
+ 						HostMO hostMo = vmMo.getRunningHost();
+ 						List<NetworkDetails> networks = vmMo.getNetworksWithDetails();
+ 
+ 						// tear down all devices first before we destroy the VM to avoid accidently delete disk backing files
 -						if (this.resource.getVmState(vmMo) != State.Stopped)
++                        if (resource.getVmState(vmMo) != PowerState.PowerOff)
+ 							vmMo.safePowerOff(_shutdown_waitMs);
+ 						vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class });
+ 						vmMo.destroy();
+ 
+ 						for (NetworkDetails netDetails : networks) {
+ 							if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) {
+ 								if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) {
 -									this.resource.cleanupNetwork(hostMo, netDetails);
++									resource.cleanupNetwork(hostMo, netDetails);
+ 								}
+ 							}
+ 						}
+ 					}
+ 
+ 					if (s_logger.isInfoEnabled())
+ 						s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk");
+ 					dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
+ 
+ 					// root volume may be created via linked-clone, delete the delta disk as well
+ 					if (_fullCloneFlag) {
+ 						if (s_logger.isInfoEnabled()) {
+ 							s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
+ 						}
+ 						dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
+ 					} else {
+ 						if (s_logger.isInfoEnabled()) {
+ 							s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-delta.vmdk");
+ 						}
+ 						dsMo.deleteFile(vol.getPath() + "-delta.vmdk", morDc, true);
+ 					}
+ 					return new Answer(cmd, true, "Success");
+ 				}
+ 
+ 				if (s_logger.isInfoEnabled()) {
+ 					s_logger.info("Destroy root volume directly from datastore");
+ 				}
+ 			} else {
+ 				// evitTemplate will be converted into DestroyCommand, test if we are running in this case
+ 				VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vol.getPath());
+ 				if (vmMo != null) {
+ 					if (s_logger.isInfoEnabled())
+ 						s_logger.info("Destroy template volume " + vol.getPath());
+ 
+ 					vmMo.destroy();
+ 					return new Answer(cmd, true, "Success");
+ 				}
+ 			}
+ 
+ 			String chainInfo = vol.getChainInfo();
+ 			if (chainInfo != null && !chainInfo.isEmpty()) {
+ 				s_logger.info("Destroy volume by chain info: " + chainInfo);
+ 				String[] diskChain = _gson.fromJson(chainInfo, String[].class);
+ 
+ 				if (diskChain != null && diskChain.length > 0) {
+ 					for (String backingName : diskChain) {
+ 						if (s_logger.isInfoEnabled()) {
+ 							s_logger.info("Delete volume backing file: " + backingName);
+ 						}
+ 						dsMo.deleteFile(backingName, morDc, true);
+ 					}
+ 				} else {
+ 					if (s_logger.isInfoEnabled()) {
+ 						s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name");
+ 					}
+ 					dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
+ 
+ 					if (s_logger.isInfoEnabled()) {
+ 						s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
+ 					}
+ 					dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
+ 				}
+ 			} else {
+ 				if (s_logger.isInfoEnabled()) {
+ 					s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk");
+ 				}
+ 				dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true);
+ 
+ 				if (s_logger.isInfoEnabled()) {
+ 					s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk");
+ 				}
+ 				dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true);
+ 			}
+ 
+ 			return new Answer(cmd, true, "Success");
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context");
 -				this.hostService.invalidateServiceContext(null);
++				hostService.invalidateServiceContext(null);
+ 			}
+ 
+ 			String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e);
+ 			s_logger.error(msg, e);
+ 			return new Answer(cmd, false, msg);
+ 		}
+ 	}
+ 	
+ 	 private Long restoreVolumeFromSecStorage(VmwareHypervisorHost hyperHost, DatastoreMO primaryDsMo, String newVolumeName,
+ 		        String secStorageUrl, String secStorageDir, String backupName) throws Exception {
+ 
+ 		        String secondaryMountPoint = mountService.getMountPoint(secStorageUrl);
+ 		        String srcOVAFileName = secondaryMountPoint + "/" +  secStorageDir + "/"
+ 		            + backupName + "." + ImageFormat.OVA.getFileExtension();
+ 		        String snapshotDir = "";
+ 		        if (backupName.contains("/")){
+ 		            snapshotDir = backupName.split("/")[0];
+ 		        }
+ 
+ 		        File ovafile = new File(srcOVAFileName);
+ 		        String srcOVFFileName = secondaryMountPoint + "/" +  secStorageDir + "/"
+ 		                + backupName + ".ovf";
+ 		        File ovfFile = new File(srcOVFFileName);
+ 		        // String srcFileName = getOVFFilePath(srcOVAFileName);
+ 		        if (!ovfFile.exists()) {
+ 		            srcOVFFileName = getOVFFilePath(srcOVAFileName);
+ 		            if(srcOVFFileName == null && ovafile.exists() ) {  // volss: ova file exists; o/w can't do tar
+ 		                Script command = new Script("tar", 0, s_logger);
+ 		                command.add("--no-same-owner");
+ 		                command.add("-xf", srcOVAFileName);
+ 		                command.setWorkDir(secondaryMountPoint + "/" +  secStorageDir + "/" + snapshotDir);
+ 		                s_logger.info("Executing command: " + command.toString());
+ 		                String result = command.execute();
+ 		                if(result != null) {
+ 		                        String msg = "Unable to unpack snapshot OVA file at: " + srcOVAFileName;
+ 		                        s_logger.error(msg);
+ 		                        throw new Exception(msg);
+ 		                }
+ 		            } else {
+ 		               String msg = "Unable to find snapshot OVA file at: " + srcOVAFileName;
+ 		               s_logger.error(msg);
+ 		               throw new Exception(msg);
+ 		           }
+ 
+ 		           srcOVFFileName = getOVFFilePath(srcOVAFileName);
+ 		        }
+ 		        if(srcOVFFileName == null) {
+ 		            String msg = "Unable to locate OVF file in template package directory: " + srcOVAFileName;
+ 		            s_logger.error(msg);
+ 		            throw new Exception(msg);
+ 		        }
+ 
+ 		        VirtualMachineMO clonedVm = null;
+ 		        try {
+ 		            hyperHost.importVmFromOVF(srcOVFFileName, newVolumeName, primaryDsMo, "thin");
+ 		            clonedVm = hyperHost.findVmOnHyperHost(newVolumeName);
+ 		            if(clonedVm == null)
+ 		                throw new Exception("Unable to create container VM for volume creation");
+ 
+ 		            clonedVm.moveAllVmDiskFiles(primaryDsMo, "", false);
+ 		            clonedVm.detachAllDisks();
+ 		            return _storage.getSize(srcOVFFileName);
+ 		        } finally {
+ 		            if(clonedVm != null) {
+ 		                clonedVm.detachAllDisks();
+ 		                clonedVm.destroy();
+ 		            }
+ 		        }
+ 		    }
+ 
+ 	@Override
+ 	public Answer createVolumeFromSnapshot(CopyCommand cmd) {
+ 		DataTO srcData = cmd.getSrcTO();
+ 		SnapshotObjectTO snapshot = (SnapshotObjectTO)srcData;
+ 		DataTO destData = cmd.getDestTO();
+ 		PrimaryDataStoreTO pool = (PrimaryDataStoreTO)destData.getDataStore();
+ 		DataStoreTO imageStore = srcData.getDataStore();
+ 
+ 
+ 		if (!(imageStore instanceof NfsTO)) {
+ 			return new CopyCmdAnswer("unsupported protocol");
+ 		}
+ 
+ 		NfsTO nfsImageStore = (NfsTO)imageStore;
+ 		String primaryStorageNameLabel = pool.getUuid();
+ 	
+         String secondaryStorageUrl = nfsImageStore.getUrl();
+ 		String backedUpSnapshotUuid = snapshot.getPath();
+ 		int index = backedUpSnapshotUuid.lastIndexOf(File.separator);
+ 		String backupPath = backedUpSnapshotUuid.substring(0, index);
+ 		backedUpSnapshotUuid = backedUpSnapshotUuid.substring(index + 1);
+ 		String details = null;
+ 		String newVolumeName = UUID.randomUUID().toString().replaceAll("-", "");
+ 
+ 		VmwareContext context = hostService.getServiceContext(cmd);
+ 		try {
+ 			VmwareHypervisorHost hyperHost = hostService.getHyperHost(context, cmd);
+ 			ManagedObjectReference morPrimaryDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost,
+ 					primaryStorageNameLabel);
+ 			if (morPrimaryDs == null) {
+ 				String msg = "Unable to find datastore: " + primaryStorageNameLabel;
+ 				s_logger.error(msg);
+ 				throw new Exception(msg);
+ 			}
+ 
+ 			DatastoreMO primaryDsMo = new DatastoreMO(hyperHost.getContext(), morPrimaryDs);
+ 			Long size = restoreVolumeFromSecStorage(hyperHost, primaryDsMo,
+ 					newVolumeName, secondaryStorageUrl, backupPath, backedUpSnapshotUuid);
+ 
+ 			VolumeObjectTO newVol = new VolumeObjectTO();
+ 			newVol.setPath(newVolumeName);
+ 			newVol.setSize(size);
+ 			return new CopyCmdAnswer(newVol);
+ 		} catch (Throwable e) {
+ 			if (e instanceof RemoteException) {
+ 				hostService.invalidateServiceContext(context);
+ 			}
+ 
+ 			s_logger.error("Unexpecpted exception ", e);
+ 			details = "CreateVolumeFromSnapshotCommand exception: " + StringUtils.getExceptionStackInfo(e);
+ 		}
+ 		return new CopyCmdAnswer(details);
+ 	}
+ 
+ 	@Override
+ 	public Answer deleteSnapshot(DeleteCommand cmd) {
+ 		SnapshotObjectTO snapshot = (SnapshotObjectTO)cmd.getData();
+ 		DataStoreTO store = snapshot.getDataStore();
+ 		if (store.getRole() == DataStoreRole.Primary) {
+ 			return new Answer(cmd);
+ 		} else {
+ 			return new Answer(cmd, false, "unsupported command");
+ 		}
+ 	}
+ }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java
index de08c93,d79d41e..cc92276
--- a/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java
+++ b/plugins/hypervisors/vmware/test/com/cloud/hypervisor/vmware/VmwareDatacenterApiUnitTest.java
@@@ -17,7 -17,7 +17,6 @@@
  
  package com.cloud.hypervisor.vmware;
  
--import static org.junit.Assert.*;
  import static org.mockito.Mockito.when;
  
  import java.io.IOException;
@@@ -28,11 -28,12 +27,6 @@@ import java.util.UUID
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
--import junit.framework.TestCase;
--
--import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
--import org.apache.cloudstack.api.command.admin.zone.RemoveVmwareDcCmd;
- import org.apache.cloudstack.test.utils.SpringUtils;
 -import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 -import org.apache.cloudstack.test.utils.SpringUtils;
  import org.junit.Before;
  import org.junit.BeforeClass;
  import org.junit.Test;
@@@ -40,7 -41,7 +34,6 @@@ import org.junit.runner.RunWith
  import org.mockito.Mock;
  import org.mockito.Mockito;
  import org.mockito.MockitoAnnotations;
--import org.mockito.Spy;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.ComponentScan;
  import org.springframework.context.annotation.ComponentScan.Filter;
@@@ -53,13 -54,13 +46,19 @@@ import org.springframework.test.context
  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  import org.springframework.test.context.support.AnnotationConfigContextLoader;
  
++import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
++import org.apache.cloudstack.api.command.admin.zone.RemoveVmwareDcCmd;
++import org.apache.cloudstack.context.CallContext;
++import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
++import org.apache.cloudstack.test.utils.SpringUtils;
++
  import com.cloud.agent.AgentManager;
  import com.cloud.cluster.ClusterManager;
  import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.dc.ClusterDetailsDao;
  import com.cloud.dc.ClusterDetailsVO;
--import com.cloud.dc.DataCenter.NetworkType;
  import com.cloud.dc.ClusterVO;
++import com.cloud.dc.DataCenter.NetworkType;
  import com.cloud.dc.DataCenterVO;
  import com.cloud.dc.HostPodVO;
  import com.cloud.dc.dao.ClusterDao;
@@@ -76,7 -77,7 +75,6 @@@ import com.cloud.hypervisor.dao.Hypervi
  import com.cloud.hypervisor.vmware.dao.LegacyZoneDao;
  import com.cloud.hypervisor.vmware.dao.VmwareDatacenterDao;
  import com.cloud.hypervisor.vmware.dao.VmwareDatacenterZoneMapDao;
--import com.cloud.hypervisor.vmware.manager.VmwareManager;
  import com.cloud.hypervisor.vmware.manager.VmwareManagerImpl;
  import com.cloud.network.NetworkModel;
  import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
@@@ -89,7 -90,7 +87,6 @@@ import com.cloud.user.Account
  import com.cloud.user.AccountManager;
  import com.cloud.user.AccountService;
  import com.cloud.user.AccountVO;
--import com.cloud.user.UserContext;
  import com.cloud.user.dao.AccountDao;
  import com.cloud.utils.component.ComponentContext;
  import com.cloud.utils.exception.CloudRuntimeException;
@@@ -175,7 -176,7 +172,7 @@@ public class VmwareDatacenterApiUnitTes
          acct.setType(Account.ACCOUNT_TYPE_ADMIN);
          acct.setAccountName("admin");
          acct.setDomainId(domainId);
--        UserContext.registerContext(1, acct, null, true);
++        CallContext.register(1, acct, null, true);
  
          when(_accountDao.findByIdIncludingRemoved(0L)).thenReturn(acct);
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java
index 6dd6f3f,c52020e..5661374b
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/XenServerGuru.java
@@@ -24,7 -24,9 +24,8 @@@ import com.cloud.hypervisor.Hypervisor.
  import com.cloud.storage.GuestOSVO;
  import com.cloud.storage.dao.GuestOSDao;
  import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 -import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
+ import com.cloud.vm.VirtualMachineProfileImpl;
  
  @Local(value=HypervisorGuru.class)
  public class XenServerGuru extends HypervisorGuruBase implements HypervisorGuru {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index c01b605,af640a2..c947af6
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@@ -1130,31 -1185,42 +1186,42 @@@ public abstract class CitrixResourceBas
          }
      }
  
-     protected VDI mount(Connection conn, String vmName, VolumeTO volume) throws XmlRpcException, XenAPIException {
-         if (volume.getType() == Volume.Type.ISO) {
-             String isopath = volume.getPath();
-             if (isopath == null) {
+     protected VDI mount(Connection conn, String vmName, DiskTO volume) throws XmlRpcException, XenAPIException {
+         DataTO data = volume.getData();
+         Volume.Type type = volume.getType();
+         if (type == Volume.Type.ISO) {
+             TemplateObjectTO iso = (TemplateObjectTO)data;
+             DataStoreTO store = iso.getDataStore();
+             
+             if (store == null) {
+                 //It's a fake iso
                  return null;
              }
-             if (isopath.startsWith("xs-tools")) {
+             
+             //corer case, xenserver pv driver iso
+             String templateName = iso.getName();
+             if (templateName.startsWith("xs-tools")) {
                  try {
-                     Set<VDI> vdis = VDI.getByNameLabel(conn, isopath);
+                     Set<VDI> vdis = VDI.getByNameLabel(conn, templateName);
                      if (vdis.isEmpty()) {
-                         throw new CloudRuntimeException("Could not find ISO with URL: " + isopath);
+                         throw new CloudRuntimeException("Could not find ISO with URL: " + templateName);
                      }
                      return vdis.iterator().next();
- 
                  } catch (XenAPIException e) {
-                     throw new CloudRuntimeException("Unable to get pv iso: " + isopath + " due to " + e.toString());
+                     throw new CloudRuntimeException("Unable to get pv iso: " + templateName + " due to " + e.toString());
                  } catch (Exception e) {
-                     throw new CloudRuntimeException("Unable to get pv iso: " + isopath + " due to " + e.toString());
+                     throw new CloudRuntimeException("Unable to get pv iso: " + templateName + " due to " + e.toString());
                  }
              }
 -            
 +
+             if (!(store instanceof NfsTO)) {
+                 throw new CloudRuntimeException("only support mount iso on nfs");
+             }
+             NfsTO nfsStore = (NfsTO)store;
+             String isoPath = nfsStore.getUrl() + File.separator + iso.getPath();
+             int index = isoPath.lastIndexOf("/");
  
-             int index = isopath.lastIndexOf("/");
- 
-             String mountpoint = isopath.substring(0, index);
+             String mountpoint = isoPath.substring(0, index);
              URI uri;
              try {
                  uri = new URI(mountpoint);
@@@ -1290,16 -1357,21 +1358,21 @@@
  
          if (!(guestOsTypeName.startsWith("Windows") || guestOsTypeName.startsWith("Citrix") || guestOsTypeName.startsWith("Other"))) {
              if (vmSpec.getBootloader() == BootloaderType.CD) {
-                 VolumeTO [] disks = vmSpec.getDisks();
-                 for (VolumeTO disk : disks) {
-                     if (disk.getType() == Volume.Type.ISO && disk.getOsType() != null) {
-                         String isoGuestOsName = getGuestOsType(disk.getOsType(), vmSpec.getBootloader() == BootloaderType.CD);
+                 DiskTO [] disks = vmSpec.getDisks();
+                 for (DiskTO disk : disks) {
+                     Volume.Type type = disk.getType();
+                     if (type == Volume.Type.ISO) {
+                         TemplateObjectTO tmpl = (TemplateObjectTO)disk.getData();
+                         String osType = tmpl.getGuestOsType();
+                         if (tmpl.getFormat() == ImageFormat.ISO && osType != null ) {
+                             String isoGuestOsName = getGuestOsType(osType, vmSpec.getBootloader() == BootloaderType.CD);
 -                            if (!isoGuestOsName.equals(guestOsTypeName)) {
 -                                vmSpec.setBootloader(BootloaderType.PyGrub);
 -                            }
 +                        if (!isoGuestOsName.equals(guestOsTypeName)) {
 +                            vmSpec.setBootloader(BootloaderType.PyGrub);
                          }
                      }
                  }
              }
++            }
              if (vmSpec.getBootloader() == BootloaderType.CD) {
                  vm.setPVBootloader(conn, "eliloader");
                  Map<String, String> otherConfig = vm.getOtherConfig(conn);


[26/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-305. Everytime a SOAP call is made some transactions are rolled back because the transactions are not committed.


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

Branch: refs/heads/vmsync
Commit: dc242039b3f13531d9969ba104c63395e0db3b18
Parents: bb50c0d
Author: Likitha Shetty <li...@citrix.com>
Authored: Mon Jun 24 14:02:19 2013 +0530
Committer: Likitha Shetty <li...@citrix.com>
Committed: Mon Jun 24 14:21:59 2013 +0530

----------------------------------------------------------------------
 .../bridge/persist/dao/CloudStackConfigurationDaoImpl.java   | 3 ++-
 .../bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java     | 2 ++
 .../com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java  | 1 +
 awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java    | 8 ++++----
 awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java | 8 ++++----
 awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java    | 8 ++++----
 .../com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java | 1 +
 7 files changed, 18 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDaoImpl.java
index 6770a9c..bc77ea1 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackConfigurationDaoImpl.java
@@ -54,7 +54,8 @@ public class CloudStackConfigurationDaoImpl extends GenericDaoBase<CloudStackCon
             }
             return configItem.getValue();
         }finally {
-
+            txn.commit();
+            txn.close();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
index f0d05d3..8021eb6 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
@@ -50,6 +50,7 @@ public class CloudStackSvcOfferingDaoImpl extends GenericDaoBase<CloudStackServi
             return findOneBy(sc);
         
         }finally {
+            txn.commit();
             txn.close();
         }
 
@@ -68,6 +69,7 @@ public class CloudStackSvcOfferingDaoImpl extends GenericDaoBase<CloudStackServi
             return findOneBy(sc);
         
         }finally {
+            txn.commit();
             txn.close();
         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java
index 5aac396..f7e1da6 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackUserDaoImpl.java
@@ -55,6 +55,7 @@ public class CloudStackUserDaoImpl extends GenericDaoBase<CloudStackUserVO, Stri
             }
             return cloudSecretKey;
         } finally {
+            txn.commit();
             txn.close();
         }
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java
index 67abf81..2223254 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/MHostDaoImpl.java
@@ -44,10 +44,10 @@ public class MHostDaoImpl extends GenericDaoBase<MHostVO, Long> implements MHost
 		SearchCriteria<MHostVO> sc = NameSearch.create();
 		sc.setParameters("MHostKey", hostKey);
 		return findOneBy(sc);
-		
-	    }finally {
-		txn.close();
-	    }
+        } finally {
+            txn.commit();
+            txn.close();
+        }
 	}
 
     @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java
index cce0f83..ea7d264 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/OfferingDaoImpl.java
@@ -43,7 +43,8 @@ public class OfferingDaoImpl extends GenericDaoBase<OfferingBundleVO, Long> impl
         try {
             txn.start();
             return listAll().size();
-        }finally {
+        } finally {
+            txn.commit();
             txn.close();
         }
 	    
@@ -61,8 +62,8 @@ public class OfferingDaoImpl extends GenericDaoBase<OfferingBundleVO, Long> impl
            SearchCriteria<OfferingBundleVO> sc = searchByAmazon.create();
            sc.setParameters("AmazonEC2Offering", amazonEC2Offering);
            return findOneBy(sc).getCloudstackOffering();
-           
         } finally {
+            txn.commit();
             txn.close();
         }
 	}
@@ -79,8 +80,8 @@ public class OfferingDaoImpl extends GenericDaoBase<OfferingBundleVO, Long> impl
 	           SearchCriteria<OfferingBundleVO> sc = searchByAmazon.create();
 	           sc.setParameters("CloudStackOffering", cloudStackOffering);
 	           return findOneBy(sc).getAmazonOffering();
-	           
 	        } finally {
+                txn.commit();
 	            txn.close();
 	        }
 	    }
@@ -109,7 +110,6 @@ public class OfferingDaoImpl extends GenericDaoBase<OfferingBundleVO, Long> impl
                 offering = persist(offering);
             else
                 update(offering.getID(), offering);
-
             txn.commit();
          } finally {
              txn.close();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java
index 5eadd06..9b6b535 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/SHostDaoImpl.java
@@ -42,8 +42,8 @@ public class SHostDaoImpl extends GenericDaoBase<SHostVO, Long> implements SHost
     		SearchCriteria<SHostVO> sc = HostSearch.create();
     		sc.setParameters("Host", host);
     		return findOneBy(sc);
-		
-	    }finally {
+        } finally {
+            txn.commit();
 	        txn.close();
 	    }
 	    
@@ -62,8 +62,8 @@ public class SHostDaoImpl extends GenericDaoBase<SHostVO, Long> implements SHost
             sc.setParameters("MHostID", mhostId);
             sc.setParameters("ExportRoot", storageRoot);
             return findOneBy(sc);
-		
-	    }finally {
+        } finally {
+            txn.commit();
             txn.close();
 	    }	
 	}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dc242039/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
index 684b00b..c45886f 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
@@ -67,6 +67,7 @@ public class UserCredentialsDaoImpl extends GenericDaoBase<UserCredentialsVO, Lo
             sc.setParameters("CertUniqueId", certId);
             return findOneBy(sc);
 	    }finally {
+            txn.commit();
 	        txn.close();
 	    }
 	    


[05/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Removing a redundant step (stop service twice in upgrade 4.0 to 4.1). Hack Day.


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

Branch: refs/heads/vmsync
Commit: 84ecc11841c73bc5442d00f68f00334e11cba7f6
Parents: 2a8297b
Author: Joe Brockmeier <jz...@zonker.net>
Authored: Sun Jun 23 14:14:19 2013 -0500
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 14:14:19 2013 -0500

----------------------------------------------------------------------
 docs/en-US/Release_Notes.xml | 5 -----
 1 file changed, 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/84ecc118/docs/en-US/Release_Notes.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/Release_Notes.xml b/docs/en-US/Release_Notes.xml
index 8843f4c..4a27cd2 100644
--- a/docs/en-US/Release_Notes.xml
+++ b/docs/en-US/Release_Notes.xml
@@ -4642,11 +4642,6 @@ under the License.
           <programlisting><prompt>#</prompt> mysqldump -u root -p cloud &gt; cloudstack-backup.sql</programlisting>
         </listitem>
         <listitem>
-          <para>Whether you're upgrading a Red Hat/CentOS based system or Ubuntu based system,
-            you're going to need to stop the CloudStack management server before proceeding.</para>
-          <programlisting language="Bash"><prompt>#</prompt> service cloud-management stop</programlisting>
-        </listitem>
-        <listitem>
           <para>If you have made changes to
               <filename>/etc/cloud/management/components.xml</filename>, you'll need to carry these
             over manually to the new file,


[24/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-1578 vmware:Egress default policy configurable using network offering on vmware


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

Branch: refs/heads/vmsync
Commit: 9121191f702bc431add8235fa4cd636d9ee2310e
Parents: c22e7d0
Author: Jayapal <ja...@apache.org>
Authored: Thu Jun 20 16:31:01 2013 +0530
Committer: Jayapal <ja...@apache.org>
Committed: Mon Jun 24 13:37:01 2013 +0530

----------------------------------------------------------------------
 .../com/cloud/hypervisor/vmware/resource/VmwareResource.java | 8 ++++++++
 1 file changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9121191f/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index c35024c..5040443 100755
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@ -764,12 +764,20 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa
         String[] results = new String[cmd.getRules().length];
         FirewallRuleTO[] allrules = cmd.getRules();
         FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
+        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
 
         String[][] rules = cmd.generateFwRules();
         String args = "";
         args += " -F ";
         if (trafficType == FirewallRule.TrafficType.Egress){
             args+= " -E ";
+            if (egressDefault.equals("true")) {
+                args+= " -P 1 ";
+            } else if (egressDefault.equals("System")) {
+                args+= " -P 2 ";
+            } else {
+                args+= " -P 0 ";
+            }
         }
 
         StringBuilder sb = new StringBuilder();


[45/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
----------------------------------------------------------------------
diff --cc engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
index 56a6651,1d36f93..95ca968
--- a/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
+++ b/engine/storage/volume/src/org/apache/cloudstack/storage/volume/VolumeServiceImpl.java
@@@ -24,15 -25,14 +25,17 @@@ import java.util.Map
  
  import javax.inject.Inject;
  
 +import org.apache.log4j.Logger;
 +import org.springframework.stereotype.Component;
 +
  import org.apache.cloudstack.engine.cloud.entity.api.VolumeEntity;
- import org.apache.cloudstack.engine.subsystem.api.storage.CommandResult;
  import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult;
  import org.apache.cloudstack.engine.subsystem.api.storage.CreateCmdResult;
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService;
  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.EndPoint;
+ import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
  import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
  import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
@@@ -47,14 -49,28 +52,26 @@@ import org.apache.cloudstack.storage.da
  import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager;
  import org.apache.cloudstack.storage.datastore.PrimaryDataStore;
  import org.apache.cloudstack.storage.datastore.PrimaryDataStoreProviderManager;
- import org.apache.cloudstack.storage.motion.DataMotionService;
+ import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO;
+ import org.apache.cloudstack.storage.to.VolumeObjectTO;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
+ import com.cloud.agent.api.Answer;
+ import com.cloud.agent.api.storage.ListVolumeAnswer;
+ import com.cloud.agent.api.storage.ListVolumeCommand;
  import com.cloud.agent.api.to.VirtualMachineTO;
+ import com.cloud.alert.AlertManager;
+ import com.cloud.configuration.Config;
+ import com.cloud.configuration.Resource.ResourceType;
+ import com.cloud.configuration.dao.ConfigurationDao;
  import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.ResourceAllocationException;
  import com.cloud.host.Host;
+ import com.cloud.storage.DataStoreRole;
  import com.cloud.storage.StoragePool;
+ import com.cloud.storage.VMTemplateStorageResourceAssoc;
+ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
  import com.cloud.storage.Volume;
- import com.cloud.storage.Volume.Type;
  import com.cloud.storage.VolumeVO;
  import com.cloud.storage.dao.VolumeDao;
  import com.cloud.storage.snapshot.SnapshotManager;
@@@ -114,16 -143,17 +145,17 @@@ public class VolumeServiceImpl implemen
          DataObject volumeOnStore = dataStore.create(volume);
          volumeOnStore.processEvent(Event.CreateOnlyRequested);
  
-         CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, volumeOnStore, future);
+         CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, volumeOnStore,
+                 future);
          AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
-         caller.setCallback(caller.getTarget().createVolumeCallback(null, null))
-         .setContext(context);
+         caller.setCallback(caller.getTarget().createVolumeCallback(null, null)).setContext(context);
 -
 +        
          dataStore.getDriver().createAsync(volumeOnStore, caller);
          return future;
      }
 -
 +    
-     protected Void createVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback, CreateVolumeContext<VolumeApiResult> context) {
+     protected Void createVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback,
+             CreateVolumeContext<VolumeApiResult> context) {
          CreateCmdResult result = callback.getResult();
          DataObject vo = context.getVolume();
          String errMsg = null;
@@@ -172,14 -201,14 +204,14 @@@
              future.complete(result);
              return future;
          }
 -
 +        
-         String vmName = null;
-         VolumeVO vol = volDao.findById(volume.getId());
-         if (vol.getVolumeType() == Type.ROOT && vol.getInstanceId() != null) {
-             VirtualMachine vm = vmDao.findByIdIncludingRemoved(vol
-                     .getInstanceId());
-             if (vm != null) {
-                 vmName = vm.getInstanceName();
+         // Find out if the volume is at state of download_in_progress on secondary storage
+         VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(volume.getId());
+         if (volumeStore != null) {
+             if (volumeStore.getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOAD_IN_PROGRESS) {
+                 s_logger.debug("Volume: " + volume.getName() + " is currently being uploaded; cant' delete it.");
+                 future.complete(result);
+                 return future;
              }
          }
  
@@@ -194,21 -224,20 +227,20 @@@
              future.complete(result);
              return future;
          }
-         VolumeObject vo = (VolumeObject)volume;
+         VolumeObject vo = (VolumeObject) volume;
 -
 +      
          volume.processEvent(Event.ExpungeRequested);
 -
 +      
-         
          DeleteVolumeContext<VolumeApiResult> context = new DeleteVolumeContext<VolumeApiResult>(null, vo, future);
          AsyncCallbackDispatcher<VolumeServiceImpl, CommandResult> caller = AsyncCallbackDispatcher.create(this);
-         caller.setCallback(caller.getTarget().deleteVolumeCallback(null, null))
-             .setContext(context);
+         caller.setCallback(caller.getTarget().deleteVolumeCallback(null, null)).setContext(context);
 -
 +        
          volume.getDataStore().getDriver().deleteAsync(volume, caller);
          return future;
      }
 -
 +    
-     public Void deleteVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CommandResult> callback, DeleteVolumeContext<VolumeApiResult> context) {
+     public Void deleteVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CommandResult> callback,
+             DeleteVolumeContext<VolumeApiResult> context) {
          CommandResult result = callback.getResult();
          VolumeObject vo = context.getVolume();
          VolumeApiResult apiResult = new VolumeApiResult(vo);
@@@ -231,19 -260,9 +263,9 @@@
  
      @Override
      public VolumeEntity getVolumeEntity(long volumeId) {
-         VolumeVO vo = volDao.findById(volumeId);
-         if (vo == null) {
 -        return null;
 -    }
 +            return null;
 +        }
  
-         if (vo.getPoolId() == null) {
-             return new VolumeEntityImpl(VolumeObject.getVolumeObject(null, vo), this);
-         } else {
-             PrimaryDataStore dataStore = dataStoreMgr.getPrimaryDataStore(vo.getPoolId());
-             return new VolumeEntityImpl(dataStore.getVolume(volumeId), this);
-         }
-     }
- 
      class CreateBaseImageContext<T> extends AsyncRpcConext<T> {
          private final VolumeInfo volume;
          private final PrimaryDataStore dataStore;
@@@ -276,31 -296,64 +299,64 @@@
          public AsyncCallFuture<VolumeApiResult> getFuture() {
              return this.future;
          }
 -
 +        
      }
 -
 +    
-     static class CreateBaseImageResult extends CommandResult {
-         final TemplateInfo template;
-         public CreateBaseImageResult(TemplateInfo template) {
-             super();
-             this.template = template;
+     private TemplateInfo waitForTemplateDownloaded(PrimaryDataStore store, TemplateInfo template) {
+         int storagePoolMaxWaitSeconds = NumbersUtil.parseInt(
+                 configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600);
+         int sleepTime = 120;
+         int tries = storagePoolMaxWaitSeconds / sleepTime;
+         while (tries > 0) {
+             TemplateInfo tmpl = store.getTemplate(template.getId());
+             if (tmpl != null) {
+                 return tmpl;
 -            }
++        }
+             try {
+                 Thread.sleep(sleepTime * 1000);
+             } catch (InterruptedException e) {
+                 s_logger.debug("waiting for template download been interrupted: " + e.toString());
+             }
+             tries--;
          }
+         return null;
      }
 -
 +    
      @DB
-     protected void createBaseImageAsync(VolumeInfo volume, PrimaryDataStore dataStore, TemplateInfo template, AsyncCallFuture<VolumeApiResult> future) {
+     protected void createBaseImageAsync(VolumeInfo volume, PrimaryDataStore dataStore, TemplateInfo template,
+             AsyncCallFuture<VolumeApiResult> future) {
 -
 +       
          DataObject templateOnPrimaryStoreObj = dataStore.create(template);
          CreateBaseImageContext<CreateCmdResult> context = new CreateBaseImageContext<CreateCmdResult>(null, volume,
-                 dataStore,
-                 template,
-                 future, templateOnPrimaryStoreObj);
+                 dataStore, template, future, templateOnPrimaryStoreObj);
          AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
-         caller.setCallback(caller.getTarget().copyBaseImageCallback(null, null))
-         .setContext(context);
+         caller.setCallback(caller.getTarget().copyBaseImageCallback(null, null)).setContext(context);
 -
 +        
+         try {
 -            templateOnPrimaryStoreObj.processEvent(Event.CreateOnlyRequested);
 +        templateOnPrimaryStoreObj.processEvent(Event.CreateOnlyRequested);
+         } catch (Exception e) {
+             s_logger.info("Got exception in case of multi-thread");
+             try {
+                 templateOnPrimaryStoreObj = waitForTemplateDownloaded(dataStore, template);
+             } catch (Exception e1) {
+                 s_logger.debug("wait for template:" + template.getId() + " downloading finished, but failed");
+                 VolumeApiResult result = new VolumeApiResult(volume);
+                 result.setResult(e1.toString());
+                 future.complete(result);
+                 return;
+             }
+             if (templateOnPrimaryStoreObj == null) {
+                 VolumeApiResult result = new VolumeApiResult(volume);
+                 result.setResult("wait for template:" + template.getId() + " downloading finished, but failed");
+                 future.complete(result);
+                 return;
+             } else {
+                 s_logger.debug("waiting for template:" + template.getId() + " downloading finished, success");
+                 createVolumeFromBaseImageAsync(volume, templateOnPrimaryStoreObj, dataStore, future);
+                 return;
+             }
+         }
 -
 +     
          try {
              motionSrv.copyAsync(template, templateOnPrimaryStoreObj, caller);
          } catch (Exception e) {
@@@ -312,12 -365,13 +368,13 @@@
          }
          return;
      }
 -
 +    
      @DB
-     protected Void copyBaseImageCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback, CreateBaseImageContext<VolumeApiResult> context) {
+     protected Void copyBaseImageCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
+             CreateBaseImageContext<VolumeApiResult> context) {
          CopyCommandResult result = callback.getResult();
          VolumeApiResult res = new VolumeApiResult(context.getVolume());
 -
 +        
          AsyncCallFuture<VolumeApiResult> future = context.getFuture();
          DataObject templateOnPrimaryStoreObj = context.destObj;
          if (!result.isSuccess()) {
@@@ -326,60 -380,59 +383,59 @@@
              future.complete(res);
              return null;
          }
 -
 +        
-         templateOnPrimaryStoreObj.processEvent(Event.OperationSuccessed);
+         templateOnPrimaryStoreObj.processEvent(Event.OperationSuccessed, result.getAnswer());
          createVolumeFromBaseImageAsync(context.volume, templateOnPrimaryStoreObj, context.dataStore, future);
          return null;
      }
 -
 +    
      private class CreateVolumeFromBaseImageContext<T> extends AsyncRpcConext<T> {
-         private final VolumeObject vo;
+         private final DataObject vo;
          private final AsyncCallFuture<VolumeApiResult> future;
-         private final DataStore primaryStore;
          private final DataObject templateOnStore;
-         public CreateVolumeFromBaseImageContext(AsyncCompletionCallback<T> callback, VolumeObject vo,
-                 DataStore primaryStore,
-                 DataObject templateOnStore,
-                 AsyncCallFuture<VolumeApiResult> future) {
+         private final SnapshotInfo snapshot;
+ 
+         public CreateVolumeFromBaseImageContext(AsyncCompletionCallback<T> callback, DataObject vo,
+                 DataStore primaryStore, DataObject templateOnStore, AsyncCallFuture<VolumeApiResult> future,
+                 SnapshotInfo snapshot) {
              super(callback);
              this.vo = vo;
              this.future = future;
-             this.primaryStore = primaryStore;
              this.templateOnStore = templateOnStore;
+             this.snapshot = snapshot;
          }
 -
 +        
- 
          public AsyncCallFuture<VolumeApiResult> getFuture() {
              return this.future;
          }
      }
 -
 +    
      @DB
-     protected void createVolumeFromBaseImageAsync(VolumeInfo volume, DataObject templateOnPrimaryStore, PrimaryDataStore pd, AsyncCallFuture<VolumeApiResult> future) {
-         VolumeObject vo = (VolumeObject)volume;
-         CreateVolumeFromBaseImageContext<VolumeApiResult> context = new CreateVolumeFromBaseImageContext<VolumeApiResult>(null, vo, pd, templateOnPrimaryStore, future);
-         AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller =  AsyncCallbackDispatcher.create(this);
-         caller.setCallback(caller.getTarget().copyBaseImageCallBack(null, null))
-         .setContext(context);
- 
+     protected void createVolumeFromBaseImageAsync(VolumeInfo volume, DataObject templateOnPrimaryStore,
+             PrimaryDataStore pd, AsyncCallFuture<VolumeApiResult> future) {
          DataObject volumeOnPrimaryStorage = pd.create(volume);
-         volume.processEvent(Event.CreateOnlyRequested);
+         volumeOnPrimaryStorage.processEvent(Event.CreateOnlyRequested);
+ 
+         CreateVolumeFromBaseImageContext<VolumeApiResult> context = new CreateVolumeFromBaseImageContext<VolumeApiResult>(
+                 null, volumeOnPrimaryStorage, pd, templateOnPrimaryStore, future, null);
+         AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
+         caller.setCallback(caller.getTarget().createVolumeFromBaseImageCallBack(null, null));
+         caller.setContext(context);
  
          motionSrv.copyAsync(context.templateOnStore, volumeOnPrimaryStorage, caller);
          return;
      }
 -
 +    
      @DB
-     public Void copyBaseImageCallBack(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback, CreateVolumeFromBaseImageContext<VolumeApiResult> context) {
-         VolumeObject vo = context.vo;
+     protected Void createVolumeFromBaseImageCallBack(
+             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
+             CreateVolumeFromBaseImageContext<VolumeApiResult> context) {
+         DataObject vo = context.vo;
          CopyCommandResult result = callback.getResult();
-         VolumeApiResult volResult = new VolumeApiResult(vo);
+         VolumeApiResult volResult = new VolumeApiResult((VolumeObject) vo);
 -
 +       
          if (result.isSuccess()) {
-             if (result.getPath() != null) {
-                 vo.setPath(result.getPath());
-             }
-             vo.processEvent(Event.OperationSuccessed);
+             vo.processEvent(Event.OperationSuccessed, result.getAnswer());
          } else {
              vo.processEvent(Event.OperationFailed);
              volResult.setResult(result.getResult());
@@@ -396,8 -450,7 +453,7 @@@
          PrimaryDataStore pd = dataStoreMgr.getPrimaryDataStore(dataStoreId);
          TemplateInfo templateOnPrimaryStore = pd.getTemplate(template.getId());
          AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
-         VolumeApiResult result = new VolumeApiResult(volume);
 -
 +        
          if (templateOnPrimaryStore == null) {
              createBaseImageAsync(volume, pd, template, future);
              return future;
@@@ -409,9 -462,8 +465,8 @@@
  
      @Override
      @DB
-     public boolean destroyVolume(long volumeId)
-             throws ConcurrentOperationException {
+     public boolean destroyVolume(long volumeId) throws ConcurrentOperationException {
 -
 +        
          VolumeInfo vol = volFactory.getVolume(volumeId);
          vol.processEvent(Event.DestroyRequested);
          snapshotMgr.deletePoliciesForVolume(volumeId);
@@@ -422,55 -474,61 +477,61 @@@
      }
  
      @Override
-     public AsyncCallFuture<VolumeApiResult> createVolumeFromSnapshot(
-             VolumeInfo volume, DataStore store, SnapshotInfo snapshot) {
+     public AsyncCallFuture<VolumeApiResult> createVolumeFromSnapshot(VolumeInfo volume, DataStore store,
+             SnapshotInfo snapshot) {
          AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
 -
 +        
          try {
 -            DataObject volumeOnStore = store.create(volume);
 +        	DataObject volumeOnStore = store.create(volume);
-             volume = this.volFactory.getVolume(volume.getId(), store);
-         	volume.processEvent(Event.CreateOnlyRequested);
-         	 CreateVolumeFromBaseImageContext<VolumeApiResult> context = new CreateVolumeFromBaseImageContext<VolumeApiResult>(null,
-         			 (VolumeObject)volume, store, volumeOnStore, future);
+             volumeOnStore.processEvent(Event.CreateOnlyRequested);
+             snapshot.processEvent(Event.CopyingRequested);
+             CreateVolumeFromBaseImageContext<VolumeApiResult> context = new CreateVolumeFromBaseImageContext<VolumeApiResult>(
+                     null, volume, store, volumeOnStore, future, snapshot);
 -            AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
 +             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller =  AsyncCallbackDispatcher.create(this);
-              caller.setCallback(caller.getTarget().createVolumeFromSnapshotCallback(null, null))
-              .setContext(context);
+             caller.setCallback(caller.getTarget().createVolumeFromSnapshotCallback(null, null)).setContext(context);
 -            motionSrv.copyAsync(snapshot, volumeOnStore, caller);
 +        	motionSrv.copyAsync(snapshot, volumeOnStore, caller);
          } catch (Exception e) {
 -            s_logger.debug("create volume from snapshot failed", e);
 -            VolumeApiResult result = new VolumeApiResult(volume);
 -            result.setResult(e.toString());
 -            future.complete(result);
 +        	s_logger.debug("create volume from snapshot failed", e);
 +        	VolumeApiResult result = new VolumeApiResult(volume);
 +        	result.setResult(e.toString());
 +        	future.complete(result);
          }
 -
 +        
          return future;
      }
 -
 +    
-     protected Void createVolumeFromSnapshotCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
+     protected Void createVolumeFromSnapshotCallback(
+             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
 -            CreateVolumeFromBaseImageContext<VolumeApiResult> context) {
 -        CopyCommandResult result = callback.getResult();
 +    		CreateVolumeFromBaseImageContext<VolumeApiResult> context) {
 +    	CopyCommandResult result = callback.getResult();
-     	VolumeInfo volume = context.vo;
+         VolumeInfo volume = (VolumeInfo) context.templateOnStore;
+         SnapshotInfo snapshot = context.snapshot;
 -        VolumeApiResult apiResult = new VolumeApiResult(volume);
 -        Event event = null;
 -        if (result.isFailed()) {
 -            apiResult.setResult(result.getResult());
 -            event = Event.OperationFailed;
 -        } else {
 -            event = Event.OperationSuccessed;
 -        }
 -
 -        try {
 +    	VolumeApiResult apiResult = new VolumeApiResult(volume);
 +    	Event event = null;
 +    	if (result.isFailed()) {
 +    		apiResult.setResult(result.getResult());
 +    		event = Event.OperationFailed;
 +    	} else {
 +    		event = Event.OperationSuccessed;
 +    	}
 +    	
 +    	try {
+             if (result.isSuccess()) {
+                 volume.processEvent(event, result.getAnswer());
+             } else {
 -                volume.processEvent(event);
 +    		volume.processEvent(event);
+             }
+             snapshot.processEvent(event);
 -        } catch (Exception e) {
 -            s_logger.debug("create volume from snapshot failed", e);
 -            apiResult.setResult(e.toString());
 -        }
 -
 -        AsyncCallFuture<VolumeApiResult> future = context.future;
 -        future.complete(apiResult);
 -        return null;
 +    	} catch (Exception e) {
 +    		s_logger.debug("create volume from snapshot failed", e);
 +    		apiResult.setResult(e.toString());
 +    	}
 +    	
 +    	AsyncCallFuture<VolumeApiResult> future = context.future;
 +    	future.complete(apiResult);
 +    	return null;
      }
 -
 +    
      protected VolumeVO duplicateVolumeOnAnotherStorage(Volume volume, StoragePool pool) {
          Long lastPoolId = volume.getPoolId();
          VolumeVO newVol = new VolumeVO(volume);
@@@ -482,8 -540,7 +543,7 @@@
          newVol.setPodId(pool.getPodId());
          return volDao.persist(newVol);
      }
 -
 +    
- 
      private class CopyVolumeContext<T> extends AsyncRpcConext<T> {
          final VolumeInfo srcVolume;
          final VolumeInfo destVolume;
@@@ -497,14 -551,135 +554,135 @@@
              super(callback);
              this.srcVolume = srcVolume;
              this.destVolume = destVolume;
-             this.destStore = destStore;
              this.future = future;
          }
 -
 +        
      }
+ 
+     protected AsyncCallFuture<VolumeApiResult> copyVolumeFromImageToPrimary(VolumeInfo srcVolume, DataStore destStore) {
+         AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
+         VolumeApiResult res = new VolumeApiResult(srcVolume);
+         VolumeInfo destVolume = null;
+         try {
+             destVolume = (VolumeInfo) destStore.create(srcVolume);
+             destVolume.processEvent(Event.CopyingRequested);
+             srcVolume.processEvent(Event.CopyingRequested);
 -
++                
+             CopyVolumeContext<VolumeApiResult> context = new CopyVolumeContext<VolumeApiResult>(null, future,
+                     srcVolume, destVolume, destStore);
+             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
+             caller.setCallback(caller.getTarget().copyVolumeFromImageToPrimaryCallback(null, null)).setContext(context);
+ 
+             motionSrv.copyAsync(srcVolume, destVolume, caller);
+             return future;
+         } catch (Exception e) {
+             s_logger.error("failed to copy volume from image store", e);
+             if (destVolume != null) {
+                 destVolume.processEvent(Event.OperationFailed);
+             }
+ 
+             srcVolume.processEvent(Event.OperationFailed);
+             res.setResult(e.toString());
 -            future.complete(res);
 -            return future;
 -        }
++                future.complete(res);
++                return future;
++            }
+     }
+ 
+     protected Void copyVolumeFromImageToPrimaryCallback(
+             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
+             CopyVolumeContext<VolumeApiResult> context) {
+         VolumeInfo srcVolume = context.srcVolume;
+         VolumeInfo destVolume = context.destVolume;
+         CopyCommandResult result = callback.getResult();
+         AsyncCallFuture<VolumeApiResult> future = context.future;
+         VolumeApiResult res = new VolumeApiResult(destVolume);
+         try {
+             if (res.isFailed()) {
+                 destVolume.processEvent(Event.OperationFailed);
+                 srcVolume.processEvent(Event.OperationFailed);
+                 res.setResult(result.getResult());
+                 future.complete(res);
+                 return null;
+             }
+ 
+             srcVolume.processEvent(Event.OperationSuccessed);
+             destVolume.processEvent(Event.OperationSuccessed, result.getAnswer());
+             srcVolume.getDataStore().delete(srcVolume);
+             future.complete(res);
+         } catch (Exception e) {
+             res.setResult(e.toString());
+             future.complete(res);
+         }
+         return null;
+     }
+ 
+ 
+     protected AsyncCallFuture<VolumeApiResult> copyVolumeFromPrimaryToImage(VolumeInfo srcVolume, DataStore destStore) {
+         AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
+         VolumeApiResult res = new VolumeApiResult(srcVolume);
+         VolumeInfo destVolume = null;
+         try {
+             destVolume = (VolumeInfo)destStore.create(srcVolume);
+             srcVolume.processEvent(Event.MigrationRequested);    // this is just used for locking that src volume record in DB to avoid using lock
+             destVolume.processEventOnly(Event.CreateOnlyRequested);
+ 
+             CopyVolumeContext<VolumeApiResult> context = new CopyVolumeContext<VolumeApiResult>(null, future, srcVolume,
+                     destVolume,
+                     destStore);
+             AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> caller = AsyncCallbackDispatcher.create(this);
+             caller.setCallback(caller.getTarget().copyVolumeFromPrimaryToImageCallback(null, null))
+             .setContext(context);
+ 
+             motionSrv.copyAsync(srcVolume, destVolume, caller);
+             return future;
+         } catch (Exception e) {
+             s_logger.error("failed to copy volume to image store", e);
+             if (destVolume != null) {
+                 destVolume.getDataStore().delete(destVolume);
+             }
+             srcVolume.processEvent(Event.OperationFailed); // unlock source volume record
+             res.setResult(e.toString());
+             future.complete(res);
+             return future;
+         }
+     }
+ 
+     protected Void copyVolumeFromPrimaryToImageCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback, CopyVolumeContext<VolumeApiResult> context) {
+         VolumeInfo srcVolume = context.srcVolume;
+         VolumeInfo destVolume = context.destVolume;
+         CopyCommandResult result = callback.getResult();
+         AsyncCallFuture<VolumeApiResult> future = context.future;
+         VolumeApiResult res = new VolumeApiResult(destVolume);
+         try {
+             if (res.isFailed()) {
+                 srcVolume.processEvent(Event.OperationFailed); // back to Ready state in Volume table
+                 destVolume.processEventOnly(Event.OperationFailed);
+                 res.setResult(result.getResult());
+                 future.complete(res);
+             }else{
+                 srcVolume.processEvent(Event.OperationSuccessed); // back to Ready state in Volume table
+                 destVolume.processEventOnly(Event.OperationSuccessed, result.getAnswer());
+                 future.complete(res);
+             }
+         } catch (Exception e) {
+             res.setResult(e.toString());
+             future.complete(res);
+         }
+         return null;
+     }
+ 
+ 
      @Override
-     public AsyncCallFuture<VolumeApiResult> copyVolume(VolumeInfo srcVolume,
-             DataStore destStore) {
+     public AsyncCallFuture<VolumeApiResult> copyVolume(VolumeInfo srcVolume, DataStore destStore) {
+ 
+         if (srcVolume.getState() == Volume.State.Uploaded) {
+             return copyVolumeFromImageToPrimary(srcVolume, destStore);
+         }
+ 
+         if (destStore.getRole() == DataStoreRole.Image) {
+             return copyVolumeFromPrimaryToImage(srcVolume, destStore);
+         }
+ 
          AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
          VolumeApiResult res = new VolumeApiResult(srcVolume);
          try {
@@@ -536,8 -708,9 +711,9 @@@
          }
          return future;
      }
 -
 +    
-     protected Void copyVolumeCallBack(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback, CopyVolumeContext<VolumeApiResult> context) {
+     protected Void copyVolumeCallBack(AsyncCallbackDispatcher<VolumeServiceImpl, CopyCommandResult> callback,
+             CopyVolumeContext<VolumeApiResult> context) {
          VolumeInfo srcVolume = context.srcVolume;
          VolumeInfo destVolume = context.destVolume;
          CopyCommandResult result = callback.getResult();
@@@ -730,85 -901,250 +904,250 @@@
  
      @Override
      public AsyncCallFuture<VolumeApiResult> registerVolume(VolumeInfo volume, DataStore store) {
 -
 +        
          AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
-         VolumeObject vo = (VolumeObject) volume;
+         DataObject volumeOnStore = store.create(volume);
  
-         CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, vo, future);
+         volumeOnStore.processEvent(Event.CreateOnlyRequested);
+ 
+         CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, volumeOnStore,
+                 future);
          AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
-         caller.setCallback(caller.getTarget().registerVolumeCallback(null, null))
-         .setContext(context);
+         caller.setCallback(caller.getTarget().registerVolumeCallback(null, null));
+         caller.setContext(context);
 -
 +        
-         dataObjectMgr.createAsync(volume, store, caller, true);
+         store.getDriver().createAsync(volumeOnStore, caller);
          return future;
      }
 -
 +    
-     protected Void registerVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback, CreateVolumeContext<VolumeApiResult> context) {
+     protected Void registerVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback,
+             CreateVolumeContext<VolumeApiResult> context) {
          CreateCmdResult result = callback.getResult();
-         VolumeObject vo = (VolumeObject)context.volume;
+         try {
+             VolumeObject vo = (VolumeObject) context.volume;
 -            if (result.isFailed()) {
 +        if (result.isFailed()) {
-             vo.stateTransit(Volume.Event.OperationFailed);
+                 vo.processEvent(Event.OperationFailed);
 -            } else {
 +        } else {
-             vo.stateTransit(Volume.Event.OperationSucceeded);
+                 vo.processEvent(Event.OperationSuccessed, result.getAnswer());
 -            }
 +        }
+ 
+             _resourceLimitMgr.incrementResourceCount(vo.getAccountId(), ResourceType.secondary_storage, vo.getSize());
 -            VolumeApiResult res = new VolumeApiResult(vo);
 -            context.future.complete(res);
 -            return null;
 +        VolumeApiResult res = new VolumeApiResult(vo);
 +        context.future.complete(res);
 +        return null;
+         } catch (Exception e) {
+             s_logger.error("register volume failed: ", e);
+             VolumeApiResult res = new VolumeApiResult(null);
+             context.future.complete(res);
+             return null;
+         }
      }
-     
  
 -    @Override
 -    public AsyncCallFuture<VolumeApiResult> resize(VolumeInfo volume) {
 -        AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
 -        VolumeApiResult result = new VolumeApiResult(volume);
 -        try {
 -            volume.processEvent(Event.ResizeRequested);
 -        } catch (Exception e) {
 -            s_logger.debug("Failed to change state to resize", e);
 -            result.setResult(e.toString());
 -            future.complete(result);
 -            return future;
 -        }
 -        CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, volume, future);
 -        AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
 +	@Override
 +	public AsyncCallFuture<VolumeApiResult> resize(VolumeInfo volume) {
 +		AsyncCallFuture<VolumeApiResult> future = new AsyncCallFuture<VolumeApiResult>();
 +		VolumeApiResult result = new VolumeApiResult(volume);
 +		try {
 +			volume.processEvent(Event.ResizeRequested);
 +		} catch (Exception e) {
 +			s_logger.debug("Failed to change state to resize", e);
 +			result.setResult(e.toString());
 +			future.complete(result);
 +			return future;
 +		}
 +		 CreateVolumeContext<VolumeApiResult> context = new CreateVolumeContext<VolumeApiResult>(null, volume, future);
 +	        AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> caller = AsyncCallbackDispatcher.create(this);
          caller.setCallback(caller.getTarget().resizeVolumeCallback(caller, context)).setContext(context);
 -        volume.getDataStore().getDriver().resize(volume, caller);
 -        return future;
 -    }
 -
 +		volume.getDataStore().getDriver().resize(volume, caller);
 +		return future;
 +	}
 +	
- 	protected Void resizeVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback, CreateVolumeContext<VolumeApiResult> context) {
+     protected Void resizeVolumeCallback(AsyncCallbackDispatcher<VolumeServiceImpl, CreateCmdResult> callback,
+             CreateVolumeContext<VolumeApiResult> context) {
 -        CreateCmdResult result = callback.getResult();
 -        AsyncCallFuture<VolumeApiResult> future = context.future;
 +		CreateCmdResult result = callback.getResult();
 +		AsyncCallFuture<VolumeApiResult> future  = context.future;
- 		VolumeInfo volume = (VolumeInfo)context.volume;
+         VolumeInfo volume = (VolumeInfo) context.volume;
 -
 -        if (result.isFailed()) {
 -            try {
 -                volume.processEvent(Event.OperationFailed);
 -            } catch (Exception e) {
 -                s_logger.debug("Failed to change state", e);
 -            }
 -            VolumeApiResult res = new VolumeApiResult(volume);
 -            res.setResult(result.getResult());
 -            future.complete(res);
 -            return null;
 -        }
 -
 -        try {
 -            volume.processEvent(Event.OperationSuccessed);
 +		
 +		if (result.isFailed()) {
 +			try {
 +				volume.processEvent(Event.OperationFailed);
 +			} catch (Exception e) {
 +				s_logger.debug("Failed to change state", e);
 +			}
 +			VolumeApiResult res = new VolumeApiResult(volume);
 +			res.setResult(result.getResult());
 +			future.complete(res);
 +			return null;
 +		}
 +		
 +		try {
 +			volume.processEvent(Event.OperationSuccessed);
- 		} catch(Exception e) {
+         } catch (Exception e) {
 -            s_logger.debug("Failed to change state", e);
 -            VolumeApiResult res = new VolumeApiResult(volume);
 -            res.setResult(result.getResult());
 -            future.complete(res);
 -            return null;
 -        }
 -
 -        VolumeApiResult res = new VolumeApiResult(volume);
 -        future.complete(res);
 -
 -        return null;
 -    }
 -
 +			s_logger.debug("Failed to change state", e);
 +			VolumeApiResult res = new VolumeApiResult(volume);
 +			res.setResult(result.getResult());
 +			future.complete(res);
 +			return null;
 +		}
 +		
 +		VolumeApiResult res = new VolumeApiResult(volume);
 +		future.complete(res);
 +		
 +		return null;
 +	}
 +	
+     @Override
+     public void handleVolumeSync(DataStore store) {
+         if (store == null) {
+             s_logger.warn("Huh? ssHost is null");
+             return;
+         }
+         long storeId = store.getId();
+ 
+         Map<Long, TemplateProp> volumeInfos = listVolume(store);
+         if (volumeInfos == null) {
+             return;
+         }
+ 
+         List<VolumeDataStoreVO> dbVolumes = _volumeStoreDao.listByStoreId(storeId);
+         List<VolumeDataStoreVO> toBeDownloaded = new ArrayList<VolumeDataStoreVO>(dbVolumes);
+         for (VolumeDataStoreVO volumeStore : dbVolumes) {
+             VolumeVO volume = _volumeDao.findById(volumeStore.getVolumeId());
+             // Exists then don't download
+             if (volumeInfos.containsKey(volume.getId())) {
+                 TemplateProp volInfo = volumeInfos.remove(volume.getId());
+                 toBeDownloaded.remove(volumeStore);
+                 s_logger.info("Volume Sync found " + volume.getUuid() + " already in the volume image store table");
+                 if (volumeStore.getDownloadState() != Status.DOWNLOADED) {
+                     volumeStore.setErrorString("");
+                 }
+                 if (volInfo.isCorrupted()) {
+                     volumeStore.setDownloadState(Status.DOWNLOAD_ERROR);
+                     String msg = "Volume " + volume.getUuid() + " is corrupted on image store ";
+                     volumeStore.setErrorString(msg);
+                     s_logger.info("msg");
+                     if (volumeStore.getDownloadUrl() == null) {
+                         msg = "Volume (" + volume.getUuid() + ") with install path " + volInfo.getInstallPath()
+                                 + "is corrupted, please check in image store: " + volumeStore.getDataStoreId();
+                         s_logger.warn(msg);
+                     } else {
+                         toBeDownloaded.add(volumeStore);
+                     }
+ 
+                 } else { // Put them in right status
+                     volumeStore.setDownloadPercent(100);
+                     volumeStore.setDownloadState(Status.DOWNLOADED);
+                     volumeStore.setInstallPath(volInfo.getInstallPath());
+                     volumeStore.setSize(volInfo.getSize());
+                     volumeStore.setPhysicalSize(volInfo.getPhysicalSize());
+                     volumeStore.setLastUpdated(new Date());
+                     _volumeStoreDao.update(volumeStore.getId(), volumeStore);
+ 
+                     if (volume.getSize() == 0) {
+                         // Set volume size in volumes table
+                         volume.setSize(volInfo.getSize());
+                         _volumeDao.update(volumeStore.getVolumeId(), volume);
+                     }
+ 
+                     if (volInfo.getSize() > 0) {
+                         try {
+                             _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(volume.getAccountId()),
+                                     com.cloud.configuration.Resource.ResourceType.secondary_storage, volInfo.getSize()
+                                             - volInfo.getPhysicalSize());
+                         } catch (ResourceAllocationException e) {
+                             s_logger.warn(e.getMessage());
+                             _alertMgr.sendAlert(AlertManager.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED,
+                                     volume.getDataCenterId(), volume.getPodId(), e.getMessage(), e.getMessage());
+                         } finally {
+                             _resourceLimitMgr.recalculateResourceCount(volume.getAccountId(), volume.getDomainId(),
+                                     com.cloud.configuration.Resource.ResourceType.secondary_storage.getOrdinal());
+                         }
+                     }
+                 }
+                 continue;
+             }
+             // Volume is not on secondary but we should download.
+             if (volumeStore.getDownloadState() != Status.DOWNLOADED) {
+                 s_logger.info("Volume Sync did not find " + volume.getName() + " ready on image store " + storeId
+                         + ", will request download to start/resume shortly");
+                 toBeDownloaded.add(volumeStore);
+             }
+         }
+ 
+         // Download volumes which haven't been downloaded yet.
+         if (toBeDownloaded.size() > 0) {
+             for (VolumeDataStoreVO volumeHost : toBeDownloaded) {
+                 if (volumeHost.getDownloadUrl() == null) { // If url is null we
+                                                            // can't initiate the
+                                                            // download
+                     continue;
+                 }
+                 s_logger.debug("Volume " + volumeHost.getVolumeId() + " needs to be downloaded to " + store.getName());
+                 // TODO: pass a callback later
+                 VolumeInfo vol = volFactory.getVolume(volumeHost.getVolumeId());
+                 createVolumeAsync(vol, store);
+             }
+         }
+ 
+         // Delete volumes which are not present on DB.
+         for (Long uniqueName : volumeInfos.keySet()) {
+             TemplateProp tInfo = volumeInfos.get(uniqueName);
+ 
+             //we cannot directly call expungeVolumeAsync here to
+             // reuse delete logic since in this case, our db does not have
+             // this template at all.
+             VolumeObjectTO tmplTO = new VolumeObjectTO();
+             tmplTO.setDataStore(store.getTO());
+             tmplTO.setPath(tInfo.getInstallPath());
+             tmplTO.setId(tInfo.getId());
+             DeleteCommand dtCommand = new DeleteCommand(tmplTO);
+             EndPoint ep = _epSelector.select(store);
+             Answer answer = ep.sendMessage(dtCommand);
+             if (answer == null || !answer.getResult()) {
+                 s_logger.info("Failed to deleted volume at store: " + store.getName());
+ 
+             } else {
+                 String description = "Deleted volume " + tInfo.getTemplateName() + " on secondary storage " + storeId;
+                 s_logger.info(description);
+             }
+         }
+     }
+ 
+     private Map<Long, TemplateProp> listVolume(DataStore store) {
+         ListVolumeCommand cmd = new ListVolumeCommand(store.getTO(), store.getUri());
+         EndPoint ep = _epSelector.select(store);
+         Answer answer = ep.sendMessage(cmd);
+         if (answer != null && answer.getResult()) {
+             ListVolumeAnswer tanswer = (ListVolumeAnswer) answer;
+             return tanswer.getTemplateInfo();
+         } else {
+             if (s_logger.isDebugEnabled()) {
+                 s_logger.debug("Can not list volumes for image store " + store.getId());
+             }
+         }
+ 
+         return null;
+     }
+ 
+     @Override
+     public SnapshotInfo takeSnapshot(VolumeInfo volume) {
+         VolumeObject vol = (VolumeObject) volume;
+         vol.stateTransit(Volume.Event.SnapshotRequested);
 -
 +	
+         SnapshotInfo snapshot = null;
+         try {
+             snapshot = snapshotMgr.takeSnapshot(volume);
+         } catch (Exception e) {
+             s_logger.debug("Take snapshot: " + volume.getId() + " failed: " + e.toString());
+         } finally {
+             if (snapshot != null) {
+                 vol.stateTransit(Volume.Event.OperationSucceeded);
+             } else {
+                 vol.stateTransit(Volume.Event.OperationFailed);
+             }
+         }
+ 
+         return snapshot;
+     }
  
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
----------------------------------------------------------------------
diff --cc framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
index 8d91f5f,acbc5b6..dbfbd03
--- a/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
+++ b/framework/ipc/src/org/apache/cloudstack/framework/async/AsyncCallbackDispatcher.java
@@@ -22,20 -22,24 +22,24 @@@ package org.apache.cloudstack.framework
  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;
  
- import net.sf.cglib.proxy.CallbackFilter;
 -import org.apache.log4j.Logger;
 -
 -import net.sf.cglib.proxy.CallbackFilter;
  import net.sf.cglib.proxy.Callback;
++import net.sf.cglib.proxy.CallbackFilter;
  import net.sf.cglib.proxy.Enhancer;
  import net.sf.cglib.proxy.MethodInterceptor;
  import net.sf.cglib.proxy.MethodProxy;
  
++import org.apache.log4j.Logger;
++
  @SuppressWarnings("rawtypes")
  public class AsyncCallbackDispatcher<T, R> implements AsyncCompletionCallback {
+     private static final Logger s_logger = Logger.getLogger(AsyncCallbackDispatcher.class);
+ 
 -    private Method _callbackMethod;
 -	private T _targetObject;
 +	private Method _callbackMethod;
- 	private T _targetObject;
++	private final T _targetObject;
  	private Object _contextObject;
  	private Object _resultObject;
 -	private AsyncCallbackDriver _driver = new InplaceAsyncCallbackDriver();
 -
 +	private AsyncCallbackDriver _driver = new InplaceAsyncCallbackDriver(); 
 +	
  	private AsyncCallbackDispatcher(T target) {
  		assert(target != null);
  		_targetObject = target;
@@@ -55,8 -59,14 +59,13 @@@
  	@SuppressWarnings("unchecked")
  	public T getTarget() {
  	    Enhancer en = new Enhancer();
- 	    en.setSuperclass(_targetObject.getClass());
- 	    en.setCallbacks(new Callback[] { new MethodInterceptor() {
 -
+ 	    Class<?> clz = _targetObject.getClass();
+ 	    String clzName = clz.getName();
+ 	    if(clzName.contains("EnhancerByCloudStack"))
+ 	        clz = clz.getSuperclass();
+ 
+ 	    en.setSuperclass(clz);
+ 	    en.setCallbacks(new Callback[]{new MethodInterceptor() {
              @Override
              public Object intercept(Object arg0, Method arg1, Object[] arg2,
                  MethodProxy arg3) throws Throwable {
@@@ -74,14 -84,21 +83,22 @@@
          }
  	    });
  	    en.setCallbackFilter(new CallbackFilter() {
--	        public int accept(Method method) {
++	        @Override
++            public int accept(Method method) {
  	            if (method.getParameterTypes().length == 0 && method.getName().equals("finalize")) {
  	                return 1;
  	            }
  	            return 0;
  	        }}
  	       );
+ 
+ 	    try {
 -	        return (T)en.create();
 +		return (T)en.create();
+ 	    } catch(Throwable e) {
+ 	        s_logger.error("Unexpected exception", e);
+ 	    }
+ 
+ 	    return null;
  	}
  
  	public AsyncCallbackDispatcher<T, R> setCallback(Object useless) {
@@@ -97,8 -114,8 +114,9 @@@
  	public <P> P getContext() {
  		return (P)_contextObject;
  	}
 -
 -	public void complete(Object resultObject) {
 +	
- 	public void complete(Object resultObject) {
++	@Override
++    public void complete(Object resultObject) {
  		_resultObject = resultObject;
  		_driver.performCompletionCallback(this);
  	}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalResourceBase.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
index e9d5499,96d702d..6d266fd
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java
@@@ -173,9 -167,9 +173,10 @@@ public class BaremetalDhcpElement exten
      }
  
      @Override
 -    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
 +    public boolean configDhcpSupportForSubnet(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context)
 +            throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
-         return false;  //To change body of implemented methods use File | Settings | File Templates.
+     	//TODO Add support for baremetal
+         return true;
      }
  
      @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeService.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeService.java
index 6a03e88,efdd221..feb23be
--- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeService.java
+++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeService.java
@@@ -24,8 -24,11 +24,10 @@@ package com.cloud.baremetal.networkserv
  
  import java.util.List;
  
+ import org.apache.cloudstack.api.AddBaremetalPxeCmd;
+ 
  import com.cloud.baremetal.database.BaremetalPxeVO;
  import com.cloud.deploy.DeployDestination;
 -import com.cloud.host.Host;
  import com.cloud.uservm.UserVm;
  import com.cloud.utils.component.Adapter;
  import com.cloud.vm.NicProfile;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalDhcpCmd.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalDhcpCmd.java
index 0000000,7c56a8a..04c9137
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalDhcpCmd.java
+++ b/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalDhcpCmd.java
@@@ -1,0 -1,155 +1,156 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package org.apache.cloudstack.api;
+ 
+ import javax.inject.Inject;
+ 
+ import org.apache.cloudstack.api.APICommand;
+ import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
+ import org.apache.cloudstack.api.BaseAsyncCmd;
+ import org.apache.cloudstack.api.BaseCmd;
+ import org.apache.cloudstack.api.BaseCmd.CommandType;
+ import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+ import org.apache.cloudstack.api.response.PodResponse;
+ import org.apache.cloudstack.api.Parameter;
+ import org.apache.cloudstack.api.ServerApiException;
++import org.apache.cloudstack.context.CallContext;
++
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.baremetal.database.BaremetalDhcpVO;
+ import com.cloud.baremetal.networkservice.BaremetalDhcpManager;
+ import com.cloud.baremetal.networkservice.BaremetalDhcpResponse;
+ import com.cloud.event.EventTypes;
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.NetworkRuleConflictException;
+ import com.cloud.exception.ResourceAllocationException;
+ import com.cloud.exception.ResourceUnavailableException;
 -import com.cloud.user.UserContext;
+ @APICommand(name="addBaremetalDhcp", description="adds a baremetal dhcp server", responseObject = BaremetalDhcpResponse.class)
+ public class AddBaremetalDhcpCmd extends BaseAsyncCmd {
+     private static final String s_name = "addexternaldhcpresponse";
+     public static final Logger s_logger = Logger.getLogger(AddBaremetalDhcpCmd.class);
+     
+     @Inject BaremetalDhcpManager mgr;
+     
+     /////////////////////////////////////////////////////
+     //////////////// API parameters /////////////////////
+     /////////////////////////////////////////////////////
+     @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, required=true, description="the Physical Network ID")
+     private Long physicalNetworkId;
+     
+     @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, required = true, description="Pod Id")
+     private Long podId;
+     
+     @Parameter(name=ApiConstants.DHCP_SERVER_TYPE, type=CommandType.STRING, required = true, description="Type of dhcp device")
+     private String dhcpType;
+     
+     @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external dhcp appliance.")
+     private String url;
+ 
+     @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to reach external dhcp device")
+     private String username;
+     
+     @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to reach external dhcp device")
+     private String password;
+     
+     @Override
+     public String getEventType() {
+         return EventTypes.EVENT_BAREMETAL_DHCP_SERVER_ADD;
+     }
+ 
+     @Override
+     public String getEventDescription() {
+         return "Adding an external DHCP server";
+     }
+ 
+     @Override
+     public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+             ResourceAllocationException, NetworkRuleConflictException {
+         try {
+             BaremetalDhcpVO vo = mgr.addDchpServer(this);
+             BaremetalDhcpResponse response = mgr.generateApiResponse(vo);
+             response.setObjectName(s_name);
+             response.setResponseName(getCommandName());
+             this.setResponseObject(response);
+         } catch (Exception e) {
+             s_logger.warn("Unable to add external dhcp server with url: " + getUrl(), e);
+             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
+         }
+     }
+ 
+     @Override
+     public String getCommandName() {
+         return s_name;
+     }
+ 
+     @Override
+     public long getEntityOwnerId() {
 -        return UserContext.current().getCaller().getId();
++        return CallContext.current().getCallingAccount().getId();
+     }
+ 
+     public Long getPodId() {
+         return podId;
+     }
+ 
+     public void setPodId(Long podId) {
+         this.podId = podId;
+     }
+ 
+     public String getDhcpType() {
+         return dhcpType;
+     }
+ 
+     public void setDhcpType(String dhcpType) {
+         this.dhcpType = dhcpType;
+     }
+ 
+     public String getUrl() {
+         return url;
+     }
+ 
+     public void setUrl(String url) {
+         this.url = url;
+     }
+ 
+     public String getUsername() {
+         return username;
+     }
+ 
+     public void setUsername(String username) {
+         this.username = username;
+     }
+ 
+     public String getPassword() {
+         return password;
+     }
+ 
+     public void setPassword(String password) {
+         this.password = password;
+     }
+ 
+     public Long getPhysicalNetworkId() {
+         return physicalNetworkId;
+     }
+ 
+     public void setPhysicalNetworkId(Long physicalNetworkId) {
+         this.physicalNetworkId = physicalNetworkId;
+     }
+ }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalPxeCmd.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalPxeCmd.java
index 0000000,e1b39e9..49effca
mode 000000,100755..100755
--- a/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalPxeCmd.java
+++ b/plugins/hypervisors/baremetal/src/org/apache/cloudstack/api/AddBaremetalPxeCmd.java
@@@ -1,0 -1,148 +1,149 @@@
+ // 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.
+ // 
+ // Automatically generated by addcopyright.py at 01/29/2013
+ package org.apache.cloudstack.api;
+ 
+ import javax.inject.Inject;
+ 
+ import org.apache.cloudstack.api.APICommand;
+ import org.apache.cloudstack.api.ApiConstants;
+ import org.apache.cloudstack.api.ApiErrorCode;
+ import org.apache.cloudstack.api.BaseAsyncCmd;
+ import org.apache.cloudstack.api.BaseCmd;
+ import org.apache.cloudstack.api.BaseCmd.CommandType;
+ import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
+ import org.apache.cloudstack.api.response.PodResponse;
+ import org.apache.cloudstack.api.Parameter;
+ import org.apache.cloudstack.api.ServerApiException;
++import org.apache.cloudstack.context.CallContext;
++
+ import org.apache.log4j.Logger;
+ 
+ import com.cloud.baremetal.database.BaremetalPxeVO;
+ import com.cloud.baremetal.networkservice.BaremetalPxeManager;
+ import com.cloud.event.EventTypes;
+ import com.cloud.exception.ConcurrentOperationException;
+ import com.cloud.exception.InsufficientCapacityException;
+ import com.cloud.exception.NetworkRuleConflictException;
+ import com.cloud.exception.ResourceAllocationException;
+ import com.cloud.exception.ResourceUnavailableException;
 -import com.cloud.user.UserContext;
+ public class AddBaremetalPxeCmd extends BaseAsyncCmd {
+     private static final String s_name = "addexternalpxeresponse";
+     public static final Logger s_logger = Logger.getLogger(AddBaremetalPxeCmd.class);
+     
+     @Inject BaremetalPxeManager pxeMgr;
+     /////////////////////////////////////////////////////
+     //////////////// API parameters /////////////////////
+     /////////////////////////////////////////////////////
+     @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, required=true, description="the Physical Network ID")
+     private Long physicalNetworkId;
+     
+     @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, description="Pod Id")
+     private Long podId;
+     
+     @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external pxe device")
+     private String url;
+ 
+     @Parameter(name=ApiConstants.PXE_SERVER_TYPE, type=CommandType.STRING, required = true, description="type of pxe device")
+     private String deviceType;
+     
+     @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required = true, description="Credentials to reach external pxe device")
+     private String username;
+     
+     @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required = true, description="Credentials to reach external pxe device")
+     private String password;
+     
+     @Override
+     public String getEventType() {
+         return EventTypes.EVENT_BAREMETAL_PXE_SERVER_ADD;
+     }
+ 
+     @Override
+     public String getEventDescription() {
+         return "Adding an external pxe server";
+     }
+ 
+     @Override
+     public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
+             ResourceAllocationException, NetworkRuleConflictException {
+         try {
+             BaremetalPxeVO vo = pxeMgr.addPxeServer(this);
+         } catch (Exception e) {
+             s_logger.warn("Unable to add external pxe server with url: " + getUrl(), e);
+             throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); 
+         }
+     }
+ 
+     @Override
+     public String getCommandName() {
+         return s_name;
+     }
+ 
+     @Override
+     public long getEntityOwnerId() {
 -        return UserContext.current().getCaller().getId();
++        return CallContext.current().getCallingAccount().getId();
+     }
+ 
+     public Long getPhysicalNetworkId() {
+         return physicalNetworkId;
+     }
+ 
+     public void setPhysicalNetworkId(Long physicalNetworkId) {
+         this.physicalNetworkId = physicalNetworkId;
+     }
+ 
+     public Long getPodId() {
+         return podId;
+     }
+ 
+     public void setPodId(Long podId) {
+         this.podId = podId;
+     }
+ 
+     public String getUrl() {
+         return url;
+     }
+ 
+     public void setUrl(String url) {
+         this.url = url;
+     }
+ 
+     public String getUsername() {
+         return username;
+     }
+ 
+     public void setUsername(String username) {
+         this.username = username;
+     }
+ 
+     public String getPassword() {
+         return password;
+     }
+ 
+     public void setPassword(String password) {
+         this.password = password;
+     }
+ 
+     public String getDeviceType() {
+         return deviceType;
+     }
+ 
+     public void setDeviceType(String deviceType) {
+         this.deviceType = deviceType;
+     }
+ }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 1d847d1,46003e9..a5548c5
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@@ -66,11 -73,6 +66,14 @@@ import org.libvirt.DomainSnapshot
  import org.libvirt.LibvirtException;
  import org.libvirt.NodeInfo;
  
++import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
++import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
++import org.apache.cloudstack.storage.to.VolumeObjectTO;
 +import org.apache.cloudstack.utils.qemu.QemuImg;
 +import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
 +import org.apache.cloudstack.utils.qemu.QemuImgException;
 +import org.apache.cloudstack.utils.qemu.QemuImgFile;
 +
  import com.cloud.agent.api.Answer;
  import com.cloud.agent.api.AttachIsoCommand;
  import com.cloud.agent.api.AttachVolumeAnswer;
@@@ -832,6 -842,10 +844,10 @@@ ServerResource 
  
          configureVifDrivers(params);
  
 -        KVMStorageProcessor storageProcessor = new KVMStorageProcessor(this._storagePoolMgr, this);
++        KVMStorageProcessor storageProcessor = new KVMStorageProcessor(_storagePoolMgr, this);
+         storageProcessor.configure(name, params);
+         storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor);
+ 
          return true;
      }
  
@@@ -1243,6 -1252,8 +1254,8 @@@
                  return execute((CheckNetworkCommand) cmd);
              } else if (cmd instanceof NetworkRulesVmSecondaryIpCommand) {
                  return execute((NetworkRulesVmSecondaryIpCommand) cmd);
+             } else if (cmd instanceof StorageSubSystemCommand) {
 -                return this.storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
++                return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
              } else if (cmd instanceof PvlanSetupCommand) {
                  return execute((PvlanSetupCommand) cmd);
              } else {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java
index 3f153a0,951badd..2e23ba6
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/OvsVifDriver.java
@@@ -93,12 -94,12 +94,12 @@@ public class OvsVifDriver extends VifDr
                  }
              } else if (nic.getBroadcastType() == Networks.BroadcastDomainType.Lswitch) {
                  s_logger.debug("nic " + nic + " needs to be connected to LogicalSwitch " + logicalSwitchUuid);
 -                intf.setVirtualPortInterfaceId(nic.getUuid());
 +                intf.setVirtualPortInterfaceId(nic.getNicUuid());
                  String brName = (trafficLabel != null && !trafficLabel.isEmpty()) ? _pifs.get(trafficLabel) : _pifs.get("private");
-                 intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType));
+                 intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
              }
              else {
-                 intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType));
+                 intf.defBridgeNet(_bridges.get("guest"), null, nic.getMac(), getGuestNicModel(guestOsType), networkRateKBps);
              }
          } else if (nic.getType() == Networks.TrafficType.Control) {
              /* Make sure the network is still there */

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java
index 089d46d,59ba001..11fa65c
--- a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java
+++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmResourceBase.java
@@@ -123,10 -129,8 +129,9 @@@ import com.cloud.utils.script.Script
  import com.cloud.utils.ssh.SSHCmdHelper;
  import com.cloud.vm.DiskProfile;
  import com.cloud.vm.VirtualMachine;
 +import com.cloud.vm.VirtualMachine.PowerState;
  import com.cloud.vm.VirtualMachine.State;
  import com.trilead.ssh2.SCPClient;
- import com.xensource.xenapi.Types.XenAPIException;
  
  public class OvmResourceBase implements ServerResource, HypervisorResource {
  	private static final Logger s_logger = Logger.getLogger(OvmResourceBase.class);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java
index 58840c8,8a03c4b..1263d7d
--- a/plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java
+++ b/plugins/hypervisors/simulator/src/com/cloud/resource/AgentRoutingResource.java
@@@ -51,9 -51,8 +51,9 @@@ import com.cloud.hypervisor.Hypervisor.
  import com.cloud.network.Networks.RouterPrivateIpStrategy;
  import com.cloud.simulator.MockVMVO;
  import com.cloud.storage.Storage.StorageResourceType;
- import com.cloud.storage.template.TemplateInfo;
+ import com.cloud.storage.template.TemplateProp;
  import com.cloud.utils.Pair;
 +import com.cloud.vm.VirtualMachine.PowerState;
  import com.cloud.vm.VirtualMachine.State;
  
  public class AgentRoutingResource extends AgentStorageResource {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java
index 21ec998,95521e8..60839b1
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/guru/VMwareGuru.java
@@@ -27,8 -27,11 +27,10 @@@ import java.util.Map
  import javax.ejb.Local;
  import javax.inject.Inject;
  
 -import org.apache.cloudstack.api.ApiConstants.VMDetails;
 -import org.apache.cloudstack.storage.command.CopyCommand;
  import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
 +
++import org.apache.cloudstack.storage.command.CopyCommand;
+ 
  import com.cloud.agent.api.BackupSnapshotCommand;
  import com.cloud.agent.api.Command;
  import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
@@@ -284,9 -291,26 +290,26 @@@ public class VMwareGuru extends Hypervi
                  cmd instanceof CopyVolumeCommand ||
                  cmd instanceof CreateVolumeOVACommand ||
                  cmd instanceof PrepareOVAPackingCommand ||
-                 cmd instanceof CreateVolumeFromSnapshotCommand) {
+                 cmd instanceof CreateVolumeFromSnapshotCommand ||
+                 cmd instanceof CopyCommand) {
+             if (cmd instanceof CopyCommand) {
+                 CopyCommand cpyCommand = (CopyCommand)cmd;
+                 DataTO srcData = cpyCommand.getSrcTO();
+                 DataStoreTO srcStoreTO = srcData.getDataStore();
+                 DataTO destData = cpyCommand.getDestTO();
+                 DataStoreTO destStoreTO = destData.getDataStore();
+                 
+                 if (destData.getObjectType() == DataObjectType.VOLUME && destStoreTO.getRole() == DataStoreRole.Primary &&
+                         srcData.getObjectType() == DataObjectType.TEMPLATE && srcStoreTO.getRole() == DataStoreRole.Primary) {
+                     needDelegation = false;
+                 } else {
 -                    needDelegation = true;
 -                }
 +            needDelegation = true;
 +        }
+             } else {
+                 needDelegation = true;
+             }
+             
+         }
          /* Fang: remove this before checking in */
          // needDelegation = false;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/VmwareServerDiscoverer.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
index 93e6b5f,4ae0f30..887c81d
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/manager/VmwareStorageManagerImpl.java
@@@ -25,12 -25,12 +25,23 @@@ import java.rmi.RemoteException
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;
--import java.util.Properties;
  import java.util.Map;
++import java.util.Properties;
  import java.util.UUID;
  
  import org.apache.log4j.Logger;
  
++import com.vmware.vim25.ManagedObjectReference;
++import com.vmware.vim25.TaskInfo;
++import com.vmware.vim25.VirtualDeviceConfigSpec;
++import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
++import com.vmware.vim25.VirtualDisk;
++import com.vmware.vim25.VirtualLsiLogicController;
++import com.vmware.vim25.VirtualMachineConfigSpec;
++import com.vmware.vim25.VirtualMachineFileInfo;
++import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
++import com.vmware.vim25.VirtualSCSISharing;
++
  import com.cloud.agent.api.Answer;
  import com.cloud.agent.api.BackupSnapshotAnswer;
  import com.cloud.agent.api.BackupSnapshotCommand;
@@@ -46,11 -46,11 +57,10 @@@ import com.cloud.agent.api.RevertToVMSn
  import com.cloud.agent.api.RevertToVMSnapshotCommand;
  import com.cloud.agent.api.storage.CopyVolumeAnswer;
  import com.cloud.agent.api.storage.CopyVolumeCommand;
--import com.cloud.agent.api.storage.PrepareOVAPackingAnswer;
--import com.cloud.agent.api.storage.PrepareOVAPackingCommand;
++import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
  import com.cloud.agent.api.storage.CreateVolumeOVAAnswer;
  import com.cloud.agent.api.storage.CreateVolumeOVACommand;
--import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
++import com.cloud.agent.api.storage.PrepareOVAPackingCommand;
  import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
  import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
  import com.cloud.agent.api.to.StorageFilerTO;
@@@ -60,7 -60,7 +70,6 @@@ import com.cloud.hypervisor.vmware.mo.D
  import com.cloud.hypervisor.vmware.mo.DatastoreMO;
  import com.cloud.hypervisor.vmware.mo.HostMO;
  import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper;
--import com.cloud.hypervisor.vmware.mo.TaskMO;
  import com.cloud.hypervisor.vmware.mo.VirtualMachineMO;
  import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost;
  import com.cloud.hypervisor.vmware.util.VmwareContext;
@@@ -76,17 -76,17 +85,6 @@@ import com.cloud.utils.Ternary
  import com.cloud.utils.script.Script;
  import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.snapshot.VMSnapshot;
--import com.vmware.vim25.ManagedObjectReference;
--import com.vmware.vim25.TaskEvent;
--import com.vmware.vim25.TaskInfo;
--import com.vmware.vim25.VirtualDeviceConfigSpec;
--import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
--import com.vmware.vim25.VirtualDisk;
--import com.vmware.vim25.VirtualLsiLogicController;
--import com.vmware.vim25.VirtualMachineConfigSpec;
--import com.vmware.vim25.VirtualMachineFileInfo;
--import com.vmware.vim25.VirtualMachineGuestOsIdentifier;
--import com.vmware.vim25.VirtualSCSISharing;
  
  public class VmwareStorageManagerImpl implements VmwareStorageManager {
      private static final Logger s_logger = Logger.getLogger(VmwareStorageManagerImpl.class);
@@@ -111,7 -111,7 +109,7 @@@
      //Fang note: use Answer here instead of the PrepareOVAPackingAnswer
      @Override
      public Answer execute(VmwareHostService hostService, PrepareOVAPackingCommand cmd) {
--		String secStorageUrl = ((PrepareOVAPackingCommand) cmd).getSecondaryStorageUrl();
++		String secStorageUrl = cmd.getSecondaryStorageUrl();
  		assert (secStorageUrl != null);
          String installPath = cmd.getTemplatePath();
          String details = null;
@@@ -165,7 -165,7 +163,7 @@@
      // Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
      @Override
      public Answer execute(VmwareHostService hostService, CreateVolumeOVACommand cmd) {
--		String secStorageUrl = ((CreateVolumeOVACommand) cmd).getSecondaryStorageUrl();
++		String secStorageUrl = cmd.getSecondaryStorageUrl();
  		assert (secStorageUrl != null);
          String installPath = cmd.getVolPath();
          String details = null;
@@@ -1467,8 -1463,8 +1465,4 @@@
              return command.execute();
          }
      }
--
--    private static String getVolumeRelativeDirInSecStroage(long volumeId) {
--        return "volumes/" + volumeId;
--    }
  }


[36/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/template/TemplateManagerImpl.java
index 3317fa1,273614c..2528b54
--- a/server/src/com/cloud/template/TemplateManagerImpl.java
+++ b/server/src/com/cloud/template/TemplateManagerImpl.java
@@@ -16,13 -16,12 +16,8 @@@
  // under the License.
  package com.cloud.template;
  
--import java.net.Inet6Address;
--import java.net.InetAddress;
--import java.net.URI;
  import java.net.URISyntaxException;
--import java.net.UnknownHostException;
  import java.util.ArrayList;
- import java.util.Collections;
  import java.util.Date;
  import java.util.List;
  import java.util.Map;
@@@ -31,15 -29,13 +25,17 @@@ import java.util.UUID
  import java.util.concurrent.ExecutionException;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
 +
  import javax.ejb.Local;
  import javax.inject.Inject;
  import javax.naming.ConfigurationException;
  
++import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
++
  import org.apache.cloudstack.acl.SecurityChecker.AccessType;
  import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd;
+ import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd;
  import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd;
  import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
  import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd;
@@@ -52,40 -49,53 +49,47 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd;
  import org.apache.cloudstack.api.command.user.template.ListTemplatePermissionsCmd;
  import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
+ import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd;
  import org.apache.cloudstack.api.command.user.template.UpdateTemplatePermissionsCmd;
 +import org.apache.cloudstack.context.CallContext;
- 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.DataStoreRole;
- 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.EndPoint;
+ import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
+ import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
 -import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager;
 -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
 -import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
  import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
++import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager;
++import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
  import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
++import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult;
  import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
  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.jobs.AsyncJobManager;
- import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
+ import org.apache.cloudstack.storage.command.AttachCommand;
+ import org.apache.cloudstack.storage.command.CommandResult;
 -import org.apache.cloudstack.storage.command.CopyCommand;
+ import org.apache.cloudstack.storage.command.DettachCommand;
+ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
- import org.apache.log4j.Logger;
- import org.springframework.stereotype.Component;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
+ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
+ import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
  
 -import com.amazonaws.services.s3.model.CannedAccessControlList;
  import com.cloud.agent.AgentManager;
  import com.cloud.agent.api.Answer;
- import com.cloud.agent.api.AttachIsoCommand;
+ import com.cloud.agent.api.Command;
  import com.cloud.agent.api.ComputeChecksumCommand;
- import com.cloud.agent.api.DownloadTemplateFromSwiftToSecondaryStorageCommand;
- import com.cloud.agent.api.UploadTemplateToSwiftFromSecondaryStorageCommand;
 -
  import com.cloud.agent.api.storage.DestroyCommand;
- import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
- import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
- import com.cloud.agent.api.to.SwiftTO;
- 
+ import com.cloud.agent.api.to.DataTO;
+ import com.cloud.agent.api.to.DiskTO;
+ import com.cloud.agent.api.to.NfsTO;
 -import com.cloud.agent.api.to.S3TO;
  import com.cloud.api.ApiDBUtils;
+ import com.cloud.api.query.dao.UserVmJoinDao;
+ import com.cloud.api.query.vo.UserVmJoinVO;
 -import com.cloud.async.AsyncJobManager;
 -import com.cloud.async.AsyncJobVO;
  import com.cloud.configuration.Config;
  import com.cloud.configuration.Resource.ResourceType;
  import com.cloud.configuration.dao.ConfigurationDao;
@@@ -104,7 -114,7 +108,6 @@@ import com.cloud.exception.InvalidParam
  import com.cloud.exception.PermissionDeniedException;
  import com.cloud.exception.ResourceAllocationException;
  import com.cloud.exception.StorageUnavailableException;
- import com.cloud.host.Host;
 -import com.cloud.exception.UnsupportedServiceException;
  import com.cloud.host.HostVO;
  import com.cloud.host.dao.HostDao;
  import com.cloud.hypervisor.Hypervisor;
@@@ -112,34 -122,34 +115,29 @@@ import com.cloud.hypervisor.Hypervisor.
  import com.cloud.hypervisor.HypervisorGuruManager;
  import com.cloud.projects.Project;
  import com.cloud.projects.ProjectManager;
--
  import com.cloud.resource.ResourceManager;
  import com.cloud.server.ConfigurationServer;
++import com.cloud.storage.DataStoreRole;
  import com.cloud.storage.GuestOSVO;
  import com.cloud.storage.LaunchPermissionVO;
++import com.cloud.storage.ScopeType;
  import com.cloud.storage.Snapshot;
  import com.cloud.storage.SnapshotVO;
  import com.cloud.storage.Storage;
--
  import com.cloud.storage.Storage.ImageFormat;
  import com.cloud.storage.Storage.TemplateType;
 -import com.cloud.storage.DataStoreRole;
 -import com.cloud.storage.ScopeType;
  import com.cloud.storage.StorageManager;
  import com.cloud.storage.StoragePool;
  import com.cloud.storage.StoragePoolHostVO;
  import com.cloud.storage.StoragePoolStatus;
  import com.cloud.storage.TemplateProfile;
  import com.cloud.storage.Upload;
--import com.cloud.storage.Upload.Type;
- 
- import com.cloud.storage.UploadVO;
 -import com.cloud.storage.VMTemplateZoneVO;
 -
 -import com.cloud.storage.UploadVO;
  import com.cloud.storage.VMTemplateHostVO;
  import com.cloud.storage.VMTemplateStoragePoolVO;
  import com.cloud.storage.VMTemplateStorageResourceAssoc;
  import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
- import com.cloud.storage.VMTemplateSwiftVO;
  import com.cloud.storage.VMTemplateVO;
 +import com.cloud.storage.VMTemplateZoneVO;
  import com.cloud.storage.Volume;
  import com.cloud.storage.VolumeManager;
  import com.cloud.storage.VolumeVO;
@@@ -157,12 -166,10 +154,9 @@@ import com.cloud.storage.dao.VMTemplate
  import com.cloud.storage.dao.VMTemplateZoneDao;
  import com.cloud.storage.dao.VolumeDao;
  import com.cloud.storage.download.DownloadMonitor;
- import com.cloud.storage.s3.S3Manager;
  import com.cloud.storage.secondary.SecondaryStorageVmManager;
- import com.cloud.storage.swift.SwiftManager;
  import com.cloud.storage.upload.UploadMonitor;
  import com.cloud.template.TemplateAdapter.TemplateAdapterType;
--
  import com.cloud.user.Account;
  import com.cloud.user.AccountManager;
  import com.cloud.user.AccountService;
@@@ -173,12 -181,14 +167,14 @@@ import com.cloud.user.dao.AccountDao
  import com.cloud.user.dao.UserAccountDao;
  import com.cloud.user.dao.UserDao;
  import com.cloud.uservm.UserVm;
+ import com.cloud.utils.EnumUtils;
  import com.cloud.utils.NumbersUtil;
  import com.cloud.utils.Pair;
  import com.cloud.utils.component.AdapterBase;
  import com.cloud.utils.component.ManagerBase;
  import com.cloud.utils.concurrency.NamedThreadFactory;
--import com.cloud.utils.db.*;
++import com.cloud.utils.db.DB;
++import com.cloud.utils.db.Transaction;
  import com.cloud.utils.exception.CloudRuntimeException;
  import com.cloud.vm.UserVmManager;
  import com.cloud.vm.UserVmVO;
@@@ -230,105 -258,121 +244,121 @@@ public class TemplateManagerImpl extend
      @Inject
      protected GuestOSDao _guestOSDao;
      long _routerTemplateId = -1;
-     @Inject StorageManager _storageMgr;
-     @Inject AsyncJobManager _asyncMgr;
-     @Inject UserVmManager _vmMgr;
-     @Inject UsageEventDao _usageEventDao;
-     @Inject HypervisorGuruManager _hvGuruMgr;
-     @Inject AccountService _accountService;
-     @Inject ResourceLimitService _resourceLimitMgr;
-     @Inject SecondaryStorageVmManager _ssvmMgr;
-     @Inject LaunchPermissionDao _launchPermissionDao;
-     @Inject ProjectManager _projectMgr;
      @Inject
-     VolumeDataFactory volFactory;
+     StorageManager _storageMgr;
+     @Inject
+     AsyncJobManager _asyncMgr;
+     @Inject
+     UserVmManager _vmMgr;
      @Inject
-     ImageDataFactory tmplFactory;
+     UsageEventDao _usageEventDao;
      @Inject
-     SnapshotDataFactory snapshotFactory;
+     HypervisorGuruManager _hvGuruMgr;
      @Inject
-     ImageService imageSvr;
+     AccountService _accountService;
      @Inject
-     DataStoreManager dataStoreMgr;
+     ResourceLimitService _resourceLimitMgr;
+     @Inject
+     SecondaryStorageVmManager _ssvmMgr;
+     @Inject
+     LaunchPermissionDao _launchPermissionDao;
+     @Inject
+     ProjectManager _projectMgr;
+     @Inject
+     VolumeDataFactory _volFactory;
+     @Inject
+     TemplateDataFactory _tmplFactory;
+     @Inject
+     SnapshotDataFactory _snapshotFactory;
+     @Inject
+     TemplateService _tmpltSvr;
+     @Inject
+     DataStoreManager _dataStoreMgr;
      @Inject
      protected ResourceManager _resourceMgr;
-     @Inject VolumeManager volumeMgr;
-     @Inject VMTemplateHostDao templateHostDao;
      @Inject
-     ConfigurationServer _configServer;
+     VolumeManager _volumeMgr;
+     @Inject
+     ImageStoreDao _imageStoreDao;
+     @Inject
+     EndPointSelector _epSelector;
+     @Inject
+     UserVmJoinDao _userVmJoinDao;
  
+     @Inject
+     ConfigurationServer _configServer;
 -
 +    
      int _primaryStorageDownloadWait;
-     protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
-     
      int _storagePoolMaxWaitSeconds = 3600;
      boolean _disableExtraction = false;
      ExecutorService _preloadExecutor;
  
      @Inject
      protected List<TemplateAdapter> _adapters;
 -
 +    
+     @Inject
+     StorageCacheManager cacheMgr;
+     @Inject
+     EndPointSelector selector;
+ 
      private TemplateAdapter getAdapter(HypervisorType type) {
 -        TemplateAdapter adapter = null;
 -        if (type == HypervisorType.BareMetal) {
 -            adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName());
 -        } else {
 -            // see HypervisorTemplateAdapter
 -            adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.Hypervisor.getName());
 -        }
 -
 -        if (adapter == null) {
 -            throw new CloudRuntimeException("Cannot find template adapter for " + type.toString());
 -        }
 -
 -        return adapter;
 +    	TemplateAdapter adapter = null;
 +    	if (type == HypervisorType.BareMetal) {
 +    		adapter = AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.BareMetal.getName());
 +    	} else {
 +    		// see HypervisorTemplateAdapter
 +    		adapter =  AdapterBase.getAdapterByName(_adapters, TemplateAdapterType.Hypervisor.getName());
 +    	}
 +    	
 +    	if (adapter == null) {
 +    		throw new CloudRuntimeException("Cannot find template adapter for " + type.toString());
 +    	}
 +    	
 +    	return adapter;
      }
 -
 +    
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_ISO_CREATE, eventDescription = "creating iso")
-     public VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws ResourceAllocationException{
+     public VirtualMachineTemplate registerIso(RegisterIsoCmd cmd) throws ResourceAllocationException {
 -        TemplateAdapter adapter = getAdapter(HypervisorType.None);
 -        TemplateProfile profile = adapter.prepare(cmd);
 -        VMTemplateVO template = adapter.create(profile);
 -
 +    	TemplateAdapter adapter = getAdapter(HypervisorType.None);
-     	TemplateProfile profile = adapter.prepare(cmd);    	
++    	TemplateProfile profile = adapter.prepare(cmd);
 +    	VMTemplateVO template = adapter.create(profile);
 +    	
-     	if (template != null){
+         if (template != null) {
 -            return template;
 +        	return template;
-         }else {
+         } else {
 -            throw new CloudRuntimeException("Failed to create ISO");
 +        	throw new CloudRuntimeException("Failed to create ISO");
          }
      }
  
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
-     public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException{
-         if(cmd.getTemplateTag() != null){
+     public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
+         if (cmd.getTemplateTag() != null) {
 -            Account account = UserContext.current().getCaller();
 +            Account account = CallContext.current().getCallingAccount();
-             if(!_accountService.isRootAdmin(account.getType())){
+             if (!_accountService.isRootAdmin(account.getType())) {
                  throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
              }
          }
 -
 -        TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
 -        TemplateProfile profile = adapter.prepare(cmd);
 -        VMTemplateVO template = adapter.create(profile);
 -
 +        
 +    	TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
 +    	TemplateProfile profile = adapter.prepare(cmd);
 +    	VMTemplateVO template = adapter.create(profile);
 +    	
-     	if (template != null){
+         if (template != null) {
 -            return template;
 +        	return template;
-         }else {
+         } else {
 -            throw new CloudRuntimeException("Failed to create a template");
 +        	throw new CloudRuntimeException("Failed to create a template");
          }
      }
 -
 +    
      @Override
      public DataStore getImageStore(String storeUuid, Long zoneId) {
          DataStore imageStore = null;
          if (storeUuid != null) {
-             imageStore = this.dataStoreMgr.getDataStore(storeUuid, DataStoreRole.Image);
 -            imageStore = this._dataStoreMgr.getDataStore(storeUuid, DataStoreRole.Image);
++            imageStore = _dataStoreMgr.getDataStore(storeUuid, DataStoreRole.Image);
          } else {
-             List<DataStore> stores = this.dataStoreMgr.getImageStores(new ZoneScope(zoneId));
 -            List<DataStore> stores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
++            List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
              if (stores.size() > 1) {
                  throw new CloudRuntimeException("multiple image stores, don't know which one to use");
              }
@@@ -340,27 -384,21 +370,21 @@@
  
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_ISO_EXTRACT, eventDescription = "extracting ISO", async = true)
-     public Long extract(ExtractIsoCmd cmd) {
-         Account account = CallContext.current().getCallingAccount();
+     public String extract(ExtractIsoCmd cmd) {
 -        Account account = UserContext.current().getCaller();
++    Account account = CallContext.current().getCallingAccount();
          Long templateId = cmd.getId();
          Long zoneId = cmd.getZoneId();
          String url = cmd.getUrl();
          String mode = cmd.getMode();
          Long eventId = cmd.getStartEventId();
 -
 +        
-         // FIXME: async job needs fixing
-         Long uploadId = extract(account, templateId, url, zoneId, mode, eventId, true, null, _asyncMgr);
-         if (uploadId != null){
-         	return uploadId;
-         }else {
-         	throw new CloudRuntimeException("Failed to extract the iso");
-         }
+         return extract(account, templateId, url, zoneId, mode, eventId, true);
      }
  
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_EXTRACT, eventDescription = "extracting template", async = true)
-     public Long extract(ExtractTemplateCmd cmd) {
-         Account caller = CallContext.current().getCallingAccount();
+     public String extract(ExtractTemplateCmd cmd) {
 -        Account caller = UserContext.current().getCaller();
++    Account caller = CallContext.current().getCallingAccount();
          Long templateId = cmd.getId();
          Long zoneId = cmd.getZoneId();
          String url = cmd.getUrl();
@@@ -374,52 -412,48 +398,48 @@@
          TemplateAdapter adapter = getAdapter(template.getHypervisorType());
          TemplateProfile profile = adapter.prepareExtractTemplate(cmd);
  
-         // FIXME: async job needs fixing
-         Long uploadId = extract(caller, templateId, url, zoneId, mode, eventId, false, null, _asyncMgr);
-         if (uploadId != null){
-         	return uploadId;
-         }else {
-         	throw new CloudRuntimeException("Failed to extract the teamplate");
-         }
+         return extract(caller, templateId, url, zoneId, mode, eventId, false);
      }
 -
 +    
      @Override
      public VirtualMachineTemplate prepareTemplate(long templateId, long zoneId) {
 -
 -        VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
 +    	
 +    	VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
-     	if(vmTemplate == null)
+         if (vmTemplate == null)
 -            throw new InvalidParameterValueException("Unable to find template id=" + templateId);
 -
 -        _accountMgr.checkAccess(UserContext.current().getCaller(), AccessType.ModifyEntry, true, vmTemplate);
 -
 -        prepareTemplateInAllStoragePools(vmTemplate, zoneId);
 -        return vmTemplate;
 +    		throw new InvalidParameterValueException("Unable to find template id=" + templateId);
 +    	
 +    	_accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.ModifyEntry, true, vmTemplate);
 +    	
 +    	prepareTemplateInAllStoragePools(vmTemplate, zoneId);
 +    	return vmTemplate;
      }
  
-     private Long extract(Account caller, Long templateId, String url, Long zoneId, String mode, Long eventId, boolean isISO, AsyncJobVO job, AsyncJobManager mgr) {
+     private String extract(Account caller, Long templateId, String url, Long zoneId, String mode, Long eventId, boolean isISO) {
          String desc = Upload.Type.TEMPLATE.toString();
          if (isISO) {
              desc = Upload.Type.ISO.toString();
          }
-         eventId = eventId == null ? 0:eventId;
+         eventId = eventId == null ? 0 : eventId;
 -
 +        
          if (!_accountMgr.isRootAdmin(caller.getType()) && _disableExtraction) {
              throw new PermissionDeniedException("Extraction has been disabled by admin");
          }
 -
 +        
          VMTemplateVO template = _tmpltDao.findById(templateId);
          if (template == null || template.getRemoved() != null) {
-             throw new InvalidParameterValueException("Unable to find " +desc+ " with id " + templateId);
+             throw new InvalidParameterValueException("Unable to find " + desc + " with id " + templateId);
          }
 -
 +        
-         if (template.getTemplateType() ==  Storage.TemplateType.SYSTEM){
-             throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it is a default System template");
-         } else if (template.getTemplateType() ==  Storage.TemplateType.PERHOST){
-             throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it resides on host and not on SSVM");
+         if (template.getTemplateType() == Storage.TemplateType.SYSTEM) {
+             throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName()
+                     + " as it is a default System template");
+         } else if (template.getTemplateType() == Storage.TemplateType.PERHOST) {
+             throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName()
+                     + " as it resides on host and not on SSVM");
          }
 -
 +        
          if (isISO) {
-             if (template.getFormat() != ImageFormat.ISO ){
+             if (template.getFormat() != ImageFormat.ISO) {
                  throw new InvalidParameterValueException("Unsupported format, could not extract the ISO");
              }
          } else {
@@@ -427,493 -461,180 +447,180 @@@
                  throw new InvalidParameterValueException("Unsupported format, could not extract the template");
              }
          }
 -
 +        
- 		if (zoneId == null && _swiftMgr.isSwiftEnabled()) {
-             zoneId = _swiftMgr.chooseZoneForTmpltExtract(templateId);
-         }
- 
-         if (zoneId == null && _s3Mgr.isS3Enabled()) {
-             zoneId = _s3Mgr.chooseZoneForTemplateExtract(template);
-         }
- 
-         if (_dcDao.findById(zoneId) == null) {
+         if (zoneId != null && _dcDao.findById(zoneId) == null) {
              throw new IllegalArgumentException("Please specify a valid zone.");
          }
 -
 +        
          if (!_accountMgr.isRootAdmin(caller.getType()) && !template.isExtractable()) {
              throw new InvalidParameterValueException("Unable to extract template id=" + templateId + " as it's not extractable");
          }
 -
 +        
          _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
 -
 -        List<DataStore> ssStores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
 +        
-         List<HostVO> sservers = getSecondaryStorageHosts(zoneId);
- 
-         VMTemplateHostVO tmpltHostRef = null;
-         if (sservers != null) {
-             for(HostVO secondaryStorageHost: sservers){
-                 tmpltHostRef = _tmpltHostDao.findByHostTemplate(secondaryStorageHost.getId(), templateId);
-                 if (tmpltHostRef != null){
-                     if (tmpltHostRef.getDownloadState() != com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
-                         tmpltHostRef = null;
-                     }
-                     else {
++        List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
+ 
+         TemplateDataStoreVO tmpltStoreRef = null;
+         ImageStoreEntity tmpltStore = null;
+         if (ssStores != null) {
+             for (DataStore store : ssStores) {
 -                tmpltStoreRef = this._tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
++                tmpltStoreRef = _tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
+                 if (tmpltStoreRef != null) {
+                     if (tmpltStoreRef.getDownloadState() == com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
+                         tmpltStore = (ImageStoreEntity) store;
                          break;
                      }
                  }
              }
          }
 -
 +        
-         if (tmpltHostRef == null && _swiftMgr.isSwiftEnabled()) {
-             SwiftTO swift = _swiftMgr.getSwiftTO(templateId);
-             if (swift != null && sservers != null) {
-                 downloadTemplateFromSwiftToSecondaryStorage(zoneId, templateId);
-             }
-         } else if (tmpltHostRef == null && _s3Mgr.isS3Enabled()) {
-             if (sservers != null) {
-                 _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(zoneId,
-                         templateId, _primaryStorageDownloadWait);
-             }
-         }
- 
-         if (tmpltHostRef == null) {
+         if (tmpltStoreRef == null) {
              throw new InvalidParameterValueException("The " + desc + " has not been downloaded ");
          }
 -
 +        
-         Upload.Mode extractMode;
-         if (mode == null || (!mode.equalsIgnoreCase(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equalsIgnoreCase(Upload.Mode.HTTP_DOWNLOAD.toString())) ){
-             throw new InvalidParameterValueException("Please specify a valid extract Mode. Supported modes: "+ Upload.Mode.FTP_UPLOAD + ", " + Upload.Mode.HTTP_DOWNLOAD);
-         } else {
-             extractMode = mode.equalsIgnoreCase(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD;
-         }
-         
-         if (extractMode == Upload.Mode.FTP_UPLOAD){
-             URI uri = null;
-             try {
-                 uri = new URI(url);
-                 if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp") )) {
-                    throw new InvalidParameterValueException("Unsupported scheme for url: " + url);
-                 }
-             } catch (Exception ex) {
-                 throw new InvalidParameterValueException("Invalid url given: " + url);
-             }
-     
-             String host = uri.getHost();
-             try {
-                 InetAddress hostAddr = InetAddress.getByName(host);
-                 if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress() || hostAddr.isMulticastAddress() ) {
-                     throw new InvalidParameterValueException("Illegal host specified in url");
-                 }
-                 if (hostAddr instanceof Inet6Address) {
-                     throw new InvalidParameterValueException("IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
-                 }
-             } catch (UnknownHostException uhe) {
-                 throw new InvalidParameterValueException("Unable to resolve " + host);
-             }
-                     
-             if (_uploadMonitor.isTypeUploadInProgress(templateId, isISO ? Type.ISO : Type.TEMPLATE) ){
-                 throw new IllegalArgumentException(template.getName() + " upload is in progress. Please wait for some time to schedule another upload for the same"); 
-             }
-         
-             return _uploadMonitor.extractTemplate(template, url, tmpltHostRef, zoneId, eventId, job.getId(), mgr);            
-         }
-         
-         UploadVO vo = _uploadMonitor.createEntityDownloadURL(template, tmpltHostRef, zoneId, eventId);
-         if (vo != null){                                  
-             return vo.getId();
-         }else{
-             return null;
-         }
+         return tmpltStore.createEntityExtractUrl(tmpltStoreRef.getInstallPath(), template.getFormat());
      }
 -
 +    
      public void prepareTemplateInAllStoragePools(final VMTemplateVO template, long zoneId) {
 -        List<StoragePoolVO> pools = _poolDao.listByStatus(StoragePoolStatus.Up);
 +    	List<StoragePoolVO> pools = _poolDao.listByStatus(StoragePoolStatus.Up);
-     	for(final StoragePoolVO pool : pools) {
-     		if(pool.getDataCenterId() == zoneId) {
+         for (final StoragePoolVO pool : pools) {
+             if (pool.getDataCenterId() == zoneId) {
 -                s_logger.info("Schedule to preload template " + template.getId() + " into primary storage " + pool.getId());
 -                this._preloadExecutor.execute(new Runnable() {
 +    			s_logger.info("Schedule to preload template " + template.getId() + " into primary storage " + pool.getId());
- 	    		this._preloadExecutor.execute(new Runnable() {
++	    		_preloadExecutor.execute(new Runnable() {
+                     @Override
 -                    public void run() {
 -                        try {
 -                            reallyRun();
 +	    			public void run() {
 +	    				try {
 +	    					reallyRun();
- 	    				} catch(Throwable e) {
+                         } catch (Throwable e) {
 -                            s_logger.warn("Unexpected exception ", e);
 -                        }
 -                    }
 -
 -                    private void reallyRun() {
 -                        s_logger.info("Start to preload template " + template.getId() + " into primary storage " + pool.getId());
 +	    					s_logger.warn("Unexpected exception ", e);
 +	    				}
 +	    			}
 +	    			
 +	    			private void reallyRun() {
 +	        			s_logger.info("Start to preload template " + template.getId() + " into primary storage " + pool.getId());
- 	        			StoragePool pol = (StoragePool)dataStoreMgr.getPrimaryDataStore(pool.getId());
+                         StoragePool pol = (StoragePool) _dataStoreMgr.getPrimaryDataStore(pool.getId());
 -                        prepareTemplateForCreate(template, pol);
 -                        s_logger.info("End of preloading template " + template.getId() + " into primary storage " + pool.getId());
 -                    }
 -                });
 -            } else {
 +	        			prepareTemplateForCreate(template, pol);
 +	        			s_logger.info("End of preloading template " + template.getId() + " into primary storage " + pool.getId());
 +	    			}
 +	    		});
 +    		} else {
-     			s_logger.info("Skip loading template " + template.getId() + " into primary storage " + pool.getId() + " as pool zone " + pool.getDataCenterId() + " is ");
-     		}
-     	}
-     }
-     
-     String downloadTemplateFromSwiftToSecondaryStorage(long dcId, long templateId){
-         VMTemplateVO template = _tmpltDao.findById(templateId);
-         if ( template == null ) {
-             String errMsg = " Can not find template " + templateId;
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
-         VMTemplateSwiftVO tmpltSwift = _swiftMgr.findByTmpltId(templateId);
-         if ( tmpltSwift == null ) {
-             String errMsg = " Template " + templateId + " doesn't exist in swift";
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
-         SwiftTO swift = _swiftMgr.getSwiftTO(tmpltSwift.getSwiftId());
-         if ( swift == null ) {
-             String errMsg = " Swift " + tmpltSwift.getSwiftId() + " doesn't exit ?";
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
- 
-         HostVO secHost = _ssvmMgr.findSecondaryStorageHost(dcId);
-         if ( secHost == null ) {
-             String errMsg = "Can not find secondary storage in data center " + dcId;
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
- 
-         DownloadTemplateFromSwiftToSecondaryStorageCommand cmd = new DownloadTemplateFromSwiftToSecondaryStorageCommand(swift, secHost.getName(), dcId, template.getAccountId(), templateId,
-                 tmpltSwift.getPath(), _primaryStorageDownloadWait);
-         try {
-             Answer answer = _agentMgr.sendToSSVM(dcId, cmd);
-             if (answer == null || !answer.getResult()) {
-                 String errMsg = "Failed to download template from Swift to secondary storage due to " + (answer == null ? "answer is null" : answer.getDetails());
-                 s_logger.warn(errMsg);
-                 throw new CloudRuntimeException(errMsg);
-             }
-             String installPath = "template/tmpl/" + template.getAccountId() + "/" + template.getId() + "/" + tmpltSwift.getPath();
-             VMTemplateHostVO tmpltHost = new VMTemplateHostVO(secHost.getId(), templateId, new Date(), 100, Status.DOWNLOADED, null, null, null, installPath, template.getUrl());
-             tmpltHost.setSize(tmpltSwift.getSize());
-             tmpltHost.setPhysicalSize(tmpltSwift.getPhysicalSize());
-             _tmpltHostDao.persist(tmpltHost);
-         } catch (Exception e) {
-             String errMsg = "Failed to download template from Swift to secondary storage due to " + e.toString();
-             s_logger.warn(errMsg);
-             throw new CloudRuntimeException(errMsg);
-         }
-         return null;
-     }
- 
-     String uploadTemplateToSwiftFromSecondaryStorage(VMTemplateHostVO templateHostRef) {
-         Long templateId = templateHostRef.getTemplateId();
-         VMTemplateVO template = _tmpltDao.findById(templateId);
-         if (template == null) {
-             String errMsg = " Can not find template " + templateId;
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
- 
-         if (template.getTemplateType() == TemplateType.PERHOST) {
-             return null;
-         }
- 
-         SwiftTO swift = _swiftMgr.getSwiftTO();
-         if (swift == null) {
-             String errMsg = " There is no Swift in this setup ";
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
- 
-         HostVO secHost = _hostDao.findById(templateHostRef.getHostId());
-         if (secHost == null) {
-             String errMsg = "Can not find secondary storage " + templateHostRef.getHostId();
-             s_logger.warn(errMsg);
-             return errMsg;
-         }
- 
-         UploadTemplateToSwiftFromSecondaryStorageCommand cmd = new UploadTemplateToSwiftFromSecondaryStorageCommand(swift, secHost.getName(), secHost.getDataCenterId(), template.getAccountId(),
-                 templateId, _primaryStorageDownloadWait);
-         Answer answer = null;
-         try {
-             answer = _agentMgr.sendToSSVM(secHost.getDataCenterId(), cmd);
-             if (answer == null || !answer.getResult()) {
-                 if (template.getTemplateType() != TemplateType.SYSTEM) {
-                     String errMsg = "Failed to upload template " + templateId + " to Swift from secondary storage due to " + ((answer == null) ? "null" : answer.getDetails());
-                     s_logger.warn(errMsg);
-                     throw new CloudRuntimeException(errMsg);
+                 s_logger.info("Skip loading template " + template.getId() + " into primary storage " + pool.getId() + " as pool zone "
+                         + pool.getDataCenterId() + " is ");
 -            }
 +                }
-                 return null;
-             }
-             String path = templateHostRef.getInstallPath();
-             int index = path.lastIndexOf('/');
-             path = path.substring(index + 1);
-             VMTemplateSwiftVO tmpltSwift = new VMTemplateSwiftVO(swift.getId(), templateHostRef.getTemplateId(), new Date(), path, templateHostRef.getSize(), templateHostRef.getPhysicalSize());
-             _tmpltSwiftDao.persist(tmpltSwift);
-             _swiftMgr.propagateTemplateOnAllZones(templateHostRef.getTemplateId());
-         } catch (Exception e) {
-             String errMsg = "Failed to upload template " + templateId + " to Swift from secondary storage due to " + e.toString();
-             s_logger.warn(errMsg);
-             throw new CloudRuntimeException(errMsg);
          }
-         return null;
      }
  
-     @Override @DB
+     @Override
+     @DB
      public VMTemplateStoragePoolVO prepareTemplateForCreate(VMTemplateVO templ, StoragePool pool) {
 -        VMTemplateVO template = _tmpltDao.findById(templ.getId(), true);
 -
 +    	VMTemplateVO template = _tmpltDao.findById(templ.getId(), true);
 +    	
          long poolId = pool.getId();
          long templateId = template.getId();
-         long dcId = pool.getDataCenterId();
          VMTemplateStoragePoolVO templateStoragePoolRef = null;
-         VMTemplateHostVO templateHostRef = null;
-         long templateStoragePoolRefId;
-         String origUrl = null;
+         TemplateDataStoreVO templateStoreRef = null;
 -
 +        
          templateStoragePoolRef = _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
          if (templateStoragePoolRef != null) {
 -            templateStoragePoolRef.setMarkedForGC(false);
 +        	templateStoragePoolRef.setMarkedForGC(false);
              _tmpltPoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef);
 -
 +            
              if (templateStoragePoolRef.getDownloadState() == Status.DOWNLOADED) {
 -                if (s_logger.isDebugEnabled()) {
 -                    s_logger.debug("Template " + templateId + " has already been downloaded to pool " + poolId);
 -                }
 -
 -                return templateStoragePoolRef;
 -            }
 -        }
 -
 -        templateStoreRef = this._tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, pool.getDataCenterId(),
 +	            if (s_logger.isDebugEnabled()) {
 +	                s_logger.debug("Template " + templateId + " has already been downloaded to pool " + poolId);
 +	            }
 +	            
 +	            return templateStoragePoolRef;
 +	        }
 +        }
 +        
-         templateHostRef = findVmTemplateHost(templateId, pool);
-         
-         if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) {
-             String result = downloadTemplateFromSwiftToSecondaryStorage(dcId, templateId);
-             if (result != null) {
-                 s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
-                 return null;
-             }
-             result = _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(dcId,
-                     templateId, _primaryStorageDownloadWait);
-             if (result != null) {
-                 s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
-                 return null;
-             }
-             templateHostRef = findVmTemplateHost(templateId, pool);
-             if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) {
++        templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, pool.getDataCenterId(),
+                 VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
+         if (templateStoreRef == null) {
 -            s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
 -            return null;
 -        }
 -
 +                s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
 +                return null;
 +            }
-         }
 +        
-         HostVO sh = _hostDao.findById(templateHostRef.getHostId());
-         origUrl = sh.getStorageUrl();
-         if (origUrl == null) {
-             throw new CloudRuntimeException("Unable to find the orig.url from host " + sh.toString());
+         List<StoragePoolHostVO> vos = _poolHostDao.listByHostStatus(poolId, com.cloud.host.Status.Up);
+         if (vos == null || vos.isEmpty()) {
+             throw new CloudRuntimeException("Cannot download " + templateId + " to poolId " + poolId
+                     + " since there is no host in the Up state connected to this pool");
          }
 -
 +        
          if (templateStoragePoolRef == null) {
              if (s_logger.isDebugEnabled()) {
                  s_logger.debug("Downloading template " + templateId + " to pool " + poolId);
              }
-             templateStoragePoolRef = new VMTemplateStoragePoolVO(poolId, templateId);
-             try {
-                 templateStoragePoolRef = _tmpltPoolDao.persist(templateStoragePoolRef);
-                 templateStoragePoolRefId =  templateStoragePoolRef.getId();
-                 
-             } catch (Exception e) {
-                 s_logger.debug("Assuming we're in a race condition: " + e.getMessage());
-                 templateStoragePoolRef = _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
-                 if (templateStoragePoolRef == null) {
-                     throw new CloudRuntimeException("Unable to persist a reference for pool " + poolId + " and template " + templateId);
-                 }
-                 templateStoragePoolRefId = templateStoragePoolRef.getId();
-             }
-         } else {
-             templateStoragePoolRefId = templateStoragePoolRef.getId();
-         }
-         
-         List<StoragePoolHostVO> vos = _poolHostDao.listByHostStatus(poolId, com.cloud.host.Status.Up);
-         if (vos == null || vos.isEmpty()){
-         	 throw new CloudRuntimeException("Cannot download " + templateId + " to poolId " + poolId + " since there is no host in the Up state connected to this pool");            
-         }                
-         
-         templateStoragePoolRef = _tmpltPoolDao.acquireInLockTable(templateStoragePoolRefId, _storagePoolMaxWaitSeconds);
-         if (templateStoragePoolRef == null) {
-             throw new CloudRuntimeException("Unable to acquire lock on VMTemplateStoragePool: " + templateStoragePoolRefId);
-         }
 -            DataStore srcSecStore = this._dataStoreMgr.getDataStore(templateStoreRef.getDataStoreId(), DataStoreRole.Image);
 -            TemplateInfo srcTemplate = this._tmplFactory.getTemplate(templateId, srcSecStore);
++            DataStore srcSecStore = _dataStoreMgr.getDataStore(templateStoreRef.getDataStoreId(), DataStoreRole.Image);
++            TemplateInfo srcTemplate = _tmplFactory.getTemplate(templateId, srcSecStore);
  
 -            AsyncCallFuture<TemplateApiResult> future = this._tmpltSvr.prepareTemplateOnPrimary(srcTemplate, pool);
 -            try {
++            AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.prepareTemplateOnPrimary(srcTemplate, pool);
 +        try {
-             if (templateStoragePoolRef.getDownloadState() == Status.DOWNLOADED) {
-                 return templateStoragePoolRef;
-             }
-             String url = origUrl + "/" + templateHostRef.getInstallPath();
-             PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(template.getUniqueName(), url, template.getFormat(), 
-                    template.getAccountId(), pool, _primaryStorageDownloadWait);
-             HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
-             assert(secondaryStorageHost != null);
-             dcmd.setSecondaryStorageUrl(secondaryStorageHost.getStorageUrl());
-             // TODO temporary hacking, hard-coded to NFS primary data store
-             dcmd.setPrimaryStorageUrl("nfs://" + pool.getHostAddress() + pool.getPath());
-             
-             for (int retry = 0; retry < 2; retry ++){
-             	Collections.shuffle(vos); // Shuffling to pick a random host in the vm deployment retries
-             	StoragePoolHostVO vo = vos.get(0);
- 	            if (s_logger.isDebugEnabled()) {
- 	                s_logger.debug("Downloading " + templateId + " via " + vo.getHostId());
- 	            }
- 	        	dcmd.setLocalPath(vo.getLocalPath());
- 	        	// set 120 min timeout for this command
- 	        	
- 	        	PrimaryStorageDownloadAnswer answer = (PrimaryStorageDownloadAnswer)_agentMgr.easySend(
- 	                   _hvGuruMgr.getGuruProcessedCommandTargetHost(vo.getHostId(), dcmd), dcmd);
- 	            if (answer != null && answer.getResult() ) {
- 	        		templateStoragePoolRef.setDownloadPercent(100);
- 	        		templateStoragePoolRef.setDownloadState(Status.DOWNLOADED);
- 	        		templateStoragePoolRef.setLocalDownloadPath(answer.getInstallPath());
- 	        		templateStoragePoolRef.setInstallPath(answer.getInstallPath());
- 	        		templateStoragePoolRef.setTemplateSize(answer.getTemplateSize());
- 	        		_tmpltPoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef);
- 	        		if (s_logger.isDebugEnabled()) {
- 	        			s_logger.debug("Template " + templateId + " is downloaded via " + vo.getHostId());
- 	        		}
- 	        		return templateStoragePoolRef;
- 	            } else {
- 	                if (s_logger.isDebugEnabled()) {
- 	                    s_logger.debug("Template " + templateId + " download to pool " + vo.getPoolId() + " failed due to " + (answer!=null?answer.getDetails():"return null"));                }
- 	            }
-             }
-         } finally {
-             _tmpltPoolDao.releaseFromLockTable(templateStoragePoolRefId);
-         }
-         if (s_logger.isDebugEnabled()) {
-             s_logger.debug("Template " + templateId + " is not found on and can not be downloaded to pool " + poolId);
-         }
+                 TemplateApiResult result = future.get();
+                 if (result.isFailed()) {
+                     s_logger.debug("prepare template failed:" + result.getResult());
 -                    return null;
 -                }
 -
 +        return null;
 +    }
 +    
-     
-     
-     
-     @Override
-     public VMTemplateHostVO findVmTemplateHost(long templateId,
-             StoragePool pool) {
-         long dcId = pool.getDataCenterId();
-         Long podId = pool.getPodId();
- 
-         List<HostVO> secHosts = _ssvmMgr
-                 .listSecondaryStorageHostsInOneZone(dcId);
- 
- 
-         if (secHosts.size() == 1) {
-             VMTemplateHostVO templateHostVO = this._tmpltHostDao
-                     .findByHostTemplate(secHosts.get(0).getId(), templateId);
-             return templateHostVO;
-         }
-         if (podId != null) {
-             List<VMTemplateHostVO> templHosts = this._tmpltHostDao
-                     .listByTemplateStatus(templateId, dcId, podId,
-                             VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
-             if (templHosts != null && !templHosts.isEmpty()) {
-                 Collections.shuffle(templHosts);
-                 return templHosts.get(0);
-             }
+                 return _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
+             } catch (Exception ex) {
+                 s_logger.debug("failed to copy template from image store:" + srcSecStore.getName() + " to primary storage");
 -            }
 +        }
-         List<VMTemplateHostVO> templHosts = this._tmpltHostDao
-                 .listByTemplateStatus(templateId, dcId,
-                         VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
-         if (templHosts != null && !templHosts.isEmpty()) {
-             Collections.shuffle(templHosts);
-             return templHosts.get(0);
          }
+ 
          return null;
      }
 -
 +    
      @Override
-     public String getChecksum(Long hostId, String templatePath) {
-         HostVO ssHost = _hostDao.findById(hostId);
-         Host.Type type = ssHost.getType();
-         if (type != Host.Type.SecondaryStorage
-                 && type != Host.Type.LocalSecondaryStorage) {
-             return null;
-         }
-         String secUrl = ssHost.getStorageUrl();
-         Answer answer;
-         answer = _agentMgr.sendToSecStorage(ssHost, new ComputeChecksumCommand(
-                 secUrl, templatePath));
+     public String getChecksum(DataStore store, String templatePath) {
+         EndPoint ep = _epSelector.select(store);
+         ComputeChecksumCommand cmd = new ComputeChecksumCommand(store.getTO(), templatePath);
+         Answer answer = ep.sendMessage(cmd);
          if (answer != null && answer.getResult()) {
              return answer.getDetails();
          }
          return null;
      }
 -
 +    
      @Override
      @DB
-     public VMTemplateHostVO prepareISOForCreate(VMTemplateVO template, StoragePool pool) {
-         template = _tmpltDao.findById(template.getId(), true);
- 
-         long poolId = pool.getId();
-         long templateId = template.getId();
-         long dcId = pool.getDataCenterId();
-         VMTemplateStoragePoolVO templateStoragePoolRef = null;
-         VMTemplateHostVO templateHostRef = null;
-         long templateStoragePoolRefId;
-         String origUrl = null;
- 
-         templateHostRef = findVmTemplateHost(templateId, pool);
- 
-         if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) {
-             String result = downloadTemplateFromSwiftToSecondaryStorage(dcId, templateId);
-             if (result != null) {
-                 s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
-                 return null;
-             }
-             result = _s3Mgr.downloadTemplateFromS3ToSecondaryStorage(dcId,
-                     templateId, _primaryStorageDownloadWait);
-             if (result != null) {
-                 s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
-                 return null;
-             }
-             templateHostRef = findVmTemplateHost(templateId, pool);
-             if (templateHostRef == null || templateHostRef.getDownloadState() != Status.DOWNLOADED) {
-                 s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
-                 return null;
-             }
-         }
-         return templateHostRef;
-     }
- 
-     @Override
-     @DB
      public boolean resetTemplateDownloadStateOnPool(long templateStoragePoolRefId) {
-     	// have to use the same lock that prepareTemplateForCreate use to maintain state consistency
+         // have to use the same lock that prepareTemplateForCreate use to
+         // maintain state consistency
 -        VMTemplateStoragePoolVO templateStoragePoolRef = _tmpltPoolDao.acquireInLockTable(templateStoragePoolRefId, 1200);
 -
 +    	VMTemplateStoragePoolVO templateStoragePoolRef = _tmpltPoolDao.acquireInLockTable(templateStoragePoolRefId, 1200);
 +    	
          if (templateStoragePoolRef == null) {
 -            s_logger.warn("resetTemplateDownloadStateOnPool failed - unable to lock TemplateStorgePoolRef " + templateStoragePoolRefId);
 +        	s_logger.warn("resetTemplateDownloadStateOnPool failed - unable to lock TemplateStorgePoolRef " + templateStoragePoolRefId);
              return false;
          }
 -
 +        
          try {
 -            templateStoragePoolRef.setDownloadState(VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED);
 -            _tmpltPoolDao.update(templateStoragePoolRefId, templateStoragePoolRef);
 +        	templateStoragePoolRef.setDownloadState(VMTemplateStorageResourceAssoc.Status.NOT_DOWNLOADED);
 +        	_tmpltPoolDao.update(templateStoragePoolRefId, templateStoragePoolRef);
          } finally {
              _tmpltPoolDao.releaseFromLockTable(templateStoragePoolRefId);
          }
 -
 +        
          return true;
      }
 -
 +    
      @Override
      @DB
-     public boolean copy(long userId, VMTemplateVO template, HostVO srcSecHost, DataCenterVO srcZone, DataCenterVO dstZone) throws StorageUnavailableException, ResourceAllocationException {
-         List<HostVO> dstSecHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(dstZone.getId());
+     public boolean copy(long userId, VMTemplateVO template, DataStore srcSecStore, DataCenterVO dstZone) throws StorageUnavailableException,
+             ResourceAllocationException {
          long tmpltId = template.getId();
          long dstZoneId = dstZone.getId();
-         if (dstSecHosts == null || dstSecHosts.isEmpty() ) {
-             throw new StorageUnavailableException("Destination zone is not ready", DataCenter.class, dstZone.getId());
+         // find all eligible image stores for the destination zone
 -        List<DataStore> dstSecStores = this._dataStoreMgr.getImageStoresByScope(new ZoneScope(dstZoneId));
++        List<DataStore> dstSecStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dstZoneId));
+         if (dstSecStores == null || dstSecStores.isEmpty()) {
+             throw new StorageUnavailableException("Destination zone is not ready, no image store associated", DataCenter.class, dstZone.getId());
          }
          AccountVO account = _accountDao.findById(template.getAccountId());
-         VMTemplateHostVO srcTmpltHost = _tmpltHostDao.findByHostTemplate(srcSecHost.getId(), tmpltId);
+         // find the size of the template to be copied
 -        TemplateDataStoreVO srcTmpltStore = this._tmplStoreDao.findByStoreTemplate(srcSecStore.getId(), tmpltId);
++        TemplateDataStoreVO srcTmpltStore = _tmplStoreDao.findByStoreTemplate(srcSecStore.getId(), tmpltId);
  
          _resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
-         _resourceLimitMgr.checkResourceLimit(account, ResourceType.secondary_storage, new Long(srcTmpltHost.getSize()));
+         _resourceLimitMgr.checkResourceLimit(account, ResourceType.secondary_storage, new Long(srcTmpltStore.getSize()));
  
          // Event details
          String copyEventType;
@@@ -929,70 -650,49 +636,49 @@@
          Transaction txn = Transaction.currentTxn();
          txn.start();
  
-         for ( HostVO dstSecHost : dstSecHosts ) {
-             VMTemplateHostVO dstTmpltHost = null;
-             try {
-             	dstTmpltHost = _tmpltHostDao.findByHostTemplate(dstSecHost.getId(), tmpltId, true);
-             	if (dstTmpltHost != null) {
-             		dstTmpltHost = _tmpltHostDao.lockRow(dstTmpltHost.getId(), true);
-             		if (dstTmpltHost != null && dstTmpltHost.getDownloadState() == Status.DOWNLOADED) {
-             			if (dstTmpltHost.getDestroyed() == false)  {
-             				return true;
-             			} else {
-             				dstTmpltHost.setDestroyed(false);
-             				_tmpltHostDao.update(dstTmpltHost.getId(), dstTmpltHost);
-             				
-             				return true;
-             			}
-             		} else if (dstTmpltHost != null && dstTmpltHost.getDownloadState() == Status.DOWNLOAD_ERROR){
-             			if (dstTmpltHost.getDestroyed() == true)  {
-             				dstTmpltHost.setDestroyed(false);
-             				dstTmpltHost.setDownloadState(Status.NOT_DOWNLOADED);
-             				dstTmpltHost.setDownloadPercent(0);
-             				dstTmpltHost.setCopy(true);
-             				dstTmpltHost.setErrorString("");
-             				dstTmpltHost.setJobId(null);
-             				_tmpltHostDao.update(dstTmpltHost.getId(), dstTmpltHost);
 -        TemplateInfo srcTemplate = this._tmplFactory.getTemplate(template.getId(), srcSecStore);
++        TemplateInfo srcTemplate = _tmplFactory.getTemplate(template.getId(), srcSecStore);
+         // Copy will just find one eligible image store for the destination zone
+         // and copy template there, not propagate to all image stores
+         // for that zone
+         for (DataStore dstSecStore : dstSecStores) {
 -            TemplateDataStoreVO dstTmpltStore = this._tmplStoreDao.findByStoreTemplate(dstSecStore.getId(), tmpltId);
++            TemplateDataStoreVO dstTmpltStore = _tmplStoreDao.findByStoreTemplate(dstSecStore.getId(), tmpltId);
+             if (dstTmpltStore != null && dstTmpltStore.getDownloadState() == Status.DOWNLOADED) {
+                 return true; // already downloaded on this image store
 -            }
 +            			}
-             		}
-             	}
-             } finally {
-             	txn.commit();
+ 
 -            AsyncCallFuture<TemplateApiResult> future = this._tmpltSvr.copyTemplate(srcTemplate, dstSecStore);
++            AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.copyTemplate(srcTemplate, dstSecStore);
+             try {
+                 TemplateApiResult result = future.get();
+                 if (result.isFailed()) {
+                     s_logger.debug("copy template failed for image store " + dstSecStore.getName() + ":" + result.getResult());
+                     continue; // try next image store
 -                }
 +            }
  
-             if(_downloadMonitor.copyTemplate(template, srcSecHost, dstSecHost) ) {
                  _tmpltDao.addTemplateToZone(template, dstZoneId);
 -
 +            	
-             	if(account.getId() != Account.ACCOUNT_ID_SYSTEM){
-                     UsageEventUtils.publishUsageEvent(copyEventType, account.getId(), dstZoneId, tmpltId, null, null, null, srcTmpltHost.getSize(),
+                 if (account.getId() != Account.ACCOUNT_ID_SYSTEM) {
+                     UsageEventUtils.publishUsageEvent(copyEventType, account.getId(), dstZoneId, tmpltId, null, null, null, srcTmpltStore.getSize(),
                              template.getClass().getName(), template.getUuid());
 -                }
 -                return true;
 +            	}
 +            	return true;
+             } catch (Exception ex) {
+                 s_logger.debug("failed to copy template to image store:" + dstSecStore.getName() + " ,will try next one");
              }
          }
          return false;
-     }
 -
 +  
+     }
 -
 +    
      @Override
      @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_COPY, eventDescription = "copying template", async = true)
      public VirtualMachineTemplate copyTemplate(CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException {
 -        Long templateId = cmd.getId();
 -        Long userId = UserContext.current().getCallerUserId();
 -        Long sourceZoneId = cmd.getSourceZoneId();
 -        Long destZoneId = cmd.getDestinationZoneId();
 -        Account caller = UserContext.current().getCaller();
 -
 +    	Long templateId = cmd.getId();
 +    	Long userId = CallContext.current().getCallingUserId();
 +    	Long sourceZoneId = cmd.getSourceZoneId();
 +    	Long destZoneId = cmd.getDestinationZoneId();
 +    	Account caller = CallContext.current().getCallingAccount();
 +        
-         if (_swiftMgr.isSwiftEnabled()) {
-             throw new CloudRuntimeException("copytemplate API is disabled in Swift setup, templates in Swift can be accessed by all Zones");
-         }
- 
-         if (_s3Mgr.isS3Enabled()) {
-             throw new CloudRuntimeException(
-                     "copytemplate API is disabled in S3 setup -- S3 templates are accessible in all zones.");
-         }
- 
-         //Verify parameters
+         // Verify parameters
          if (sourceZoneId.equals(destZoneId)) {
              throw new InvalidParameterValueException("Please specify different source and destination zones.");
          }
@@@ -1011,80 -711,85 +697,85 @@@
          if (template == null || template.getRemoved() != null) {
              throw new InvalidParameterValueException("Unable to find template with id");
          }
 -
 +      
-         HostVO dstSecHost = getSecondaryStorageHost(destZoneId, templateId);
-         if ( dstSecHost != null ) {
-             s_logger.debug("There is template " + templateId + " in secondary storage " + dstSecHost.getId() + " in zone " + destZoneId + " , don't need to copy");
+         DataStore dstSecStore = getImageStore(destZoneId, templateId);
+         if (dstSecStore != null) {
+             s_logger.debug("There is template " + templateId + " in secondary storage " + dstSecStore.getName() + " in zone " + destZoneId
+                     + " , don't need to copy");
              return template;
          }
 -
 +        
-         HostVO srcSecHost = getSecondaryStorageHost(sourceZoneId, templateId);
-         if ( srcSecHost == null ) {
-             throw new InvalidParameterValueException("There is no template " + templateId + " in zone " + sourceZoneId );
+         DataStore srcSecStore = getImageStore(sourceZoneId, templateId);
+         if (srcSecStore == null) {
+             throw new InvalidParameterValueException("There is no template " + templateId + " in zone " + sourceZoneId);
+         }
+         if (srcSecStore.getScope().getScopeType() == ScopeType.REGION) {
+             s_logger.debug("Template " + templateId + " is in region-wide secondary storage " + dstSecStore.getName() + " , don't need to copy");
+             return template;
          }
 -
 +       
          _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
 -
 +        
-         boolean success = copy(userId, template, srcSecHost, sourceZone, dstZone);
+         boolean success = copy(userId, template, srcSecStore, dstZone);
 -
 +        
-     	if (success){
+         if (success) {
 -            return template;
 +        	return template;
-         }else {
+         } else {
 -            throw new CloudRuntimeException("Failed to copy template");
 +        	throw new CloudRuntimeException("Failed to copy template");
          }
      }
  
      @Override
      public boolean delete(long userId, long templateId, Long zoneId) {
 -        VMTemplateVO template = _tmpltDao.findById(templateId);
 -        if (template == null || template.getRemoved() != null) {
 -            throw new InvalidParameterValueException("Please specify a valid template.");
 -        }
 -
 -        TemplateAdapter adapter = getAdapter(template.getHypervisorType());
 -        return adapter.delete(new TemplateProfile(userId, template, zoneId));
 +    	VMTemplateVO template = _tmpltDao.findById(templateId);
 +    	if (template == null || template.getRemoved() != null) {
 +    		throw new InvalidParameterValueException("Please specify a valid template.");
 +    	}
 +    	
 +    	TemplateAdapter adapter = getAdapter(template.getHypervisorType());
 +    	return adapter.delete(new TemplateProfile(userId, template, zoneId));
      }
 -
 +    
      @Override
      public List<VMTemplateStoragePoolVO> getUnusedTemplatesInPool(StoragePoolVO pool) {
 -        List<VMTemplateStoragePoolVO> unusedTemplatesInPool = new ArrayList<VMTemplateStoragePoolVO>();
 -        List<VMTemplateStoragePoolVO> allTemplatesInPool = _tmpltPoolDao.listByPoolId(pool.getId());
 -
 -        for (VMTemplateStoragePoolVO templatePoolVO : allTemplatesInPool) {
 -            VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
 -
 -            // If this is a routing template, consider it in use
 -            if (template.getTemplateType() == TemplateType.SYSTEM) {
 -                continue;
 -            }
 -
 +		List<VMTemplateStoragePoolVO> unusedTemplatesInPool = new ArrayList<VMTemplateStoragePoolVO>();
 +		List<VMTemplateStoragePoolVO> allTemplatesInPool = _tmpltPoolDao.listByPoolId(pool.getId());
 +		
 +		for (VMTemplateStoragePoolVO templatePoolVO : allTemplatesInPool) {
- 			VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());			
++			VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
 +		
 +			// If this is a routing template, consider it in use
 +			if (template.getTemplateType() == TemplateType.SYSTEM) {
 +				continue;
 +			}
 +			
- 			// If the template is not yet downloaded to the pool, consider it in use
+             // If the template is not yet downloaded to the pool, consider it in
+             // use
 -            if (templatePoolVO.getDownloadState() != Status.DOWNLOADED) {
 -                continue;
 -            }
 +			if (templatePoolVO.getDownloadState() != Status.DOWNLOADED) {
 +				continue;
 +			}
  
 -            if (template.getFormat() != ImageFormat.ISO && !_volumeDao.isAnyVolumeActivelyUsingTemplateOnPool(template.getId(), pool.getId())) {
 +			if (template.getFormat() != ImageFormat.ISO && !_volumeDao.isAnyVolumeActivelyUsingTemplateOnPool(template.getId(), pool.getId())) {
                  unusedTemplatesInPool.add(templatePoolVO);
 -            }
 -        }
 -
 -        return unusedTemplatesInPool;
 -    }
 -
 +			}
 +		}
 +		
 +		return unusedTemplatesInPool;
 +	}
 +    
      @Override
      public void evictTemplateFromStoragePool(VMTemplateStoragePoolVO templatePoolVO) {
-         StoragePool pool = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
 -        StoragePool pool = (StoragePool) this._dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
 -        VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
 -
 -        if (s_logger.isDebugEnabled()) {
 -            s_logger.debug("Evicting " + templatePoolVO);
 -        }
 -        DestroyCommand cmd = new DestroyCommand(pool, templatePoolVO);
 -
++        StoragePool pool = (StoragePool) _dataStoreMgr.getPrimaryDataStore(templatePoolVO.getPoolId());
 +		VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templatePoolVO.getTemplateId());
 +		
- 		
 +		if (s_logger.isDebugEnabled()) {
 +		    s_logger.debug("Evicting " + templatePoolVO);
 +		}
 +		DestroyCommand cmd = new DestroyCommand(pool, templatePoolVO);
 +		
          try {
              Answer answer = _storageMgr.sendToPool(pool, cmd);
 -
 +		
              if (answer != null && answer.getResult()) {
                  // Remove the templatePoolVO
                  if (_tmpltPoolDao.remove(templatePoolVO.getId())) {
@@@ -1094,94 -799,14 +785,14 @@@
                  s_logger.info("Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
              }
          } catch (StorageUnavailableException e) {
-             s_logger.info("Storage is unavailable currently.  Will retry evicte template: " + template.getName() + " from storage pool: " + pool.getName());
+             s_logger.info("Storage is unavailable currently.  Will retry evicte template: " + template.getName() + " from storage pool: "
+                     + pool.getName());
          }
  
 -    }
 -
 +	}
 +    
-     void swiftTemplateSync() {
-         GlobalLock swiftTemplateSyncLock = GlobalLock.getInternLock("templatemgr.swiftTemplateSync");
-         try {
-             if (!_swiftMgr.isSwiftEnabled()) {
-                 return;
-             }
-             List<HypervisorType> hypers = _clusterDao.getAvailableHypervisorInZone(null);
-             List<VMTemplateVO> templates = _tmpltDao.listByHypervisorType(hypers);
-             List<Long> templateIds = new ArrayList<Long>();
-             for (VMTemplateVO template : templates) {
-                 if (template.getTemplateType() != TemplateType.PERHOST) {
-                     templateIds.add(template.getId());
-                 }
-             }
-             List<VMTemplateSwiftVO> templtSwiftRefs = _tmpltSwiftDao.listAll();
-             for (VMTemplateSwiftVO templtSwiftRef : templtSwiftRefs) {
-                 templateIds.remove((Long) templtSwiftRef.getTemplateId());
-             }
-             if (templateIds.size() < 1) {
-                 return;
-             }
-             if (swiftTemplateSyncLock.lock(3)) {
-                 try {
-                     List<VMTemplateHostVO> templtHostRefs = _tmpltHostDao.listByState(VMTemplateHostVO.Status.DOWNLOADED);
-                     for (VMTemplateHostVO templtHostRef : templtHostRefs) {
-                         if (templtHostRef.getDestroyed()) {
-                             continue;
-                         }
-                         if (!templateIds.contains(templtHostRef.getTemplateId())) {
-                             continue;
-                         }
-                         try {
-                             uploadTemplateToSwiftFromSecondaryStorage(templtHostRef);
-                         } catch (Exception e) {
-                             s_logger.debug("failed to upload template " + templtHostRef.getTemplateId() + " to Swift due to " + e.toString());
-                         }
-                     }
-                 } catch (Throwable e) {
-                     s_logger.error("Problem with sync swift template due to " + e.toString(), e);
-                 } finally {
-                     swiftTemplateSyncLock.unlock();
-                 }
-             }
-         } catch (Throwable e) {
-             s_logger.error("Problem with sync swift template due to " + e.toString(), e);
-         } finally {
-             swiftTemplateSyncLock.releaseRef();
-         }
-     }
- 
-     private Runnable getSwiftTemplateSyncTask() {
-         return new Runnable() {
-             @Override
-             public void run() {
-                 if (s_logger.isDebugEnabled()) {
-                     s_logger.trace("Start Swift Template sync at" + (new Date()));
-                 }
-                 swiftTemplateSync();
-                 if (s_logger.isTraceEnabled()) {
-                     s_logger.trace("Finish Swift Template sync at" + (new Date()));
-                 }
-             }
-         };
-     }
- 
      @Override
      public boolean start() {
-         _swiftTemplateSyncExecutor.scheduleAtFixedRate(getSwiftTemplateSyncTask(), 60, 60, TimeUnit.SECONDS);
- 
-         if (_s3TemplateSyncExecutor != null) {
- 
-             final int initialDelay = 60;
-             final int period = 60;
- 
-             _s3TemplateSyncExecutor.scheduleAtFixedRate(new S3SyncTask(
-                     this._tmpltDao, this._s3Mgr), initialDelay, period,
-                     TimeUnit.SECONDS);
-             s_logger.info(String.format("Started S3 sync task to execute "
-                     + "execute every %1$s after an initial delay of %2$s.",
-                     period, initialDelay));
- 
-         }
- 
          return true;
      }
  
@@@ -1205,31 -824,11 +810,11 @@@
          String value = _configDao.getValue(Config.PrimaryStorageDownloadWait.toString());
          _primaryStorageDownloadWait = NumbersUtil.parseInt(value, Integer.parseInt(Config.PrimaryStorageDownloadWait.getDefaultValue()));
  
 -        String disableExtraction = _configDao.getValue(Config.DisableExtraction.toString());
 -        _disableExtraction = (disableExtraction == null) ? false : Boolean.parseBoolean(disableExtraction);
 +        String disableExtraction =  _configDao.getValue(Config.DisableExtraction.toString());
 +        _disableExtraction  = (disableExtraction == null) ? false : Boolean.parseBoolean(disableExtraction);
  
-         HostTemplateStatesSearch = _tmpltHostDao.createSearchBuilder();
-         HostTemplateStatesSearch.and("id", HostTemplateStatesSearch.entity().getTemplateId(), SearchCriteria.Op.EQ);
-         HostTemplateStatesSearch.and("state", HostTemplateStatesSearch.entity().getDownloadState(), SearchCriteria.Op.EQ);
-         
-         SearchBuilder<HostVO> HostSearch = _hostDao.createSearchBuilder();
-         HostSearch.and("dcId", HostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
-         
-         HostTemplateStatesSearch.join("host", HostSearch, HostSearch.entity().getId(), HostTemplateStatesSearch.entity().getHostId(), JoinBuilder.JoinType.INNER);
-         HostSearch.done();
-         HostTemplateStatesSearch.done();
-         
          _storagePoolMaxWaitSeconds = NumbersUtil.parseInt(_configDao.getValue(Config.StoragePoolMaxWaitSeconds.key()), 3600);
          _preloadExecutor = Executors.newFixedThreadPool(8, new NamedThreadFactory("Template-Preloader"));
-         _swiftTemplateSyncExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("swift-template-sync-Executor"));
- 
-         if (_s3Mgr.isS3Enabled()) {
-             _s3TemplateSyncExecutor = Executors
-                     .newSingleThreadScheduledExecutor(new NamedThreadFactory(
-                             "s3-template-sync"));
-         } else {
-             s_logger.info("S3 secondary storage synchronization is disabled.");
-         }
  
          return true;
      }
@@@ -1237,52 -836,73 +822,73 @@@
      protected TemplateManagerImpl() {
      }
  
 -    @Override
 -    public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) {
 -        VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templateHostRef.getTemplateId());
 -        long templateId = template.getId();
 -        HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
 -        long zoneId = secondaryStorageHost.getDataCenterId();
 -        DataCenterVO zone = _dcDao.findById(zoneId);
 +	@Override
 +	public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) {
 +	    VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templateHostRef.getTemplateId());
 +	    long templateId = template.getId();
 +	    HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
 +	    long zoneId = secondaryStorageHost.getDataCenterId();
 +	    DataCenterVO zone = _dcDao.findById(zoneId);
  
- 	    // Check if there are VMs running in the template host ref's zone that use the template
+         // Check if there are VMs running in the template host ref's zone that
+         // use the template
 -        List<VMInstanceVO> nonExpungedVms = _vmInstanceDao.listNonExpungedByZoneAndTemplate(zoneId, templateId);
 +	    List<VMInstanceVO> nonExpungedVms = _vmInstanceDao.listNonExpungedByZoneAndTemplate(zoneId, templateId);
  
 -        if (!nonExpungedVms.isEmpty()) {
 +	    if (!nonExpungedVms.isEmpty()) {
- 	        s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are non-expunged VMs deployed from this template.");
+             s_logger.debug("Template " + template.getName() + " in zone " + zone.getName()
+                     + " is not deleteable because there are non-expunged VMs deployed from this template.");
 -            return false;
 -        }
 -        List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(templateId);
 +	        return false;
 +	    }
 +	    List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(templateId);
- 	    //check if there is any VM using this ISO.
+         // check if there is any VM using this ISO.
 -        if (!userVmUsingIso.isEmpty()) {
 +	    if (!userVmUsingIso.isEmpty()) {
- 	        s_logger.debug("ISO " + template.getName() + " in zone " + zone.getName() + " is not deleteable because it is attached to " + userVmUsingIso.size() + " VMs");
+             s_logger.debug("ISO " + template.getName() + " in zone " + zone.getName() + " is not deleteable because it is attached to "
+                     + userVmUsingIso.size() + " VMs");
 -            return false;
 -        }
 +	        return false;
 +	    }
- 	    // Check if there are any snapshots for the template in the template host ref's zone
+         // Check if there are any snapshots for the template in the template
+         // host ref's zone
 -        List<VolumeVO> volumes = _volumeDao.findByTemplateAndZone(templateId, zoneId);
 -        for (VolumeVO volume : volumes) {
 -            List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdVersion(volume.getId(), "2.1");
 -            if (!snapshots.isEmpty()) {
 +	    List<VolumeVO> volumes = _volumeDao.findByTemplateAndZone(templateId, zoneId);
 +	    for (VolumeVO volume : volumes) {
 +	        List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdVersion(volume.getId(), "2.1");
 +	        if (!snapshots.isEmpty()) {
- 	            s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are 2.1 snapshots using this template.");
+                 s_logger.debug("Template " + template.getName() + " in zone " + zone.getName()
+                         + " is not deleteable because there are 2.1 snapshots using this template.");
 -                return false;
 -            }
 -        }
 +	            return false;
 +	        }
 +	    }
  
 -        return true;
 -    }
 +	    return true;
 +	}
  
 -    @Override
 +	@Override
+     public boolean templateIsDeleteable(long templateId) {
+         List<UserVmJoinVO> userVmUsingIso = _userVmJoinDao.listActiveByIsoId(templateId);
+         // check if there is any Vm using this ISO. We only need to check the
+         // case where templateId is an ISO since
+         // VM can be launched from ISO in secondary storage, while template will
+         // always be copied to
+         // primary storage before deploying VM.
+         if (!userVmUsingIso.isEmpty()) {
+             s_logger.debug("ISO " + templateId + " is not deleteable because it is attached to " + userVmUsingIso.size() + " VMs");
+             return false;
+         }
+ 
+         return true;
+     }
+ 
+     @Override
      @ActionEvent(eventType = EventTypes.EVENT_ISO_DETACH, eventDescription = "detaching ISO", async = true)
 -    public boolean detachIso(long vmId) {
 -        Account caller = UserContext.current().getCaller();
 -        Long userId = UserContext.current().getCallerUserId();
 -
 +	public boolean detachIso(long vmId)  {
 +        Account caller = CallContext.current().getCallingAccount();
 +        Long userId = CallContext.current().getCallingUserId();
 +        
          // Verify input parameters
          UserVmVO vmInstanceCheck = _userVmDao.findById(vmId);
          if (vmInstanceCheck == null) {
-             throw new InvalidParameterValueException ("Unable to find a virtual machine with id " + vmId);
+             throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
          }
 -
 +        
          UserVm userVM = _userVmDao.findById(vmId);
          if (userVM == null) {
              throw new InvalidParameterValueException("Please specify a valid VM.");
@@@ -1294,69 -914,93 +900,93 @@@
          if (isoId == null) {
              throw new InvalidParameterValueException("The specified VM has no ISO attached to it.");
          }
 -        UserContext.current().setEventDetails("Vm Id: " + vmId + " ISO Id: " + isoId);
 -
 +    	CallContext.current().setEventDetails("Vm Id: " +vmId+ " ISO Id: "+isoId);
 +        
          State vmState = userVM.getState();
          if (vmState != State.Running && vmState != State.Stopped) {
 -            throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
 +        	throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
          }
  
-         boolean result = attachISOToVM(vmId, userId, isoId, false); //attach=false => detach
-         if (result){
+         boolean result = attachISOToVM(vmId, userId, isoId, false); // attach=false
+                                                                     // => detach
+         if (result) {
 -            return result;
 +        	return result;
-         }else {
+         } else {
 -            throw new CloudRuntimeException("Failed to detach iso");
 +        	throw new CloudRuntimeException("Failed to detach iso");
-         }        
+         }
 -    }
 -
 -    @Override
 +	}
 +	
 +	@Override
      @ActionEvent(eventType = EventTypes.EVENT_ISO_ATTACH, eventDescription = "attaching ISO", async = true)
 -    public boolean attachIso(long isoId, long vmId) {
 -        Account caller = UserContext.current().getCaller();
 -        Long userId = UserContext.current().getCallerUserId();
 -
 -        // Verify input parameters
 -        UserVmVO vm = _userVmDao.findById(vmId);
 -        if (vm == null) {
 +	public boolean attachIso(long isoId, long vmId) {
 +        Account caller = CallContext.current().getCallingAccount();
 +        Long userId = CallContext.current().getCallingUserId();
 +        
 +    	// Verify input parameters
 +    	UserVmVO vm = _userVmDao.findById(vmId);
 +    	if (vm == null) {
              throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
          }
 -
 -        VMTemplateVO iso = _tmpltDao.findById(isoId);
 -        if (iso == null || iso.getRemoved() != null) {
 +    	
 +    	VMTemplateVO iso = _tmpltDao.findById(isoId);
 +    	if (iso == null || iso.getRemoved() != null) {
              throw new InvalidParameterValueException("Unable to find an ISO with id " + isoId);
 -        }
 -
 +    	}
 +    	
-     	//check permissions
-     	//check if caller has access to VM and ISO 
-     	//and also check if the VM's owner has access to the ISO.
+         // check permissions
+         // check if caller has access to VM and ISO
+         // and also check if the VM's owner has access to the ISO.
 -
 -        _accountMgr.checkAccess(caller, null, false, iso, vm);
 -
 -        Account vmOwner = _accountDao.findById(vm.getAccountId());
 -        _accountMgr.checkAccess(vmOwner, null, false, iso, vm);
 -
 +    	
 +    	_accountMgr.checkAccess(caller, null, false, iso, vm);
 +    	
 +    	Account vmOwner = _accountDao.findById(vm.getAccountId());
 +    	_accountMgr.checkAccess(vmOwner, null, false, iso, vm);
 +    	
          State vmState = vm.getState();
          if (vmState != State.Running && vmState != State.Stopped) {
 -            throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
 +        	throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
          }
 -
 +        
-         if ("xen-pv-drv-iso".equals(iso.getDisplayText()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer){
+         if ("xen-pv-drv-iso".equals(iso.getDisplayText()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer) {
 -            throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
 +        	throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
          }
 -
 +        
-         if("vmware-tools.iso".equals(iso.getName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
+         if ("vmware-tools.iso".equals(iso.getName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
 -            throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
 +        	throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
          }
          boolean result = attachISOToVM(vmId, userId, isoId, true);
-         if (result){
+         if (result) {
 -            return result;
 +        	return result;
-         }else {
+         } else {
 -            throw new CloudRuntimeException("Failed to attach iso");
 +        	throw new CloudRuntimeException("Failed to attach iso");
          }
 -    }
 -
 +	}
 +	
+     // for ISO, we need to consider whether to copy to cache storage or not if it is not on NFS, since our hypervisor resource always assumes that they are in NFS
+     @Override
+     public TemplateInfo prepareIso(long isoId, long dcId){
 -        TemplateInfo tmplt = this._tmplFactory.getTemplate(isoId, DataStoreRole.Image, dcId);
++        TemplateInfo tmplt = _tmplFactory.getTemplate(isoId, DataStoreRole.Image, dcId);
+         if (tmplt == null || tmplt.getFormat() != ImageFormat.ISO ) {
+             s_logger.warn("ISO: " + isoId + " does not exist in vm_template table");
+             return null;
+         }
+ 
+         if (tmplt.getDataStore() != null && !(tmplt.getDataStore().getTO() instanceof NfsTO)) {
+             // if it is s3, need to download into cache storage first
+             Scope destScope = new ZoneScope(dcId);
+             TemplateInfo cacheData = (TemplateInfo) cacheMgr.createCacheObject(tmplt, destScope);
+             if (cacheData == null) {
+                 s_logger.error("Failed in copy iso from S3 to cache storage");
+                 return null;
+             }
+             return cacheData;
+         } else{
+             return tmplt;
+         }
+     }
+ 
      private boolean attachISOToVM(long vmId, long isoId, boolean attach) {
--        UserVmVO vm = this._userVmDao.findById(vmId);
++        UserVmVO vm = _userVmDao.findById(vmId);
  
          if (vm == null) {
              return false;
@@@ -1401,22 -1032,22 +1018,22 @@@
      }
  
      private boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach) {
 -        UserVmVO vm = _userVmDao.findById(vmId);
 -        VMTemplateVO iso = _tmpltDao.findById(isoId);
 +    	UserVmVO vm = _userVmDao.findById(vmId);
 +    	VMTemplateVO iso = _tmpltDao.findById(isoId);
  
          boolean success = attachISOToVM(vmId, isoId, attach);
-         if ( success && attach) {
+         if (success && attach) {
 -            vm.setIsoId(iso.getId());
 +             vm.setIsoId(iso.getId());
              _userVmDao.update(vmId, vm);
-         } 
-         if ( success && !attach ) {
+         }
+         if (success && !attach) {
              vm.setIsoId(null);
              _userVmDao.update(vmId, vm);
-         }    
+         }
          return success;
      }
 -
 -    @Override
 +	
 +	@Override
      @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_DELETE, eventDescription = "deleting template", async = true)
      public boolean deleteTemplate(DeleteTemplateCmd cmd) {
          Long templateId = cmd.getId();
@@@ -1426,100 -1057,68 +1043,68 @@@
          if (template == null) {
              throw new InvalidParameterValueException("unable to find template with id " + templateId);
          }
 -
 +        
          _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
 +    	
 +    	if (template.getFormat() == ImageFormat.ISO) {
 +    		throw new InvalidParameterValueException("Please specify a valid template.");
 +    	}
-         if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) {
-             _swiftMgr.deleteTemplate(cmd);
-         }
-         if (cmd.getZoneId() == null && _s3Mgr.isS3Enabled()) {
-             _s3Mgr.deleteTemplate(cmd.getId(), caller.getAccountId());
-         }
  
 -        if (template.getFormat() == ImageFormat.ISO) {
 -            throw new InvalidParameterValueException("Please specify a valid template.");
 -        }
 -
 -        TemplateAdapter adapter = getAdapter(template.getHypervisorType());
 -        TemplateProfile profile = adapter.prepareDelete(cmd);
 +    	TemplateAdapter adapter = getAdapter(template.getHypervisorType());
 +    	TemplateProfile profile = adapter.prepareDelete(cmd);
-     	boolean result = adapter.delete(profile);
-     	
-     	if (result){
-             if (cmd.getZoneId() == null
-                     && (_swiftMgr.isSwiftEnabled() || _s3Mgr.isS3Enabled())) {
-                 List<VMTemplateZoneVO> templateZones = _tmpltZoneDao
-                         .listByZoneTemplate(null, templateId);
-                 if (templateZones != null) {
-                     for (VMTemplateZoneVO templateZone : templateZones) {
-                         _tmpltZoneDao.remove(templateZone.getId());
-                     }
-                 }
-             }
-     		return true;
-     	}else{
-     		throw new CloudRuntimeException("Failed to delete template");
-     	}
+         return adapter.delete(profile);
 -    }
 -
 -    @Override
 +	}
 +	
 +	@Override
      @ActionEvent(eventType = EventTypes.EVENT_ISO_DELETE, eventDescription = "deleting iso", async = true)
      public boolean deleteIso(DeleteIsoCmd cmd) {
          Long templateId = cmd.getId();
 -        Account caller = UserContext.current().getCaller();
 +        Account caller = CallContext.current().getCallingAccount();
          Long zoneId = cmd.getZoneId();
 -
 +        
-         VirtualMachineTemplate template = getTemplate(templateId);;
+         VirtualMachineTemplate template = getTemplate(templateId);
+         ;
          if (template == null) {
              throw new InvalidParameterValueException("unable to find iso with id " + templateId);
          }
 -
 +        
          _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
 -
 -        if (template.getFormat() != ImageFormat.ISO) {
 -            throw new InvalidParameterValueException("Please specify a valid iso.");
 -        }
 +         	
 +    	if (template.getFormat() != ImageFormat.ISO) {
 +    		throw new InvalidParameterValueException("Please specify a valid iso.");
 +    	}
-         if (cmd.getZoneId() == null && _swiftMgr.isSwiftEnabled()) {
-             _swiftMgr.deleteIso(cmd);
-     	}
-

<TRUNCATED>

[35/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/vm/UserVmManagerImpl.java
index 52580b6,66103fb..ae96297
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@@ -58,15 -59,16 +58,18 @@@ import org.apache.cloudstack.api.comman
  import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd;
  import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd;
  import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd;
 +import org.apache.cloudstack.context.CallContext;
  import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity;
  import org.apache.cloudstack.engine.service.api.OrchestrationService;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
 +import org.apache.cloudstack.framework.jobs.AsyncJobManager;
 +import org.apache.cloudstack.framework.jobs.Outcome;
  import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
+ import org.apache.cloudstack.storage.to.TemplateObjectTO;
  
  import com.cloud.agent.AgentManager;
 -import com.cloud.agent.AgentManager.OnError;
  import com.cloud.agent.api.Answer;
  import com.cloud.agent.api.GetVmDiskStatsAnswer;
  import com.cloud.agent.api.GetVmDiskStatsCommand;
@@@ -75,11 -77,15 +78,11 @@@ import com.cloud.agent.api.GetVmStatsCo
  import com.cloud.agent.api.PvlanSetupCommand;
  import com.cloud.agent.api.StartAnswer;
  import com.cloud.agent.api.StopAnswer;
 -import com.cloud.agent.api.UnPlugNicAnswer;
 -import com.cloud.agent.api.UnPlugNicCommand;
  import com.cloud.agent.api.VmDiskStatsEntry;
  import com.cloud.agent.api.VmStatsEntry;
+ import com.cloud.agent.api.to.DiskTO;
  import com.cloud.agent.api.to.NicTO;
  import com.cloud.agent.api.to.VirtualMachineTO;
- import com.cloud.agent.api.to.VolumeTO;
  import com.cloud.agent.manager.Commands;
  import com.cloud.alert.AlertManager;
  import com.cloud.api.ApiDBUtils;
@@@ -1702,7 -1708,8 +1700,8 @@@ public class UserVmManagerImpl extends 
          Long id = cmd.getId();
          Long osTypeId = cmd.getOsTypeId();
          String userData = cmd.getUserData();
 +        Account caller = CallContext.current().getCallingAccount();
+         Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
 -        Account caller = UserContext.current().getCaller();
  
          // Input validation
          UserVmVO vmInstance = null;
@@@ -2869,30 -2893,11 +2885,11 @@@
          vm.setDetails(details);
  
          if (vm.getIsoId() != null) {
-             String isoPath = null;
- 
-             VirtualMachineTemplate template = _templateDao.findById(vm
-                     .getIsoId());
-             if (template == null || template.getFormat() != ImageFormat.ISO) {
-                 throw new CloudRuntimeException(
-                         "Can not find ISO in vm_template table for id "
-                                 + vm.getIsoId());
-             }
- 
-             Pair<String, String> isoPathPair = templateMgr.getAbsoluteIsoPath(
-                     template.getId(), vm.getDataCenterId());
- 
-             if (template.getTemplateType() == TemplateType.PERHOST) {
-                 isoPath = template.getName();
-             } else {
-                 if (isoPathPair == null) {
-                     s_logger.warn("Couldn't get absolute iso path");
-                     return false;
-                 } else {
-                     isoPath = isoPathPair.first();
 -            TemplateInfo template = this.templateMgr.prepareIso(vm.getIsoId(), vm.getDataCenterId());
++            TemplateInfo template = templateMgr.prepareIso(vm.getIsoId(), vm.getDataCenterId());
+             if (template == null){
+                 s_logger.error("Failed to prepare ISO on secondary or cache storage");
+                 throw new CloudRuntimeException("Failed to prepare ISO on secondary or cache storage");
 -            }
 +                }
-             }
- 
              if (template.isBootable()) {
                  profile.setBootLoaderType(BootloaderType.CD);
              }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/com/cloud/agent/MockAgentManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/com/cloud/async/TestAsyncJobManager.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/async/TestAsyncJobManager.java
index 6b4788b,e323393..8e27247
--- a/server/test/com/cloud/async/TestAsyncJobManager.java
+++ b/server/test/com/cloud/async/TestAsyncJobManager.java
@@@ -223,24 -157,96 +223,24 @@@ public class TestAsyncJobManager extend
  				}
  			}
  		});
 -
 -		t1.start();
 -		t2.start();
 -
 -		try {
 -			t1.join();
 -			t2.join();
 -		} catch (InterruptedException e) {
 -		}
 -	}
 -     */
 -
 -    private long getRandomLockId() {
 -        return 1L;
 -
 -        /*
 -         *  will use in the future test cases
 -		int i = new Random().nextInt();
 -		if(i % 2 == 0)
 -			return 1L;
 -		return 2L;
 -         */
 -    }
 -
 -    public void tstLocking() {
 -
 -        int testThreads = 20;
 -        Thread[] threads = new Thread[testThreads];
 -
 -        for(int i = 0; i < testThreads; i++) {
 -            final int current = i;
 -            threads[i] = new Thread(new Runnable() {
 -                @Override
 -                public void run() {
 -
 -                    final HostDao hostDao = new HostDaoImpl();
 -                    while(true) {
 -                        Transaction txn = Transaction.currentTxn();
 -                        try {
 -                            HostVO host = hostDao.acquireInLockTable(getRandomLockId(), 10);
 -                            if(host != null) {
 -                                s_logger.info("Thread " + (current + 1) + " acquired lock");
 -
 -                                try { Thread.sleep(1000); } catch (InterruptedException e) {}
 -
 -                                s_logger.info("Thread " + (current + 1) + " released lock");
 -                                hostDao.releaseFromLockTable(host.getId());
 -
 -                                try { Thread.sleep(1000); } catch (InterruptedException e) {}
 -                            } else {
 -                                s_logger.info("Thread " + (current + 1) + " is not able to acquire lock");
 -                            }
 -                        } finally {
 -                            txn.close();
 -                        }
 -                    }
 -                }
 -            });
 -            threads[i].start();
 -        }
 -
 -        try {
 -            for(int i = 0; i < testThreads; i++)
 -                threads[i].join();
 -        } catch(InterruptedException e) {
 -        }
 -    }
 -
 -    public void testDomain() {
 -        DomainDao domainDao = new DomainDaoImpl();
 -
 -		DomainVO domain1 = new DomainVO("d1", 2L, 1L, null, 1);
 -        domainDao.create(domain1);
 -
 -		DomainVO domain2 = new DomainVO("d2", 2L, 1L, null, 1);
 -        domainDao.create(domain2);
 -
 -		DomainVO domain3 = new DomainVO("d3", 2L, 1L, null, 1);
 -        domainDao.create(domain3);
 -
 -		DomainVO domain11 = new DomainVO("d11", 2L, domain1.getId(), null, 1);
 -        domainDao.create(domain11);
 -
 -        domainDao.remove(domain11.getId());
 -
 -		DomainVO domain12 = new DomainVO("d12", 2L, domain1.getId(), null, 1);
 -        domainDao.create(domain12);
 -
 -        domainDao.remove(domain3.getId());
 -		DomainVO domain4 = new DomainVO("d4", 2L, 1L, null, 1);
 -        domainDao.create(domain4);
 +		thread.start();
 +    
 +		jobMonitor.registerActiveTask(1, 1);
 +		
-     	asyncMgr.waitAndCheck(new String[] {"VM"}, 5000L, 10000L, new Predicate() {
++        asyncMgr.waitAndCheck(new AsyncJobVO(), new String[] {"VM"}, 5000L, 10000L, new Predicate() {
 +    		@Override
 +            public boolean checkCondition() {
 +    			System.out.println("Check condition to exit");
 +                messageBus.publish(null, AsyncJob.Topics.JOB_HEARTBEAT, PublishScope.LOCAL, 1L);
 +    			return false;
 +    		}
 +    	});
 +    	
 +		jobMonitor.unregisterActiveTask(1);
 +    	
 +    	try {
 +    		thread.join();
 +    	} catch(InterruptedException e) {
 +    	}
      }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/com/cloud/network/DedicateGuestVlanRangesTest.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
index d4ded07,0000000..cc6b906
mode 100644,000000..100644
--- a/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
+++ b/server/test/com/cloud/vm/VmWorkMockVirtualMachineManagerImpl.java
@@@ -1,327 -1,0 +1,325 @@@
 +// 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.vm;
 +
 +import java.net.URI;
 +import java.util.List;
 +import java.util.Map;
 +
 +import javax.inject.Inject;
 +import javax.naming.ConfigurationException;
 +
 +import org.apache.log4j.Logger;
 +
 +import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
 +import org.apache.cloudstack.framework.jobs.Outcome;
 +import org.apache.cloudstack.framework.messagebus.MessageBus;
 +import org.apache.cloudstack.jobs.JobInfo;
 +
 +import com.cloud.agent.api.to.NicTO;
 +import com.cloud.agent.api.to.VirtualMachineTO;
 +import com.cloud.deploy.DeployDestination;
 +import com.cloud.deploy.DeploymentPlan;
 +import com.cloud.exception.AgentUnavailableException;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.InsufficientCapacityException;
 +import com.cloud.exception.InsufficientServerCapacityException;
 +import com.cloud.exception.ManagementServerException;
 +import com.cloud.exception.OperationTimedoutException;
 +import com.cloud.exception.ResourceUnavailableException;
 +import com.cloud.exception.VirtualMachineMigrationException;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.network.Network;
 +import com.cloud.network.dao.NetworkVO;
 +import com.cloud.offering.ServiceOffering;
 +import com.cloud.service.ServiceOfferingVO;
 +import com.cloud.storage.DiskOfferingVO;
 +import com.cloud.storage.StoragePool;
 +import com.cloud.storage.VMTemplateVO;
 +import com.cloud.storage.Volume;
 +import com.cloud.user.Account;
 +import com.cloud.utils.Pair;
 +import com.cloud.utils.fsm.NoTransitionException;
 +import com.cloud.vm.VirtualMachine.Event;
 +import com.cloud.vm.VirtualMachine.Type;
 +import com.cloud.vm.VirtualMachineProfile.Param;
 +
 +public class VmWorkMockVirtualMachineManagerImpl implements VirtualMachineManager {
 +    private static final Logger s_logger = Logger.getLogger(VmWorkMockVirtualMachineManagerImpl.class);
 +	
 +	@Inject MessageBus _msgBus;
 +	
 +	@Override
 +	public String getName() {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +	public void setName(String name) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +	public void setConfigParams(Map<String, Object> params) {
 +		// TODO Auto-generated method stub
 +		
 +	}
 +
 +	@Override
 +	public Map<String, Object> getConfigParams() {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +	public int getRunLevel() {
 +		// TODO Auto-generated method stub
 +		return 0;
 +	}
 +
 +	@Override
 +	public void setRunLevel(int level) {
 +		// TODO Auto-generated method stub
 +		
 +	}
 +
 +	@Override
 +	public boolean configure(String name, Map<String, Object> params)
 +			throws ConfigurationException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public boolean start() {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public boolean stop() {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +    public boolean allocate(String vmInstanceName, VMTemplateVO template,
 +			ServiceOfferingVO serviceOffering,
 +			Pair<? extends DiskOfferingVO, Long> rootDiskOffering,
 +			List<Pair<DiskOfferingVO, Long>> dataDiskOfferings,
 +			List<Pair<NetworkVO, NicProfile>> networks,
 +			Map<Param, Object> params, DeploymentPlan plan,
 +            HypervisorType hyperType, Account owner) {
 +		// TODO Auto-generated method stub
 +        return false;
 +	}
 +
 +
 +	@Override
 +    public boolean allocate(String vmInstanceName, VMTemplateVO template,
 +			ServiceOfferingVO serviceOffering,
 +			List<Pair<NetworkVO, NicProfile>> networkProfiles,
 +            DeploymentPlan plan, HypervisorType hyperType, Account owner) {
 +		// TODO Auto-generated method stub
 +        return false;
 +	}
 +
 +	@Override
 +    public void easyStart(String vmUuid, Map<Param, Object> params) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public void easyStart(String vmUuid, Map<Param, Object> params, DeploymentPlan planToDeploy) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public void easyStop(String vmUuid) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public void expunge(String vmUuid) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public void registerGuru(Type type, VirtualMachineGuru guru) {
 +		// TODO Auto-generated method stub
 +		
 +	}
 +
 +	@Override
 +	public boolean stateTransitTo(VMInstanceVO vm, Event e, Long hostId)
 +			throws NoTransitionException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +    public Outcome<VirtualMachine> start(String vmUuid, Map<Param, Object> params,
 +            DeploymentPlan planToDeploy) {
 +        return null;
 +	}
 +
 +	@Override
 +    public Outcome<VirtualMachine> stop(String vmUuid, boolean forced) {
 +        return null;
 +	}
 +
 +	@Override
 +    public void advanceExpunge(String vmUuid) throws ResourceUnavailableException,
 +			OperationTimedoutException, ConcurrentOperationException {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public boolean destroy(String vmUuid) throws AgentUnavailableException,
 +			OperationTimedoutException, ConcurrentOperationException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public boolean migrateAway(Type type, long vmid, long hostId)
 +			throws InsufficientServerCapacityException,
 +			VirtualMachineMigrationException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
-     public VirtualMachine migrate(String vmUuid, long srcHostId,
- 			DeployDestination dest) throws ResourceUnavailableException,
- 			ConcurrentOperationException, ManagementServerException,
- 			VirtualMachineMigrationException {
++    public Outcome<VirtualMachine> migrate(String vmUuid, long srcHostId,
++            DeployDestination dest) {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +    public void reboot(String vmUuid) {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public void advanceReboot(String vmUuid)
 +			throws InsufficientCapacityException, ResourceUnavailableException,
 +			ConcurrentOperationException, OperationTimedoutException {
 +		// TODO Auto-generated method stub
 +	}
 +
 +	@Override
 +    public VirtualMachine storageMigration(String vmUuid,
 +			StoragePool storagePoolId) {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +	public void checkIfCanUpgrade(VirtualMachine vmInstance,
 +			long newServiceOfferingId) {
 +		// TODO Auto-generated method stub
 +		
 +	}
 +
 +	@Override
 +	public boolean upgradeVmDb(long vmId, long serviceOfferingId) {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public NicProfile addVmToNetwork(VirtualMachine vm, Network network,
 +			NicProfile requested) throws ConcurrentOperationException,
 +			ResourceUnavailableException, InsufficientCapacityException {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +	public boolean removeNicFromVm(VirtualMachine vm, NicVO nic)
 +			throws ConcurrentOperationException, ResourceUnavailableException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public boolean removeVmFromNetwork(VirtualMachine vm, Network network,
 +			URI broadcastUri) throws ConcurrentOperationException,
 +			ResourceUnavailableException {
 +		// TODO Auto-generated method stub
 +		return false;
 +	}
 +
 +	@Override
 +	public NicTO toNicTO(NicProfile nic, HypervisorType hypervisorType) {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +	public VirtualMachineTO toVmTO(
 +			VirtualMachineProfile profile) {
 +		// TODO Auto-generated method stub
 +		return null;
 +	}
 +
 +	@Override
 +    public boolean reConfigureVm(VirtualMachine vm,
 +			ServiceOffering newServiceOffering, boolean sameHost)
 +			throws ResourceUnavailableException, ConcurrentOperationException {
 +		// TODO Auto-generated method stub
 +        return false;
 +	}
 +
 +	@Override
 +    public boolean findHostAndMigrate(String vmUUid,
 +			Long newSvcOfferingId) throws InsufficientCapacityException,
 +			ConcurrentOperationException, ResourceUnavailableException,
 +			VirtualMachineMigrationException, ManagementServerException {
 +		// TODO Auto-generated method stub
 +        return false;
 +	}
 +
 +	@Override
 +    public boolean migrateForScale(String vmUuid, long srcHostId,
 +			DeployDestination dest, Long newSvcOfferingId)
 +			throws ResourceUnavailableException, ConcurrentOperationException,
 +			ManagementServerException, VirtualMachineMigrationException {
 +		// TODO Auto-generated method stub
 +        return false;
 +	}
 +
 +	int wakeupCount = 0;
 +	public void processVmStartWakeup() {
 +		s_logger.info("processVmStartWakeup. job-" + AsyncJobExecutionContext.getCurrentExecutionContext().getJob().getId());
 +		
 +		if(wakeupCount++ < 3) {
 +			AsyncJobExecutionContext.getCurrentExecutionContext().resetSyncSource();
 +		} else {
 +			AsyncJobExecutionContext.getCurrentExecutionContext().completeAsyncJob(JobInfo.Status.SUCCEEDED, 0, null);
 +		}
 +	}
 +	
 +    @Override
 +    public VirtualMachine migrateWithStorage(String vmUuid, long srcId, long destId, Map<Volume, StoragePool> volumeToPool) throws ResourceUnavailableException,
 +            ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
 +        // TODO Auto-generated method stub
 +        return null;
 +    }
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
----------------------------------------------------------------------
diff --cc server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
index 2fe9dda,6398e20..89c1fe9
--- a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
+++ b/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
@@@ -29,14 -35,7 +29,15 @@@ import org.springframework.core.type.cl
  import org.springframework.core.type.classreading.MetadataReaderFactory;
  import org.springframework.core.type.filter.TypeFilter;
  
 +import org.apache.cloudstack.acl.SecurityChecker;
 +import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 +import org.apache.cloudstack.region.PortableIpDaoImpl;
 +import org.apache.cloudstack.region.PortableIpRangeDaoImpl;
 +import org.apache.cloudstack.region.dao.RegionDaoImpl;
 +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl;
 +import org.apache.cloudstack.test.utils.SpringUtils;
 +
  import com.cloud.agent.AgentManager;
  import com.cloud.alert.AlertManager;
  import com.cloud.api.query.dao.UserAccountJoinDaoImpl;
@@@ -357,10 -363,10 +357,10 @@@ public class ChildTestConfiguration 
      public AccountDetailsDao accountDetailsDao() {
          return Mockito.mock(AccountDetailsDao.class);
      }
 -
 +    
      @Bean
-     public ConfigurationManager configurationMgr() {
-     	return Mockito.mock(ConfigurationManager.class);
+     public DataStoreManager dataStoreManager() {
+         return Mockito.mock(DataStoreManager.class);
      }
  
      public static class Library implements TypeFilter {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/setup/db/db/schema-410to420.sql
----------------------------------------------------------------------
diff --cc setup/db/db/schema-410to420.sql
index 2046f6c,325924b..75088e5
--- a/setup/db/db/schema-410to420.sql
+++ b/setup/db/db/schema-410to420.sql
@@@ -86,9 -94,135 +94,141 @@@ CREATE TABLE `cloud`.`image_store` 
    PRIMARY KEY(`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  
++<<<<<<< HEAD
 +ALTER TABLE `cloud`.`async_job` ADD COLUMN `related` CHAR(40) NOT NULL;
 +
 +ALTER TABLE `cloud`.`vm_template` ADD COLUMN `image_data_store_id` bigint unsigned;
++=======
+ CREATE TABLE `cloud`.`image_store_details` (
+   `id` bigint unsigned UNIQUE NOT NULL AUTO_INCREMENT COMMENT 'id',
+   `store_id` bigint unsigned NOT NULL COMMENT 'store the detail is related to',
+   `name` varchar(255) NOT NULL COMMENT 'name of the detail',
+   `value` varchar(255) NOT NULL COMMENT 'value of the detail',
+   PRIMARY KEY (`id`),
+   CONSTRAINT `fk_image_store_details__store_id` FOREIGN KEY `fk_image_store__store_id`(`store_id`) REFERENCES `image_store`(`id`) ON DELETE CASCADE,
+   INDEX `i_image_store__name__value`(`name`(128), `value`(128))
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+ 
+ DROP VIEW IF EXISTS `cloud`.`image_store_view`;
+ CREATE VIEW `cloud`.`image_store_view` AS
+     select 
+         image_store.id,
+         image_store.uuid,
+         image_store.name,
+         image_store.image_provider_name,
+         image_store.protocol,
+         image_store.url,
+         image_store.scope,
+         image_store.role,
+         image_store.removed,
+         data_center.id data_center_id,
+         data_center.uuid data_center_uuid,
+         data_center.name data_center_name,
+         image_store_details.name detail_name,
+         image_store_details.value detail_value
+     from
+         `cloud`.`image_store`
+             left join
+         `cloud`.`data_center` ON image_store.data_center_id = data_center.id
+             left join
+         `cloud`.`image_store_details` ON image_store_details.store_id = image_store.id;
+ 
+             
+ -- here we have to allow null for store_id to accomodate baremetal case to search for ready templates since template state is only stored in this table
+ -- FK also commented out due to this            
+ CREATE TABLE  `cloud`.`template_store_ref` (
+   `id` bigint unsigned NOT NULL auto_increment,
+   `store_id` bigint unsigned,
+   `template_id` bigint unsigned NOT NULL,
+   `created` DATETIME NOT NULL,
+   `last_updated` DATETIME,
+   `job_id` varchar(255),
+   `download_pct` int(10) unsigned,
+   `size` bigint unsigned,
+   `store_role` varchar(255),  
+   `physical_size` bigint unsigned DEFAULT 0,
+   `download_state` varchar(255),
+   `error_str` varchar(255),
+   `local_path` varchar(255),
+   `install_path` varchar(255),
+   `url` varchar(255),
+   `state` varchar(255) NOT NULL,
+   `destroyed` tinyint(1) COMMENT 'indicates whether the template_store entry was destroyed by the user or not',
+   `is_copy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'indicates whether this was copied ',
+   `update_count` bigint unsigned,
+   `ref_cnt` bigint unsigned,
+   `updated` datetime, 
+   PRIMARY KEY  (`id`),
+ --  CONSTRAINT `fk_template_store_ref__store_id` FOREIGN KEY `fk_template_store_ref__store_id` (`store_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE,
+   INDEX `i_template_store_ref__store_id`(`store_id`),
+   CONSTRAINT `fk_template_store_ref__template_id` FOREIGN KEY `fk_template_store_ref__template_id` (`template_id`) REFERENCES `vm_template` (`id`),
+   INDEX `i_template_store_ref__template_id`(`template_id`)
+ ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
+ 
+ -- ALTER TABLE `cloud`.`vm_template` ADD COLUMN `image_data_store_id` bigint unsigned;
+ 
+ -- Do we still need these columns? TODO, to delete them, remove FK constraints from snapshots table
+ -- ALTER TABLE `cloud`.`snapshots` DROP COLUMN `swift_id`;
+ -- ALTER TABLE `cloud`.`snapshots` DROP COLUMN `s3_id`;
+ -- ALTER TABLE `cloud`.`snapshots` DROP COLUMN `sechost_id`;
+ 
+ -- change upload host_id FK to point to image_store table
+ ALTER TABLE `cloud`.`upload` DROP FOREIGN KEY `fk_upload__host_id`; 
+ ALTER TABLE `cloud`.`upload` ADD CONSTRAINT `fk_upload__store_id` FOREIGN KEY(`host_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE;
+ 
+ CREATE TABLE  `cloud`.`snapshot_store_ref` (
+   `id` bigint unsigned NOT NULL auto_increment,
+   `store_id` bigint unsigned NOT NULL,
+   `snapshot_id` bigint unsigned NOT NULL,
+   `created` DATETIME NOT NULL,
+   `last_updated` DATETIME,
+   `job_id` varchar(255),
+   `store_role` varchar(255),
+   `size` bigint unsigned,
+   `physical_size` bigint unsigned DEFAULT 0,
+   `parent_snapshot_id` bigint unsigned DEFAULT 0,
+   `install_path` varchar(255),
+   `state` varchar(255) NOT NULL,  
+   -- `removed` datetime COMMENT 'date removed if not null',  
+   `update_count` bigint unsigned,
+   `ref_cnt` bigint unsigned,
+   `updated` datetime,   
+   PRIMARY KEY  (`id`),
+   INDEX `i_snapshot_store_ref__store_id`(`store_id`),
+   CONSTRAINT `fk_snapshot_store_ref__snapshot_id` FOREIGN KEY `fk_snapshot_store_ref__snapshot_id` (`snapshot_id`) REFERENCES `snapshots` (`id`),
+   INDEX `i_snapshot_store_ref__snapshot_id`(`snapshot_id`)
+ ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
+ 
+ CREATE TABLE  `cloud`.`volume_store_ref` (
+   `id` bigint unsigned NOT NULL auto_increment,
+   `store_id` bigint unsigned NOT NULL,
+   `volume_id` bigint unsigned NOT NULL,
+   `zone_id` bigint unsigned NOT NULL,
+   `created` DATETIME NOT NULL,
+   `last_updated` DATETIME,
+   `job_id` varchar(255),
+   `download_pct` int(10) unsigned,
+   `size` bigint unsigned,
+   `physical_size` bigint unsigned DEFAULT 0,
+   `download_state` varchar(255),
+   `checksum` varchar(255) COMMENT 'checksum for the data disk',
+   `error_str` varchar(255),
+   `local_path` varchar(255),
+   `install_path` varchar(255),
+   `url` varchar(255),
+   `state` varchar(255) NOT NULL,  
+   `destroyed` tinyint(1) COMMENT 'indicates whether the volume_host entry was destroyed by the user or not',
+   `update_count` bigint unsigned,
+   `ref_cnt` bigint unsigned,
+   `updated` datetime,   
+   PRIMARY KEY  (`id`),
+   CONSTRAINT `fk_volume_store_ref__store_id` FOREIGN KEY `fk_volume_store_ref__store_id` (`store_id`) REFERENCES `image_store` (`id`) ON DELETE CASCADE,
+   INDEX `i_volume_store_ref__store_id`(`store_id`),
+   CONSTRAINT `fk_volume_store_ref__volume_id` FOREIGN KEY `fk_volume_store_ref__volume_id` (`volume_id`) REFERENCES `volumes` (`id`),
+   INDEX `i_volume_store_ref__volume_id`(`volume_id`)
+ ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
+ 
++>>>>>>> master
  
  ALTER TABLE `cloud`.`service_offering` ADD COLUMN `is_volatile` tinyint(1) unsigned NOT NULL DEFAULT 0  COMMENT 'true if the vm needs to be volatile, i.e., on every reboot of vm from API root disk is discarded and creates a new root disk';
  
@@@ -1632,10 -1718,13 +1791,13 @@@ CREATE VIEW `cloud`.`user_vm_view` A
          `cloud`.`async_job` ON async_job.instance_id = vm_instance.id
              and async_job.instance_type = 'VirtualMachine'
              and async_job.job_status = 0
 -            left join
 -        `cloud`.`affinity_group_vm_map` ON vm_instance.id = affinity_group_vm_map.instance_id
 -            left join
 +	left join 
 +	`cloud`.`affinity_group_vm_map` ON vm_instance.id = affinity_group_vm_map.instance_id
 +	left join 
- 	`cloud`.`affinity_group` ON affinity_group_vm_map.affinity_group_id = affinity_group.id;
+         `cloud`.`affinity_group` ON affinity_group_vm_map.affinity_group_id = affinity_group.id
+             left join
+         `cloud`.`user_vm_details` vm_details ON vm_details.vm_id = vm_instance.id
+             and vm_details.name = 'enable.dynamic.scaling';
  
  DROP VIEW IF EXISTS `cloud`.`volume_view`;
  CREATE VIEW `cloud`.`volume_view` AS
@@@ -1766,7 -1960,10 +2033,10 @@@ CREATE TABLE `cloud`.`account_vnet_map
  
  ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD COLUMN account_vnet_map_id bigint unsigned;
  ALTER TABLE `cloud`.`op_dc_vnet_alloc` ADD CONSTRAINT `fk_op_dc_vnet_alloc__account_vnet_map_id` FOREIGN KEY `fk_op_dc_vnet_alloc__account_vnet_map_id` (`account_vnet_map_id`) REFERENCES `account_vnet_map` (`id`);
 -            
 +
+  update  `cloud`.`vm_template` set state='Allocated' where state is NULL;
+  update  `cloud`.`vm_template` set update_count=0 where update_count is NULL;
+ 
  CREATE TABLE `cloud`.`network_acl` (
    `id` bigint unsigned NOT NULL auto_increment COMMENT 'id',
    `name` varchar(255) NOT NULL COMMENT 'name of the network acl',

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/tools/devcloud/devcloud.cfg
----------------------------------------------------------------------
diff --cc tools/devcloud/devcloud.cfg
index 353a259,e209b55..5abea54
--- a/tools/devcloud/devcloud.cfg
+++ b/tools/devcloud/devcloud.cfg
@@@ -84,10 -84,12 +84,12 @@@
              "internaldns1": "192.168.56.1", 
              "secondaryStorages": [
                  {
-                     "url": "nfs://192.168.56.10:/opt/storage/secondary"
+                     "url": "nfs://192.168.56.10/opt/storage/secondary",
+                     "provider": "NFS",
+                     "details": [ ]
 -                 }
 +                }
              ]
 -         }
 +        }
      ], 
      "logger": [
          {


[11/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3143: add response in the response string


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

Branch: refs/heads/vmsync
Commit: 5f06500ed47815b904ceecad911eb340854d91d4
Parents: 3e430cc
Author: Sebastien Goasguen <ru...@gmail.com>
Authored: Sun Jun 23 23:32:56 2013 -0400
Committer: Sebastien Goasguen <ru...@gmail.com>
Committed: Sun Jun 23 23:32:56 2013 -0400

----------------------------------------------------------------------
 .../command/user/securitygroup/RevokeSecurityGroupEgressCmd.java   | 2 +-
 .../command/user/securitygroup/RevokeSecurityGroupIngressCmd.java  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5f06500e/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java
index 8e7f2ec..c03d3e4 100644
--- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java
@@ -35,7 +35,7 @@ import com.cloud.user.Account;
 public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd {
     public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupEgressCmd.class.getName());
 
-    private static final String s_name = "revokesecuritygroupegress";
+    private static final String s_name = "revokesecuritygroupegressresponse";
 
     // ///////////////////////////////////////////////////
     // ////////////// API parameters /////////////////////

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5f06500e/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java
index 1d45064..c2fdb8b 100644
--- a/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java
@@ -35,7 +35,7 @@ import com.cloud.user.Account;
 public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd {
     public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName());
 
-    private static final String s_name = "revokesecuritygroupingress";
+    private static final String s_name = "revokesecuritygroupingressresponse";
 
     // ///////////////////////////////////////////////////
     // ////////////// API parameters /////////////////////


[27/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-757


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

Branch: refs/heads/vmsync
Commit: 90838d7292bf646a910f2a385f536f29effaf883
Parents: dc24203
Author: Radhika PC <ra...@citrix.com>
Authored: Mon Jun 24 16:16:43 2013 +0530
Committer: Radhika PC <ra...@citrix.com>
Committed: Mon Jun 24 16:17:30 2013 +0530

----------------------------------------------------------------------
 docs/en-US/add-gateway-vpc.xml | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/90838d72/docs/en-US/add-gateway-vpc.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/add-gateway-vpc.xml b/docs/en-US/add-gateway-vpc.xml
index 6aaa5d0..9a270f9 100644
--- a/docs/en-US/add-gateway-vpc.xml
+++ b/docs/en-US/add-gateway-vpc.xml
@@ -158,8 +158,9 @@
     <title>Blacklisting Routes</title>
     <para>&PRODUCT; enables you to block a list of routes so that they are not assigned to any of
       the VPC private gateways. Specify the list of routes that you want to blacklist in the
-        <code>blacklisted.routes</code> global parameter. Note that the parameter update affects only new
-      static route creations. If you block an existing static route, it remains intact and
-      continue functioning. </para>
+        <code>blacklisted.routes</code> global parameter. Note that the parameter update affects
+      only new static route creations. If you block an existing static route, it remains intact and
+      continue functioning. You cannot add a static route if the route is blacklisted for the zone.
+    </para>
   </section>
 </section>


[48/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java
index cc62d9c,5fbe106..8d34cf9
--- a/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java
@@@ -16,12 -16,9 +16,10 @@@
  // under the License.
  package org.apache.cloudstack.api.command.user.volume;
  
--import java.net.URISyntaxException;
- 
 +import org.apache.log4j.Logger;
  
  import org.apache.cloudstack.api.APICommand;
 +import org.apache.cloudstack.api.ApiCommandJobType;
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.ApiErrorCode;
  import org.apache.cloudstack.api.BaseAsyncCmd;
@@@ -96,10 -95,10 +94,12 @@@ public class ExtractVolumeCmd extends B
          return s_name;
      }
  
 -    public AsyncJob.Type getInstanceType() {
 -        return AsyncJob.Type.Volume;
++    @Override
 +    public ApiCommandJobType getInstanceType() {
 +        return ApiCommandJobType.Volume;
      }
  
++    @Override
      public Long getInstanceId() {
          return getId();
      }
@@@ -127,33 -126,26 +127,26 @@@
  
      @Override
      public void execute(){
-         try {
-             CallContext.current().setEventDetails("Volume Id: "+getId());
-             Long uploadId = _mgr.extractVolume(this);
-             if (uploadId != null){
-                 Upload uploadInfo = _entityMgr.findById(Upload.class, uploadId);
 -        UserContext.current().setEventDetails("Volume Id: " + getId());
++        CallContext.current().setEventDetails("Volume Id: " + getId());
+         String uploadUrl = _volumeService.extractVolume(this);
+         if (uploadUrl != null) {
 -            ExtractResponse response = new ExtractResponse();
 -            response.setResponseName(getCommandName());
 -            response.setObjectName("volume");
 -            Volume vol = _entityMgr.findById(Volume.class, id);
 -            response.setId(vol.getUuid());
 -            response.setName(vol.getName());
 -            DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
 -            response.setZoneId(zone.getUuid());
 -            response.setZoneName(zone.getName());
 -            response.setMode(mode);
 +                ExtractResponse response = new ExtractResponse();
 +                response.setResponseName(getCommandName());
 +                response.setObjectName("volume");
 +                Volume vol = _entityMgr.findById(Volume.class, id);
 +                response.setId(vol.getUuid());
 +                response.setName(vol.getName());
 +                DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
 +                response.setZoneId(zone.getUuid());
 +                response.setZoneName(zone.getName());
 +                response.setMode(mode);
-                 response.setUploadId(uploadInfo.getUuid());
-                 response.setState(uploadInfo.getUploadState().toString());
+             response.setState(Upload.Status.DOWNLOAD_URL_CREATED.toString());
 -            Account account = _entityMgr.findById(Account.class, getEntityOwnerId());
 -            response.setAccountId(account.getUuid());
 +                Account account = _entityMgr.findById(Account.class, getEntityOwnerId());
 +                response.setAccountId(account.getUuid());
-                 response.setUrl(uploadInfo.getUploadUrl());
-                 this.setResponseObject(response);
+             response.setUrl(uploadUrl);
 -            this.setResponseObject(response);
 -        } else {
 -            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract volume");
 -        }
++                setResponseObject(response);
 +            } else {
 +                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to extract volume");
 +            }
-         } catch (URISyntaxException ex) {
-             s_logger.info(ex);
-             throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage());
-         }
      }
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/ClusterResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/ClusterResponse.java
index 5d9bb05,68aa892..c9e909b
--- a/api/src/org/apache/cloudstack/api/response/ClusterResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/ClusterResponse.java
@@@ -47,10 -45,7 +47,7 @@@ public class ClusterResponse extends Ba
  
      @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the cluster")
      private String zoneName;
 -
 +    
-     @SerializedName(ApiConstants.ZONE_TYPE) @Param(description = "network type of the availability zone")
-     private String zoneType;
-     
      @SerializedName("hypervisortype") @Param(description="the hypervisor type of the cluster")
      private String hypervisorType;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/HostResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/HostResponse.java
index e4eb01b,687687d..4cb2b1a
--- a/api/src/org/apache/cloudstack/api/response/HostResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/HostResponse.java
@@@ -60,10 -59,7 +60,7 @@@ public class HostResponse extends BaseR
  
      @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the host")
      private String zoneName;
 -
 +    
-     @SerializedName(ApiConstants.ZONE_TYPE) @Param(description = "network type of the availability zone")
-     private String zoneType;
-     
      @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the host")
      private String podId;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/NetworkResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/NetworkResponse.java
index 3a8b875,3102433..f9be96f
--- a/api/src/org/apache/cloudstack/api/response/NetworkResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/NetworkResponse.java
@@@ -67,10 -66,7 +67,7 @@@ public class NetworkResponse extends Ba
  
      @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the network belongs to")
      private String zoneName;
 -
 +    
-     @SerializedName(ApiConstants.ZONE_TYPE) @Param(description="the networktype of the zone the network belongs to")
-     private String zoneType;
- 
      @SerializedName("networkofferingid") @Param(description="network offering id the network is created from")
      private String networkOfferingId;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/PodResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/SnapshotResponse.java
index ffb6002,e9cb109..2abc7bc
--- a/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java
@@@ -180,14 -180,7 +172,7 @@@ public class SnapshotResponse extends B
      public void setZoneId(String zoneId) {
          this.zoneId = zoneId;
      }
-     public void setZoneName(String zoneName) {
-         this.zoneName = zoneName;
-     }
- 
-     public void setZoneType(String zoneType) {
-         this.zoneType = zoneType;
-     }
 - 
 +    
      public void setTags(List<ResourceTagResponse> tags) {
          this.tags = tags;
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java
index 57257a7,0050000..d7b391d
--- a/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java
@@@ -39,9 -37,7 +39,7 @@@ public class StoragePoolResponse extend
      @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the storage pool")
      private String zoneName;
  
-     @SerializedName(ApiConstants.ZONE_TYPE) @Param(description = "network type of the availability zone")
-     private String zoneType;
 -
 +    
      @SerializedName("podid") @Param(description="the Pod ID of the storage pool")
      private String podId;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/SystemVmResponse.java
index 3f1d955,8d2798a..8612ff2
--- a/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java
@@@ -148,15 -150,7 +145,7 @@@ public class SystemVmResponse extends B
      public void setZoneName(String zoneName) {
          this.zoneName = zoneName;
      }
 -
 +      
-     public String getZoneType() {
-         return zoneType;
-     }
- 
-     public void setZoneType(String zoneType) {
-         this.zoneType = zoneType;
-     }        
-     
      public String getDns1() {
          return dns1;
      }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/TemplateResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/TemplateResponse.java
index 8bbfe47,e6221f7..00a5668
--- a/api/src/org/apache/cloudstack/api/response/TemplateResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/TemplateResponse.java
@@@ -17,11 -17,11 +17,13 @@@
  package org.apache.cloudstack.api.response;
  
  import java.util.Date;
+ import java.util.LinkedHashSet;
  import java.util.List;
  import java.util.Map;
+ import java.util.Set;
  
 +import com.google.gson.annotations.SerializedName;
 +
  import org.apache.cloudstack.api.ApiConstants;
  import org.apache.cloudstack.api.BaseResponse;
  import org.apache.cloudstack.api.EntityReference;
@@@ -88,10 -91,7 +92,7 @@@ public class TemplateResponse extends B
  
      @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone for this template")
      private String zoneName;
 -
 +    
-     @SerializedName(ApiConstants.ZONE_TYPE) @Param(description="the networktype of the zone for this template")
-     private String zoneType;
- 
      @SerializedName(ApiConstants.STATUS) @Param(description="the status of the template")
      private String status;
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/UserVmResponse.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/api/src/org/apache/cloudstack/api/response/VolumeResponse.java
----------------------------------------------------------------------
diff --cc api/src/org/apache/cloudstack/api/response/VolumeResponse.java
index 47e620f,b643de1..a006e57
--- a/api/src/org/apache/cloudstack/api/response/VolumeResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/VolumeResponse.java
@@@ -47,11 -47,7 +47,7 @@@ public class VolumeResponse extends Bas
      @SerializedName(ApiConstants.ZONE_NAME)
      @Param(description = "name of the availability zone")
      private String zoneName;
 -
 +    
-     @SerializedName(ApiConstants.ZONE_TYPE)
-     @Param(description = "network type of the availability zone")
-     private String zoneType;
- 
      @SerializedName(ApiConstants.TYPE)
      @Param(description = "type of the disk volume (ROOT or DATADISK)")
      private String volumeType;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/client/tomcatconf/applicationContext.xml.in
----------------------------------------------------------------------
diff --cc client/tomcatconf/applicationContext.xml.in
index d3b5369,ac1f3e4..627c655
--- a/client/tomcatconf/applicationContext.xml.in
+++ b/client/tomcatconf/applicationContext.xml.in
@@@ -196,9 -196,8 +194,8 @@@
    <bean id="dataCenterJoinDaoImpl" class="com.cloud.api.query.dao.DataCenterJoinDaoImpl" />
    <bean id="dataCenterLinkLocalIpAddressDaoImpl" class="com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl" />
    <bean id="dataCenterVnetDaoImpl" class="com.cloud.dc.dao.DataCenterVnetDaoImpl" />
-   <bean id="dataStoreProviderDaoImpl" class="org.apache.cloudstack.storage.datastore.db.DataStoreProviderDaoImpl" />
    <bean id="dcDetailsDaoImpl" class="com.cloud.dc.dao.DcDetailsDaoImpl" />
 -  <bean id="engineDcDetailsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.api.db.dao.DcDetailsDaoImpl" />
 +  <bean id="engineDcDetailsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.dao.DcDetailsDaoImpl" />
    <bean id="diskOfferingJoinDaoImpl" class="com.cloud.api.query.dao.DiskOfferingJoinDaoImpl" />
    <bean id="domainDaoImpl" class="com.cloud.domain.dao.DomainDaoImpl" />
    <bean id="domainRouterDaoImpl" class="com.cloud.vm.dao.DomainRouterDaoImpl" />
@@@ -219,12 -218,13 +216,13 @@@
    <bean id="globalLoadBalancerLbRuleMapDaoImpl" class="org.apache.cloudstack.region.gslb.GlobalLoadBalancerLbRuleMapDaoImpl" />
    <bean id="guestOSCategoryDaoImpl" class="com.cloud.storage.dao.GuestOSCategoryDaoImpl" />
    <bean id="guestOSDaoImpl" class="com.cloud.storage.dao.GuestOSDaoImpl" />
+   <bean id="guestOSHypervisorDaoImpl" class="com.cloud.storage.dao.GuestOSHypervisorDaoImpl" />
    <bean id="highAvailabilityDaoImpl" class="com.cloud.ha.dao.HighAvailabilityDaoImpl" />
    <bean id="hostDaoImpl" class="com.cloud.host.dao.HostDaoImpl" />
 -  <bean id="engineHostDetailsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.api.db.dao.HostDetailsDaoImpl" />
 +  <bean id="engineHostDetailsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.dao.HostDetailsDaoImpl" />
    <bean id="hostDetailsDaoImpl" class="com.cloud.host.dao.HostDetailsDaoImpl" />
    <bean id="hostJoinDaoImpl" class="com.cloud.api.query.dao.HostJoinDaoImpl" />
 -  <bean id="engineHostTagsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.api.db.dao.HostTagsDaoImpl" />
 +  <bean id="engineHostTagsDaoImpl" class="org.apache.cloudstack.engine.datacenter.entity.dao.HostTagsDaoImpl" />
    <bean id="hostTagsDaoImpl" class="com.cloud.host.dao.HostTagsDaoImpl" />
    <bean id="hostTransferMapDaoImpl" class="com.cloud.cluster.agentlb.dao.HostTransferMapDaoImpl" />
    <bean id="iPAddressDaoImpl" class="com.cloud.network.dao.IPAddressDaoImpl" />
@@@ -773,11 -780,12 +773,10 @@@
    <bean id="snapshotStateMachineManagerImpl" class="org.apache.cloudstack.storage.snapshot.SnapshotStateMachineManagerImpl" />
    <bean id="statsCollector" class="com.cloud.server.StatsCollector" />
    <bean id="storagePoolAutomationImpl" class="com.cloud.storage.StoragePoolAutomationImpl" />
-   <bean id="templateInstallStrategyImpl" class="org.apache.cloudstack.storage.volume.TemplateInstallStrategyImpl" />
    <bean id="unknown" class="org.apache.cloudstack.storage.image.format.Unknown" />
    <bean id="usageEventUtils" class="com.cloud.event.UsageEventUtils" />
 -  <bean id="userContextInitializer" class="com.cloud.user.UserContextInitializer" />
    <bean id="VHD" class="org.apache.cloudstack.storage.image.format.VHD" />
 -  <bean id="vMEntityManagerImpl" class="org.apache.cloudstack.engine.cloud.entity.api.VMEntityManagerImpl" />
 -  <bean id="virtualMachineEntityFactory" class="org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntityFactory" />
 +  <bean id="vMEntityManagerImpl" class="org.apache.cloudstack.engine.vm.VMEntityManagerImpl" />
    <bean id="virtualMachineEntityImpl" class="org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntityImpl" />
    <bean id="virtualMachineRestService" class="org.apache.cloudstack.engine.rest.service.api.VirtualMachineRestService" />
    <bean id="volumeDataFactoryImpl" class="org.apache.cloudstack.storage.volume.VolumeDataFactoryImpl" />
@@@ -799,11 -807,13 +798,15 @@@
    <bean id="vMSnapshotManagerImpl" class="com.cloud.vm.snapshot.VMSnapshotManagerImpl" />
    <bean id="volumeManagerImpl" class="com.cloud.storage.VolumeManagerImpl" />
    <bean id="ClassicalPrimaryDataStoreProvider" class="org.apache.cloudstack.storage.datastore.provider.CloudStackPrimaryDataStoreProviderImpl" />
+   <bean id="cloudStackImageStoreProviderImpl" class="org.apache.cloudstack.storage.datastore.provider.CloudStackImageStoreProviderImpl" />
+   <bean id="s3ImageStoreProviderImpl" class="org.apache.cloudstack.storage.datastore.provider.S3ImageStoreProviderImpl" />
+   <bean id="swiftImageStoreProviderImpl" class="org.apache.cloudstack.storage.datastore.provider.SwiftImageStoreProviderImpl" />  
    <bean id="ApplicationLoadBalancerService" class="org.apache.cloudstack.network.lb.ApplicationLoadBalancerManagerImpl" />
    <bean id="InternalLoadBalancerVMManager" class="org.apache.cloudstack.network.lb.InternalLoadBalancerVMManagerImpl" />
+   <bean id="StorageCacheReplacementAlgorithm" class="org.apache.cloudstack.storage.cache.manager.StorageCacheReplacementAlgorithmLRU" />
  
 +  <bean id="VirtualMachinePowerStateSyncImpl" class="com.cloud.vm.VirtualMachinePowerStateSyncImpl" />
 +
  
  <!--=======================================================================================================-->
  <!--                                                                                                       -->
@@@ -873,8 -858,7 +875,7 @@@
    <bean id="BAREMETAL" class="org.apache.cloudstack.storage.image.format.BAREMETAL" />
    <bean id="baremetalDhcpDaoImpl" class="com.cloud.baremetal.database.BaremetalDhcpDaoImpl" />
    <bean id="baremetalPxeDaoImpl" class="com.cloud.baremetal.database.BaremetalPxeDaoImpl" />
- -->
 -
 +  
    <bean id="AffinityGroupServiceImpl" class="org.apache.cloudstack.affinity.AffinityGroupServiceImpl"/>
    <bean id="DeploymentPlanningManager" class="com.cloud.deploy.DeploymentPlanningManagerImpl">
      <property name="Planners" value="#{deploymentPlanners.Adapters}" />

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/core/src/com/cloud/agent/api/StopCommand.java
----------------------------------------------------------------------
diff --cc core/src/com/cloud/agent/api/StopCommand.java
index 7d3fd43,a3ee3c9..e0dde7d
--- a/core/src/com/cloud/agent/api/StopCommand.java
+++ b/core/src/com/cloud/agent/api/StopCommand.java
@@@ -23,34 -23,33 +23,38 @@@ public class StopCommand extends Reboot
      private boolean isProxy=false;
      private String urlPort=null;
      private String publicConsoleProxyIpAddress=null;
 +    private boolean cleanupOnly;
+     boolean executeInSequence = false;
  
      protected StopCommand() {
      }
  
-     public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress, boolean cleanupOnly) {
 -    public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress, boolean executeInSequence) {
++    public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress, boolean cleanupOnly, boolean executeInSequence) {
      	super(vm);
      	this.isProxy = isProxy;
      	this.urlPort = urlPort;
      	this.publicConsoleProxyIpAddress = publicConsoleProxyIpAddress;
 -    	this.executeInSequence = executeInSequence;
 +        this.cleanupOnly = cleanupOnly;
      }
  
-     public StopCommand(VirtualMachine vm, String vnet) {
+     public StopCommand(VirtualMachine vm, String vnet, boolean executeInSequence) {
          super(vm);
          this.vnet = vnet;
+         this.executeInSequence = executeInSequence;
      }
      
 +    public boolean isCleanupOnly() {
 +        return cleanupOnly;
 +    }
 +
-     public StopCommand(VirtualMachine vm) {
+     public StopCommand(VirtualMachine vm, boolean executeInSequence) {
          super(vm);
+         this.executeInSequence = executeInSequence;
      }
  
-     public StopCommand(String vmName) {
+     public StopCommand(String vmName, boolean executeInSequence) {
          super(vmName);
+         this.executeInSequence = executeInSequence;
      }
  
      public String getVnet() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/core/src/com/cloud/hypervisor/hyperv/resource/HypervResource.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java
----------------------------------------------------------------------
diff --cc engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java
index 51714ec,eccf0f4..01b5e78
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/StoragePoolAllocator.java
@@@ -23,23 -23,29 +23,28 @@@ import com.cloud.deploy.DeploymentPlann
  import com.cloud.storage.StoragePool;
  import com.cloud.utils.component.Adapter;
  import com.cloud.vm.DiskProfile;
--import com.cloud.vm.VirtualMachine;
  import com.cloud.vm.VirtualMachineProfile;
  
  /**
   */
  public interface StoragePoolAllocator extends Adapter {
- 	/** 
- 	* Determines which storage pools are suitable for the guest virtual machine 
 -    /**
 -     * Determines which storage pools are suitable for the guest virtual machine
 -     * 
++	/**
++	* Determines which storage pools are suitable for the guest virtual machine
 +	* 
- 	* @param DiskProfile dskCh
- 	* @param VirtualMachineProfile vmProfile
- 	* @param DeploymentPlan plan
- 	* @param ExcludeList avoid
+      * @param DiskProfile
+      *            dskCh
+      * @param VirtualMachineProfile
+      *            vmProfile
+      * @param DeploymentPlan
+      *            plan
+      * @param ExcludeList
+      *            avoid
 -     * @param int returnUpTo (use -1 to return all possible pools)
 +	* @param int returnUpTo (use -1 to return all possible pools)
- 	* @return List<StoragePool> List of storage pools that are suitable for the VM 
- 	**/ 
- 	List<StoragePool> allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoid, int returnUpTo);	
+      * @return List<StoragePool> List of storage pools that are suitable for the
+      *         VM
 -     **/
 -    List<StoragePool> allocateToPool(DiskProfile dskCh, VirtualMachineProfile<? extends VirtualMachine> vmProfile,
++	**/
++    List<StoragePool> allocateToPool(DiskProfile dskCh, VirtualMachineProfile vmProfile,
+             DeploymentPlan plan, ExcludeList avoid, int returnUpTo);
 -
 +	
- 	public static int RETURN_UPTO_ALL = -1;
+     static int RETURN_UPTO_ALL = -1;
  }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/components-api/src/com/cloud/agent/AgentManager.java
----------------------------------------------------------------------
diff --cc engine/components-api/src/com/cloud/agent/AgentManager.java
index 306a40f,0000000..5b12ff1
mode 100755,000000..100755
--- a/engine/components-api/src/com/cloud/agent/AgentManager.java
+++ b/engine/components-api/src/com/cloud/agent/AgentManager.java
@@@ -1,153 -1,0 +1,150 @@@
 +// 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.agent;
 +
 +import com.cloud.agent.api.Answer;
 +import com.cloud.agent.api.Command;
 +import com.cloud.agent.manager.Commands;
 +import com.cloud.exception.AgentUnavailableException;
 +import com.cloud.exception.OperationTimedoutException;
 +import com.cloud.host.HostVO;
 +import com.cloud.host.Status;
 +import com.cloud.host.Status.Event;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.utils.component.Manager;
 +
 +/**
 + * AgentManager manages hosts. It directly coordinates between the DAOs and the connections it manages.
 + */
 +public interface AgentManager extends Manager {
 +    public enum OnError {
 +        Continue, Stop
 +    }
 +
 +    public enum TapAgentsAction {
 +        Add,
 +        Del,
 +        Contains,
 +    }
 +    
 +    /**
 +     * easy send method that returns null if there's any errors. It handles all exceptions.
 +     * 
 +     * @param hostId
 +     *            host id
 +     * @param cmd
 +     *            command to send.
 +     * @return Answer if successful; null if not.
 +     */
 +    Answer easySend(Long hostId, Command cmd);
 +
 +    /**
 +     * Synchronous sending a command to the agent.
 +     * 
 +     * @param hostId
 +     *            id of the agent on host
 +     * @param cmd
 +     *            command
 +     * @return an Answer
 +     */
 +
 +    Answer send(Long hostId, Command cmd) throws AgentUnavailableException, OperationTimedoutException;
 +
 +    /**
 +     * Synchronous sending a list of commands to the agent.
 +     * 
 +     * @param hostId
 +     *            id of the agent on host
 +     * @param cmds
 +     *            array of commands
 +     * @param isControl
 +     *            Commands sent contains control commands
 +     * @param stopOnError
 +     *            should the agent stop execution on the first error.
 +     * @return an array of Answer
 +     */
 +    Answer[] send(Long hostId, Commands cmds) throws AgentUnavailableException, OperationTimedoutException;
 +
 +    Answer[] send(Long hostId, Commands cmds, int timeout) throws AgentUnavailableException, OperationTimedoutException;
 +
 +    /**
 +     * Asynchronous sending of a command to the agent.
 +     * 
 +     * @param hostId
 +     *            id of the agent on the host.
 +     * @param cmds
 +     *            Commands to send.
 +     * @param stopOnError
 +     *            should the agent stop execution on the first error.
 +     * @param listener
 +     *            the listener to process the answer.
 +     * @return sequence number.
 +     */
 +    long send(Long hostId, Commands cmds, Listener listener) throws AgentUnavailableException;
 +
 +    /**
 +     * Register to listen for host events. These are mostly connection and disconnection events.
 +     * 
 +     * @param listener
 +     * @param connections
 +     *            listen for connections
 +     * @param commands
 +     *            listen for connections
 +     * @param priority
 +     *            in listening for events.
 +     * @return id to unregister if needed.
 +     */
 +    int registerForHostEvents(Listener listener, boolean connections, boolean commands, boolean priority);
 +
 +
 +    /**
 +     * Register to listen for initial agent connections.
 +     * @param creator
 +     * @param priority in listening for events.
 +     * @return id to unregister if needed.
 +     */
 +    int registerForInitialConnects(StartupCommandProcessor creator,  boolean priority);
 +
 +    /**
 +     * Unregister for listening to host events.
 +     * 
 +     * @param id
 +     *            returned from registerForHostEvents
 +     */
 +    void unregisterForHostEvents(int id);
 +
 +    public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException;
 +
 +    Answer sendTo(Long dcId, HypervisorType type, Command cmd);
 +
-     void sendToSecStorage(HostVO ssHost, Command cmd, Listener listener) throws AgentUnavailableException;
 +
-     Answer sendToSecStorage(HostVO ssHost, Command cmd);
-     
 +    /* working as a lock while agent is being loaded */
 +    public boolean tapLoadingAgents(Long hostId, TapAgentsAction action);
 +    
 +    public boolean agentStatusTransitTo(HostVO host, Status.Event e, long msId);
 +    
 +    void disconnectWithoutInvestigation(long hostId, Status.Event event);
 +    
 +    public void pullAgentToMaintenance(long hostId);
 +    
 +    public void pullAgentOutMaintenance(long hostId);
 +
 +	boolean reconnect(long hostId);
 +    Answer sendToSSVM(Long dcId, final Command cmd);
 +
 +    void disconnectWithInvestigation(final long hostId, final Status.Event event);
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/components-api/src/com/cloud/agent/Listener.java
----------------------------------------------------------------------
diff --cc engine/components-api/src/com/cloud/agent/Listener.java
index 47b9bc3,0000000..242f90c
mode 100755,000000..100755
--- a/engine/components-api/src/com/cloud/agent/Listener.java
+++ b/engine/components-api/src/com/cloud/agent/Listener.java
@@@ -1,119 -1,0 +1,119 @@@
 +// 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.agent;
 +
 +import com.cloud.agent.api.AgentControlAnswer;
 +import com.cloud.agent.api.AgentControlCommand;
 +import com.cloud.agent.api.Answer;
 +import com.cloud.agent.api.Command;
 +import com.cloud.agent.api.StartupCommand;
 +import com.cloud.exception.ConnectionException;
- import com.cloud.host.HostVO;
++import com.cloud.host.Host;
 +import com.cloud.host.Status;
 +
 +/**
 + * There are several types of events that the AgentManager forwards
-  * 
++ *
 + *   1. Agent Connect & Disconnect
 + *   2. Commands sent by the agent.
 + *   3. Answers sent by the agent.
 + */
 +public interface Listener {
 +
- 	/**
- 	 * 
- 	 * @param agentId id of the agent
- 	 * @param seq sequence number return by the send() method.
- 	 * @param answers answers to the commands.
- 	 * @return true if processed.  false if not.
- 	 */
++    /**
++     *
++     * @param agentId id of the agent
++     * @param seq sequence number return by the send() method.
++     * @param answers answers to the commands.
++     * @return true if processed.  false if not.
++     */
 +    boolean processAnswers(long agentId, long seq, Answer[] answers);
 +
 +    /**
 +     * This method is called by the AgentManager when an agent sent
 +     * a command to the server.  In order to process these commands,
 +     * the Listener must be registered for host commands.
-      * 
++     *
 +     * @param agentId id of the agent.
 +     * @param seq sequence number of the command sent.
 +     * @param commands commands that were sent.
 +     * @return true if you processed the commands.  false if not.
 +     */
 +    boolean processCommands(long agentId, long seq, Command[] commands);
-     
++
 +    /**
 +     * process control command sent from agent under its management
 +     * @param agentId
 +     * @param cmd
 +     * @return
 +     */
 +    AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd);
 +
 +    /**
 +     * This method is called by AgentManager when an agent made a
 +     * connection to this server if the listener has
 +     * been registered for host events.
 +     * @param cmd command sent by the agent to the server on startup.
 +     * @param forRebalance TODO
 +     * @param agentId id of the agent
 +     * @throws ConnectionException if host has problems and needs to put into maintenance state.
 +     */
-     void processConnect(HostVO host, StartupCommand cmd, boolean forRebalance) throws ConnectionException;
-     
++    void processConnect(Host host, StartupCommand cmd, boolean forRebalance) throws ConnectionException;
++
 +    /**
 +     * This method is called by AgentManager when an agent disconnects
 +     * from this server if the listener has been registered for host events.
-      * 
++     *
 +     * If the Listener is passed to the send() method, this method is
 +     * also called by AgentManager if the agent disconnected.
-      * 
++     *
 +     * @param agentId id of the agent
 +     * @param state the current state of the agent.
 +     */
 +    boolean processDisconnect(long agentId, Status state);
-         
++
 +    /**
 +     * If this Listener is passed to the send() method, this method
 +     * is called by AgentManager after processing an answer
 +     * from the agent.  Returning true means you're expecting more
 +     * answers from the agent using the same sequence number.
-      * 
++     *
 +     * @return true if expecting more answers using the same sequence number.
 +     */
 +    boolean isRecurring();
 +
 +    /**
 +     * If the Listener is passed to the send() method, this method is
 +     * called to determine how long to wait for the reply.  The value
 +     * is in seconds.  -1 indicates to wait forever.  0 indicates to
 +     * use the default timeout.  If the timeout is
 +     * reached, processTimeout on this same Listener is called.
-      * 
++     *
 +     * @return timeout in seconds before processTimeout is called.
 +     */
 +    int getTimeout();
 +
 +    /**
 +     * If the Listener is passed to the send() method, this method is
 +     * called by the AgentManager to process a command timeout.
 +     * @param agentId id of the agent
 +     * @param seq sequence number returned by the send().
 +     * @return true if processed; false if not.
 +     */
 +    boolean processTimeout(long agentId, long seq);
-   
++
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/components-api/src/com/cloud/network/NetworkManager.java
----------------------------------------------------------------------
diff --cc engine/components-api/src/com/cloud/network/NetworkManager.java
index 0054c9a,0000000..3e73a8c
mode 100755,000000..100755
--- a/engine/components-api/src/com/cloud/network/NetworkManager.java
+++ b/engine/components-api/src/com/cloud/network/NetworkManager.java
@@@ -1,388 -1,0 +1,389 @@@
 +// 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.network;
 +
 +import java.util.List;
 +import java.util.Map;
 +
 +import org.apache.cloudstack.acl.ControlledEntity.ACLType;
 +
 +import com.cloud.dc.DataCenter;
 +import com.cloud.dc.Pod;
 +import com.cloud.dc.Vlan.VlanType;
 +import com.cloud.deploy.DataCenterDeployment;
 +import com.cloud.deploy.DeployDestination;
 +import com.cloud.deploy.DeploymentPlan;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.InsufficientAddressCapacityException;
 +import com.cloud.exception.InsufficientCapacityException;
 +import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
 +import com.cloud.exception.ResourceAllocationException;
 +import com.cloud.exception.ResourceUnavailableException;
 +import com.cloud.network.Network.Provider;
 +import com.cloud.network.Network.Service;
 +import com.cloud.network.addr.PublicIp;
 +import com.cloud.network.dao.IPAddressVO;
 +import com.cloud.network.dao.NetworkVO;
 +import com.cloud.network.element.DhcpServiceProvider;
 +import com.cloud.network.element.LoadBalancingServiceProvider;
 +import com.cloud.network.element.StaticNatServiceProvider;
 +import com.cloud.network.element.UserDataServiceProvider;
 +import com.cloud.network.guru.NetworkGuru;
 +import com.cloud.network.rules.FirewallRule;
 +import com.cloud.network.rules.LoadBalancerContainer.Scheme;
 +import com.cloud.network.rules.StaticNat;
 +import com.cloud.offering.NetworkOffering;
 +import com.cloud.offerings.NetworkOfferingVO;
 +import com.cloud.user.Account;
 +import com.cloud.user.User;
 +import com.cloud.utils.Pair;
 +import com.cloud.vm.Nic;
 +import com.cloud.vm.NicProfile;
 +import com.cloud.vm.NicVO;
 +import com.cloud.vm.ReservationContext;
 +import com.cloud.vm.VirtualMachine;
 +import com.cloud.vm.VirtualMachine.Type;
 +import com.cloud.vm.VirtualMachineProfile;
 +
 +/**
 + * NetworkManager manages the network for the different end users.
 + * 
 + */
 +public interface NetworkManager  {
 +    /**
 +     * Assigns a new public ip address.
 +     * 
 +     * @param dcId
 +     * @param podId
 +     *            TODO
 +     * @param owner
 +     * @param type
 +     * @param networkId
 +     * @param requestedIp
 +     *            TODO
 +     * @param allocatedBy
 +     *            TODO
 +     * @return
 +     * @throws InsufficientAddressCapacityException
 +     */
 +
 +    PublicIp assignPublicIpAddress(long dcId, Long podId, Account owner, VlanType type, Long networkId, String requestedIp,
 +            boolean isSystem) throws InsufficientAddressCapacityException;
 +
 +
 +    /**
 +     * Do all of the work of releasing public ip addresses. Note that if this method fails, there can be side effects.
 +     * 
 +     * @param userId
 +     * @param caller
 +     *            TODO
 +     * @param IpAddress
 +     * @return true if it did; false if it didn't
 +     */
 +    public boolean disassociatePublicIpAddress(long id, long userId, Account caller);
 +
 +    List<NetworkVO> setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, String displayText, boolean isDefault)
 +            throws ConcurrentOperationException;
 +
 +    List<NetworkVO> setupNetwork(Account owner, NetworkOffering offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId,
 +            ACLType aclType, Boolean subdomainAccess, Long vpcId, Boolean isDisplayNetworkEnabled) throws ConcurrentOperationException;
 +
 +    void allocate(VirtualMachineProfile vm, List<Pair<NetworkVO, NicProfile>> networks) throws InsufficientCapacityException, ConcurrentOperationException;
 +
 +    void prepare(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws InsufficientCapacityException, ConcurrentOperationException,
 +            ResourceUnavailableException;
 +
 +    void release(VirtualMachineProfile vmProfile, boolean forced) throws
 +			ConcurrentOperationException, ResourceUnavailableException;
 +
 +    void cleanupNics(VirtualMachineProfile vm);
 +
 +    void expungeNics(VirtualMachineProfile vm);
 +
 +    List<NicProfile> getNicProfiles(VirtualMachine vm);
 +
 +    boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose, NetworkRuleApplier applier, boolean continueOnError) throws ResourceUnavailableException;
 +
 +    Pair<NetworkGuru, NetworkVO> implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException,
 +            InsufficientCapacityException;
 +
 +    /**
 +     * prepares vm nic change for migration
 +     * 
 +     * This method will be called in migration transaction before the vm migration.
 +     * @param vm
 +     * @param dest
 +     */
 +    void prepareNicForMigration(VirtualMachineProfile vm, DeployDestination dest);
 +
 +    /**
 +     * commit vm nic change for migration
 +     * 
 +     * This method will be called in migration transaction after the successful
 +     * vm migration.
 +     * @param src
 +     * @param dst
 +     */
 +    void commitNicForMigration(VirtualMachineProfile src, VirtualMachineProfile dst);
 +
 +    /**
 +     * rollback vm nic change for migration
 +     * 
 +     * This method will be called in migaration transaction after vm migration
 +     * failure.
 +     * @param src
 +     * @param dst
 +     */
 +    void rollbackNicForMigration(VirtualMachineProfile src, VirtualMachineProfile dst);
 +
 +    boolean shutdownNetwork(long networkId, ReservationContext context, boolean cleanupElements);
 +
 +    boolean destroyNetwork(long networkId, ReservationContext context);
 +
 +    Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr,
 +            String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork physicalNetwork,
 +                               long zoneId, ACLType aclType, Boolean subdomainAccess, Long vpcId, String ip6Gateway, String ip6Cidr,
 +                               Boolean displayNetworkEnabled, String isolatedPvlan)
 +                    throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException;
 +
 +    /**
 +     * @throws ResourceAllocationException TODO
 +     * @throws InsufficientCapacityException
 +     *             Associates an ip address list to an account. The list of ip addresses are all addresses associated
 +     *             with the
 +     *             given vlan id.
 +     * @param userId
 +     * @param accountId
 +     * @param zoneId
 +     * @param vlanId
 +     * @throws InsufficientAddressCapacityException
 +     * @throws
 +     */
 +    boolean associateIpAddressListToAccount(long userId, long accountId, long zoneId, Long vlanId, Network guestNetwork) throws InsufficientCapacityException, ConcurrentOperationException,
 +            ResourceUnavailableException, ResourceAllocationException;
 +
 +    UserDataServiceProvider getPasswordResetProvider(Network network);
 +
 +    UserDataServiceProvider getSSHKeyResetProvider(Network network);
 +
 +    boolean applyIpAssociations(Network network, boolean continueOnError) throws ResourceUnavailableException;
 +    
 +    boolean applyIpAssociations(Network network, boolean rulesRevoked, boolean continueOnError, List<? extends PublicIpAddress> publicIps) throws ResourceUnavailableException;
 +
 +    boolean startNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
 +
 +    IPAddressVO markIpAsUnavailable(long addrId);
 +
 +    public String acquireGuestIpAddress(Network network, String requestedIp);
 +
 +    boolean applyStaticNats(List<? extends StaticNat> staticNats, boolean continueOnError) throws ResourceUnavailableException;
 +
 +    boolean reallocate(VirtualMachineProfile vm,
 +            DataCenterDeployment dest) throws InsufficientCapacityException, ConcurrentOperationException;
 +
 +    IpAddress assignSystemIp(long networkId, Account owner,
 +            boolean forElasticLb, boolean forElasticIp)
 +            throws InsufficientAddressCapacityException;
 +
 +    boolean handleSystemIpRelease(IpAddress ip);
 +
 +    void allocateDirectIp(NicProfile nic, DataCenter dc,
 +            VirtualMachineProfile vm,
 +            Network network, String requestedIpv4, String requestedIpv6)
 +            throws InsufficientVirtualNetworkCapcityException,
 +            InsufficientAddressCapacityException;
 +
 +    /**
 +     * @param owner
 +     * @param guestNetwork
 +     * @return
 +     * @throws ConcurrentOperationException
 +     * @throws InsufficientAddressCapacityException
 +     */
 +    PublicIp assignSourceNatIpAddressToGuestNetwork(Account owner, Network guestNetwork) throws InsufficientAddressCapacityException, ConcurrentOperationException;
 +
 +
 +    /**
 +     * @param requested
 +     * @param network
 +     * @param isDefaultNic
 +     * @param deviceId
 +     * @param vm
 +     * @return
 +     * @throws InsufficientVirtualNetworkCapcityException
 +     * @throws InsufficientAddressCapacityException
 +     * @throws ConcurrentOperationException
 +     */
 +    Pair<NicProfile,Integer> allocateNic(NicProfile requested, Network network, Boolean isDefaultNic, int deviceId,
 +            VirtualMachineProfile vm) throws InsufficientVirtualNetworkCapcityException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException;
 +
 +
 +    /**
 +     * @param vmProfile
 +     * @param dest
 +     * @param context
 +     * @param nicId
 +     * @param network
 +     * @return
 +     * @throws InsufficientVirtualNetworkCapcityException
 +     * @throws InsufficientAddressCapacityException
 +     * @throws ConcurrentOperationException
 +     * @throws InsufficientCapacityException
 +     * @throws ResourceUnavailableException
 +     */
 +    NicProfile prepareNic(VirtualMachineProfile vmProfile, DeployDestination dest,
 +            ReservationContext context, long nicId, NetworkVO network) throws InsufficientVirtualNetworkCapcityException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException;
 +
 +
 +    /**
 +     * @param vm
 +     * @param nic TODO
 +     */
 +    void removeNic(VirtualMachineProfile vm, Nic nic);
 +
 +
 +    /**
 +     * @param ipAddrId
 +     * @param networkId
 +     * @param releaseOnFailure TODO
 +     */
 +    IPAddressVO associateIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
 +        InsufficientAddressCapacityException, ConcurrentOperationException;
 +
 +    IpAddress allocatePortableIp(Account ipOwner, Account caller, long dcId, Long networkId, Long vpcID)
 +            throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException;
 +
 +    boolean releasePortableIpAddress(long addrId);
 +
 +    IPAddressVO associatePortableIPToGuestNetwork(long ipAddrId, long networkId, boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException;
 +
 +    IPAddressVO disassociatePortableIPToGuestNetwork(long ipAddrId, long networkId) throws ResourceAllocationException, ResourceUnavailableException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException;
 +
 +    boolean isPortableIpTransferableFromNetwork(long ipAddrId, long networkId);
 +
 +    void transferPortableIP(long ipAddrId, long currentNetworkId, long newNetworkId)  throws ResourceAllocationException, ResourceUnavailableException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException;;
 +
 +    /**
 +     * @param network
 +     * @param provider
 +     * @return
 +     */
 +    boolean setupDns(Network network, Provider provider);
 +
 +
 +    /**
 +     * @param vmProfile
 +     * @param nic TODO
 +     * @throws ConcurrentOperationException
 +     * @throws ResourceUnavailableException
 +     */
 +    void releaseNic(VirtualMachineProfile vmProfile, Nic nic)
 +            throws ConcurrentOperationException, ResourceUnavailableException;
 +
 +
 +    /**
 +     * @param network
 +     * @param requested
 +     * @param context
 +     * @param vmProfile
 +     * @param prepare TODO
 +     * @return
 +     * @throws InsufficientVirtualNetworkCapcityException
 +     * @throws InsufficientAddressCapacityException
 +     * @throws ConcurrentOperationException
 +     * @throws InsufficientCapacityException
 +     * @throws ResourceUnavailableException
 +     */
 +    NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare) throws InsufficientVirtualNetworkCapcityException,
 +            InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException;
 +
 +
 +    /**
 +     * @param addr
 +     */
 +    void markPublicIpAsAllocated(IPAddressVO addr);
 +
 +
 +    /**
 +     * @param owner
 +     * @param guestNtwkId
 +     * @param vpcId
 +     * @param dcId
 +     * @param isSourceNat
 +     * @return
 +     * @throws ConcurrentOperationException
 +     * @throws InsufficientAddressCapacityException
 +     */
 +    PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat) throws ConcurrentOperationException, InsufficientAddressCapacityException;
 +
 +    NetworkProfile convertNetworkToNetworkProfile(long networkId);
 +
 +    /**
 +     * @return
 +     */
 +    int getNetworkLockTimeout();
 +
 +
 +    boolean restartNetwork(Long networkId, Account callerAccount,
 +            User callerUser, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException;
 +
 +
 +    boolean shutdownNetworkElementsAndResources(ReservationContext context,
 +            boolean b, NetworkVO network);
 +
 +
 +	void implementNetworkElementsAndResources(DeployDestination dest,
 +			ReservationContext context, NetworkVO network,
 +			NetworkOfferingVO findById) throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException;
 +
 +
 +	IpAddress allocateIp(Account ipOwner, boolean isSystem, Account caller, long callerId,
 +			DataCenter zone) throws ConcurrentOperationException, ResourceAllocationException, InsufficientAddressCapacityException;
 +
 +	Map<String, String> finalizeServicesAndProvidersForNetwork(NetworkOffering offering,
 +			Long physicalNetworkId);
 +
 +    List<Provider> getProvidersForServiceInNetwork(Network network, Service service);
 +
 +    StaticNatServiceProvider getStaticNatProviderForNetwork(Network network);
 +    
 +    boolean isNetworkInlineMode(Network network);
 +
 +    int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state);
 +
 +    LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network, Scheme lbScheme);
 +
 +    boolean isSecondaryIpSetForNic(long nicId);
 +
 +    public String allocateGuestIP(Account ipOwner, boolean isSystem, long zoneId, Long networkId, String requestedIp) throws InsufficientAddressCapacityException;
 +
 +    List<? extends Nic> listVmNics(Long vmId, Long nicId);
 +    
 +    String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod, Account caller, String requestedIp) throws InsufficientAddressCapacityException;
 +
 +    NicVO savePlaceholderNic(Network network, String ip4Address, String ip6Address, Type vmType);
 +
 +    DhcpServiceProvider getDhcpServiceProvider(Network network);
 +
 +    PublicIp assignPublicIpAddressFromVlans(long dcId, Long podId, Account owner, VlanType type, List<Long> vlanDbIds, Long networkId, String requestedIp, boolean isSystem) throws InsufficientAddressCapacityException;
++
 +}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/engine/components-api/src/com/cloud/storage/VolumeManager.java
----------------------------------------------------------------------
diff --cc engine/components-api/src/com/cloud/storage/VolumeManager.java
index 5345aa7,0000000..15f24f7
mode 100644,000000..100644
--- a/engine/components-api/src/com/cloud/storage/VolumeManager.java
+++ b/engine/components-api/src/com/cloud/storage/VolumeManager.java
@@@ -1,121 -1,0 +1,122 @@@
 +/*
 + * 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;
 +
 +import java.util.Map;
 +
 +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd;
 +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd;
 +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
 +
 +import com.cloud.agent.api.to.VirtualMachineTO;
 +import com.cloud.deploy.DeployDestination;
 +import com.cloud.exception.ConcurrentOperationException;
 +import com.cloud.exception.InsufficientStorageCapacityException;
 +import com.cloud.exception.ResourceAllocationException;
 +import com.cloud.exception.StorageUnavailableException;
 +import com.cloud.host.Host;
 +import com.cloud.hypervisor.Hypervisor.HypervisorType;
 +import com.cloud.storage.Volume.Type;
 +import com.cloud.user.Account;
 +import com.cloud.vm.DiskProfile;
 +import com.cloud.vm.VMInstanceVO;
 +import com.cloud.vm.VirtualMachine;
 +import com.cloud.vm.VirtualMachineProfile;
 +
 +public interface VolumeManager extends VolumeApiService {
 +
 +    VolumeInfo moveVolume(VolumeInfo volume, long destPoolDcId, Long destPoolPodId,
 +            Long destPoolClusterId, HypervisorType dataDiskHyperType)
 +            throws ConcurrentOperationException;
 +
 +    @Override
 +    VolumeVO uploadVolume(UploadVolumeCmd cmd)
 +            throws ResourceAllocationException;
 +
 +    VolumeVO allocateDuplicateVolume(VolumeVO oldVol, Long templateId);
 +
 +    boolean volumeOnSharedStoragePool(VolumeVO volume);
 +
 +    boolean volumeInactive(Volume volume);
 +
 +    String getVmNameOnVolume(Volume volume);
 +
 +    @Override
 +    VolumeVO allocVolume(CreateVolumeCmd cmd)
 +            throws ResourceAllocationException;
 +
 +    @Override
 +    VolumeVO createVolume(CreateVolumeCmd cmd);
 +
 +    @Override
 +    VolumeVO resizeVolume(ResizeVolumeCmd cmd)
 +            throws ResourceAllocationException;
 +
 +    @Override
 +    boolean deleteVolume(long volumeId, Account caller)
 +            throws ConcurrentOperationException;
 +    
 +    void destroyVolume(VolumeVO volume);
 +
 +    DiskProfile allocateRawVolume(Type type, String name, DiskOfferingVO offering, Long size, VMInstanceVO vm, Account owner);
 +    @Override
 +    Volume attachVolumeToVM(AttachVolumeCmd command);
 +
 +    @Override
 +    Volume detachVolumeFromVM(DetachVolumeCmd cmmd);
 +
 +    void release(VirtualMachineProfile profile);
 +
 +    void cleanupVolumes(long vmId) throws ConcurrentOperationException;
 +
 +    @Override
 +    Volume migrateVolume(MigrateVolumeCmd cmd);
 +
 +    void migrateVolumes(VirtualMachine vm, VirtualMachineTO vmTo, Host srcHost, Host destHost,
 +            Map<Volume, StoragePool> volumeToPool);
 +
 +    boolean storageMigration(
 +            VirtualMachineProfile vm,
 +            StoragePool destPool);
 +
 +    void prepareForMigration(
 +            VirtualMachineProfile vm,
 +            DeployDestination dest);
 +
 +    void prepare(VirtualMachineProfile vm,
 +            DeployDestination dest) throws StorageUnavailableException,
 +            InsufficientStorageCapacityException, ConcurrentOperationException;
 +
 +    boolean canVmRestartOnAnotherServer(long vmId);
 +
 +    DiskProfile allocateTemplatedVolume(Type type, String name,
 +            DiskOfferingVO offering, VMTemplateVO template, VMInstanceVO vm,
 +            Account owner);
 +
++
 +    String getVmNameFromVolumeId(long volumeId);
 +
 +    String getStoragePoolOfVolume(long volumeId);
 +
 +    boolean validateVolumeSizeRange(long size);
 +}


[10/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
cloud-early-config: add device file existence check

If device file was not found, then it should be logged.


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

Branch: refs/heads/vmsync
Commit: 5c4578ef26adcc51e059963144174c955ba5542b
Parents: 009da93
Author: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Authored: Mon Jun 24 11:24:42 2013 +0900
Committer: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Committed: Mon Jun 24 11:24:42 2013 +0900

----------------------------------------------------------------------
 patches/systemvm/debian/config/etc/init.d/cloud-early-config | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5c4578ef/patches/systemvm/debian/config/etc/init.d/cloud-early-config
----------------------------------------------------------------------
diff --git a/patches/systemvm/debian/config/etc/init.d/cloud-early-config b/patches/systemvm/debian/config/etc/init.d/cloud-early-config
index b215271..f93c39d 100755
--- a/patches/systemvm/debian/config/etc/init.d/cloud-early-config
+++ b/patches/systemvm/debian/config/etc/init.d/cloud-early-config
@@ -112,6 +112,9 @@ get_boot_params() {
           sed -i "s/%/ /g" /var/cache/cloud/cmdline
           ;;
      kvm)
+          if [ ! -e /dev/vport0p1 ]; then
+            log_it "/dev/vport0p1 not loaded, perhaps guest kernel is too old." && exit 2
+          fi
           while read line; do
             if [[ $line == cmdline:* ]]; then
               cmd=${line//cmdline:/}
@@ -133,7 +136,7 @@ get_boot_params() {
           mount -t ntfs /dev/sdb1 $EXTRA_MOUNT
           cp -f $EXTRA_MOUNT/cmdline /var/cache/cloud/cmdline
           umount $EXTRA_MOUNT
-          ;;          
+          ;;
   esac
 
 }


[34/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
migration working


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

Branch: refs/heads/vmsync
Commit: a49109ae0bc25271c8d71f529ab52f5749a3b6bb
Parents: 95fe42c
Author: Alex Huang <al...@gmail.com>
Authored: Mon Jun 24 13:31:11 2013 -0700
Committer: Alex Huang <al...@gmail.com>
Committed: Mon Jun 24 13:31:11 2013 -0700

----------------------------------------------------------------------
 .../com/cloud/vm/VirtualMachineManagerImpl.java | 130 +++++++++----------
 .../test/com/cloud/vm/VmWorkTest.java           |   6 +-
 .../cloud/vm/VmWorkTestApiJobDispatcher.java    |   5 +-
 3 files changed, 66 insertions(+), 75 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a49109ae/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
index a1c2db4..97a3990 100755
--- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -56,6 +56,7 @@ import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
 import org.apache.cloudstack.framework.messagebus.MessageBus;
 import org.apache.cloudstack.framework.messagebus.MessageDispatcher;
 import org.apache.cloudstack.framework.messagebus.MessageHandler;
+import org.apache.cloudstack.jobs.JobInfo;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import org.apache.cloudstack.vm.jobs.VmWorkJobDao;
 import org.apache.cloudstack.vm.jobs.VmWorkJobVO;
@@ -511,7 +512,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
         _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
 
-        _agentMgr.registerForHost)Events(this, true, true, true);
+        _agentMgr.registerForHostEvents(this, true, true, true);
         
         RootVolumeSearch = _entityMgr.createSearchBuilder(VolumeVO.class);
         VolumeVO rvsEntity = RootVolumeSearch.entity();
@@ -1002,10 +1003,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                         VmWorkJobVO.Step prevStep = work.getStep();
                         _workJobDao.updateStep(work.getId(), VmWorkJobVO.Step.Release);
                         if (prevStep == VmWorkJobVO.Step.Started || prevStep == VmWorkJobVO.Step.Starting) {
-                            cleanup(vmGuru, vmProfile, work, VirtualMachine.Event.OperationFailed, false);
+                            cleanup(vmGuru, vmProfile, work, false);
                         } else {
                             //if step is not starting/started, send cleanup command with force=true
-                            cleanup(vmGuru, vmProfile, work, VirtualMachine.Event.OperationFailed, true);
+                            cleanup(vmGuru, vmProfile, work, true);
                         }
                     }
                 }
@@ -1225,7 +1226,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             }
 
             if (doCleanup) {
-                if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, VirtualMachine.Event.StopRequested, forced)) {
+                if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, forced)) {
                     try {
                         if (s_logger.isDebugEnabled()) {
                             s_logger.debug("Updating work item to Done, id:" + work.getId());
@@ -1589,25 +1590,57 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
                 _alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName()
                         + " in zone " + dest.getDataCenter().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed.  Please check logs.");
+
+                boolean cleanup = false;
                 try {
-                    _agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
-                } catch (AgentUnavailableException ae) {
-                    s_logger.info("Looks like the destination Host is unavailable for cleanup");
+                    cleanupMigration(work, dstVm, vm, false);
+                    cleanup = true;
+                } catch (Exception ae) {
+                    s_logger.warn("Unable to cleanup migration for " + vm);
                 }
 
-                try {
-                    stateTransitTo(vm, VirtualMachine.Event.OperationFailed, srcHostId);
-                } catch (NoTransitionException e) {
-                    s_logger.warn(e.getMessage());
+                if (cleanup) {
+                    _networkMgr.rollbackNicForMigration(srcVm, dstVm);
+
+                    work.setStep(Step.Done);
+                    _workJobDao.update(work.getId(), work);
                 }
-                _networkMgr.rollbackNicForMigration(srcVm, dstVm);
-                
-                work.setStep(Step.Done);
-                _workJobDao.update(work.getId(), work);
             }
         }
     }
 
+    private void determineVmLocation(VirtualMachineProfile vm, VMInstanceVO vo, boolean confirmedStopped) {
+        try {
+            if (checkVmOnHost(vo, vo.getLastHostId())) {
+                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getLastHostId());
+            } else if (checkVmOnHost(vo, vo.getHostId())) {
+                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId());
+            } else {
+                s_logger.warn("Unable to find " + vo + " on source " + vo.getLastHostId() + " or on destination " + vo.getHostId()
+                        + (!confirmedStopped ? ".  Either call Stop with cleanup option or wait for vmsync to check where the VM is." : "."));
+                stateTransitTo(vo, VirtualMachine.Event.AgentReportStopped, null);
+            }
+        } catch (AgentUnavailableException e) {
+            if (confirmedStopped) {
+                s_logger.debug("Agent is unavailable to determine state for " + vo + " but continuing with confirmed stopped option");
+            } else {
+                throw new CloudRuntimeException("Unable to determine the state for " + vo).add(VirtualMachine.class, vo.getUuid());
+            }
+        } catch (OperationTimedoutException e) {
+            if (confirmedStopped) {
+                s_logger.debug("Operation timedout while determining state for " + vo + " but continuing with confirmed stopped option");
+            } else {
+                throw new CloudRuntimeException("Unable to determine the state for " + vo).add(VirtualMachine.class, vo.getUuid());
+            }
+        } catch (NoTransitionException e) {
+            throw new CloudRuntimeException("Unable to change VM state ", e).add(VirtualMachine.class, vo.getUuid());
+        }
+
+        if (confirmedStopped) {
+            s_logger.info("Cleanup was requested on " + vo);
+            cleanup(getVmGuru(vo), vm, null, true);
+        }
+    }
     /**
      * Migration goes through the following steps.
      *   Prepare - nics and storage are prepared
@@ -1622,8 +1655,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
      * @param vo - vo object representing the VM.
      */
     private void cleanupMigration(VmWorkJobVO job, VirtualMachineProfile vm, VMInstanceVO vo, boolean confirmedStopped) {
-        boolean uncertain = false;
-        boolean rollbackPreparation = false;
         if (job == null) {
             s_logger.info("Cleaning up " + vo + " with no job to track progress");
             if (vo.getState() != VirtualMachine.State.Migrating) {
@@ -1632,48 +1663,20 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                 }
                 return;
             }
-            if (checkVmOnHost(vo, vo.getLastHostId())) {
-                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getLastHostId());
-            } else if (checkVmOnHost(vo, vo.getHostId())) {
-                stateTransitTo(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId());
-            } else {
-                s_logger.warn("Unable to find " + vo + " on source " + vo.getLastHostId() + " or on destination " + vo.getHostId() + (!confirmedStopped ? ".  Either call Stop with cleanup option or wait for vmsync to check where the VM is." : "."));
-            }
-            
-            if (confirmedStopped) {
-                s_logger.info("Cleanup was requested on " + vo);
-                cleanup(getVmGuru(vo), vm, null, true);
-            }
+            determineVmLocation(vm, vo, confirmedStopped);
             return;
         }
         
         Step step = job.getStep();
         
-        s_logger.info("Cleaning up based on what stage the current job is at: " + step);
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Migration operation was at " + step + " for " + vo);
+        }
         if (step == Step.Started) {
-            if (checkVmOnHost(vo, vo.getLastHostId())) {
-                changeState2(vo, VirtualMachine.Event.AgentReportRunning, vo.getHostId(), job, Event.OperationSucceeded);
-            } else {
-                changeState2(vo, VirtualMachine.Event.AgentReportStopped, vo.getHostId(), job, Event.OperationFailed);
-            }
+            determineVmLocation(vm, vo, confirmedStopped);
         } else if (step == Step.Migrating) {
-            s_logger.debug("We are at the migrating step.  We have to find out if the operation succeeded or ");
-        }
-        if (step == Step.Prepare) {
-            s_logger.debug("Prepare Step: ");
-            rollbackPreparation = true;
-        }
-
-        if (uncertain) {
-            Long srcHostId = vo.getLastHostId();
-            Long dstHostId = vo.getHostId();
-
-            if (!checkVmOnHost(vo, srcHostId)) {
-                changeState2(vo, Event.OperationFailed, job,)
-            }
-
+            determineVmLocation(vm, vo, confirmedStopped);
         }
-
     }
 
 
@@ -1827,7 +1830,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                     } catch (AgentUnavailableException e) {
                         s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                     }
-                    cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, VirtualMachine.Event.AgentReportStopped, true);
+                    cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, true);
                     return null;
                 }
             } catch (OperationTimedoutException e) {
@@ -1952,27 +1955,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
             excludes.addHost(dest.getHost().getId());
             VirtualMachine vmInstance = null;
+            Outcome<VirtualMachine> outcome = migrate(vm.getUuid(), srcHostId, dest);
             try {
-                vmInstance = migrate(vm.getUuid(), srcHostId, dest);
-            } catch (ResourceUnavailableException e) {
-                s_logger.debug("Unable to migrate to unavailable " + dest);
-            } catch (ConcurrentOperationException e) {
-                s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
-            } catch (ManagementServerException e) {
-                s_logger.debug("Unable to migrate VM: " + e.getMessage());
-            } catch (VirtualMachineMigrationException e) {
-                s_logger.debug("Got VirtualMachineMigrationException, Unable to migrate: " + e.getMessage());
-                if (vm.getState() == State.Starting) {
-                    s_logger.debug("VM seems to be still Starting, we should retry migration later");
-                    throw e;
-                } else {
-                    s_logger.debug("Unable to migrate VM, VM is not in Running or even Starting state, current state: " + vm.getState().toString());
-                }
+                vmInstance = outcome.get();
+            } catch (InterruptedException e1) {
+                s_logger.warn("Unable to migrate teh VM", e1);
+            } catch (java.util.concurrent.ExecutionException e1) {
+                s_logger.warn("Unable to migrate the VM", e1);
             }
             if (vmInstance != null) {
                 return true;
             }
-            Outcome<VirtualMachine> outcome = stop(vm.getUuid(), true);
+            outcome = stop(vm.getUuid(), true);
             try {
                 outcome.get(_jobTimeout.value(), TimeUnit.MILLISECONDS);
                 return true;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a49109ae/engine/orchestration/test/com/cloud/vm/VmWorkTest.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/test/com/cloud/vm/VmWorkTest.java b/engine/orchestration/test/com/cloud/vm/VmWorkTest.java
index 09fa10f..dfbe0a8 100644
--- a/engine/orchestration/test/com/cloud/vm/VmWorkTest.java
+++ b/engine/orchestration/test/com/cloud/vm/VmWorkTest.java
@@ -112,7 +112,7 @@ public class VmWorkTest extends TestCase {
 	
 	@Test
 	public void testVmWorkStart() {
-		VmWorkStart work = new VmWorkStart();
+        VmWorkStart work = new VmWorkStart(1L, 1L, 1L);
 		Map<VirtualMachineProfile.Param, Object> params = new HashMap<VirtualMachineProfile.Param, Object>();
 		params.put(VirtualMachineProfile.Param.HaTag, "HA");
 		params.put(VirtualMachineProfile.Param.ControlNic, new Long(100));
@@ -133,12 +133,12 @@ public class VmWorkTest extends TestCase {
 		workJob.setVmType(VirtualMachine.Type.ConsoleProxy);
 		workJob.setVmInstanceId(1L);
 		
-		VmWorkStart workInfo = new VmWorkStart();
+        VmWorkStart workInfo = new VmWorkStart(1L, 1L, 1L);
         workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));
 		
 		_jobMgr.submitAsyncJob(workJob, "VM", 1);
 		
-		_jobMgr.waitAndCheck(new String[] {"Done"}, 120000, 120000, new Predicate() {
+        _jobMgr.waitAndCheck(workJob, new String[] {"Done"}, 120000, 120000, new Predicate() {
 
 			@Override
 			public boolean checkCondition() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a49109ae/engine/orchestration/test/com/cloud/vm/VmWorkTestApiJobDispatcher.java
----------------------------------------------------------------------
diff --git a/engine/orchestration/test/com/cloud/vm/VmWorkTestApiJobDispatcher.java b/engine/orchestration/test/com/cloud/vm/VmWorkTestApiJobDispatcher.java
index 766929a..98f5474 100644
--- a/engine/orchestration/test/com/cloud/vm/VmWorkTestApiJobDispatcher.java
+++ b/engine/orchestration/test/com/cloud/vm/VmWorkTestApiJobDispatcher.java
@@ -65,10 +65,7 @@ public class VmWorkTestApiJobDispatcher extends AdapterBase implements AsyncJobD
 		workJob.setVmInstanceId(1L);
 
 		// save work context info (there are some duplications)
-		VmWorkStart workInfo = new VmWorkStart();
-		workInfo.setAccountId(1L);
-		workInfo.setUserId(1L);
-		workInfo.setVmId(1L);
+        VmWorkStart workInfo = new VmWorkStart(1L, 1L, 1L);
 		workInfo.setPlan(null);
 		workInfo.setParams(null);
         workJob.setCmdInfo(VmWorkJobDispatcher.serialize(workInfo));


[06/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
More edits to release notes.


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

Branch: refs/heads/vmsync
Commit: 0015ac8bd32a1b7042427811e8e3f8fb33a8e5e8
Parents: 84ecc11
Author: Joe Brockmeier <jz...@zonker.net>
Authored: Sun Jun 23 16:17:42 2013 -0500
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 16:17:42 2013 -0500

----------------------------------------------------------------------
 docs/en-US/Release_Notes.xml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0015ac8b/docs/en-US/Release_Notes.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/Release_Notes.xml b/docs/en-US/Release_Notes.xml
index 4a27cd2..a4fcd47 100644
--- a/docs/en-US/Release_Notes.xml
+++ b/docs/en-US/Release_Notes.xml
@@ -5593,7 +5593,7 @@ service cloudstack-agent start
               <programlisting language="Bash">$ sudo apt-get install cloudstack-management</programlisting>
             </listitem>
             <listitem id="kvm-agent-deb-22">
-              <para>You will need to manually install the <filename>cloudstack-agent</filename>
+              <para>On KVM hosts, you will need to manually install the <filename>cloudstack-agent</filename>
                 package:</para>
               <programlisting language="Bash">$ sudo apt-get install cloudstack-agent</programlisting>
               <para>During the installation of <filename>cloudstack-agent</filename>, APT will copy
@@ -5616,7 +5616,7 @@ service cloudstack-agent start
 service cloud-agent stop
 killall jsvc
 service cloudstack-agent start
-                            </programlisting>
+              </programlisting>
             </listitem>
             <listitem>
               <para>During the upgrade, <filename>log4j-cloud.xml</filename> was simply copied over,


[07/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Remove unused code

The files xt_CHECKSUM.ko, iptables_1.4.8-3local1checksum1_i386
and xe-guest-utilities_5.6.0-595_i386 does not exist in the
repo now.


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

Branch: refs/heads/vmsync
Commit: bdfce2bc7e349949112876fa21c55b4bd7d6248a
Parents: 0015ac8
Author: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Authored: Mon Jun 24 11:09:09 2013 +0900
Committer: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Committed: Mon Jun 24 11:09:09 2013 +0900

----------------------------------------------------------------------
 patches/systemvm/debian/buildsystemvm.sh | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bdfce2bc/patches/systemvm/debian/buildsystemvm.sh
----------------------------------------------------------------------
diff --git a/patches/systemvm/debian/buildsystemvm.sh b/patches/systemvm/debian/buildsystemvm.sh
index 5134f89..d8a6da7 100755
--- a/patches/systemvm/debian/buildsystemvm.sh
+++ b/patches/systemvm/debian/buildsystemvm.sh
@@ -477,9 +477,9 @@ scriptdir=$(dirname $PWD/$0)
 
 rm -rf /tmp/systemvm
 mkdir -p /tmp/systemvm
-cp ./xt_CHECKSUM.ko /tmp/systemvm
-cp ./iptables_1.4.8-3local1checksum1_i386.deb /tmp/systemvm
-cp ./xe-guest-utilities_5.6.0-595_i386.deb /tmp/systemvm
+#cp ./xt_CHECKSUM.ko /tmp/systemvm
+#cp ./iptables_1.4.8-3local1checksum1_i386.deb /tmp/systemvm
+#cp ./xe-guest-utilities_5.6.0-595_i386.deb /tmp/systemvm
 
 rm -f $IMAGELOC
 begin=$(date +%s)


[18/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3155 [VMware] Deletion of zone should not be allowed if VMware DC is still associated with that zone.

Check if there exists any VMware DC already associated with this zone. Deny zone deletion if true.

Signed-off-by: Sateesh Chodapuneedi <sa...@apache.org>


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

Branch: refs/heads/vmsync
Commit: e9df9c29bde4374e443c91ed91e2706b6074082f
Parents: bd5ad44
Author: Sateesh Chodapuneedi <sa...@apache.org>
Authored: Mon Jun 24 12:11:31 2013 +0530
Committer: Sateesh Chodapuneedi <sa...@apache.org>
Committed: Mon Jun 24 12:11:31 2013 +0530

----------------------------------------------------------------------
 .../src/com/cloud/configuration/ConfigurationManagerImpl.java  | 6 ++++++
 1 file changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e9df9c29/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index 425c8be..89a640d 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -1301,6 +1301,12 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         physicalNetworks.add(2, "there are physical networks in this zone");
         tablesToCheck.add(physicalNetworks);
 
+        List<String> vmwareDcs = new ArrayList<String>();
+        vmwareDcs.add(0, "vmware_data_center_zone_map");
+        vmwareDcs.add(1, "zone_id");
+        vmwareDcs.add(2, "there are VMware datacenters associated with this zone. Remove VMware DC from this zone.");
+        tablesToCheck.add(vmwareDcs);
+
         for (List<String> table : tablesToCheck) {
             String tableName = table.get(0);
             String column = table.get(1);


[23/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3148 failed to create private gw with default acl id


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

Branch: refs/heads/vmsync
Commit: bb50c0d2d654e9a18c8bb04660ae407c54c6ac35
Parents: 0cd8f9e
Author: Jayapal <ja...@apache.org>
Authored: Mon Jun 24 12:56:27 2013 +0530
Committer: Jayapal <ja...@apache.org>
Committed: Mon Jun 24 13:37:01 2013 +0530

----------------------------------------------------------------------
 server/src/com/cloud/network/vpc/VpcManagerImpl.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bb50c0d2/server/src/com/cloud/network/vpc/VpcManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java
index fb9e9b7..93413b4 100644
--- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java
+++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java
@@ -1389,7 +1389,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
             if ( aclVO == null) {
                 throw new InvalidParameterValueException("Invalid network acl id passed ");
             }
-            if (aclVO.getVpcId() != vpcId ) {
+            if ((aclVO.getVpcId() != vpcId) && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
                 throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
             }
 


[17/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-2181: Scale down is allowed when one resource(say cpu) is being scale up and other resource (say ram) is
 being scale down ;but not allowed when both resources are being scaledown
Signed off by : Nitin Mehta<ni...@citrix.com>


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

Branch: refs/heads/vmsync
Commit: 1eb744fa1600f9400e407c6e3615da40b18758c1
Parents: 7767472
Author: Harikrishna Patnala <ha...@citrix.com>
Authored: Mon Jun 24 12:09:44 2013 +0530
Committer: Nitin Mehta <ni...@citrix.com>
Committed: Mon Jun 24 12:09:55 2013 +0530

----------------------------------------------------------------------
 server/src/com/cloud/vm/UserVmManagerImpl.java | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/1eb744fa/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 7b3b1bc..66103fb 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -1160,9 +1160,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         int currentMemory = currentServiceOffering.getRamSize();
         int currentSpeed = currentServiceOffering.getSpeed();
 
-        if(newSpeed     <= currentSpeed
-           && newMemory <= currentMemory
-           && newCpu    <= currentCpu){
+        // Don't allow to scale when (Any of the new values less than current values) OR (All current and new values are same)
+        if( (newSpeed < currentSpeed || newMemory < currentMemory || newCpu < currentCpu)
+                ||  ( newSpeed == currentSpeed && newMemory == currentMemory && newCpu == currentCpu)){
             throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering should have both cpu and memory greater than the old values");
         }
 


[16/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-308. ec2-describe-instances - Instance type should return right service offering name


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

Branch: refs/heads/vmsync
Commit: 77674721cacba4bdf446c048118f10c474c92f03
Parents: f3fa54e
Author: Likitha Shetty <li...@citrix.com>
Authored: Mon Jun 24 11:07:19 2013 +0530
Committer: Likitha Shetty <li...@citrix.com>
Committed: Mon Jun 24 11:29:12 2013 +0530

----------------------------------------------------------------------
 .../com/cloud/bridge/model/CloudStackServiceOfferingVO.java | 9 +++++++--
 .../bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java    | 4 ++--
 awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java | 2 +-
 3 files changed, 10 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/77674721/awsapi/src/com/cloud/bridge/model/CloudStackServiceOfferingVO.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/model/CloudStackServiceOfferingVO.java b/awsapi/src/com/cloud/bridge/model/CloudStackServiceOfferingVO.java
index de2941e..f63301a 100644
--- a/awsapi/src/com/cloud/bridge/model/CloudStackServiceOfferingVO.java
+++ b/awsapi/src/com/cloud/bridge/model/CloudStackServiceOfferingVO.java
@@ -30,7 +30,10 @@ public class CloudStackServiceOfferingVO {
     @Id
     @Column(name="id")
     private String id;
-    
+
+    @Column(name="uuid")
+    private String uuid;
+
     @Column(name="name")
     private String name;
     
@@ -61,7 +64,9 @@ public class CloudStackServiceOfferingVO {
     public void setDomainId(String domainId) {
         this.domainId = domainId;
     }
-    
 
+    public String getUuid() {
+        return uuid;
+    }
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/77674721/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
index 8cca13e..f0d05d3 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/CloudStackSvcOfferingDaoImpl.java
@@ -58,13 +58,13 @@ public class CloudStackSvcOfferingDaoImpl extends GenericDaoBase<CloudStackServi
 	@Override
     public CloudStackServiceOfferingVO getSvcOfferingById( String id ){
         SearchBuilder <CloudStackServiceOfferingVO> searchByID = createSearchBuilder();
-        searchByID.and("id", searchByID.entity().getName(), SearchCriteria.Op.EQ);
+        searchByID.and("uuid", searchByID.entity().getUuid(), SearchCriteria.Op.EQ);
         searchByID.done();
         Transaction txn = Transaction.open(Transaction.CLOUD_DB);
         try {
             txn.start();
             SearchCriteria<CloudStackServiceOfferingVO> sc = searchByID.create();
-            sc.setParameters("id", id);
+            sc.setParameters("uuid", id);
             return findOneBy(sc);
         
         }finally {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/77674721/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
index 1859bb8..f24bfed 100644
--- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
+++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
@@ -1772,7 +1772,7 @@ public class EC2Engine extends ManagerBase {
     private String serviceOfferingIdToInstanceType( String serviceOfferingId ) throws Exception {
         try{
 
-            CloudStackServiceOfferingVO offering =  scvoDao.getSvcOfferingById(serviceOfferingId); //dao.getSvcOfferingById(serviceOfferingId);
+            CloudStackServiceOfferingVO offering =  scvoDao.getSvcOfferingById(serviceOfferingId);
             if(offering == null){
                 logger.warn( "No instanceType match for serviceOfferingId: [" + serviceOfferingId + "]" );
                 return "m1.small";


[08/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Add iptables-persistent service in guest OS.

cloud-passwd-srvr depends on iptables-persistent.


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

Branch: refs/heads/vmsync
Commit: 3123fe6bbad5c9e216f52c7fa882db4c2b6b5d91
Parents: bdfce2b
Author: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Authored: Mon Jun 24 11:14:16 2013 +0900
Committer: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Committed: Mon Jun 24 11:14:16 2013 +0900

----------------------------------------------------------------------
 patches/systemvm/debian/buildsystemvm.sh | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3123fe6b/patches/systemvm/debian/buildsystemvm.sh
----------------------------------------------------------------------
diff --git a/patches/systemvm/debian/buildsystemvm.sh b/patches/systemvm/debian/buildsystemvm.sh
index d8a6da7..dac785c 100755
--- a/patches/systemvm/debian/buildsystemvm.sh
+++ b/patches/systemvm/debian/buildsystemvm.sh
@@ -409,7 +409,9 @@ services() {
   chroot . chkconfig xl2tpd off
   chroot . chkconfig --add cloud-early-config
   chroot . chkconfig cloud-early-config on
-  chroot . chkconfig --add cloud-passwd-srvr 
+  chroot . chkconfig --add iptables-persistent
+  chroot . chkconfig iptables-persistent off
+  chroot . chkconfig --force --add cloud-passwd-srvr
   chroot . chkconfig cloud-passwd-srvr off
   chroot . chkconfig --add cloud
   chroot . chkconfig cloud off


[04/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Adding instructions for restarting MySQL on Debian/Ubuntu systems, since the name of the service differs. Found during Hack Day.


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

Branch: refs/heads/vmsync
Commit: 2a8297bee5417a76fbe87dd0361dbfecdeb76022
Parents: 2e06da5
Author: Joe Brockmeier <jz...@zonker.net>
Authored: Sun Jun 23 14:05:19 2013 -0500
Committer: Joe Brockmeier <jz...@zonker.net>
Committed: Sun Jun 23 14:05:58 2013 -0500

----------------------------------------------------------------------
 docs/en-US/database-replication.xml | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/2a8297be/docs/en-US/database-replication.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/database-replication.xml b/docs/en-US/database-replication.xml
index bb14457..8ca8071 100644
--- a/docs/en-US/database-replication.xml
+++ b/docs/en-US/database-replication.xml
@@ -37,10 +37,14 @@ server_id=1
         <para>The server_id must be unique with respect to other servers. The recommended way to achieve this is to give the master an ID of 1 and each slave a sequential number greater than 1, so that the servers are numbered 1, 2, 3, etc.</para>
     </listitem>
     <listitem>
-        <para>Restart the MySQL service:</para>
+        <para>Restart the MySQL service. On RHEL/CentOS systems, use:</para>
         <programlisting>
 # service mysqld restart
         </programlisting>
+        <para>On Debian/Ubuntu systems, use:</para>
+        <programlisting>
+# service mysql restart
+        </programlisting>
     </listitem>
     <listitem>
         <para>Create a replication account on the master and give it privileges. We will use the "cloud-repl" user with the password "password". This assumes that master and slave run on the 172.16.1.0/24 network.</para>
@@ -90,10 +94,14 @@ innodb_lock_wait_timeout=600
         </programlisting>
     </listitem>
     <listitem>
-        <para>Restart MySQL.</para>
+        <para>Restart MySQL. Use "mysqld" on RHEL/CentOS systems:</para>
         <programlisting>
 # service mysqld restart
         </programlisting>
+        <para>On Ubuntu/Debian systems use "mysql."</para>
+        <programlisting>
+# service mysql restart
+        </programlisting>
     </listitem>
     <listitem>
         <para>Instruct the slave to connect to and replicate from the master. Replace the IP address, password, log file, and position with the values you have used in the previous steps.</para>


[25/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-1578 SRX: Egress default policy configurable using network offering on SRX firewall


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

Branch: refs/heads/vmsync
Commit: c22e7d00523ed3b194984d080355080ab1c881dd
Parents: 6a7ae63
Author: Jayapal <ja...@apache.org>
Authored: Thu Jun 20 16:28:09 2013 +0530
Committer: Jayapal <ja...@apache.org>
Committed: Mon Jun 24 13:37:01 2013 +0530

----------------------------------------------------------------------
 .../com/cloud/agent/api/to/FirewallRuleTO.java  | 19 ++++-
 .../network/resource/JuniperSrxResource.java    | 86 ++++++++++++++------
 scripts/network/juniper/security-policy-add.xml |  3 +-
 .../ExternalFirewallDeviceManagerImpl.java      | 24 ++----
 4 files changed, 86 insertions(+), 46 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c22e7d00/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
index f296aa4..29d9c6f 100644
--- a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
+++ b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java
@@ -53,6 +53,9 @@ public class FirewallRuleTO implements InternalIdentity {
     private Integer icmpType;
     private Integer icmpCode;
     private FirewallRule.TrafficType trafficType;
+    private String guestCidr;
+    private boolean defaultEgressPolicy;
+    private FirewallRule.FirewallRuleType type;
 
     protected FirewallRuleTO() {
     }
@@ -110,9 +113,12 @@ public class FirewallRuleTO implements InternalIdentity {
         this(rule.getId(),srcVlanTag, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), revokeState, alreadyAdded, purpose,rule.getSourceCidrList(),rule.getIcmpType(),rule.getIcmpCode());
     }
 
-    public FirewallRuleTO(FirewallRule rule, String guestVlanTag, FirewallRule.TrafficType trafficType) {
+    public FirewallRuleTO(FirewallRule rule, String guestVlanTag, FirewallRule.TrafficType trafficType, String guestCidr, boolean defaultEgressPolicy, FirewallRule.FirewallRuleType type) {
         this(rule.getId(), guestVlanTag, null, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(), rule.getSourceCidrList(), rule.getIcmpType(), rule.getIcmpCode());
         this.trafficType = trafficType;
+        this.defaultEgressPolicy = defaultEgressPolicy;
+        this.guestCidr = guestCidr;
+        this.type = type;
     }
 
     public FirewallRule.TrafficType getTrafficType(){
@@ -170,4 +176,15 @@ public class FirewallRuleTO implements InternalIdentity {
         return purpose;
     }
 
+    public boolean isDefaultEgressPolicy() {
+        return defaultEgressPolicy;
+    }
+
+    public String getGuestCidr() {
+        return guestCidr;
+    }
+
+    public FirewallRule.FirewallRuleType getType() {
+        return type;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c22e7d00/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java
index fd065d5..3d3d797 100644
--- a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java
+++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
 import java.io.StringReader;
+import java.lang.String;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
 import java.util.ArrayList;
@@ -321,7 +322,8 @@ public class JuniperSrxResource implements ServerResource {
         STATIC_NAT("staticnat"),
         DESTINATION_NAT("destnat"),
         VPN("vpn"),
-        SECURITYPOLICY_EGRESS("egress");
+        SECURITYPOLICY_EGRESS("egress"),
+        SECURITYPOLICY_EGRESS_DEFAULT("egress-default");
 
         private String identifier;
 
@@ -828,15 +830,37 @@ public class JuniperSrxResource implements ServerResource {
             if (rules[0].getTrafficType() == FirewallRule.TrafficType.Egress) {
                 Map<String, ArrayList<FirewallRuleTO>> activeRules = getActiveFirewallEgressRules(rules);
                 Set<String> guestVlans = activeRules.keySet();
-                List<String> cidrs = new ArrayList();
+               // List<String> cidrs = new ArrayList();
+                boolean defaultEgressPolicy = rules[0].isDefaultEgressPolicy();
+                FirewallRule.FirewallRuleType type = rules[0].getType();
+                //getting
+                String guestCidr = rules[0].getGuestCidr();
 
                 for (String guestVlan : guestVlans) {
                     List<FirewallRuleTO> activeRulesForGuestNw = activeRules.get(guestVlan);
 
-                    removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractCidrs(activeRulesForGuestNw));
-                    if (activeRulesForGuestNw.size() > 0) {
-                        addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractApplications(activeRulesForGuestNw), extractCidrs(activeRulesForGuestNw));
+                    removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractCidrs(activeRulesForGuestNw), defaultEgressPolicy);
+                    if (activeRulesForGuestNw.size() > 0 && type == FirewallRule.FirewallRuleType.User) {
+                        addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS, guestVlan, extractApplications(activeRulesForGuestNw), extractCidrs(activeRulesForGuestNw), defaultEgressPolicy);
                     }
+
+                    List<Object[]> applications = new ArrayList<Object[]>();
+                    Object[] application = new Object[3];
+                    application[0] = Protocol.all;
+                    application[1] = NetUtils.PORT_RANGE_MIN;
+                    application[2] = NetUtils.PORT_RANGE_MAX;
+                    applications.add(application);
+
+                    List<String> cidrs = new ArrayList<String>();
+                    cidrs.add(guestCidr);
+                    //remove required with out comparing default policy  because in upgrade network offering we may required to delete
+                    // the previously added rule
+                    removeEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, cidrs, false);
+                    if (defaultEgressPolicy == true) {
+                        //add default egress security policy
+                        addEgressSecurityPolicyAndApplications(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT, guestVlan, applications, cidrs, false);
+                    }
+
                 }
                 commitConfiguration();
             } else {
@@ -1046,7 +1070,7 @@ public class JuniperSrxResource implements ServerResource {
 		
 		// Delete all security policies
 		for (String securityPolicyName : getVpnObjectNames(SrxXml.SECURITY_POLICY_GETALL, accountId)) {
-            manageSecurityPolicy(SecurityPolicyType.VPN, SrxCommand.DELETE, accountId, null, null, null, null, securityPolicyName);
+            manageSecurityPolicy(SecurityPolicyType.VPN, SrxCommand.DELETE, accountId, null, null, null, null, securityPolicyName, false);
 		}
 		
 		// Delete all address book entries 
@@ -1118,7 +1142,7 @@ public class JuniperSrxResource implements ServerResource {
     			manageAddressBookEntry(srxCmd, _privateZone , guestNetworkCidr, ipsecVpnName);
     			
     			// Security policy
-                manageSecurityPolicy(SecurityPolicyType.VPN, srxCmd, null, null, guestNetworkCidr, null, null, ipsecVpnName);
+                manageSecurityPolicy(SecurityPolicyType.VPN, srxCmd, null, null, guestNetworkCidr, null, null, ipsecVpnName, false);
     		}
     		
     		commitConfiguration();
@@ -2511,7 +2535,7 @@ public class JuniperSrxResource implements ServerResource {
         if (protocol.equals(Protocol.any)) {
             return Protocol.any.toString();
         } else {
-            if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS)) {
+            if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
                 return genObjectName(type.getIdentifier(), protocol.toString(), String.valueOf(startPort), String.valueOf(endPort));
             } else {
                 return genObjectName(protocol.toString(), String.valueOf(startPort), String.valueOf(endPort));
@@ -2528,7 +2552,7 @@ public class JuniperSrxResource implements ServerResource {
         Integer endPort;
         int offset = 0;
         try {
-            offset = type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) ? 1 : 0;
+            offset = (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT))? 1 : 0;
             protocol = getProtocol(applicationComponents[offset + 0]);
             startPort = Integer.parseInt(applicationComponents[offset + 1]);
             endPort = Integer.parseInt(applicationComponents[offset + 2]);
@@ -2694,7 +2718,7 @@ public class JuniperSrxResource implements ServerResource {
         }    		    
     }
 
-    private boolean manageSecurityPolicy(SecurityPolicyType type, SrxCommand command, Long accountId, String username, String privateIp, List<String> applicationNames, List<String> cidrs, String ipsecVpnName) throws ExecutionException {
+    private boolean manageSecurityPolicy(SecurityPolicyType type, SrxCommand command, Long accountId, String username, String privateIp, List<String> applicationNames, List<String> cidrs, String ipsecVpnName, boolean defaultEgressAction) throws ExecutionException {
         String fromZone = _publicZone;
         String toZone = _privateZone;
         
@@ -2704,7 +2728,7 @@ public class JuniperSrxResource implements ServerResource {
         if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) {
             securityPolicyName = ipsecVpnName;
             addressBookEntryName = ipsecVpnName;
-        } else if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS)) {
+        } else if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
             fromZone = _privateZone;
             toZone = _publicZone;
             securityPolicyName = genSecurityPolicyName(type, accountId, username, fromZone, toZone, privateIp);
@@ -2748,7 +2772,7 @@ public class JuniperSrxResource implements ServerResource {
             return false;
 
         case ADD:
-            if (!type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS)) {
+            if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT))) {
                 if (!manageAddressBookEntry(SrxCommand.CHECK_IF_EXISTS, toZone, privateIp, addressBookEntryName)) {
                     throw new ExecutionException("No address book entry for policy: " + securityPolicyName);
                 }
@@ -2756,9 +2780,10 @@ public class JuniperSrxResource implements ServerResource {
 
             String srcAddrs = "";
             String dstAddrs = "";
+            String action = "";
             xml = SrxXml.SECURITY_POLICY_ADD.getXml();
             xml = replaceXmlValue(xml, "policy-name", securityPolicyName);
-            if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS)) {
+            if (type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT)) {
                 xml = replaceXmlValue(xml, "from-zone", _privateZone);
                 xml = replaceXmlValue(xml, "to-zone", _publicZone);
                 if (cidrs == null) {
@@ -2771,6 +2796,13 @@ public class JuniperSrxResource implements ServerResource {
                 xml = replaceXmlValue(xml, "src-address", srcAddrs);
                 dstAddrs = "<destination-address>any</destination-address>";
                 xml = replaceXmlValue(xml, "dst-address", dstAddrs);
+                if (defaultEgressAction == true) {
+                    //configure block rules and default allow the traffic
+                    action = "<deny></deny>";
+                } else {
+                    action = "<permit></permit>";
+                }
+                xml = replaceXmlValue(xml, "action", action);
             } else {
                 xml = replaceXmlValue(xml, "from-zone", fromZone);
                 xml = replaceXmlValue(xml, "to-zone", toZone);
@@ -2781,9 +2813,13 @@ public class JuniperSrxResource implements ServerResource {
             }
 
             if (type.equals(SecurityPolicyType.VPN) && ipsecVpnName != null) {
-            	xml = replaceXmlValue(xml, "tunnel", "<tunnel><ipsec-vpn>" + ipsecVpnName + "</ipsec-vpn></tunnel>");
+                xml = replaceXmlValue(xml, "tunnel", "<permit><tunnel><ipsec-vpn>" + ipsecVpnName + "</ipsec-vpn></tunnel></permit>");
             } else {      	
             	xml = replaceXmlValue(xml, "tunnel", "");
+                if (!(type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS_DEFAULT) || type.equals(SecurityPolicyType.SECURITYPOLICY_EGRESS))) {
+                    action = "<permit></permit>";
+                    xml = replaceXmlValue(xml, "action", action);
+                }
             }
                         
             String applications;
@@ -2805,11 +2841,11 @@ public class JuniperSrxResource implements ServerResource {
             }
 
         case DELETE:
-            if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, applicationNames, cidrs, ipsecVpnName)) {
+            if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) {
                 return true;
             }
 
-            if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, applicationNames, cidrs, ipsecVpnName)) {
+            if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, applicationNames, cidrs, ipsecVpnName, defaultEgressAction)) {
                 return true;
             }
 
@@ -2874,17 +2910,17 @@ public class JuniperSrxResource implements ServerResource {
         }
 
         // Add a new security policy
-        manageSecurityPolicy(type, SrxCommand.ADD, null, null, privateIp, applicationNames, null, null);
+        manageSecurityPolicy(type, SrxCommand.ADD, null, null, privateIp, applicationNames, null, null, false);
 
         return true;
     }
 
     private boolean removeSecurityPolicyAndApplications(SecurityPolicyType type, String privateIp) throws ExecutionException {
-        if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, null,null, null)) {
+        if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, privateIp, null,null, null, false)) {
             return true;
         }
 
-        if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, null, null, null)) {
+        if (manageSecurityPolicy(type, SrxCommand.CHECK_IF_IN_USE, null, null, privateIp, null, null, null, false)) {
             return true;
         }
 
@@ -2892,7 +2928,7 @@ public class JuniperSrxResource implements ServerResource {
         List<String> applications = getApplicationsForSecurityPolicy(type, privateIp, _publicZone, _privateZone);
 
         // Remove the security policy
-        manageSecurityPolicy(type, SrxCommand.DELETE, null, null, privateIp, null, null, null);
+        manageSecurityPolicy(type, SrxCommand.DELETE, null, null, privateIp, null, null, null, false);
 
         // Remove any applications for the removed security policy that are no longer in use
         List<String> unusedApplications = getUnusedApplications(applications, _publicZone, _privateZone);
@@ -2916,8 +2952,8 @@ public class JuniperSrxResource implements ServerResource {
     }
 
 
-    private boolean removeEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List <String> cidrs) throws ExecutionException {
-        if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, guestVlan, null, cidrs, null)) {
+    private boolean removeEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List <String> cidrs, boolean defaultEgressAction) throws ExecutionException {
+        if (!manageSecurityPolicy(type, SrxCommand.CHECK_IF_EXISTS, null, null, guestVlan, null, cidrs, null, defaultEgressAction)) {
             return true;
         }
         // Get a list of applications for this security policy
@@ -2925,7 +2961,7 @@ public class JuniperSrxResource implements ServerResource {
         applications = getApplicationsForSecurityPolicy(type, guestVlan, _privateZone, _publicZone);
 
         // Remove the security policy even if it is in use
-        manageSecurityPolicy(type, SrxCommand.DELETE, null, null, guestVlan, null, cidrs, null);
+        manageSecurityPolicy(type, SrxCommand.DELETE, null, null, guestVlan, null, cidrs, null, defaultEgressAction);
 
         // Remove any applications for the removed security policy that are no longer in use
         List<String> unusedApplications;
@@ -2953,7 +2989,7 @@ public class JuniperSrxResource implements ServerResource {
         return true;
     }
 
-    private boolean addEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List<Object[]> applications, List <String> cidrs) throws ExecutionException {
+    private boolean addEgressSecurityPolicyAndApplications(SecurityPolicyType type, String guestVlan, List<Object[]> applications, List <String> cidrs, boolean defaultEgressAction) throws ExecutionException {
         // Add all necessary applications
         List<String> applicationNames = new ArrayList<String>();
         for (Object[] application : applications) {
@@ -2975,7 +3011,7 @@ public class JuniperSrxResource implements ServerResource {
             }
 
         // Add a new security policy
-        manageSecurityPolicy(type, SrxCommand.ADD, null, null, guestVlan, applicationNames, cidrs, null);
+        manageSecurityPolicy(type, SrxCommand.ADD, null, null, guestVlan, applicationNames, cidrs, null, defaultEgressAction);
         s_logger.debug("Added Egress firewall rule for guest network " + guestVlan);
         return true;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c22e7d00/scripts/network/juniper/security-policy-add.xml
----------------------------------------------------------------------
diff --git a/scripts/network/juniper/security-policy-add.xml b/scripts/network/juniper/security-policy-add.xml
index 595e026..2e5a7d0 100644
--- a/scripts/network/juniper/security-policy-add.xml
+++ b/scripts/network/juniper/security-policy-add.xml
@@ -32,9 +32,8 @@ under the License.
 %applications%
 </match>
 <then>
-<permit>
+%action%
 %tunnel%
-</permit>
 <count>
 </count>
 </then>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c22e7d00/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java
index 9b190aa..4f5a2d5 100644
--- a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java
+++ b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java
@@ -26,6 +26,8 @@ import java.util.Map;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import com.cloud.network.dao.*;
+import com.cloud.offerings.NetworkOfferingVO;
 import org.apache.cloudstack.api.ApiConstants;
 import org.apache.cloudstack.api.response.ExternalFirewallResponse;
 import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice;
@@ -65,23 +67,6 @@ import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.host.dao.HostDetailsDao;
 import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.dao.ExternalFirewallDeviceDao;
-import com.cloud.network.dao.ExternalFirewallDeviceVO;
-import com.cloud.network.dao.FirewallRulesDao;
-import com.cloud.network.dao.IPAddressDao;
-import com.cloud.network.dao.IPAddressVO;
-import com.cloud.network.dao.InlineLoadBalancerNicMapDao;
-import com.cloud.network.dao.InlineLoadBalancerNicMapVO;
-import com.cloud.network.dao.LoadBalancerDao;
-import com.cloud.network.dao.NetworkDao;
-import com.cloud.network.dao.NetworkExternalFirewallDao;
-import com.cloud.network.dao.NetworkExternalFirewallVO;
-import com.cloud.network.dao.NetworkServiceMapDao;
-import com.cloud.network.dao.PhysicalNetworkDao;
-import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
-import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
-import com.cloud.network.dao.PhysicalNetworkVO;
-import com.cloud.network.dao.VpnUserDao;
 import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.FirewallRule.Purpose;
 import com.cloud.network.rules.FirewallRuleVO;
@@ -538,6 +523,9 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
         }
 
         List<FirewallRuleTO> rulesTO = new ArrayList<FirewallRuleTO>();
+        NetworkVO networkVO = _networkDao.findById(network.getId());
+        NetworkOfferingVO offering = _networkOfferingDao.findById(networkVO.getNetworkOfferingId());
+        Boolean defaultEgressPolicy = offering.getEgressDefaultPolicy();
 
         for (FirewallRule rule : rules) {
             if (rule.getSourceCidrList() == null && (rule.getPurpose() == Purpose.Firewall || rule.getPurpose() == Purpose.NetworkACL)) {
@@ -547,7 +535,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
             if (rule.getPurpose() == Purpose.Firewall && rule.getTrafficType() == FirewallRule.TrafficType.Egress) {
                 String guestVlanTag = network.getBroadcastUri().getHost();
                 String guestCidr = network.getCidr();
-                ruleTO = new FirewallRuleTO(rule, guestVlanTag, rule.getTrafficType());
+                ruleTO = new FirewallRuleTO(rule, guestVlanTag, rule.getTrafficType(), guestCidr, defaultEgressPolicy, rule.getType());
             } else {
                 IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
                 Vlan vlan = _vlanDao.findById(sourceIp.getVlanId());


[21/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-1578 Egress default policy configurable using network offering in xenserver with VR as firewall provider


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

Branch: refs/heads/vmsync
Commit: 6a7ae637dd3043c1fcf432c4e7037037f07def04
Parents: 4f45673
Author: Jayapal <ja...@apache.org>
Authored: Thu Jun 20 16:27:02 2013 +0530
Committer: Jayapal <ja...@apache.org>
Committed: Mon Jun 24 13:37:00 2013 +0530

----------------------------------------------------------------------
 api/src/com/cloud/offering/NetworkOffering.java |  1 +
 .../org/apache/cloudstack/api/ApiConstants.java |  1 +
 .../admin/network/CreateNetworkOfferingCmd.java | 10 ++++++
 .../api/response/NetworkOfferingResponse.java   |  7 ++++
 .../api/routing/NetworkElementCommand.java      |  1 +
 .../com/cloud/network/rules/FirewallRuleVO.java |  7 ++++
 .../com/cloud/offerings/NetworkOfferingVO.java  | 10 +++++-
 .../debian/config/root/firewallRule_egress.sh   | 26 +++++++++++---
 .../xen/resource/CitrixResourceBase.java        |  8 +++++
 server/src/com/cloud/api/ApiResponseHelper.java |  1 +
 .../configuration/ConfigurationManager.java     |  2 +-
 .../configuration/ConfigurationManagerImpl.java | 10 ++++--
 .../com/cloud/network/NetworkManagerImpl.java   | 37 +++++++++++++-------
 .../network/firewall/FirewallManagerImpl.java   | 31 ++++++++++++++++
 .../VirtualNetworkApplianceManagerImpl.java     | 32 ++++++++++++-----
 .../cloud/network/rules/FirewallManager.java    |  1 +
 .../cloud/server/ConfigurationServerImpl.java   |  2 +-
 .../cloud/network/MockFirewallManagerImpl.java  |  5 +++
 .../cloud/vpc/MockConfigurationManagerImpl.java |  2 +-
 .../CreateNetworkOfferingTest.java              | 20 +++++------
 setup/db/db/schema-410to420.sql                 |  1 +
 21 files changed, 173 insertions(+), 42 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/api/src/com/cloud/offering/NetworkOffering.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java
index 5f522eb..43312db 100644
--- a/api/src/com/cloud/offering/NetworkOffering.java
+++ b/api/src/com/cloud/offering/NetworkOffering.java
@@ -127,5 +127,6 @@ public interface NetworkOffering extends InfrastructureEntity, InternalIdentity,
     boolean getInternalLb();
 
     boolean getPublicLb();
+    boolean getEgressDefaultPolicy();
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index 50832a3..8ac7c3f 100755
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -121,6 +121,7 @@ public class ApiConstants {
     public static final String IS_PORTABLE = "isportable";
     public static final String IS_PUBLIC = "ispublic";
     public static final String IS_PERSISTENT = "ispersistent";
+    public static final String EGRESS_DEFAULT_POLICY = "egressdefaultpolicy";
     public static final String IS_READY = "isready";
     public static final String IS_RECURSIVE = "isrecursive";
     public static final String ISO_FILTER = "isofilter";

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java
index febb0c3..94e263c 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java
@@ -99,6 +99,9 @@ public class CreateNetworkOfferingCmd extends BaseCmd {
     		" Supported keys are internallbprovider/publiclbprovider with service provider as a value")
     protected Map details;
 
+    @Parameter(name=ApiConstants.EGRESS_DEFAULT_POLICY, type=CommandType.BOOLEAN, description="true if default guest network egress policy is allow; false if default egress policy is deny")
+    private Boolean egressDefaultPolicy;
+
     /////////////////////////////////////////////////////
     /////////////////// Accessors ///////////////////////
     /////////////////////////////////////////////////////
@@ -162,6 +165,13 @@ public class CreateNetworkOfferingCmd extends BaseCmd {
         return isPersistent == null ? false : isPersistent;
     }
 
+    public Boolean getEgressDefaultPolicy() {
+        if (egressDefaultPolicy == null) {
+            return true;
+        }
+        return egressDefaultPolicy;
+    }
+
     public Map<String, List<String>> getServiceProviders() {
         Map<String, List<String>> serviceProviderMap = null;
         if (serviceProviderList != null && !serviceProviderList.isEmpty()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java
index 7a7e371..6b35d7b 100644
--- a/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java
+++ b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java
@@ -88,6 +88,9 @@ public class NetworkOfferingResponse extends BaseResponse {
     @SerializedName(ApiConstants.DETAILS) @Param(description="additional key/value details tied with network offering", since="4.2.0")
     private Map details;
 
+    @SerializedName(ApiConstants.EGRESS_DEFAULT_POLICY) @Param(description="true if network offering supports persistent networks, false otherwise")
+    private Boolean egressDefaultPolicy;
+
 
     public void setId(String id) {
         this.id = id;
@@ -166,4 +169,8 @@ public class NetworkOfferingResponse extends BaseResponse {
         this.details = details;
     }
 
+    public void setEgressDefaultPolicy(Boolean egressDefaultPolicy) {
+        this.egressDefaultPolicy = egressDefaultPolicy;
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
index ddb7ac8..843d213 100644
--- a/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
+++ b/core/src/com/cloud/agent/api/routing/NetworkElementCommand.java
@@ -33,6 +33,7 @@ public abstract class NetworkElementCommand extends Command {
     public static final String ZONE_NETWORK_TYPE = "zone.network.type";
     public static final String GUEST_BRIDGE = "guest.bridge";
     public static final String VPC_PRIVATE_GATEWAY = "vpc.gateway.private";
+    public static final String FIREWALL_EGRESS_DEFAULT = "firewall.egress.default";
 
 
     protected NetworkElementCommand() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/engine/schema/src/com/cloud/network/rules/FirewallRuleVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/network/rules/FirewallRuleVO.java b/engine/schema/src/com/cloud/network/rules/FirewallRuleVO.java
index 9f73029..a51c364 100644
--- a/engine/schema/src/com/cloud/network/rules/FirewallRuleVO.java
+++ b/engine/schema/src/com/cloud/network/rules/FirewallRuleVO.java
@@ -223,6 +223,13 @@ public class FirewallRuleVO implements FirewallRule {
     }
 
 
+    public FirewallRuleVO(String xId, Long ipAddressId, Integer portStart, Integer portEnd, String protocol,
+                          long networkId, long accountId, long domainId, Purpose purpose, List<String> sourceCidrs, Integer icmpCode,
+                          Integer icmpType, Long related, TrafficType trafficType, FirewallRuleType type) {
+        this(xId, ipAddressId, portStart, portEnd, protocol, networkId, accountId, domainId, purpose, sourceCidrs, icmpCode, icmpType, related, trafficType);
+        this.type = type;
+    }
+
     public FirewallRuleVO(String xId, long ipAddressId, int port, String protocol, long networkId, long accountId, 
             long domainId, Purpose purpose, List<String> sourceCidrs, Integer icmpCode, Integer icmpType, Long related) {
         this(xId, ipAddressId, port, port, protocol, networkId, accountId, domainId, purpose, sourceCidrs, icmpCode, icmpType, related, null);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java b/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java
index fae315b..6317f72 100755
--- a/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java
+++ b/engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java
@@ -130,6 +130,9 @@ public class NetworkOfferingVO implements NetworkOffering {
     @Column(name = "is_persistent")
     boolean isPersistent;
 
+    @Column(name = "egress_default_policy")
+    boolean egressdefaultpolicy;
+
     @Override
     public String getDisplayText() {
         return displayText;
@@ -275,6 +278,10 @@ public class NetworkOfferingVO implements NetworkOffering {
         this.redundantRouter = redundantRouter;
     }
 
+    public boolean getEgressDefaultPolicy() {
+        return egressdefaultpolicy;
+    }
+
     public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
             Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean specifyIpRanges, boolean isPersistent, boolean internalLb, boolean publicLb) {
         this.name = name;
@@ -306,7 +313,7 @@ public class NetworkOfferingVO implements NetworkOffering {
 
     public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
             Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb,
-            boolean specifyIpRanges, boolean inline, boolean isPersistent, boolean associatePublicIP, boolean publicLb, boolean internalLb) {
+            boolean specifyIpRanges, boolean inline, boolean isPersistent, boolean associatePublicIP, boolean publicLb, boolean internalLb, boolean egressdefaultpolicy) {
         this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges, isPersistent, internalLb, publicLb);
         this.dedicatedLB = dedicatedLb;
         this.sharedSourceNat = sharedSourceNat;
@@ -315,6 +322,7 @@ public class NetworkOfferingVO implements NetworkOffering {
         this.elasticLb = elasticLb;
         this.inline = inline;
         this.eipAssociatePublicIp = associatePublicIP;
+        this.egressdefaultpolicy = egressdefaultpolicy;
     }
 
     public NetworkOfferingVO() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/patches/systemvm/debian/config/root/firewallRule_egress.sh
----------------------------------------------------------------------
diff --git a/patches/systemvm/debian/config/root/firewallRule_egress.sh b/patches/systemvm/debian/config/root/firewallRule_egress.sh
index 0da7718..b1e7a40 100755
--- a/patches/systemvm/debian/config/root/firewallRule_egress.sh
+++ b/patches/systemvm/debian/config/root/firewallRule_egress.sh
@@ -82,15 +82,14 @@ fw_entry_for_egress() {
       [ "$eport" == "-1" ] && typecode="$sport"
       [ "$sport" == "-1" ] && typecode="any"
       sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr --icmp-type $typecode \
-                     -j ACCEPT
+                     -j $target
       result=$?
     elif [ "$prot" == "all" ]
     then
-	    sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr -j ACCEPT
+	    sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr -j $target
 	    result=$?
     else
-	    sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr \
-	     	    $DPORT -j ACCEPT
+	    sudo iptables -A FW_EGRESS_RULES -p $prot -s $lcidr  $DPORT -j $target
 	    result=$?
     fi
   
@@ -109,14 +108,18 @@ rules=""
 rules_list=""
 ip=""
 dev=""
+pflag=0
 shift
 shift
-while getopts 'a:' OPTION
+while getopts 'a:P:' OPTION
 do
   case $OPTION in
   a)	aflag=1
 		rules="$OPTARG"
 		;;
+  P)   pflag=1
+       pvalue="$OPTARG"
+       ;;
   ?)	usage
                 unlock_exit 2 $lock $locked
 		;;
@@ -142,6 +145,13 @@ fi
 
 success=0
 
+if [ "$pvalue" == "0" -o "$pvalue" == "2" ]
+  then
+     target="ACCEPT"
+  else
+     target="DROP"
+  fi
+
 fw_egress_chain
 for r in $rules_list
 do
@@ -162,6 +172,12 @@ then
   fw_egress_backup_restore
 else
   logger -t cloud "deleting backup for guest network"
+    if [ "$pvalue" == "1" -o "$pvalue" == "2" ]
+       then
+       #Adding default policy rule
+       sudo iptables -A FW_EGRESS_RULES  -j ACCEPT
+    fi
+
 fi
 
 fw_egress_remove_backup

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index fa0e1d0..af640a2 100644
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@ -7994,6 +7994,7 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         String callResult;
         Connection conn = getConnection();
         String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+        String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT);
         FirewallRuleTO[] allrules = cmd.getRules();
         FirewallRule.TrafficType trafficType = allrules[0].getTrafficType();
         if (routerIp == null) {
@@ -8005,6 +8006,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe
         args += routerIp + " -F";
         if (trafficType == FirewallRule.TrafficType.Egress){
             args+= " -E";
+            if (egressDefault.equals("true")) {
+                args+= " -P 1";
+            } else if (egressDefault.equals("System")) {
+                args+= " -P 2";
+            } else {
+                args+= " -P 0";
+            }
         }
         StringBuilder sb = new StringBuilder();
         String[] fwRules = rules[0];

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index 7d91e95..b56aa4a 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -2009,6 +2009,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         response.setAvailability(offering.getAvailability().toString());
         response.setIsPersistent(offering.getIsPersistent());
         response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId()));
+        response.setEgressDefaultPolicy(offering.getEgressDefaultPolicy());
         Long so = null;
         if (offering.getServiceOfferingId() != null) {
             so = offering.getServiceOfferingId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/configuration/ConfigurationManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManager.java b/server/src/com/cloud/configuration/ConfigurationManager.java
index 93cadfa..98eae37 100755
--- a/server/src/com/cloud/configuration/ConfigurationManager.java
+++ b/server/src/com/cloud/configuration/ConfigurationManager.java
@@ -215,7 +215,7 @@ public interface ConfigurationManager extends ConfigurationService, Manager {
 
     NetworkOfferingVO createNetworkOffering(String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate, Map<Service, Set<Provider>> serviceProviderMap,
             boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map<Service, Map<Capability, String>> serviceCapabilityMap,
-            boolean specifyIpRanges, boolean isPersistent, Map<NetworkOffering.Detail,String> details);
+            boolean specifyIpRanges, boolean isPersistent, Map<NetworkOffering.Detail,String> details, boolean egressDefaultPolicy);
 
     Vlan createVlanAndPublicIpRange(long zoneId, long networkId, long physicalNetworkId, boolean forVirtualNetwork, Long podId, String startIP, String endIP, String vlanGateway, String vlanNetmask, String vlanId, Account vlanOwner, String startIPv6, String endIPv6, String vlanIp6Gateway, String vlanIp6Cidr) throws InsufficientCapacityException, ConcurrentOperationException, InvalidParameterValueException;
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index f7440c0..425c8be 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -3824,6 +3824,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         boolean specifyIpRanges = cmd.getSpecifyIpRanges();
         boolean isPersistent = cmd.getIsPersistent();
         Map<String, String> detailsStr = cmd.getDetails();
+        Boolean egressDefaultPolicy = cmd.getEgressDefaultPolicy();
 
         // Verify traffic type
         for (TrafficType tType : TrafficType.values()) {
@@ -4011,6 +4012,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             Set<Provider> firewallProviderSet = new HashSet<Provider>();
             firewallProviderSet.add(firewallProvider);
             serviceProviderMap.put(Service.Firewall, firewallProviderSet);
+            if (!(firewallProvider.getName().equals(Provider.JuniperSRX.getName()) || firewallProvider.getName().equals(Provider.VirtualRouter.getName())) && egressDefaultPolicy == false) {
+                throw new InvalidParameterValueException("Firewall egress with default policy " +  egressDefaultPolicy + "is not supported by the provider "+ firewallProvider.getName());
+            }
         }
 
         Map<NetworkOffering.Detail, String> details = new HashMap<NetworkOffering.Detail, String>();
@@ -4032,7 +4036,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
 
         return createNetworkOffering(name, displayText, trafficType, tags, specifyVlan, availability, networkRate,
                 serviceProviderMap, false, guestType, false, serviceOfferingId, conserveMode, serviceCapabilityMap,
-                specifyIpRanges, isPersistent, details);
+                specifyIpRanges, isPersistent, details, egressDefaultPolicy);
     }
 
     void validateLoadBalancerServiceCapabilities(Map<Capability, String> lbServiceCapabilityMap) {
@@ -4167,7 +4171,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, Network.GuestType type,
             boolean systemOnly, Long serviceOfferingId, boolean conserveMode,
             Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent,
-            Map<NetworkOffering.Detail, String> details) {
+            Map<NetworkOffering.Detail, String> details, boolean egressDefaultPolicy) {
 
         String multicastRateStr = _configDao.getValue("multicast.throttling.rate");
         int multicastRate = ((multicastRateStr == null) ? 10 : Integer.parseInt(multicastRateStr));
@@ -4310,7 +4314,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         NetworkOfferingVO offering = new NetworkOfferingVO(name, displayText, trafficType, systemOnly, specifyVlan,
                 networkRate, multicastRate, isDefault, availability, tags, type, conserveMode, dedicatedLb,
                 sharedSourceNat, redundantRouter, elasticIp, elasticLb, specifyIpRanges, inline, isPersistent,
-                associatePublicIp, publicLb, internalLb);
+                associatePublicIp, publicLb, internalLb, egressDefaultPolicy);
 
         if (serviceOfferingId != null) {
             offering.setServiceOfferingId(serviceOfferingId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java
index 541082e..674a35f 100755
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@ -1307,7 +1307,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
                     _configMgr.createNetworkOffering(NetworkOffering.QuickCloudNoServices,
                             "Offering for QuickCloud with no services", TrafficType.Guest, null, true,
                             Availability.Optional, null, new HashMap<Network.Service, Set<Network.Provider>>(), true,
-                            Network.GuestType.Shared, false, null, true, null, true, false, null);
+                            Network.GuestType.Shared, false, null, true, null, true, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1318,7 +1318,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
                     _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOfferingWithSGService,
                             "Offering for Shared Security group enabled networks", TrafficType.Guest, null, true,
                             Availability.Optional, null, defaultSharedNetworkOfferingProviders, true,
-                            Network.GuestType.Shared, false, null, true, null, true, false, null);
+                            Network.GuestType.Shared, false, null, true, null, true, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1326,7 +1326,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
         //#3 - shared network offering with no SG service
         if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedNetworkOffering) == null) {
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedNetworkOffering, "Offering for Shared networks", TrafficType.Guest, null, true, Availability.Optional, null,
-                    defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true, false, null);
+                    defaultSharedNetworkOfferingProviders, true, Network.GuestType.Shared, false, null, true, null, true, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1337,7 +1337,8 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService,
                     "Offering for Isolated networks with Source Nat service enabled", TrafficType.Guest,
                     null, false, Availability.Required, null, defaultIsolatedSourceNatEnabledNetworkOfferingProviders,
-                    true, Network.GuestType.Isolated, false, null, true, null, false, false, null);
+                    true, Network.GuestType.Isolated, false, null, true, null, false, false, null, false);
+
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1347,7 +1348,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworks,
                     "Offering for Isolated VPC networks with Source Nat service enabled", TrafficType.Guest,
                     null, false, Availability.Optional, null, defaultVPCOffProviders,
-                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null);
+                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null,false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1359,7 +1360,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB,
                     "Offering for Isolated VPC networks with Source Nat service enabled and LB service disabled", TrafficType.Guest,
                     null, false, Availability.Optional, null, defaultVPCOffProviders,
-                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null);
+                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1369,7 +1370,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOffering,
                     "Offering for Isolated networks with no Source Nat service", TrafficType.Guest, null, true,
                     Availability.Optional, null, defaultIsolatedNetworkOfferingProviders, true, Network.GuestType.Isolated,
-                    false, null, true, null, true, false, null);
+                    false, null, true, null, true, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             _networkOfferingDao.update(offering.getId(), offering);
         }
@@ -1395,7 +1396,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksWithInternalLB,
                     "Offering for Isolated VPC networks with Internal Lb support", TrafficType.Guest,
                     null, false, Availability.Optional, null, internalLbOffProviders,
-                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null);
+                    true, Network.GuestType.Isolated, false, null, false, null, false, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             offering.setInternalLb(true);
             _networkOfferingDao.update(offering.getId(), offering);
@@ -1425,7 +1426,7 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
 
         if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultSharedEIPandELBNetworkOffering) == null) {
             offering = _configMgr.createNetworkOffering(NetworkOffering.DefaultSharedEIPandELBNetworkOffering, "Offering for Shared networks with Elastic IP and Elastic LB capabilities", TrafficType.Guest, null, true,
-                    Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true, false, null);
+                    Availability.Optional, null, netscalerServiceProviders, true, Network.GuestType.Shared, false, null, true, serviceCapabilityMap, true, false, null, false);
             offering.setState(NetworkOffering.State.Enabled);
             offering.setDedicatedLB(false);
             _networkOfferingDao.update(offering.getId(), offering);
@@ -3089,9 +3090,21 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
         }
 
         List<FirewallRuleVO> firewallEgressRulesToApply = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Egress);
-        if (!_firewallMgr.applyFirewallRules(firewallEgressRulesToApply, false, caller)) {
-            s_logger.warn("Failed to reapply firewall Egress rule(s) as a part of network id=" + networkId + " restart");
-            success = false;
+        if (firewallEgressRulesToApply.size() == 0) {
+            NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
+            //there are no egress rules then apply the default egress rule
+            DataCenter zone = _dcDao.findById(network.getDataCenterId());
+            if (offering.getEgressDefaultPolicy() && _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall)
+                    && (network.getGuestType() == Network.GuestType.Isolated ||
+                    (network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced))) {
+                // add default egress rule to accept the traffic
+                _firewallMgr.applyDefaultEgressFirewallRule(network.getId(), true);
+            }
+        } else {
+            if (!_firewallMgr.applyFirewallRules(firewallEgressRulesToApply, false, caller)) {
+                s_logger.warn("Failed to reapply firewall Egress rule(s) as a part of network id=" + networkId + " restart");
+                success = false;
+            }
         }
 
         // apply port forwarding rules

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
index f7275b0..d250a08 100644
--- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
+++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
@@ -616,6 +616,7 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService,
     @Override
     public boolean applyEgressFirewallRules (FirewallRule rule, Account caller) throws ResourceUnavailableException {
                 List<FirewallRuleVO> rules = _firewallDao.listByNetworkPurposeTrafficType(rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
+                applyDefaultEgressFirewallRule(rule.getNetworkId(), true);
                 return applyFirewallRules(rules, false, caller);
     }
 
@@ -649,6 +650,36 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService,
     }
 
     @Override
+    public boolean applyDefaultEgressFirewallRule(Long networkId, boolean defaultPolicy) throws ResourceUnavailableException {
+
+        if (defaultPolicy == false) {
+            //If default policy is false no need apply rules on backend because firewall provider blocks by default
+            return true;
+        }
+        s_logger.debug("applying default firewall egress rules ");
+
+        NetworkVO network = _networkDao.findById(networkId);
+        List<String> sourceCidr = new ArrayList<String>();
+
+        sourceCidr.add(NetUtils.ALL_CIDRS);
+        FirewallRuleVO ruleVO = new FirewallRuleVO(null, null, null, null, "all", networkId, network.getAccountId(), network.getDomainId(), Purpose.Firewall, sourceCidr,
+                null, null, null, FirewallRule.TrafficType.Egress, FirewallRuleType.System);
+        List<FirewallRuleVO> rules = new ArrayList<FirewallRuleVO>();
+        rules.add(ruleVO);
+
+        try {
+            //this is not required to store in db because we don't to add this rule along with the normal rules
+            if (!applyRules(rules, false, false)) {
+                return  false;
+            }
+        } catch (ResourceUnavailableException ex) {
+            s_logger.warn("Failed to apply default egress rules for guest network due to ", ex);
+            return false;
+        }
+        return true;
+    }
+
+    @Override
     @ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
     public boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) {
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index fbb8cf2..5a8cf5d 100755
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -164,6 +164,7 @@ import com.cloud.network.rules.dao.PortForwardingRulesDao;
 import com.cloud.network.vpn.Site2SiteVpnManager;
 import com.cloud.offering.NetworkOffering;
 import com.cloud.offering.ServiceOffering;
+import com.cloud.offerings.NetworkOfferingVO;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.resource.ResourceManager;
 import com.cloud.server.ConfigurationServer;
@@ -3680,29 +3681,44 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V
 
     private void createFirewallRulesCommands(List<? extends FirewallRule> rules, VirtualRouter router, Commands cmds, long guestNetworkId) {
         List<FirewallRuleTO> rulesTO = null;
+        String systemRule = null;
         if (rules != null) {
+            if (rules.size() > 0) {
+                if (rules.get(0).getTrafficType() == FirewallRule.TrafficType.Egress && rules.get(0).getType() == FirewallRule.FirewallRuleType.System) {
+                    systemRule = String.valueOf(FirewallRule.FirewallRuleType.System);
+                }
+            }
             rulesTO = new ArrayList<FirewallRuleTO>();
             for (FirewallRule rule : rules) {
                 FirewallRule.TrafficType traffictype = rule.getTrafficType();
                 if(traffictype == FirewallRule.TrafficType.Ingress){
-                IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
-                        FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(),Purpose.Firewall,traffictype);
-                rulesTO.add(ruleTO);
-            }
-                else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress){
-                        assert (rule.getSourceIpAddressId()==null) : "ipAddressId should be null for egress firewall rule. ";
-                        FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null,"",Purpose.Firewall,traffictype);
-                        rulesTO.add(ruleTO);
+                    IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
+                    FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr(),Purpose.Firewall,traffictype);
+                    rulesTO.add(ruleTO);
+                } else if (rule.getTrafficType() == FirewallRule.TrafficType.Egress){
+                    assert (rule.getSourceIpAddressId()==null) : "ipAddressId should be null for egress firewall rule. ";
+                    FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null,"",Purpose.Firewall, traffictype);
+                    rulesTO.add(ruleTO);
                 }
             }
         }
 
+
+        NetworkVO network = _networkDao.findById(guestNetworkId);
+        NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
+        Boolean defaultEgressPolicy = offering.getEgressDefaultPolicy();
         SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(rulesTO);
         cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId()));
         cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, getRouterIpInNetwork(guestNetworkId, router.getId()));
         cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
         DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
         cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
+        if (systemRule != null) {
+            cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, systemRule);
+        } else {
+            cmd.setAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT, String.valueOf(defaultEgressPolicy));
+        }
+
         cmds.addCommand(cmd);
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/network/rules/FirewallManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/rules/FirewallManager.java b/server/src/com/cloud/network/rules/FirewallManager.java
index 2bce8fe..6d36ed3 100644
--- a/server/src/com/cloud/network/rules/FirewallManager.java
+++ b/server/src/com/cloud/network/rules/FirewallManager.java
@@ -85,4 +85,5 @@ public interface FirewallManager extends FirewallService {
      */
     void removeRule(FirewallRule rule);
 
+    boolean applyDefaultEgressFirewallRule(Long networkId, boolean defaultPolicy) throws ResourceUnavailableException;
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/src/com/cloud/server/ConfigurationServerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java
index 8e952aa..1ddfcfa 100755
--- a/server/src/com/cloud/server/ConfigurationServerImpl.java
+++ b/server/src/com/cloud/server/ConfigurationServerImpl.java
@@ -1093,7 +1093,7 @@ public class ConfigurationServerImpl extends ManagerBase implements Configuratio
                 "Offering for Shared networks with Elastic IP and Elastic LB capabilities",
                 TrafficType.Guest,
                 false, true, null, null, true, Availability.Optional,
-                null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false);
+                null, Network.GuestType.Shared, true, false, false, false, true, true, true, false, false, true, true, false, false);
 
         defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled);
         defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/test/com/cloud/network/MockFirewallManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/MockFirewallManagerImpl.java b/server/test/com/cloud/network/MockFirewallManagerImpl.java
index 95bb1d1..c50459e 100644
--- a/server/test/com/cloud/network/MockFirewallManagerImpl.java
+++ b/server/test/com/cloud/network/MockFirewallManagerImpl.java
@@ -169,6 +169,11 @@ public class MockFirewallManagerImpl extends ManagerBase implements FirewallMana
 	}
 
     @Override
+    public boolean applyDefaultEgressFirewallRule(Long networkId, boolean defaultPolicy) throws ResourceUnavailableException {
+        return false;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    @Override
     public FirewallRule createFirewallRule(Long ipAddrId, Account caller,
             String xId, Integer portStart, Integer portEnd, String protocol,
             List<String> sourceCidrList, Integer icmpCode, Integer icmpType,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java
index 6e3d187..95230a5 100755
--- a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java
+++ b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java
@@ -555,7 +555,7 @@ public class MockConfigurationManagerImpl extends ManagerBase implements Configu
     @Override
     public NetworkOfferingVO createNetworkOffering(String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate,
             Map<Service, Set<Provider>> serviceProviderMap, boolean isDefault, GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode,
-            Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent, Map<NetworkOffering.Detail,String> details) {
+            Map<Service, Map<Capability, String>> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent, Map<NetworkOffering.Detail,String> details, boolean egressDefaultPolicy) {
         // TODO Auto-generated method stub
         return null;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java b/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
index 4a2c867..36564d9 100644
--- a/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
+++ b/server/test/org/apache/cloudstack/networkoffering/CreateNetworkOfferingTest.java
@@ -94,7 +94,7 @@ public class CreateNetworkOfferingTest extends TestCase{
     public void createSharedNtwkOffWithVlan() {
         NetworkOfferingVO off = configMgr.createNetworkOffering("shared", "shared", TrafficType.Guest, null, true,
                 Availability.Optional, 200, null, false, Network.GuestType.Shared, false,
-                null, false, null, true, false, null);
+                null, false, null, true, false, null, false);
         assertNotNull("Shared network offering with specifyVlan=true failed to create ", off);
     }
     
@@ -103,7 +103,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         try {
             NetworkOfferingVO off = configMgr.createNetworkOffering("shared", "shared", TrafficType.Guest, null, false,
                     Availability.Optional, 200, null, false, Network.GuestType.Shared, false,
-                    null, false, null, true, false, null);
+                    null, false, null, true, false, null, false);
             assertNull("Shared network offering with specifyVlan=false was created", off);
         } catch (InvalidParameterValueException ex) {
         }
@@ -113,7 +113,7 @@ public class CreateNetworkOfferingTest extends TestCase{
     public void createSharedNtwkOffWithSpecifyIpRanges() {
         NetworkOfferingVO off = configMgr.createNetworkOffering("shared", "shared", TrafficType.Guest, null, true,
                 Availability.Optional, 200, null, false, Network.GuestType.Shared, false,
-                null, false, null, true, false, null);
+                null, false, null, true, false, null, false);
         
         assertNotNull("Shared network offering with specifyIpRanges=true failed to create ", off);
     }
@@ -123,7 +123,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         try {
             NetworkOfferingVO off = configMgr.createNetworkOffering("shared", "shared", TrafficType.Guest, null, true,
                     Availability.Optional, 200, null, false, Network.GuestType.Shared, false,
-                    null, false, null, false, false, null);
+                    null, false, null, false, false, null, false);
             assertNull("Shared network offering with specifyIpRanges=false was created", off);
         } catch (InvalidParameterValueException ex) {
         }
@@ -138,7 +138,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         serviceProviderMap.put(Network.Service.SourceNat, vrProvider);
         NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, false,
                 Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false,
-                null, false, null, false, false, null);
+                null, false, null, false, false, null, false);
         
         assertNotNull("Isolated network offering with specifyIpRanges=false failed to create ", off);
     }
@@ -151,7 +151,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         serviceProviderMap.put(Network.Service.SourceNat, vrProvider);
         NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, true,
                 Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false,
-                null, false, null, false, false, null);
+                null, false, null, false, false, null, false);
         assertNotNull("Isolated network offering with specifyVlan=true wasn't created", off);
        
     }
@@ -165,7 +165,7 @@ public class CreateNetworkOfferingTest extends TestCase{
             serviceProviderMap.put(Network.Service.SourceNat, vrProvider);
             NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, false,
                     Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false,
-                    null, false, null, true, false, null);
+                    null, false, null, true, false, null, false);
             assertNull("Isolated network offering with specifyIpRanges=true and source nat service enabled, was created", off);
         } catch (InvalidParameterValueException ex) {
         }
@@ -178,7 +178,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         Set<Network.Provider> vrProvider = new HashSet<Network.Provider>();
         NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, false,
                 Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false,
-                null, false, null, true, false, null);
+                null, false, null, true, false, null, false);
         assertNotNull("Isolated network offering with specifyIpRanges=true and with no sourceNatService, failed to create", off);
         
     }
@@ -196,7 +196,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         serviceProviderMap.put(Network.Service.Lb , vrProvider);
         NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, true,
                 Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false,
-                null, false, null, false, false, null);
+                null, false, null, false, false, null, false);
         // System.out.println("Creating Vpc Network Offering");
         assertNotNull("Vpc Isolated network offering with Vpc provider ", off);
     }
@@ -216,7 +216,7 @@ public class CreateNetworkOfferingTest extends TestCase{
         serviceProviderMap.put(Network.Service.Lb, lbProvider);
         NetworkOfferingVO off = configMgr.createNetworkOffering("isolated", "isolated", TrafficType.Guest, null, true,
                 Availability.Optional, 200, serviceProviderMap, false, Network.GuestType.Isolated, false, null, false,
-                null, false, false, null);
+                null, false, false, null, false);
         // System.out.println("Creating Vpc Network Offering");
         assertNotNull("Vpc Isolated network offering with Vpc and Netscaler provider ", off);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6a7ae637/setup/db/db/schema-410to420.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-410to420.sql b/setup/db/db/schema-410to420.sql
index db30c04..325924b 100644
--- a/setup/db/db/schema-410to420.sql
+++ b/setup/db/db/schema-410to420.sql
@@ -2147,3 +2147,4 @@ ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devi
 ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_host_id` FOREIGN KEY (`host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE;
 ALTER TABLE `cloud`.`baremetal_pxe_devices` ADD CONSTRAINT `fk_external_pxe_devices_physical_network_id` FOREIGN KEY (`physical_network_id`) REFERENCES `physical_network`(`id`) ON DELETE CASCADE;
 
+alter table `cloud`.`network_offerings` add column egress_default_policy boolean default false;


[20/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-757


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

Branch: refs/heads/vmsync
Commit: 4f45673849dd8147c0ee95c160d7dc4e6762fcb8
Parents: aac9224
Author: Radhika PC <ra...@citrix.com>
Authored: Mon Jun 24 13:12:18 2013 +0530
Committer: Radhika PC <ra...@citrix.com>
Committed: Mon Jun 24 13:12:59 2013 +0530

----------------------------------------------------------------------
 docs/en-US/add-gateway-vpc.xml | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4f456738/docs/en-US/add-gateway-vpc.xml
----------------------------------------------------------------------
diff --git a/docs/en-US/add-gateway-vpc.xml b/docs/en-US/add-gateway-vpc.xml
index 5ef8b63..6aaa5d0 100644
--- a/docs/en-US/add-gateway-vpc.xml
+++ b/docs/en-US/add-gateway-vpc.xml
@@ -156,6 +156,10 @@
   </section>
   <section id="blacklist-route">
     <title>Blacklisting Routes</title>
-    <para/>
+    <para>&PRODUCT; enables you to block a list of routes so that they are not assigned to any of
+      the VPC private gateways. Specify the list of routes that you want to blacklist in the
+        <code>blacklisted.routes</code> global parameter. Note that the parameter update affects only new
+      static route creations. If you block an existing static route, it remains intact and
+      continue functioning. </para>
   </section>
 </section>


[12/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cloudstack


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

Branch: refs/heads/vmsync
Commit: 1a50e2fddcb39b89adec71c6f7591a0e22764a13
Parents: 5f06500 5c4578e
Author: Sebastien Goasguen <ru...@gmail.com>
Authored: Sun Jun 23 23:33:45 2013 -0400
Committer: Sebastien Goasguen <ru...@gmail.com>
Committed: Sun Jun 23 23:33:45 2013 -0400

----------------------------------------------------------------------
 docs/en-US/Release_Notes.xml                    |  9 ++---
 docs/en-US/about-password-encryption.xml        |  2 +-
 docs/en-US/citrix-xenserver-installation.xml    |  5 ++-
 docs/en-US/database-replication.xml             | 12 +++++--
 .../management-server-install-db-external.xml   |  2 +-
 .../management-server-install-db-local.xml      |  4 +--
 .../management-server-install-multi-node.xml    |  4 +--
 docs/en-US/region-add.xml                       |  6 ++--
 patches/systemvm/debian/buildsystemvm.sh        | 37 ++++++++++----------
 .../debian/config/etc/init.d/cloud-early-config |  5 ++-
 10 files changed, 47 insertions(+), 39 deletions(-)
----------------------------------------------------------------------



[19/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
CLOUDSTACK-3143: add response in the response string (ui change)


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

Branch: refs/heads/vmsync
Commit: aac922450c500c8ba4b10d61fad66fb0ec6c7d7a
Parents: 1eb744f
Author: Wei Zhou <w....@leaseweb.com>
Authored: Mon Jun 24 09:18:41 2013 +0200
Committer: Wei Zhou <w....@leaseweb.com>
Committed: Mon Jun 24 09:18:41 2013 +0200

----------------------------------------------------------------------
 ui/scripts/network.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/aac92245/ui/scripts/network.js
----------------------------------------------------------------------
diff --git a/ui/scripts/network.js b/ui/scripts/network.js
index d18e796..fbd8b01 100755
--- a/ui/scripts/network.js
+++ b/ui/scripts/network.js
@@ -4123,7 +4123,7 @@
                           dataType: 'json',
                           async: true,
                           success: function(data) {
-                            var jobID = data.revokesecuritygroupingress.jobid;
+                            var jobID = data.revokesecuritygroupingressresponse.jobid;
 
                             args.response.success({
                               _custom: {
@@ -4295,7 +4295,7 @@
                           dataType: 'json',
                           async: true,
                           success: function(data) {
-                            var jobID = data.revokesecuritygroupegress.jobid;
+                            var jobID = data.revokesecuritygroupegressresponse.jobid;
 
                             args.response.success({
                               _custom: {


[42/50] [abbrv] merge is complete

Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java
index 0000000,d4c9560..f6d7b40
mode 000000,100644..100644
--- a/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/TemplateJoinDaoImpl.java
@@@ -1,0 -1,462 +1,463 @@@
+ // 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.api.query.dao;
+ 
+ import java.util.ArrayList;
+ import java.util.HashMap;
+ import java.util.List;
+ import java.util.Map;
+ 
+ import javax.ejb.Local;
+ import javax.inject.Inject;
+ 
++import org.apache.log4j.Logger;
++import org.springframework.stereotype.Component;
++
+ import org.apache.cloudstack.api.BaseCmd;
+ import org.apache.cloudstack.api.response.TemplateResponse;
+ import org.apache.cloudstack.api.response.TemplateZoneResponse;
++import org.apache.cloudstack.context.CallContext;
+ import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
+ import org.apache.cloudstack.engine.subsystem.api.storage.TemplateState;
 -import org.apache.log4j.Logger;
 -import org.springframework.stereotype.Component;
+ 
+ import com.cloud.api.ApiDBUtils;
+ import com.cloud.api.ApiResponseHelper;
+ import com.cloud.api.query.vo.ResourceTagJoinVO;
+ import com.cloud.api.query.vo.TemplateJoinVO;
+ import com.cloud.configuration.dao.ConfigurationDao;
+ import com.cloud.storage.Storage;
 -import com.cloud.storage.VMTemplateHostVO;
+ import com.cloud.storage.Storage.TemplateType;
++import com.cloud.storage.VMTemplateHostVO;
+ import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
+ import com.cloud.template.VirtualMachineTemplate;
+ import com.cloud.user.Account;
 -import com.cloud.user.UserContext;
+ import com.cloud.utils.db.GenericDaoBase;
+ import com.cloud.utils.db.SearchBuilder;
+ import com.cloud.utils.db.SearchCriteria;
+ 
+ 
+ @Component
+ @Local(value={TemplateJoinDao.class})
+ public class TemplateJoinDaoImpl extends GenericDaoBase<TemplateJoinVO, Long> implements TemplateJoinDao {
+ 
+ 
+ 
+     public static final Logger s_logger = Logger.getLogger(TemplateJoinDaoImpl.class);
+ 
+     @Inject
+     private ConfigurationDao  _configDao;
+ 
+     private final SearchBuilder<TemplateJoinVO> tmpltSearch;
+ 
+     private final SearchBuilder<TemplateJoinVO> tmpltIdSearch;
+ 
+     private final SearchBuilder<TemplateJoinVO> tmpltZoneSearch;
+ 
+     private final SearchBuilder<TemplateJoinVO> activeTmpltSearch;
+ 
+ 
+     protected TemplateJoinDaoImpl() {
+ 
+         tmpltSearch = createSearchBuilder();
+         tmpltSearch.and("idIN", tmpltSearch.entity().getId(), SearchCriteria.Op.IN);
+         tmpltSearch.done();
+ 
+         tmpltIdSearch = createSearchBuilder();
+         tmpltIdSearch.and("id", tmpltIdSearch.entity().getId(), SearchCriteria.Op.EQ);
+         tmpltIdSearch.done();
+ 
+         tmpltZoneSearch = createSearchBuilder();
+         tmpltZoneSearch.and("id", tmpltZoneSearch.entity().getId(), SearchCriteria.Op.EQ);
+         tmpltZoneSearch.and("dataCenterId", tmpltZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+         tmpltZoneSearch.and("state", tmpltZoneSearch.entity().getState(), SearchCriteria.Op.EQ);
+         tmpltZoneSearch.done();
+ 
+         activeTmpltSearch = createSearchBuilder();
+         activeTmpltSearch.and("store_id", activeTmpltSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
+         activeTmpltSearch.and("type", activeTmpltSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
+         activeTmpltSearch.done();
+ 
+         // select distinct pair (template_id, zone_id)
 -        this._count = "select count(distinct id) from template_view WHERE ";
++        _count = "select count(distinct id) from template_view WHERE ";
+     }
+ 
+ 
+ 
+ 
+     @Override
+     public TemplateResponse newTemplateResponse(TemplateJoinVO template) {
+         TemplateResponse templateResponse = new TemplateResponse();
+         templateResponse.setId(template.getUuid());
+         templateResponse.setName(template.getName());
+         templateResponse.setDisplayText(template.getDisplayText());
+         templateResponse.setPublic(template.isPublicTemplate());
+         templateResponse.setCreated(template.getCreatedOnStore());
+         if ( template.getFormat() == Storage.ImageFormat.BAREMETAL ){
+             // for baremetal template, we didn't download, but is ready to use.
+             templateResponse.setReady(true);
+         }
+         else{
+             templateResponse.setReady(template.getState() == ObjectInDataStoreStateMachine.State.Ready);
+         }
+         templateResponse.setFeatured(template.isFeatured());
+         templateResponse.setExtractable(template.isExtractable() && !(template.getTemplateType() == TemplateType.SYSTEM));
+         templateResponse.setPasswordEnabled(template.isEnablePassword());
+         templateResponse.setSshKeyEnabled(template.isEnableSshKey());
+         templateResponse.setCrossZones(template.isCrossZones());
+         templateResponse.setFormat(template.getFormat());
+         if (template.getTemplateType() != null) {
+             templateResponse.setTemplateType(template.getTemplateType().toString());
+         }
+ 
+         templateResponse.setHypervisor(template.getHypervisorType().toString());
+ 
+ 
+         templateResponse.setOsTypeId(template.getGuestOSUuid());
+         templateResponse.setOsTypeName(template.getGuestOSName());
+ 
+         // populate owner.
+         ApiResponseHelper.populateOwner(templateResponse, template);
+ 
+         // populate domain
+         templateResponse.setDomainId(template.getDomainUuid());
+         templateResponse.setDomainName(template.getDomainName());
+ 
+ 
+ 
+         boolean isAdmin = false;
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+         if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
+             isAdmin = true;
+         }
+ 
+         // If the user is an Admin, add the template download status
+         if (isAdmin || caller.getId() == template.getAccountId()) {
+             // add download status
+             if (template.getDownloadState() != Status.DOWNLOADED) {
+                 String templateStatus = "Processing";
+                 if (template.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
+                     if (template.getDownloadPercent() == 100) {
+                         templateStatus = "Installing Template";
+                     } else {
+                         templateStatus = template.getDownloadPercent() + "% Downloaded";
+                     }
+                 } else {
+                     templateStatus = template.getErrorString();
+                 }
+                 templateResponse.setStatus(templateStatus);
+             } else if (template.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
+                 templateResponse.setStatus("Download Complete");
+             } else {
+                 templateResponse.setStatus("Successfully Installed");
+             }
+         }
+ 
+         Long templateSize = template.getSize();
+         if (templateSize > 0) {
+             templateResponse.setSize(templateSize);
+         }
+ 
+         templateResponse.setChecksum(template.getChecksum());
+         if (template.getSourceTemplateId() != null) {
+             templateResponse.setSourceTemplateId(template.getSourceTemplateUuid());
+         }
+         templateResponse.setTemplateTag(template.getTemplateTag());
+ 
+         // set template zone information
+         if (template.getDataCenterId() > 0 ){
+             TemplateZoneResponse tmplZoneResp = new TemplateZoneResponse(template.getDataCenterUuid(), template.getDataCenterName());
+             templateResponse.addZone(tmplZoneResp);
+             // set the first found associated zone directly in TemplateResponse
+             templateResponse.setZoneId(template.getDataCenterUuid());
+             templateResponse.setZoneName(template.getDataCenterName());
+         }
+ 
+         // set details map
+         if (template.getDetailName() != null){
+             Map<String, String> details = new HashMap<String, String>();
+             details.put(template.getDetailName(), template.getDetailValue());
+             templateResponse.setDetails(details);
+         }
+ 
+         // update tag information
+         long tag_id = template.getTagId();
+         if (tag_id > 0) {
+             ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
+             if ( vtag != null ){
+                 templateResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
+             }
+         }
+ 
+ 
+         templateResponse.setObjectName("template");
+         return templateResponse;
+     }
+ 
+ 
+     //TODO: This is to keep compatibility with 4.1 API, where updateTemplateCmd and updateIsoCmd will return a simpler TemplateResponse
+     // compared to listTemplates and listIsos.
+     @Override
+     public TemplateResponse newUpdateResponse(TemplateJoinVO result) {
+         TemplateResponse response = new TemplateResponse();
+         response.setId(result.getUuid());
+         response.setName(result.getName());
+         response.setDisplayText(result.getDisplayText());
+         response.setPublic(result.isPublicTemplate());
+         response.setCreated(result.getCreated());
+         response.setFormat(result.getFormat());
+         response.setOsTypeId(result.getGuestOSUuid());
+         response.setOsTypeName(result.getGuestOSName());
+         response.setBootable(result.isBootable());
+         response.setHypervisor(result.getHypervisorType().toString());
+ 
+         // populate owner.
+         ApiResponseHelper.populateOwner(response, result);
+ 
+         // populate domain
+         response.setDomainId(result.getDomainUuid());
+         response.setDomainName(result.getDomainName());
+ 
+         // set details map
+         if (result.getDetailName() != null) {
+             Map<String, String> details = new HashMap<String, String>();
+             details.put(result.getDetailName(), result.getDetailValue());
+             response.setDetails(details);
+         }
+ 
+         // update tag information
+         long tag_id = result.getTagId();
+         if (tag_id > 0) {
+             ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
+             if (vtag != null) {
+                 response.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
+             }
+         }
+ 
+         response.setObjectName("iso");
+         return response;
+     }
+ 
+ 
+ 
+ 
+     @Override
+     public TemplateResponse setTemplateResponse(TemplateResponse templateResponse, TemplateJoinVO template) {
+ 
+         // update template zone information
+         if (template.getDataCenterId() > 0 ){
+             TemplateZoneResponse tmplZoneResp = new TemplateZoneResponse(template.getDataCenterUuid(), template.getDataCenterName());
+             templateResponse.addZone(tmplZoneResp);
+             if (templateResponse.getZoneId() == null) {
+                 // set the first found associated zone directly in
+                 // TemplateResponse
+                 templateResponse.setZoneId(template.getDataCenterUuid());
+                 templateResponse.setZoneName(template.getDataCenterName());
+             }
+         }
+ 
+         // update details map
+         if (template.getDetailName() != null){
+             Map<String, String> details = templateResponse.getDetails();
+             if ( details == null ){
+                 details = new HashMap<String, String>();
+             }
+             details.put(template.getDetailName(), template.getDetailValue());
+             templateResponse.setDetails(details);
+         }
+ 
+         // update tag information
+         long tag_id = template.getTagId();
+         if (tag_id > 0) {
+             ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
+             if ( vtag != null ){
+                 templateResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
+             }
+         }
+ 
+         return templateResponse;
+     }
+ 
+ 
+     @Override
+     public TemplateResponse newIsoResponse(TemplateJoinVO iso) {
+ 
+         TemplateResponse isoResponse = new TemplateResponse();
+         isoResponse.setId(iso.getUuid());
+         isoResponse.setName(iso.getName());
+         isoResponse.setDisplayText(iso.getDisplayText());
+         isoResponse.setPublic(iso.isPublicTemplate());
+         isoResponse.setExtractable(iso.isExtractable() && !(iso.getTemplateType() == TemplateType.PERHOST));
+         isoResponse.setCreated(iso.getCreatedOnStore());
+         if ( iso.getTemplateType() == TemplateType.PERHOST ){
+             // for xs-tools.iso and vmware-tools.iso, we didn't download, but is ready to use.
+             isoResponse.setReady(true);
+         }
+         else{
+             isoResponse.setReady(iso.getState() == ObjectInDataStoreStateMachine.State.Ready);
+         }
+         isoResponse.setBootable(iso.isBootable());
+         isoResponse.setFeatured(iso.isFeatured());
+         isoResponse.setCrossZones(iso.isCrossZones());
+         isoResponse.setPublic(iso.isPublicTemplate());
+         isoResponse.setChecksum(iso.getChecksum());
+ 
+         isoResponse.setOsTypeId(iso.getGuestOSUuid());
+         isoResponse.setOsTypeName(iso.getGuestOSName());
+ 
+         // populate owner.
+         ApiResponseHelper.populateOwner(isoResponse, iso);
+ 
+         // populate domain
+         isoResponse.setDomainId(iso.getDomainUuid());
+         isoResponse.setDomainName(iso.getDomainName());
+ 
+         // set template zone information
+         if (iso.getDataCenterId() > 0 ){
+             TemplateZoneResponse tmplZoneResp = new TemplateZoneResponse(iso.getDataCenterUuid(), iso.getDataCenterName());
+             isoResponse.addZone(tmplZoneResp);
+             // set the first found associated zone directly in TemplateResponse
+             isoResponse.setZoneId(iso.getDataCenterUuid());
+             isoResponse.setZoneName(iso.getDataCenterName());
+         }
+ 
+ 
 -        Account caller = UserContext.current().getCaller();
++        Account caller = CallContext.current().getCallingAccount();
+         boolean isAdmin = false;
+         if ((caller == null) || BaseCmd.isAdmin(caller.getType())) {
+             isAdmin = true;
+         }
+ 
+ 
+         // If the user is an admin, add the template download status
+         if (isAdmin || caller.getId() == iso.getAccountId()) {
+             // add download status
+             if (iso.getDownloadState() != Status.DOWNLOADED) {
+                 String isoStatus = "Processing";
+                 if (iso.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
+                     isoStatus = "Download Complete";
+                 } else if (iso.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
+                     if (iso.getDownloadPercent() == 100) {
+                         isoStatus = "Installing ISO";
+                     } else {
+                         isoStatus = iso.getDownloadPercent() + "% Downloaded";
+                     }
+                 } else {
+                     isoStatus = iso.getErrorString();
+                 }
+                 isoResponse.setStatus(isoStatus);
+             } else {
+                 isoResponse.setStatus("Successfully Installed");
+             }
+         }
+ 
+         Long isoSize = iso.getSize();
+         if (isoSize > 0) {
+             isoResponse.setSize(isoSize);
+         }
+ 
+         // update tag information
+         long tag_id = iso.getTagId();
+         if (tag_id > 0) {
+             ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
+             if ( vtag != null ){
+                 isoResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
+             }
+         }
+ 
+         isoResponse.setObjectName("iso");
+         return isoResponse;
+ 
+     }
+ 
+     @Override
+     public List<TemplateJoinVO> newTemplateView(VirtualMachineTemplate template) {
+         SearchCriteria<TemplateJoinVO> sc = tmpltIdSearch.create();
+         sc.setParameters("id", template.getId());
+         return searchIncludingRemoved(sc, null, null, false);
+     }
+ 
+     @Override
+     public List<TemplateJoinVO> newTemplateView(VirtualMachineTemplate template, long zoneId, boolean readyOnly) {
+         SearchCriteria<TemplateJoinVO> sc = tmpltZoneSearch.create();
+         sc.setParameters("id", template.getId());
+         sc.setParameters("dataCenterId", zoneId);
+         if ( readyOnly ){
+             sc.setParameters("state", TemplateState.Ready);
+         }
+         return searchIncludingRemoved(sc, null, null, false);
+     }
+ 
+ 
+ 
+     @Override
+     public List<TemplateJoinVO> searchByIds(Long... tmplIds) {
+         // set detail batch query size
+         int DETAILS_BATCH_SIZE = 2000;
+         String batchCfg = _configDao.getValue("detail.batch.query.size");
+         if ( batchCfg != null ){
+             DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg);
+         }
+         // query details by batches
+         List<TemplateJoinVO> uvList = new ArrayList<TemplateJoinVO>();
+         // query details by batches
+         int curr_index = 0;
+         if ( tmplIds.length > DETAILS_BATCH_SIZE ){
+             while ( (curr_index + DETAILS_BATCH_SIZE ) <= tmplIds.length ) {
+                 Long[] ids = new Long[DETAILS_BATCH_SIZE];
+                 for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) {
+                     ids[k] = tmplIds[j];
+                 }
+                 SearchCriteria<TemplateJoinVO> sc = tmpltSearch.create();
+                 sc.setParameters("idIN", ids);
+                 List<TemplateJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
+                 if (vms != null) {
+                     uvList.addAll(vms);
+                 }
+                 curr_index += DETAILS_BATCH_SIZE;
+             }
+         }
+         if (curr_index < tmplIds.length) {
+             int batch_size = (tmplIds.length - curr_index);
+             // set the ids value
+             Long[] ids = new Long[batch_size];
+             for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) {
+                 ids[k] = tmplIds[j];
+             }
+             SearchCriteria<TemplateJoinVO> sc = tmpltSearch.create();
+             sc.setParameters("idIN", ids);
+             List<TemplateJoinVO> vms = searchIncludingRemoved(sc, null, null, false);
+             if (vms != null) {
+                 uvList.addAll(vms);
+             }
+         }
+         return uvList;
+     }
+ 
+ 
+ 
+ 
+     @Override
+     public List<TemplateJoinVO> listActiveTemplates(long storeId) {
+         SearchCriteria<TemplateJoinVO> sc = activeTmpltSearch.create();
+         sc.setParameters("store_id", storeId);
+         sc.setParameters("type", TemplateType.USER);
+         return searchIncludingRemoved(sc, null, null, false);
+     }
+ 
+ 
+ 
+ }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java
index 5406122,ed2732e..562cf65
--- a/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java
+++ b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java
@@@ -87,8 -86,7 +87,7 @@@ public class VolumeJoinDaoImpl extends 
  
          volResponse.setZoneId(volume.getDataCenterUuid());
          volResponse.setZoneName(volume.getDataCenterName());
-         volResponse.setZoneType(volume.getDataCenterType());
 -
 +        
          volResponse.setVolumeType(volume.getVolumeType().toString());
          volResponse.setDeviceId(volume.getDeviceId());
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/capacity/CapacityManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/capacity/CapacityManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/Config.java
index 7cb6c6b,3a6d3aa..390b51e
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@@ -72,7 -72,10 +72,10 @@@ public enum Config 
  	StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null, ConfigurationParameterScope.zone.toString()),
  	StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null),
  	MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null),
+     StorageCacheReplacementLRUTimeInterval("Storage", ManagementServer.class, Integer.class, "storage.cache.replacement.lru.interval", "30", "time interval for unsed data on cache storage (in days).", null),
+     StorageCacheReplacementEnabled("Storage", ManagementServer.class, Boolean.class, "storage.cache.replacement.enabled", "true", "enable or disable cache storage replacement algorithm.", null),
+     StorageCacheReplacementInterval("Storage", ManagementServer.class, Integer.class, "storage.cache.replacement.interval", "86400", "time interval between cache replacement threads (in seconds).", null),
 -    MaxUploadVolumeSize("Storage",  ManagementServer.class, Integer.class, "storage.max.volume.upload.size", "500", "The maximum size for a uploaded volume(in GB).", null),
 +	MaxUploadVolumeSize("Storage",  ManagementServer.class, Integer.class, "storage.max.volume.upload.size", "500", "The maximum size for a uploaded volume(in GB).", null),
  	TotalRetries("Storage", AgentManager.class, Integer.class, "total.retries", "4", "The number of times each command sent to a host should be retried in case of failure.", null),
  	StoragePoolMaxWaitSeconds("Storage", ManagementServer.class, Integer.class, "storage.pool.max.waitseconds", "3600", "Timeout (in seconds) to synchronize storage pool operations.", null),
  	StorageTemplateCleanupEnabled("Storage", ManagementServer.class, Boolean.class, "storage.template.cleanup.enabled", "true", "Enable/disable template cleanup activity, only take effect when overall storage cleanup is enabled", null),
@@@ -413,7 -419,9 +420,9 @@@
      ApiLimitMax("Advanced", ManagementServer.class, Integer.class, "api.throttling.max", "25", "Max allowed number of APIs within fixed interval", null),
      ApiLimitCacheSize("Advanced", ManagementServer.class, Integer.class, "api.throttling.cachesize", "50000", "Account based API count cache size", null),
  
+     // object store
+     S3EnableRRS("Advanced", ManagementServer.class, Boolean.class, "s3.rrs.enabled", "false", "enable s3 reduced redundancy storage", null),
 -
 +	
  	// VMSnapshots
      VMSnapshotMax("Advanced", VMSnapshotManager.class, Integer.class, "vmsnapshot.max", "10", "Maximum vm snapshots for a vm", null),
      VMSnapshotCreateWait("Advanced", VMSnapshotManager.class, Integer.class, "vmsnapshot.create.wait", "1800", "In second, timeout for create vm snapshot", null),

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7b7db056/server/src/com/cloud/configuration/ConfigurationManager.java
----------------------------------------------------------------------


[09/50] [abbrv] git commit: updated refs/heads/vmsync to 049dd72

Posted by ah...@apache.org.
upgrade debian systemvm to wheezy

New kvm libvirt requres virtio-console (/dev/vport*), so
upgrading debian guest base OS to wheezy.


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

Branch: refs/heads/vmsync
Commit: 009da930580fba039b4b8a7532a8a6809d00ed02
Parents: 3123fe6
Author: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Authored: Mon Jun 24 11:16:40 2013 +0900
Committer: Hiroaki KAWAI <ka...@stratosphere.co.jp>
Committed: Mon Jun 24 11:16:40 2013 +0900

----------------------------------------------------------------------
 patches/systemvm/debian/buildsystemvm.sh | 27 ++++++++++++---------------
 1 file changed, 12 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/009da930/patches/systemvm/debian/buildsystemvm.sh
----------------------------------------------------------------------
diff --git a/patches/systemvm/debian/buildsystemvm.sh b/patches/systemvm/debian/buildsystemvm.sh
index dac785c..c2fe344 100755
--- a/patches/systemvm/debian/buildsystemvm.sh
+++ b/patches/systemvm/debian/buildsystemvm.sh
@@ -50,8 +50,8 @@ baseimage() {
   
   mount -o loop,offset=$offset $IMAGELOC  $MOUNTPOINT
   
-  #debootstrap --variant=minbase --keyring=/usr/share/keyrings/debian-archive-keyring.gpg squeeze $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR}
-  debootstrap --variant=minbase --arch=i386 squeeze $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR}
+  #debootstrap --variant=minbase --keyring=/usr/share/keyrings/debian-archive-keyring.gpg wheezy $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR}
+  debootstrap --variant=minbase --arch=i386 wheezy $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR}
 }
 
 
@@ -63,11 +63,14 @@ EOF
   fi
 
   cat > etc/apt/sources.list << EOF
-deb http://ftp.us.debian.org/debian/ squeeze main contrib non-free
-deb-src http://ftp.us.debian.org/debian/ squeeze main contrib non-free
+deb http://ftp.us.debian.org/debian/ wheezy main contrib non-free
+deb-src http://ftp.us.debian.org/debian/ wheezy main contrib non-free
 
-deb http://security.debian.org/ squeeze/updates main
-deb-src http://security.debian.org/ squeeze/updates main
+deb http://security.debian.org/ wheezy/updates main
+deb-src http://security.debian.org/ wheezy/updates main
+
+deb http://ftp.us.debian.org/debian/ wheezy-backports main
+deb-src http://ftp.us.debian.org/debian/ wheezy-backports main
 EOF
 
   cat >> etc/apt/apt.conf << EOF
@@ -347,7 +350,7 @@ packages() {
   export DEBIAN_FRONTEND DEBIAN_PRIORITY DEBCONF_DB_OVERRIDE
 
   #basic stuff
-  chroot .  apt-get --no-install-recommends -q -y --force-yes install rsyslog logrotate cron chkconfig insserv net-tools ifupdown vim-tiny netbase iptables openssh-server grub-legacy e2fsprogs dhcp3-client dnsmasq tcpdump socat wget  python bzip2 sed gawk diff grep gzip less tar telnet ftp rsync traceroute psmisc lsof procps monit inetutils-ping iputils-arping httping dnsutils zip unzip ethtool uuid file iproute acpid iptables-persistent virt-what sudo
+  chroot .  apt-get --no-install-recommends -q -y --force-yes install rsyslog logrotate cron chkconfig insserv net-tools ifupdown vim-tiny netbase iptables openssh-server grub-legacy e2fsprogs dhcp3-client dnsmasq tcpdump socat wget  python bzip2 sed gawk diffutils grep gzip less tar telnet ftp rsync traceroute psmisc lsof procps monit inetutils-ping iputils-arping httping dnsutils zip unzip ethtool uuid file iproute acpid iptables-persistent virt-what sudo
   #fix hostname in openssh-server generated keys
   sed -i "s/root@\(.*\)$/root@systemvm/g" etc/ssh/ssh_host_*.pub
 
@@ -373,14 +376,8 @@ packages() {
   #ipcalc
   chroot . apt-get --no-install-recommends -q -y --force-yes install ipcalc
 
-  echo "***** getting sun jre 6*********"
-  chroot . echo 'sun-java6-bin shared/accepted-sun-dlj-v1-1 boolean true
-	sun-java6-jre shared/accepted-sun-dlj-v1-1 boolean true
-	sun-java6-jre sun-java6-jre/stopthread boolean true
-	sun-java6-jre sun-java6-jre/jcepolicy note
-	sun-java6-bin shared/present-sun-dlj-v1-1 note
-	sun-java6-jre shared/present-sun-dlj-v1-1 note ' | chroot . debconf-set-selections
-  chroot .  apt-get --no-install-recommends -q -y install  sun-java6-jre 
+  echo "***** getting jre 7 *********"
+  chroot .  apt-get --no-install-recommends -q -y install openjdk-7-jre-headless
 }