use of com.cloud.agent.api.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method migrate.
protected void migrate(final VMInstanceVO vm, final long srcHostId, final DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
s_logger.info("Migrating " + vm + " to " + dest);
final long dstHostId = dest.getHost().getId();
final Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
final List<VolumeVO> volumes = _volsDao.findCreatedByInstance(vm.getId());
for (final VolumeVO volume : volumes) {
if (!_storagePoolDao.findById(volume.getPoolId()).getScope().equals(ScopeType.ZONE)) {
s_logger.info("Source and destination host are not in same cluster and all volumes are not on zone wide primary store, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster and all volumes are not on zone wide primary store, unable to migrate to host: " + dest.getHost().getId());
}
}
}
final VirtualMachineGuru vmGuru = getVmGuru(vm);
if (vm.getState() != State.Running) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
final VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm);
for (final NicProfile nic : _networkMgr.getNicProfiles(vm)) {
vmSrc.addNic(nic);
}
final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()), null, null);
_networkMgr.prepareNicForMigration(profile, dest);
volumeMgr.prepareForMigration(profile, dest);
profile.setConfigDriveLabel(VmConfigDriveLabel.value());
final VirtualMachineTO to = toVmTO(profile);
final PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
Answer pfma = null;
try {
pfma = _agentMgr.send(dstHostId, pfmc);
if (pfma == null || !pfma.getResult()) {
final String details = pfma != null ? pfma.getDetails() : "null answer returned";
final String msg = "Unable to prepare for migration due to " + details;
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (final OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (final NoTransitionException e1) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
final boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
final MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, getExecuteInSequence(vm.getHypervisorType()));
mc.setHostGuid(dest.getHost().getGuid());
try {
final Answer ma = _agentMgr.send(vm.getLastHostId(), mc);
if (ma == null || !ma.getResult()) {
final String details = ma != null ? ma.getDetails() : "null answer returned";
throw new CloudRuntimeException(details);
}
} catch (final OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (final NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm)), null);
} catch (final AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("Unable to complete migration for " + vm);
}
} catch (final OperationTimedoutException e) {
s_logger.debug("Error while checking the vm " + vm + " on host " + dstHostId, e);
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_networkMgr.rollbackNicForMigration(vmSrc, profile);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getZone().getName() + " and pod " + dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
} catch (final AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (final NoTransitionException e) {
s_logger.warn(e.getMessage());
}
} else {
_networkMgr.commitNicForMigration(vmSrc, profile);
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
use of com.cloud.agent.api.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method syncDiskChainChange.
private void syncDiskChainChange(final StartAnswer answer) {
final VirtualMachineTO vmSpec = answer.getVirtualMachine();
for (final DiskTO disk : vmSpec.getDisks()) {
if (disk.getType() != Volume.Type.ISO) {
final VolumeObjectTO vol = (VolumeObjectTO) disk.getData();
final VolumeVO volume = _volsDao.findById(vol.getId());
// returned null instead of an actual path (because it was out of date with the DB).
if (vol.getPath() != null) {
volumeMgr.updateVolumeDiskChain(vol.getId(), vol.getPath(), vol.getChainInfo());
} else {
volumeMgr.updateVolumeDiskChain(vol.getId(), volume.getPath(), vol.getChainInfo());
}
}
}
}
use of com.cloud.agent.api.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method orchestrateAddVmToNetwork.
private NicProfile orchestrateAddVmToNetwork(final VirtualMachine vm, final Network network, final NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
final CallContext cctx = CallContext.current();
s_logger.debug("Orchestrating add vm " + vm + " to network " + network + " with requested nic profile " + requested);
final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
final Zone zone = _zoneRepository.findOne(network.getDataCenterId());
final Host host = _hostDao.findById(vm.getHostId());
final DeployDestination dest = new DeployDestination(zone, null, null, host);
// check vm state
if (vm.getState() == State.Running) {
// 1) allocate and prepare nic
final NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true);
// 2) Convert vmProfile to vmTO
final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
// 3) Convert nicProfile to NicTO
final NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType());
// 4) plug the nic to the vm
s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
boolean result = false;
try {
result = plugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now");
final long isDefault = nic.isDefaultNic() ? 1 : 0;
// insert nic's Id into DB as resource_name
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
return null;
}
} finally {
if (!result) {
s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
_networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
}
}
} else if (vm.getState() == State.Stopped) {
// 1) allocate nic
return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
} else {
s_logger.warn("Unable to add vm " + vm + " to network " + network);
throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
}
use of com.cloud.agent.api.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testPrepareForMigrationCommandMigration.
@Test
public void testPrepareForMigrationCommandMigration() {
final Connect conn = Mockito.mock(Connect.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
final KvmStoragePoolManager storagePoolManager = Mockito.mock(KvmStoragePoolManager.class);
final NicTO nicTO = Mockito.mock(NicTO.class);
final DiskTO diskTO = Mockito.mock(DiskTO.class);
final VifDriver vifDriver = Mockito.mock(VifDriver.class);
final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
} catch (final LibvirtException e) {
fail(e.getMessage());
}
when(vm.getNics()).thenReturn(new NicTO[] { nicTO });
when(vm.getDisks()).thenReturn(new DiskTO[] { diskTO });
when(nicTO.getType()).thenReturn(TrafficType.Guest);
when(diskTO.getType()).thenReturn(Volume.Type.ISO);
when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
when(storagePoolManager.connectPhysicalDisksViaVmSpec(vm)).thenReturn(true);
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, libvirtComputingResource);
assertTrue(answer.getResult());
verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(vm, times(1)).getNics();
verify(vm, times(1)).getDisks();
verify(diskTO, times(1)).getType();
}
use of com.cloud.agent.api.to.VirtualMachineTO in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testStartCommandLibvirtException.
@Test
public void testStartCommandLibvirtException() {
final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);
final boolean executeInSequence = false;
final StartCommand command = new StartCommand(vmSpec, host, executeInSequence);
final KvmStoragePoolManager storagePoolMgr = Mockito.mock(KvmStoragePoolManager.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final LibvirtVmDef vmDef = Mockito.mock(LibvirtVmDef.class);
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[] { nic };
final String vmName = "Test";
when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(vmSpec.getNics()).thenReturn(nics);
when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
when(vmSpec.getName()).thenReturn(vmName);
when(libvirtComputingResource.createVmFromSpec(vmSpec)).thenReturn(vmDef);
when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenThrow(LibvirtException.class);
} catch (final LibvirtException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, libvirtComputingResource);
assertFalse(answer.getResult());
verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
}
Aggregations