cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [2/3] VirtualMachineManager no longer takes generic types
Date Thu, 23 May 2013 21:18:59 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/src/com/cloud/servlet/ConsoleProxyServlet.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java
index 097986b..ff16119 100644
--- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java
+++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java
@@ -35,12 +35,17 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
-import org.apache.cloudstack.api.IdentityService;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 import org.springframework.web.context.support.SpringBeanAutowiringSupport;
 
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import org.apache.cloudstack.api.IdentityService;
+
+import com.cloud.dao.EntityManager;
 import com.cloud.exception.PermissionDeniedException;
 import com.cloud.host.HostVO;
 import com.cloud.server.ManagementServer;
@@ -55,8 +60,6 @@ import com.cloud.utils.db.Transaction;
 import com.cloud.vm.VMInstanceVO;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachineManager;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
 
 /**
  * Thumbnail access : /console?cmd=thumbnail&vm=xxx&w=xxx&h=xxx
@@ -74,10 +77,12 @@ public class ConsoleProxyServlet extends HttpServlet {
     @Inject VirtualMachineManager _vmMgr;
     @Inject ManagementServer _ms;
     @Inject IdentityService _identityService;
+    @Inject
+    EntityManager _entityMgr;
 
     static ManagementServer s_ms;
 
-    private Gson _gson = new GsonBuilder().create();
+    private final Gson _gson = new GsonBuilder().create();
 
     public ConsoleProxyServlet() {
     }
@@ -179,7 +184,7 @@ public class ConsoleProxyServlet extends HttpServlet {
     }
 
     private void handleThumbnailRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) {
-        VMInstanceVO vm = _vmMgr.findById(vmId);
+        VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, vmId);
         if(vm == null) {
             s_logger.warn("VM " + vmId + " does not exist, sending blank response for thumbnail request");
             sendResponse(resp, "");
@@ -230,7 +235,7 @@ public class ConsoleProxyServlet extends HttpServlet {
     }
 
     private void handleAccessRequest(HttpServletRequest req, HttpServletResponse resp, long vmId) {
-        VMInstanceVO vm = _vmMgr.findById(vmId);
+        VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, vmId);
         if(vm == null) {
             s_logger.warn("VM " + vmId + " does not exist, sending blank response for console access request");
             sendResponse(resp, "");
@@ -258,7 +263,7 @@ public class ConsoleProxyServlet extends HttpServlet {
 
         String vmName = vm.getHostName();
         if(vm.getType() == VirtualMachine.Type.User) {
-            UserVm userVm = (UserVm)_vmMgr.findByIdAndType(VirtualMachine.Type.User, vmId);
+            UserVm userVm = _entityMgr.findById(UserVm.class, vmId);
             String displayName = userVm.getDisplayName();
             if(displayName != null && !displayName.isEmpty() && !displayName.equals(vmName)) {
                 vmName += "(" + displayName + ")";
@@ -276,7 +281,7 @@ public class ConsoleProxyServlet extends HttpServlet {
 
         // TODO authentication channel between console proxy VM and management server needs to be secured,
         // the data is now being sent through private network, but this is apparently not enough
-        VMInstanceVO vm = _vmMgr.findById(vmId);
+        VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, vmId);
         if(vm == null) {
             s_logger.warn("VM " + vmId + " does not exist, sending failed response for authentication request from console proxy");
             sendResponse(resp, "failed");
@@ -454,7 +459,7 @@ public class ConsoleProxyServlet extends HttpServlet {
 
     private boolean checkSessionPermision(HttpServletRequest req, long vmId, Account accountObj) {
 
-        VMInstanceVO vm = _vmMgr.findById(vmId);
+        VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, vmId);
         if(vm == null) {
             s_logger.debug("Console/thumbnail access denied. VM " + vmId + " does not exist in system any more");
             return false;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/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 9bba979..40e0321 100644
--- a/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
+++ b/server/src/com/cloud/storage/StoragePoolAutomationImpl.java
@@ -22,16 +22,14 @@ 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.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.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.api.Answer;
@@ -108,7 +106,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
         Long userId = UserContext.current().getCallerUserId();
         User user = _userDao.findById(userId);
         Account account = UserContext.current().getCaller();
-        StoragePoolVO pool = this.primaryDataStoreDao.findById(store.getId());
+        StoragePoolVO pool = primaryDataStoreDao.findById(store.getId());
         try {
             StoragePool storagePool = (StoragePool) store;
             List<HostVO> hosts = _resourceMgr.listHostsInClusterByStatus(
@@ -151,7 +149,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
             }
 
             // 2. Get a list of all the ROOT volumes within this storage pool
-            List<VolumeVO> allVolumes = this.volumeDao.findByPoolId(pool
+            List<VolumeVO> allVolumes = volumeDao.findByPoolId(pool
                     .getId());
 
             // 3. Enqueue to the work queue
@@ -208,7 +206,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                     // call the consoleproxymanager
                     ConsoleProxyVO consoleProxy = _consoleProxyDao
                             .findById(vmInstance.getId());
-                    if (!vmMgr.advanceStop(consoleProxy, true, user, account)) {
+                    if (!vmMgr.advanceStop(consoleProxy.getUuid(), false, user, account)) {
                         String errorMsg = "There was an error stopping the console proxy id: "
                                 + vmInstance.getId()
                                 + " ,cannot enable storage maintenance";
@@ -222,7 +220,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
 
                     if (restart) {
 
-                        if (this.vmMgr.advanceStart(consoleProxy, null, user,
+                        if (vmMgr.advanceStart(consoleProxy.getUuid(), null, user,
                                 account) == null) {
                             String errorMsg = "There was an error starting the console proxy id: "
                                     + vmInstance.getId()
@@ -239,7 +237,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                 // if the instance is of type uservm, call the user vm manager
                 if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
                     UserVmVO userVm = userVmDao.findById(vmInstance.getId());
-                    if (!vmMgr.advanceStop(userVm, true, user, account)) {
+                    if (!vmMgr.advanceStop(userVm.getUuid(), false, user, account)) {
                         String errorMsg = "There was an error stopping the user vm id: "
                                 + vmInstance.getId()
                                 + " ,cannot enable storage maintenance";
@@ -258,7 +256,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                         VirtualMachine.Type.SecondaryStorageVm)) {
                     SecondaryStorageVmVO secStrgVm = _secStrgDao
                             .findById(vmInstance.getId());
-                    if (!vmMgr.advanceStop(secStrgVm, true, user, account)) {
+                    if (!vmMgr.advanceStop(secStrgVm.getUuid(), false, user, account)) {
                         String errorMsg = "There was an error stopping the ssvm id: "
                                 + vmInstance.getId()
                                 + " ,cannot enable storage maintenance";
@@ -271,7 +269,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                     }
 
                     if (restart) {
-                        if (vmMgr.advanceStart(secStrgVm, null, user, account) == null) {
+                        if (vmMgr.advanceStart(secStrgVm.getUuid(), null, user, account) == null) {
                             String errorMsg = "There was an error starting the ssvm id: "
                                     + vmInstance.getId()
                                     + " on another storage pool, cannot enable primary storage maintenance";
@@ -289,7 +287,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                 if (vmInstance.getType().equals(
                         VirtualMachine.Type.DomainRouter)) {
                     DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
-                    if (!vmMgr.advanceStop(domR, true, user, account)) {
+                    if (!vmMgr.advanceStop(domR.getUuid(), false, user, account)) {
                         String errorMsg = "There was an error stopping the domain router id: "
                                 + vmInstance.getId()
                                 + " ,cannot enable primary storage maintenance";
@@ -302,7 +300,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                     }
 
                     if (restart) {
-                        if (vmMgr.advanceStart(domR, null, user, account) == null) {
+                        if (vmMgr.advanceStart(domR.getUuid(), null, user, account) == null) {
                             String errorMsg = "There was an error starting the domain router id: "
                                     + vmInstance.getId()
                                     + " on another storage pool, cannot enable primary storage maintenance";
@@ -320,7 +318,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
             s_logger.error(
                     "Exception in enabling primary storage maintenance:", e);
             pool.setStatus(StoragePoolStatus.ErrorInMaintenance);
-            this.primaryDataStoreDao.update(pool.getId(), pool);
+            primaryDataStoreDao.update(pool.getId(), pool);
             throw new CloudRuntimeException(e.getMessage());
         }
         return true;
@@ -332,7 +330,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
         Long userId = UserContext.current().getCallerUserId();
         User user = _userDao.findById(userId);
         Account account = UserContext.current().getCaller();
-        StoragePoolVO poolVO = this.primaryDataStoreDao
+        StoragePoolVO poolVO = primaryDataStoreDao
                 .findById(store.getId());
         StoragePool pool = (StoragePool)store;
        
@@ -379,7 +377,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
 
                     ConsoleProxyVO consoleProxy = _consoleProxyDao
                             .findById(vmInstance.getId());
-                    if (vmMgr.advanceStart(consoleProxy, null, user, account) == null) {
+                    if (vmMgr.advanceStart(consoleProxy.getUuid(), null, user, account) == null) {
                         String msg = "There was an error starting the console proxy id: "
                                 + vmInstance.getId()
                                 + " on storage pool, cannot complete primary storage maintenance";
@@ -397,7 +395,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                         VirtualMachine.Type.SecondaryStorageVm)) {
                     SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance
                             .getId());
-                    if (vmMgr.advanceStart(ssVm, null, user, account) == null) {
+                    if (vmMgr.advanceStart(ssVm.getUuid(), null, user, account) == null) {
                         String msg = "There was an error starting the ssvm id: "
                                 + vmInstance.getId()
                                 + " on storage pool, cannot complete primary storage maintenance";
@@ -414,7 +412,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                 if (vmInstance.getType().equals(
                         VirtualMachine.Type.DomainRouter)) {
                     DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
-                    if (vmMgr.advanceStart(domR, null, user, account) == null) {
+                    if (vmMgr.advanceStart(domR.getUuid(), null, user, account) == null) {
                         String msg = "There was an error starting the domR id: "
                                 + vmInstance.getId()
                                 + " on storage pool, cannot complete primary storage maintenance";
@@ -431,7 +429,7 @@ public class StoragePoolAutomationImpl implements StoragePoolAutomation {
                 if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
                     UserVmVO userVm = userVmDao.findById(vmInstance.getId());
 
-                    if (vmMgr.advanceStart(userVm, null, user, account) == null) {
+                    if (vmMgr.advanceStart(userVm.getUuid(), null, user, account) == null) {
 
                         String msg = "There was an error starting the user vm id: "
                                 + vmInstance.getId()

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
index 481c61a..6d25daa 100755
--- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
+++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
@@ -31,8 +31,6 @@ import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
 
-import org.apache.cloudstack.framework.jobs.AsyncJobConstants;
-
 import com.cloud.agent.AgentManager;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
@@ -49,7 +47,6 @@ import com.cloud.agent.api.StopAnswer;
 import com.cloud.agent.api.check.CheckSshAnswer;
 import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.manager.Commands;
-import com.cloud.async.AsyncJobExecutionContext;
 import com.cloud.capacity.dao.CapacityDao;
 import com.cloud.cluster.ClusterManager;
 import com.cloud.cluster.ManagementServerNode;
@@ -92,7 +89,6 @@ import com.cloud.resource.ResourceManager;
 import com.cloud.resource.ResourceStateAdapter;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.UnableDeleteHostException;
-import com.cloud.serializer.SerializerHelper;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.SnapshotVO;
@@ -109,10 +105,8 @@ import com.cloud.storage.swift.SwiftManager;
 import com.cloud.storage.template.TemplateConstants;
 import com.cloud.user.Account;
 import com.cloud.user.AccountService;
-import com.cloud.user.AccountVO;
 import com.cloud.user.User;
 import com.cloud.user.UserContext;
-import com.cloud.user.UserVO;
 import com.cloud.utils.DateUtil;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
@@ -138,9 +132,6 @@ import com.cloud.vm.VirtualMachineGuru;
 import com.cloud.vm.VirtualMachineManager;
 import com.cloud.vm.VirtualMachineName;
 import com.cloud.vm.VirtualMachineProfile;
-import com.cloud.vm.VmWork;
-import com.cloud.vm.VmWorkStart;
-import com.cloud.vm.VmWorkStop;
 import com.cloud.vm.dao.SecondaryStorageVmDao;
 import com.cloud.vm.dao.UserVmDetailsDao;
 import com.cloud.vm.dao.VMInstanceDao;
@@ -269,7 +260,11 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
             SecondaryStorageVmVO secStorageVm = _secStorageVmDao.findById(secStorageVmId);
             Account systemAcct = _accountMgr.getSystemAccount();
             User systemUser = _accountMgr.getSystemUser();
-            return _itMgr.start(secStorageVm, null, systemUser, systemAcct);
+            if (_itMgr.start(secStorageVm.getUuid(), null, systemUser, systemAcct) != null) {
+                return _secStorageVmDao.findById(secStorageVmId);
+            } else {
+                return null;
+            }
         } catch (StorageUnavailableException e) {
             s_logger.warn("Exception while trying to start secondary storage vm", e);
             return null;
@@ -587,12 +582,14 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
 
         SecondaryStorageVmVO secStorageVm = new SecondaryStorageVmVO(id, _serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
                 systemAcct.getDomainId(), systemAcct.getId(), role, _serviceOffering.getOfferHA());
-        try {
-            secStorageVm = _itMgr.allocate(secStorageVm, template, _serviceOffering, networks, plan, null, systemAcct);
-        } catch (InsufficientCapacityException e) {
-            s_logger.warn("InsufficientCapacity", e);
-            throw new CloudRuntimeException("Insufficient capacity exception", e);
+        secStorageVm = _secStorageVmDao.persist(secStorageVm);
+        if (_itMgr.allocate(secStorageVm.getInstanceName(), template, _serviceOffering, networks, plan, null, systemAcct) == null) {
+            s_logger.warn("Unable to allocate");
+            _secStorageVmDao.remove(secStorageVm.getId());
+            throw new CloudRuntimeException("Unable to allocate sec storage vm");
         }
+        
+        secStorageVm = _secStorageVmDao.findById(secStorageVm.getId());
 
         Map<String, Object> context = new HashMap<String, Object>();
         context.put("secStorageVmId", secStorageVm.getId());
@@ -923,38 +920,29 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
             }
             return false;
         }
-        try {
-            if (secStorageVm.getHostId() != null) {
-                GlobalLock secStorageVmLock = GlobalLock.getInternLock(getSecStorageVmLockName(secStorageVm.getId()));
-                try {
-                    if (secStorageVmLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
-                        try {
-                            boolean result = _itMgr.stop(secStorageVm, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
-                            if (result) {
-                            }
-
-                            return result;
-                        } finally {
-                            secStorageVmLock.unlock();
-                        }
-                    } else {
-                        String msg = "Unable to acquire secondary storage vm lock : " + secStorageVm.toString();
-                        s_logger.debug(msg);
-                        return false;
+        if (secStorageVm.getHostId() != null) {
+            GlobalLock secStorageVmLock = GlobalLock.getInternLock(getSecStorageVmLockName(secStorageVm.getId()));
+            try {
+                if (secStorageVmLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
+                    try {
+                        boolean result = _itMgr.stop(secStorageVm.getUuid(), _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
+                        return result;
+                    } finally {
+                        secStorageVmLock.unlock();
                     }
-                } finally {
-                    secStorageVmLock.releaseRef();
+                } else {
+                    String msg = "Unable to acquire secondary storage vm lock : " + secStorageVm.toString();
+                    s_logger.debug(msg);
+                    return false;
                 }
+            } finally {
+                secStorageVmLock.releaseRef();
             }
-
-            // vm was already stopped, return true
-            return true;
-        } catch (ResourceUnavailableException e) {
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Stopping secondary storage vm " + secStorageVm.getHostName() + " faled : exception " + e.toString());
-            }
-            return false;
         }
+
+        // vm was already stopped, return true
+        return true;
+
     }
 
     @Override
@@ -995,7 +983,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
         SecondaryStorageVmVO ssvm = _secStorageVmDao.findById(vmId);
 
         try {
-            boolean result = _itMgr.expunge(ssvm, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
+            boolean result = _itMgr.expunge(ssvm.getUuid(), _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
             if (result) {
                 HostVO host = _hostDao.findByTypeNameAndZoneId(ssvm.getDataCenterId(), ssvm.getHostName(),
                         Host.Type.SecondaryStorageVM);
@@ -1464,44 +1452,44 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
     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(AsyncJobConstants.STATUS_SUCCEEDED, null);
-    	} catch(Exception e) {
-    		s_logger.error("Exception in process VM-start work", e);
-    		String result = SerializerHelper.toObjectSerializedString(e);
-    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(AsyncJobConstants.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(AsyncJobConstants.STATUS_SUCCEEDED, null);
-    	} catch(Exception e) {
-    		s_logger.error("Exception in process VM-stop work", e);
-    		String result = SerializerHelper.toObjectSerializedString(e);
-    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(AsyncJobConstants.STATUS_FAILED, result);
-    	}
-    }
+//    @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(AsyncJobConstants.STATUS_SUCCEEDED, null);
+//    	} catch(Exception e) {
+//    		s_logger.error("Exception in process VM-start work", e);
+//    		String result = SerializerHelper.toObjectSerializedString(e);
+//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(AsyncJobConstants.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(AsyncJobConstants.STATUS_SUCCEEDED, null);
+//    	} catch(Exception e) {
+//    		s_logger.error("Exception in process VM-stop work", e);
+//    		String result = SerializerHelper.toObjectSerializedString(e);
+//    		AsyncJobExecutionContext.getCurrentExecutionContext().completeJobAndJoin(AsyncJobConstants.STATUS_FAILED, result);
+//    	}
+//    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java
index 4088f64..8b8447a 100755
--- a/server/src/com/cloud/user/AccountManagerImpl.java
+++ b/server/src/com/cloud/user/AccountManagerImpl.java
@@ -37,6 +37,9 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.RoleType;
 import org.apache.cloudstack.acl.SecurityChecker;
@@ -46,8 +49,6 @@ import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd;
 import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd;
 import org.apache.cloudstack.api.command.admin.user.RegisterCmd;
 import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
 
 import com.cloud.api.ApiDBUtils;
 import com.cloud.api.query.dao.UserAccountJoinDao;
@@ -265,7 +266,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
 	}
 
 	public void setSecurityCheckers(List<SecurityChecker> securityCheckers) {
-		this._securityCheckers = securityCheckers;
+		_securityCheckers = securityCheckers;
 	}
     
     @Override
@@ -603,7 +604,7 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             for (VolumeVO volume : volumes) {
                 if (!volume.getState().equals(Volume.State.Destroy)) {
                     try {
-                        this.volumeMgr.deleteVolume(volume.getId(), caller);
+                        volumeMgr.deleteVolume(volume.getId(), caller);
                     } catch (Exception ex) {
                         s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
                         accountCleanupNeeded = true;
@@ -774,11 +775,11 @@ public class AccountManagerImpl extends ManagerBase implements AccountManager, M
             try {
                 try {
                     if (vm.getType() == Type.User) {
-                        success = (success && _itMgr.advanceStop(_userVmDao.findById(vm.getId()), false, getSystemUser(), getSystemAccount()));
+                        success = (success && _itMgr.advanceStop(vm.getUuid(), false, getSystemUser(), getSystemAccount()));
                     } else if (vm.getType() == Type.DomainRouter) {
-                        success = (success && _itMgr.advanceStop(_routerDao.findById(vm.getId()), false, getSystemUser(), getSystemAccount()));
+                        success = (success && _itMgr.advanceStop(vm.getUuid(), false, getSystemUser(), getSystemAccount()));
                     } else {
-                        success = (success && _itMgr.advanceStop(vm, false, getSystemUser(), getSystemAccount()));
+                        success = (success && _itMgr.advanceStop(vm.getUuid(), false, getSystemUser(), getSystemAccount()));
                     }
                 } catch (OperationTimedoutException ote) {
                     s_logger.warn("Operation for stopping vm timed out, unable to stop vm " + vm.getHostName(), ote);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/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 55cdc18..dd0b98a 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -718,8 +718,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         }
     }
 
-    private UserVm rebootVirtualMachine(long userId, long vmId)
-            throws InsufficientCapacityException, ResourceUnavailableException {
+    private UserVm rebootVirtualMachine(long userId, long vmId) {
         UserVmVO vm = _vmDao.findById(vmId);
         User caller = _accountMgr.getActiveUser(userId);
         Account owner = _accountMgr.getAccount(vm.getAccountId());
@@ -730,13 +729,10 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             return null;
         }
 
-        if (vm.getState() == State.Running && vm.getHostId() != null) {
-            return _itMgr.reboot(vm, null, caller, owner);
-        } else {
-            s_logger.error("Vm id=" + vmId
-                    + " is not in Running state, failed to reboot");
+        if (_itMgr.reboot(vm.getUuid(), caller, owner)) {
             return null;
         }
+        return _vmDao.findById(vmId);
     }
 
     @Override
@@ -1091,7 +1087,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         Account caller = UserContext.current().getCaller();
 
         // Verify input parameters
-        VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
+        VirtualMachine vmInstance = _vmInstanceDao.findById(vmId);
         if(vmInstance.getHypervisorType() != HypervisorType.XenServer && vmInstance.getHypervisorType() != HypervisorType.VMware){
             throw new InvalidParameterValueException("This operation not permitted for this hypervisor of the vm");
         }
@@ -1126,7 +1122,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
                     // #2 migrate the vm if host doesn't have capacity
                     if (!existingHostHasCapacity){
-                        vmInstance = _itMgr.findHostAndMigrate(vmInstance.getType(), vmInstance, newServiceOfferingId);
+                        vmInstance = _itMgr.findHostAndMigrate(vmInstance.getUuid(), newServiceOfferingId);
                     }
 
                     // #3 scale the vm now
@@ -1405,12 +1401,20 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         ctx.setAccountId(vm.getAccountId());
 
         try {
+            List<VolumeVO> rootVol = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT);
             // expunge the vm
-            if (!_itMgr.advanceExpunge(vm, _accountMgr.getSystemUser(), caller)) {
+            if (!_itMgr.advanceExpunge(vm.getUuid(), _accountMgr.getSystemUser(), caller)) {
                 s_logger.info("Did not expunge " + vm);
                 return false;
             }
 
+            // Update Resource count
+            if (vm.getAccountId() != Account.ACCOUNT_ID_SYSTEM && !rootVol.isEmpty()) {
+                _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.volume);
+                _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.primary_storage,
+                        new Long(rootVol.get(0).getSize()));
+            }
+
             // Only if vm is not expunged already, cleanup it's resources
             if (vm != null && vm.getRemoved() == null) {
                 // Cleanup vm resources - all the PF/LB/StaticNat rules
@@ -1425,8 +1429,6 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                             + vm + " expunge");
                     return false;
                 }
-
-                _itMgr.remove(vm, _accountMgr.getSystemUser(), caller);
             }
 
             return true;
@@ -3525,7 +3527,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                             + destHypervisorType.toString() + ", vm: "
                             + vm.getHypervisorType().toString());
         }
-        VMInstanceVO migratedVm = _itMgr.storageMigration(vm, destPool);
+        VirtualMachine migratedVm = _itMgr.storageMigration(vm.getUuid(), destPool);
         return migratedVm;
 
     }
@@ -3642,8 +3644,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                             + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
         }
 
-        VMInstanceVO migratedVm = _itMgr.migrate(vm, srcHostId, dest);
-        return migratedVm;
+        return _itMgr.migrate(vm.getUuid(), srcHostId, dest);
     }
 
     @Override
@@ -3763,8 +3764,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                     " migrate to this host");
         }
 
-        VMInstanceVO migratedVm = _itMgr.migrateWithStorage(vm, srcHostId, destinationHost.getId(), volToPoolObjectMap);
-        return migratedVm;
+        return _itMgr.migrateWithStorage(vm.getUuid(), srcHostId, destinationHost.getId(), volToPoolObjectMap);
     }
 
     @DB
@@ -3956,7 +3956,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
         txn.commit();
 
-        VMInstanceVO vmoi = _itMgr.findByIdAndType(vm.getType(), vm.getId());
+        VMInstanceVO vmoi = _vmInstanceDao.findById(vm.getId());
         VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
 
         // OS 3: update the network
@@ -4033,7 +4033,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
             networks.add(new Pair<NetworkVO, NicProfile>(networkList.get(0),
                     profile));
 
-            VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(), vm.getId());
+            VMInstanceVO vmi = _vmInstanceDao.findById(vm.getId());
             VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
             _networkMgr.allocate(vmProfile, networks);
 
@@ -4166,8 +4166,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
                     networks.add(new Pair<NetworkVO, NicProfile>(appNet,
                             defaultNic));
                 }
-                VMInstanceVO vmi = _itMgr.findByIdAndType(vm.getType(),
-                        vm.getId());
+                VMInstanceVO vmi = _vmInstanceDao.findById(vm.getId());
                 VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
                 _networkMgr.allocate(vmProfile, networks);
                 s_logger.debug("AssignVM: Advance virtual, adding networks no "
@@ -4263,12 +4262,9 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
         }
 
         if (needRestart) {
-            try {
-                _itMgr.stop(vm, user, caller);
-            } catch (ResourceUnavailableException e) {
-                s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
-                CloudRuntimeException ex = new CloudRuntimeException(
-                        "Stop vm failed for specified vmId");
+            if (!_itMgr.stop(vm.getUuid(), user, caller)) {
+                s_logger.debug("Stop vm " + vm.getUuid() + " failed");
+                CloudRuntimeException ex = new CloudRuntimeException("Stop vm failed for specified vmId");
                 ex.addProxyObject(vm, vmId, "vmId");
                 throw ex;
             }
@@ -4317,7 +4313,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
 
         if (needRestart) {
             try {
-                _itMgr.start(vm, null, user, caller);
+                _itMgr.start(vm.getUuid(), null, user, caller);
             } catch (Exception e) {
                 s_logger.debug("Unable to start VM " + vm.getUuid(), e);
                 CloudRuntimeException ex = new CloudRuntimeException(
@@ -4337,12 +4333,12 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Use
     public void prepareStop(VirtualMachineProfile profile) {
     }
     
-    @Override
-    public void vmWorkStart(VmWork work) {
-    }
-    
-    @Override
-    public void vmWorkStop(VmWork work) {
-    }
+//    @Override
+//    public void vmWorkStart(VmWork work) {
+//    }
+//
+//    @Override
+//    public void vmWorkStop(VmWork work) {
+//    }
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
index c584098..4c421e6 100755
--- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
+++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
@@ -83,7 +83,6 @@ import com.cloud.capacity.CapacityManager;
 import com.cloud.cluster.ClusterManager;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationManager;
-import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.ClusterDetailsDao;
 import com.cloud.dc.ClusterDetailsVO;
@@ -345,9 +344,12 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
     @Override
     @DB
-    public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Pair<? extends DiskOfferingVO, Long> rootDiskOffering,
+    public VirtualMachine 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) throws InsufficientCapacityException {
+            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);
         }
@@ -358,13 +360,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         if (plan.getPodId() != null) {
             vm.setPodId(plan.getPodId());
         }
-        assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
-
-        VirtualMachineGuru guru = _vmGurus.get(vm.getType());
 
         Transaction txn = Transaction.currentTxn();
         txn.start();
-//        vm = guru.persist(vm);
+        _vmDao.update(vm.getId(), vm);
 
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Allocating nics for " + vm);
@@ -374,6 +373,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             _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) {
@@ -405,41 +406,28 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, Long rootSize, Pair<DiskOfferingVO, Long> dataDiskOffering,
-            List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan, HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
-        List<Pair<DiskOfferingVO, Long>> diskOfferings = new ArrayList<Pair<DiskOfferingVO, Long>>(1);
-        if (dataDiskOffering != null) {
-            diskOfferings.add(dataDiskOffering);
-        }
-        return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, rootSize), diskOfferings, networks, null, plan, hyperType, owner);
+    public VirtualMachine 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 <T extends VMInstanceVO> T allocate(T vm, VMTemplateVO template, ServiceOfferingVO serviceOffering, List<Pair<NetworkVO, NicProfile>> networks, DeploymentPlan plan,
-            HypervisorType hyperType, Account owner) throws InsufficientCapacityException {
-        return allocate(vm, template, serviceOffering, new Pair<DiskOfferingVO, Long>(serviceOffering, null), null, networks, null, plan, hyperType, owner);
-    }
-
-    @Override
-    public <T extends VMInstanceVO> boolean expunge(T vm, User caller, Account account) throws ResourceUnavailableException {
+    public boolean expunge(String vmUuid, User caller, Account account) {
         try {
-            if (advanceExpunge(vm, caller, account)) {
-                // Mark vms as removed
-                remove(vm, caller, account);
-                return true;
-            } else {
-                s_logger.info("Did not expunge " + vm);
-                return false;
-            }
+            return advanceExpunge(vmUuid, caller, account);
         } 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 <T extends VMInstanceVO> boolean advanceExpunge(T vm, User caller, Account account) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    public boolean advanceExpunge(String vmUuid, User caller, Account account) 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);
@@ -447,12 +435,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             return true;
         }
 
-        if (!this.advanceStop(vm, false, caller, account)) {
+        if (!advanceStop(vmUuid, false, caller, account)) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Unable to stop the VM so we can't expunge it.");
             }
         }
 
+        vm = _vmDao.findByUuid(vmUuid);
         try {
             if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
                 s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
@@ -471,7 +460,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         s_logger.debug("Cleaning up NICS");
         _networkMgr.cleanupNics(profile);
         // Clean up volumes based on the vm's instance id
-        List<VolumeVO> rootVol = _volsDao.findByInstanceAndType(vm.getId(), Volume.Type.ROOT);
         volumeMgr.cleanupVolumes(vm.getId());
 
         VirtualMachineGuru guru = getVmGuru(vm);
@@ -505,13 +493,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Expunged " + vm);
         }
+        
+        _vmDao.remove(vm.getId());
 
-        // Update Resource count
-        if (vm.getAccountId() != Account.ACCOUNT_ID_SYSTEM && !rootVol.isEmpty()) {
-            _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.volume);
-            _resourceLimitMgr.decrementResourceCount(vm.getAccountId(), ResourceType.primary_storage,
-                    new Long(rootVol.get(0).getSize()));
-        }
         return true;
     }
 
@@ -557,15 +541,17 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
-        return start(vm, params, caller, account, null);
+    public VirtualMachine start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
+            ResourceUnavailableException {
+        return start(vmUuid, params, caller, account, null);
     }
 
     @Override
-    public <T extends VMInstanceVO> T start(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy) throws InsufficientCapacityException,
+    public VirtualMachine start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
+            throws InsufficientCapacityException,
     	ResourceUnavailableException {
         try {
-            return advanceStart(vm, params, caller, account, planToDeploy);
+            return advanceStart(vmUuid, params, caller, account, planToDeploy);
         } catch (ConcurrentOperationException e) {
             throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e);
         }
@@ -607,7 +593,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     
     /*
         @DB
-        protected <T extends VMInstanceVO> Ternary<T, ReservationContext, VmWorkJobVO> changeToStartState(VirtualMachineGuru<T> vmGuru, T vm, User caller, Account account)
+        protected VirtualMachineernary<T, ReservationContext, VmWorkJobVO> changeToStartState(VirtualMachineGuru<T> vmGuru, String vmUuid, User caller, Account account)
                 throws ConcurrentOperationException {
             long vmId = vm.getId();
 
@@ -707,7 +693,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         throw new ConcurrentOperationException("Unable to change the state of " + vm);
     }
     
-    protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, VmWorkJobVO work, Step step) throws NoTransitionException {
+    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();
         
@@ -734,15 +720,16 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T advanceStart(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
+    public VirtualMachine advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
     	ConcurrentOperationException, ResourceUnavailableException {
-        return advanceStart(vm, params, caller, account, null);
+        return advanceStart(vmUuid, params, caller, account, null);
     }
     
     @Override
     @DB
-    public <T extends VMInstanceVO> T advanceStart(final T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
+    public VirtualMachine advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
         throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
     	
     	VmWorkJobVO workJob = null;
     	Transaction txn = Transaction.currentTxn();
@@ -821,18 +808,18 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T processVmStartWork(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
+    public VirtualMachine processVmStartWork(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account, DeploymentPlan planToDeploy)
             throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         VirtualMachineGuru vmGuru = getVmGuru(vm);
-        VMInstanceVO vm2 = _vmDao.findById(vm.getId());
   
-        Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO> start = changeToStartState(vmGuru, vm2, caller, account);
+        Ternary<VMInstanceVO, ReservationContext, VmWorkJobVO> start = changeToStartState(vmGuru, vm, caller, account);
         assert(start != null);
 
         ReservationContext ctx = start.second();
         VmWorkJobVO work = start.third();
 
-        T startedVm = null;
+        VMInstanceVO startedVm = null;
         ServiceOfferingVO offering = _offeringDao.findById(vm.getServiceOfferingId());
         VMTemplateVO template = _templateDao.findById(vm.getTemplateId());
 
@@ -1094,13 +1081,15 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
     
     @Override
-    public <T extends VMInstanceVO> boolean stop(T vm, User user, Account account) throws ResourceUnavailableException {
+    public boolean stop(String vmUuid, User user, Account account) {
         try {
-            return advanceStop(vm, false, user, account);
+            return advanceStop(vmUuid, false, user, account);
         } catch (OperationTimedoutException e) {
-            throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", vm.getHostId(), e);
+            throw new CloudRuntimeException("Unable to stop vm because the operation to stop timed out", e);
         } catch (ConcurrentOperationException e) {
             throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e);
+        } catch (AgentUnavailableException e) {
+            throw new CloudRuntimeException("Unable to reach host to stop vm", e);
         }
     }
 
@@ -1193,7 +1182,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
     
     @Override
-    public <T extends VMInstanceVO> boolean advanceStop(final T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    public boolean advanceStop(final String vmUuid, boolean forced, User user, Account account) throws AgentUnavailableException,
+            OperationTimedoutException, ConcurrentOperationException {
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
     	VmWorkJobVO workJob = null;
     	Transaction txn = Transaction.currentTxn();
     	try {
@@ -1274,9 +1265,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> boolean processVmStopWork(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    public boolean processVmStopWork(String vmUuid, boolean forced, User user, Account account) throws AgentUnavailableException,
+            OperationTimedoutException, ConcurrentOperationException {
         VmWorkJobVO work = _workJobDao.findById(AsyncJobExecutionContext.getCurrentExecutionContext().getJob().getId());
 
+        final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         Long hostId = vm.getHostId();
         if (hostId == null) {
             if (!forced) {
@@ -1408,7 +1401,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
 
     /*
         @Override
-        public <T extends VMInstanceVO> boolean advanceStop(T vm, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+        public boolean advanceStop(String vmUuid, boolean forced, User user, Account account) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
             State state = vm.getState();
             if (state == State.Stopped) {
                 if (s_logger.isDebugEnabled()) {
@@ -1611,12 +1604,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> boolean remove(T vm, User user, Account caller) {
-        return _vmDao.remove(vm.getId());
-    }
-
-    @Override
-    public <T extends VMInstanceVO> boolean destroy(T vm, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
+    public boolean destroy(String vmUuid, User user, Account caller) throws AgentUnavailableException, OperationTimedoutException,
+            ConcurrentOperationException {
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Destroying vm " + vm);
         }
@@ -1627,11 +1617,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             return true;
         }
 
-        if (!advanceStop(vm, _forceStop, user, caller)) {
+        if (!advanceStop(vmUuid, _forceStop, user, caller)) {
             s_logger.debug("Unable to stop " + vm);
             return false;
         }
         
+        vm = _vmDao.findById(vm.getId());
+
         if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(),null)){
             s_logger.debug("Unable to delete all snapshots for " + vm);
             return false;
@@ -1660,11 +1652,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T storageMigration(T vm, StoragePool destPool) {
-        VirtualMachineGuru vmGuru = getVmGuru(vm);
+    public VirtualMachine storageMigration(String vmUuid, StoragePool destPool) {
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 
         long vmId = vm.getId();
-        VMInstanceVO vm2 = _vmDao.findById(vmId);
 
         try {
             stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
@@ -1718,8 +1709,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T migrate(T vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
+    public VirtualMachine migrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException,
+            ManagementServerException,
     	VirtualMachineMigrationException {
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         s_logger.info("Migrating " + vm + " to " + dest);
         
         return vm;
@@ -1931,7 +1924,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         return volumeToPool;
     }
 
-    private <T extends VMInstanceVO> void moveVmToMigratingState(T vm, Long hostId, VmWorkJobVO work)
+    private void moveVmToMigratingState(VMInstanceVO vm, Long hostId, VmWorkJobVO work)
             throws ConcurrentOperationException {
         // Put the vm in migrating state.
         try {
@@ -1945,7 +1938,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         }
     }
 
-    private <T extends VMInstanceVO> void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, VmWorkJobVO work)
+    private void moveVmOutofMigratingStateOnSuccess(VMInstanceVO vm, Long hostId, VmWorkJobVO work)
             throws ConcurrentOperationException {
         // Put the vm in running state.
         try {
@@ -1960,10 +1953,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T migrateWithStorage(T vm, long srcHostId, long destHostId,
+    public VirtualMachine migrateWithStorage(String vmUuid, long srcHostId, long destHostId,
             Map<VolumeVO, StoragePoolVO> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException,
             ManagementServerException, VirtualMachineMigrationException {
 
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
         HostVO srcHost = _hostDao.findById(srcHostId);
         HostVO destHost = _hostDao.findById(destHostId);
         VirtualMachineGuru vmGuru = getVmGuru(vm);
@@ -2150,9 +2144,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             }
 
             excludes.addHost(dest.getHost().getId());
-            VMInstanceVO vmInstance = null;
+            VirtualMachine vmInstance = null;
             try {
-                vmInstance = migrate(vm, srcHostId, dest);
+                vmInstance = migrate(vm.getUuid(), srcHostId, dest);
             } catch (ResourceUnavailableException e) {
                 s_logger.debug("Unable to migrate to unavailable " + dest);
             } catch (ConcurrentOperationException e) {
@@ -2172,7 +2166,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
                 return true;
             }
             try {
-                boolean result = advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
+                boolean result = advanceStop(vm.getUuid(), true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
                 return result;
             } catch (ResourceUnavailableException e) {
                 s_logger.debug("Unable to stop VM due to " + e.getMessage());
@@ -2208,8 +2202,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         }
     }
 
-    @Override
-    public boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) {
+    private boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) {
         boolean isMachineUpgradable = true;
         for(HostAllocator allocator : _hostAllocators) {
             isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering);
@@ -2223,27 +2216,28 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public <T extends VMInstanceVO> T reboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException, ResourceUnavailableException {
+    public boolean reboot(String vmUuid, User caller, Account account) {
         try {
-            return advanceReboot(vm, params, caller, account);
+            return advanceReboot(vmUuid, caller, account);
         } catch (ConcurrentOperationException e) {
             throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e);
+        } catch (InsufficientCapacityException e) {
+            throw new CloudRuntimeException("Unable to reboot a VM due to insufficient capacity", e);
+        } catch (ResourceUnavailableException e) {
+            throw new CloudRuntimeException("Unable to reboot a VM due to resource unavailable", e);
         }
     }
 
     @Override
-    public <T extends VMInstanceVO> T advanceReboot(T vm, Map<VirtualMachineProfile.Param, Object> params, User caller, Account account) throws InsufficientCapacityException,
+    public boolean advanceReboot(String vmUuid, User caller, Account account) throws InsufficientCapacityException,
     ConcurrentOperationException, ResourceUnavailableException {
-        T rebootedVm = null;
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
+        if (vm.getHostId() == null) {
+            s_logger.debug("No need to reboot " + vm + " when it doesn't have a host id");
+            return false;
+        }
 
-        DataCenter dc = _configMgr.getZone(vm.getDataCenterId());
         Host host = _hostDao.findById(vm.getHostId());
-        Cluster cluster = null;
-        if (host != null) {
-            cluster = _configMgr.getCluster(host.getClusterId());
-        }
-        HostPodVO pod = _configMgr.getPod(host.getPodId());
-        DeployDestination dest = new DeployDestination(dc, pod, cluster, host);
 
         try {
 
@@ -2252,22 +2246,14 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
             _agentMgr.send(host.getId(), cmds);
 
             Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
-            if (rebootAnswer != null && rebootAnswer.getResult()) {
-                rebootedVm = vm;
-                return rebootedVm;
+            if (rebootAnswer == null || !rebootAnswer.getResult()) {
+                s_logger.debug("Unable to reboot VM " + vm + " on " + host + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
             }
-            s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
+            return true;
         } catch (OperationTimedoutException e) {
-            s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
-            throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
+            s_logger.warn("Unable to send the reboot command to host " + host + " for the vm " + vm + " due to operation timeout", e);
+            return false;
         }
-
-        return rebootedVm;
-    }
-
-    @Override
-    public VMInstanceVO findByIdAndType(VirtualMachine.Type type, long vmId) {
-        return _vmDao.findById(vmId);
     }
 
     public Command cleanup(VirtualMachine vm) {
@@ -3062,11 +3048,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public VMInstanceVO findById(long vmId) {
-        return _vmDao.findById(vmId);
-    }
-
-    @Override
     public void checkIfCanUpgrade(VirtualMachine vmInstance, long newServiceOfferingId) {
         ServiceOfferingVO newServiceOffering = _offeringDao.findById(newServiceOfferingId);
         if (newServiceOffering == null) {
@@ -3418,8 +3399,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
     @Override
-    public VMInstanceVO findHostAndMigrate(VirtualMachine.Type vmType, VMInstanceVO vm, Long newSvcOfferingId)
+    public VirtualMachine findHostAndMigrate(String vmUuid, Long newSvcOfferingId)
             throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, VirtualMachineMigrationException, ManagementServerException {
+        VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
 
         VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
 
@@ -3459,9 +3441,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         }
 
         excludes.addHost(dest.getHost().getId());
-        VMInstanceVO vmInstance = null;
+        VirtualMachine vmInstance = null;
         try {
-            vmInstance = migrateForScale(vm, srcHostId, dest, oldSvcOfferingId);
+            vmInstance = migrateForScale(vm.getUuid(), srcHostId, dest, oldSvcOfferingId);
         } catch (ResourceUnavailableException e) {
             s_logger.debug("Unable to migrate to unavailable " + dest);
             throw e;
@@ -3488,10 +3470,11 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
     }
 
         @Override
-        public <T extends VMInstanceVO> T migrateForScale(T vm, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException,
+    public VirtualMachine migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId) throws ResourceUnavailableException,
+            ConcurrentOperationException, ManagementServerException,
                 VirtualMachineMigrationException {
-            s_logger.info("Migrating " + vm + " to " + dest);
-            return vm;
+//            s_logger.info("Migrating " + vm + " to " + dest);
+        return null;
         /*
                     Long newSvcOfferingId = vm.getServiceOfferingId();
                     long dstHostId = dest.getHost().getId();
@@ -3644,7 +3627,8 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac
         */
         }
     @Override
