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:52:22 UTC

[46/50] [abbrv] merge is complete

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;
 +	}
  }