-    public VMInstanceVO reConfigureVm(VMInstanceVO vm , ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException, ConcurrentOperationException {
+    public VirtualMachine reConfigureVm(VirtualMachine vm, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException,
+            ConcurrentOperationException {
         /*
                 long newServiceofferingId = vm.getServiceOfferingId();
                 ServiceOffering newServiceOffering = _configMgr.getServiceOffering(newServiceofferingId);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/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 8687163..162d87b 100644
--- a/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
+++ b/server/src/com/cloud/vm/snapshot/VMSnapshotManagerImpl.java
@@ -27,12 +27,13 @@ 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.vmsnapshot.ListVMSnapshotCmd;
 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.agent.AgentManager;
 import com.cloud.agent.api.Answer;
@@ -59,8 +60,8 @@ import com.cloud.host.Host;
 import com.cloud.host.HostVO;
 import com.cloud.host.dao.HostDao;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
-import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
 import com.cloud.hypervisor.HypervisorGuruManager;
+import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
 import com.cloud.storage.GuestOSVO;
 import com.cloud.storage.Snapshot;
@@ -204,7 +205,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         }
 
         if (state == null) {
-            VMSnapshot.State[] status = { VMSnapshot.State.Ready, VMSnapshot.State.Creating, VMSnapshot.State.Allocated, 
+            VMSnapshot.State[] status = { VMSnapshot.State.Ready, VMSnapshot.State.Creating, VMSnapshot.State.Allocated,
                     VMSnapshot.State.Error, VMSnapshot.State.Expunging, VMSnapshot.State.Reverting };
             sc.setParameters("status", (Object[]) status);
         } else {
@@ -236,7 +237,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
     }
     
     @Override
-    public VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDescription, Boolean snapshotMemory) 
+    public VMSnapshot allocVMSnapshot(Long vmId, String vsDisplayName, String vsDescription, Boolean snapshotMemory)
             throws ResourceAllocationException {
 
         Account caller = getCaller();
@@ -264,7 +265,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
             vsDisplayName = vmSnapshotName;
         }
         if(_vmSnapshotDao.findByName(vmId,vsDisplayName) != null){
-            throw new InvalidParameterValueException("Creating VM snapshot failed due to VM snapshot with name" + vsDisplayName + "  already exists"); 
+            throw new InvalidParameterValueException("Creating VM snapshot failed due to VM snapshot with name" + vsDisplayName + "  already exists");
         }
         
         // check VM state
@@ -321,7 +322,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         } catch (Exception e) {
             String msg = e.getMessage();
             s_logger.error("Create vm snapshot record failed for vm: " + vmId + " due to: " + msg);
-        }  
+        }
         return null;
     }
 
@@ -351,7 +352,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
     }
 
     protected VMSnapshot createVmSnapshotInternal(UserVmVO userVm, VMSnapshotVO vmSnapshot, Long hostId) {
-        try { 
+        try {
             CreateVMSnapshotAnswer answer = null;
             GuestOSVO guestOS = _guestOSDao.findById(userVm.getGuestOSId());
             
@@ -411,7 +412,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         List<VolumeVO> volumeVos = _volumeDao.findByInstance(vmId);
         
         for (VolumeVO volume : volumeVos) {
-            StoragePool pool = (StoragePool)this.dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
+            StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(volume.getPoolId());
             VolumeTO volumeTO = new VolumeTO(volume, pool);
             volumeTOs.add(volumeTO);
         }
@@ -487,7 +488,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
             _vmSnapshotDao.persist(child);
         }
         
-        // update current snapshot 
+        // update current snapshot
         VMSnapshotVO current = _vmSnapshotDao.findCurrentSnapshotByVmId(vmSnapshot.getVmId());
         if(current != null && current.getId() == vmSnapshot.getId() && vmSnapshot.getParent() != null){
             VMSnapshotVO parent = _vmSnapshotDao.findById(vmSnapshot.getParent());
@@ -549,7 +550,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
     
     @Override
     public boolean hasActiveVMSnapshotTasks(Long vmId){
-        List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(vmId, 
+        List<VMSnapshotVO> activeVMSnapshots = _vmSnapshotDao.listByInstanceId(vmId,
                 VMSnapshot.State.Creating, VMSnapshot.State.Expunging,VMSnapshot.State.Reverting,VMSnapshot.State.Allocated);
         return activeVMSnapshots.size() > 0;
     }
@@ -601,7 +602,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
             // prepare DeleteVMSnapshotCommand
             String vmInstanceName = userVm.getInstanceName();
             VMSnapshotTO parent = getSnapshotWithParents(vmSnapshot).getParent();
-            VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(vmSnapshot.getId(), vmSnapshot.getName(), vmSnapshot.getType(), 
+            VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(vmSnapshot.getId(), vmSnapshot.getName(), vmSnapshot.getType(),
                     vmSnapshot.getCreated().getTime(), vmSnapshot.getDescription(), vmSnapshot.getCurrent(), parent);
             GuestOSVO guestOS = _guestOSDao.findById(userVm.getGuestOSId());
             DeleteVMSnapshotCommand deleteSnapshotCommand = new DeleteVMSnapshotCommand(vmInstanceName, vmSnapshotTO, volumeTOs,guestOS.getDisplayName());
@@ -672,7 +673,9 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         // start or stop VM first, if revert from stopped state to running state, or from running to stopped
         if(userVm.getState() == VirtualMachine.State.Stopped && vmSnapshotVo.getType() == VMSnapshot.Type.DiskAndMemory){
             try {
-        	    vm = _itMgr.advanceStart(userVm, new HashMap<VirtualMachineProfile.Param, Object>(), callerUser, owner);
+                if (_itMgr.advanceStart(userVm.getUuid(), new HashMap<VirtualMachineProfile.Param, Object>(), callerUser, owner) != null) {
+                    userVm = _userVMDao.findById(userVm.getId());
+                }
         	    hostId = vm.getHostId();
         	} catch (Exception e) {
         	    s_logger.error("Start VM " + userVm.getInstanceName() + " before reverting failed due to " + e.getMessage());
@@ -681,7 +684,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
         }else {
             if(userVm.getState() == VirtualMachine.State.Running && vmSnapshotVo.getType() == VMSnapshot.Type.Disk){
                 try {
-    			    _itMgr.advanceStop(userVm, true, callerUser, owner);
+                    _itMgr.advanceStop(userVm.getUuid(), false, callerUser, owner);
                 } catch (Exception e) {
                     s_logger.error("Stop VM " + userVm.getInstanceName() + " before reverting failed due to " + e.getMessage());
     			    throw new CloudRuntimeException(e.getMessage());
@@ -714,7 +717,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
             List<VolumeTO> volumeTOs = getVolumeTOList(userVm.getId());
             String vmInstanceName = userVm.getInstanceName();
             VMSnapshotTO parent = getSnapshotWithParents(snapshot).getParent();
-            VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(snapshot.getId(), snapshot.getName(), snapshot.getType(), 
+            VMSnapshotTO vmSnapshotTO = new VMSnapshotTO(snapshot.getId(), snapshot.getName(), snapshot.getType(),
             		snapshot.getCreated().getTime(), snapshot.getDescription(), snapshot.getCurrent(), parent);
             
             GuestOSVO guestOS = _guestOSDao.findById(userVm.getGuestOSId());
@@ -745,7 +748,7 @@ public class VMSnapshotManagerImpl extends ManagerBase implements VMSnapshotMana
             String errMsg = "revert vm: " + userVm.getInstanceName() + " to snapshot " + vmSnapshotVo.getName() + " failed due to " + e.getMessage();
             s_logger.error(errMsg);
             throw new CloudRuntimeException(e.getMessage());
-        } 
+        }
         return userVm;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/test/com/cloud/vm/UserVmManagerTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/UserVmManagerTest.java b/server/test/com/cloud/vm/UserVmManagerTest.java
index 6a97114..16feb98 100755
--- a/server/test/com/cloud/vm/UserVmManagerTest.java
+++ b/server/test/com/cloud/vm/UserVmManagerTest.java
@@ -33,17 +33,18 @@ import java.lang.reflect.Field;
 import java.util.List;
 import java.util.UUID;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.Spy;
+
 import org.apache.cloudstack.acl.ControlledEntity;
 import org.apache.cloudstack.acl.SecurityChecker.AccessType;
 import org.apache.cloudstack.api.ServerApiException;
 import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd;
 import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd;
 import org.apache.cloudstack.api.command.user.vm.ScaleVMCmd;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.Spy;
 
 import com.cloud.capacity.CapacityManager;
 import com.cloud.configuration.ConfigurationManager;
@@ -177,8 +178,8 @@ public class UserVmManagerTest {
         when(_rootVols.get(eq(0))).thenReturn(_volumeMock);
         doReturn(3L).when(_volumeMock).getTemplateId();
         when(_templateDao.findById(anyLong())).thenReturn(_templateMock);
-        when(_itMgr.stop(_vmMock, _userMock, _account)).thenReturn(true);
-        when(_itMgr.start(_vmMock, null, _userMock, _account)).thenReturn(_vmMock);
+        when(_itMgr.stop(null, _userMock, _account)).thenReturn(true);
+        when(_itMgr.start(null, null, _userMock, _account)).thenReturn(_vmMock);
         when(_storageMgr.allocateDuplicateVolume(_volumeMock, null)).thenReturn(_volumeMock);
         doNothing().when(_volsDao).attachVolume(anyLong(), anyLong(), anyLong());
         when(_volumeMock.getId()).thenReturn(3L);
@@ -202,13 +203,13 @@ public class UserVmManagerTest {
         doReturn(3L).when(_volumeMock).getTemplateId();
         when(_templateDao.findById(anyLong())).thenReturn(_templateMock);
         doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock);
-        when(_itMgr.stop(_vmMock, _userMock, _account)).thenReturn(true);
+        when(_itMgr.stop(null, _userMock, _account)).thenReturn(true);
         when(_storageMgr.allocateDuplicateVolume(_volumeMock, 14L)).thenReturn(_volumeMock);
         when(_templateMock.getGuestOSId()).thenReturn(5L);
         doNothing().when(_vmMock).setGuestOSId(anyLong());
         doNothing().when(_vmMock).setTemplateId(3L);
         when(_vmDao.update(314L, _vmMock)).thenReturn(true);
-        when(_itMgr.start(_vmMock, null, _userMock, _account)).thenReturn(_vmMock);
+        when(_itMgr.start(null, null, _userMock, _account)).thenReturn(_vmMock);
         when(_storageMgr.allocateDuplicateVolume(_volumeMock, null)).thenReturn(_volumeMock);
         doNothing().when(_volsDao).attachVolume(anyLong(), anyLong(), anyLong());
         when(_volumeMock.getId()).thenReturn(3L);
@@ -236,7 +237,7 @@ public class UserVmManagerTest {
         serviceOfferingIdField.set(cmd, 1L);
 
        // UserContext.current().setEventDetails("Vm Id: "+getId());
-        Account account = (Account) new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
+        Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
         //AccountVO(String accountName, long domainId, String networkDomain, short type, int regionId)
        UserContext.registerContext(1, account, null, true);
 
@@ -272,8 +273,8 @@ public class UserVmManagerTest {
         doNothing().when(_itMgr).checkIfCanUpgrade(_vmMock, cmd.getServiceOfferingId());
 
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so1);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
@@ -306,8 +307,8 @@ public class UserVmManagerTest {
         doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
 
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
@@ -346,8 +347,8 @@ public class UserVmManagerTest {
         when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
         doReturn(Hypervisor.HypervisorType.XenServer).when(_vmInstance).getHypervisorType();
 
-        ServiceOffering so1 =  (ServiceOffering) getSvcoffering(512);
-        ServiceOffering so2 =  (ServiceOffering) getSvcoffering(256);
+        ServiceOffering so1 =  getSvcoffering(512);
+        ServiceOffering so2 =  getSvcoffering(256);
 
         when(_configMgr.getServiceOffering(anyLong())).thenReturn(so2);
         when(_configMgr.getServiceOffering(1L)).thenReturn(so1);
@@ -401,7 +402,7 @@ public class UserVmManagerTest {
         domainIdField.set(cmd, 1L);
 
         // caller is of type 0
-        Account caller = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0,
+        Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 0,
                 UUID.randomUUID().toString());
         UserContext.registerContext(1, caller, null, true);
 
@@ -428,13 +429,13 @@ public class UserVmManagerTest {
         domainIdField.set(cmd, 1L);
 
         // caller is of type 0
-        Account caller = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 1,
+        Account caller = new AccountVO("testaccount", 1, "networkdomain", (short) 1,
                 UUID.randomUUID().toString());
         UserContext.registerContext(1, caller, null, true);
 
-        Account oldAccount = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 0,
+        Account oldAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 0,
                 UUID.randomUUID().toString());
-        Account newAccount = (Account) new AccountVO("testaccount", 1, "networkdomain", (short) 1,
+        Account newAccount = new AccountVO("testaccount", 1, "networkdomain", (short) 1,
                 UUID.randomUUID().toString());
 
         UserVmVO vm = new UserVmVO(10L, "test", "test", 1L, HypervisorType.Any, 1L, false, false, 1L, 1L,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3716f1f3/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java b/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
index b41e58c..e7dd38d 100644
--- a/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
+++ b/server/test/com/cloud/vm/VirtualMachineManagerImplTest.java
@@ -226,7 +226,7 @@ public class VirtualMachineManagerImplTest {
         long l = 1L;
 
         when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
-        _vmMgr.migrateForScale(_vmInstance, l, dest, l);
+        _vmMgr.migrateForScale(_vmInstance.getUuid(), l, dest, l);
 
     }
 
@@ -259,7 +259,7 @@ public class VirtualMachineManagerImplTest {
 
         when(_vmInstance.getHostId()).thenReturn(null);
         when(_vmInstanceDao.findById(anyLong())).thenReturn(_vmInstance);
-        _vmMgr.findHostAndMigrate(VirtualMachine.Type.User, _vmInstance, 2l);
+        _vmMgr.findHostAndMigrate(_vmInstance.getUuid(), 2l);
 
     }
 
@@ -387,7 +387,7 @@ public class VirtualMachineManagerImplTest {
         when(_srcHostMock.getClusterId()).thenReturn(3L);
         when(_destHostMock.getClusterId()).thenReturn(3L);
 
-        _vmMgr.migrateWithStorage(_vmInstance, _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
+        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
     }
 
     // Check migration of a vm with its volumes across a cluster.
@@ -399,7 +399,7 @@ public class VirtualMachineManagerImplTest {
         when(_srcHostMock.getClusterId()).thenReturn(3L);
         when(_destHostMock.getClusterId()).thenReturn(4L);
 
-        _vmMgr.migrateWithStorage(_vmInstance, _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
+        _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
@@ -415,7 +415,7 @@ public class VirtualMachineManagerImplTest {
         when(_destStoragePoolMock.isLocal()).thenReturn(true);
         when(_diskOfferingMock.getUseLocalStorage()).thenReturn(false);
 
-        _vmMgr.migrateWithStorage(_vmInstance, _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
+        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
     }
 
     // Check migration of a vm fails when vm is not in Running state.
@@ -429,6 +429,6 @@ public class VirtualMachineManagerImplTest {
 
         when(_vmMock.getState()).thenReturn(State.Stopped);
 
-        _vmMgr.migrateWithStorage(_vmInstance, _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
+        _vmMgr.migrateWithStorage(_vmInstance.getUuid(), _srcHostMock.getId(), _destHostMock.getId(), _volumeToPoolMock);
     }
 }


Mime
View raw message