Search in sources :

Example 16 with DeployDestination

use of com.cloud.deploy.DeployDestination in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateRemoveNicFromVm.

private boolean orchestrateRemoveNicFromVm(final VirtualMachine vm, final Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
    final CallContext cctx = CallContext.current();
    final VMInstanceVO vmVO = _vmDao.findById(vm.getId());
    final NetworkVO network = _networkDao.findById(nic.getNetworkId());
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
    final DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
    final Host host = _hostDao.findById(vm.getHostId());
    final DeployDestination dest = new DeployDestination(dc, null, null, host);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
    final VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
    final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()), _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
    //1) Unplug the nic
    if (vm.getState() == State.Running) {
        final NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
        s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network);
        final boolean result = unplugNic(network, nicTO, vmTO, context, dest);
        if (result) {
            s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
            final long isDefault = nic.isDefaultNic() ? 1 : 0;
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplay());
        } else {
            s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
            return false;
        }
    } else if (vm.getState() != State.Stopped) {
        s_logger.warn("Unable to remove vm " + vm + " from network  " + network);
        throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
    }
    //2) Release the nic
    _networkMgr.releaseNic(vmProfile, nic);
    s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
    //3) Remove the nic
    _networkMgr.removeNic(vmProfile, nic);
    _nicsDao.expunge(nic.getId());
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) Host(com.cloud.host.Host) CallContext(org.apache.cloudstack.context.CallContext) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) DataCenter(com.cloud.dc.DataCenter) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NicTO(com.cloud.agent.api.to.NicTO)

Example 17 with DeployDestination

use of com.cloud.deploy.DeployDestination in project cloudstack by apache.

the class VmWorkMigrate method getDeployDestination.

public DeployDestination getDeployDestination() {
    DataCenter zone = zoneId != null ? s_entityMgr.findById(DataCenter.class, zoneId) : null;
    Pod pod = podId != null ? s_entityMgr.findById(Pod.class, podId) : null;
    Cluster cluster = clusterId != null ? s_entityMgr.findById(Cluster.class, clusterId) : null;
    Host host = hostId != null ? s_entityMgr.findById(Host.class, hostId) : null;
    Map<Volume, StoragePool> vols = null;
    if (storage != null) {
        vols = new HashMap<Volume, StoragePool>(storage.size());
        for (Map.Entry<String, String> entry : storage.entrySet()) {
            vols.put(s_entityMgr.findByUuid(Volume.class, entry.getKey()), s_entityMgr.findByUuid(StoragePool.class, entry.getValue()));
        }
    }
    DeployDestination dest = new DeployDestination(zone, pod, cluster, host, vols);
    return dest;
}
Also used : DataCenter(com.cloud.dc.DataCenter) StoragePool(com.cloud.storage.StoragePool) Pod(com.cloud.dc.Pod) Volume(com.cloud.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) Map(java.util.Map) HashMap(java.util.HashMap)

Example 18 with DeployDestination

use of com.cloud.deploy.DeployDestination in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateMigrateAway.

private void orchestrateMigrateAway(final String vmUuid, final long srcHostId, final DeploymentPlanner planner) throws InsufficientServerCapacityException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    if (vm == null) {
        s_logger.debug("Unable to find a VM for " + vmUuid);
        throw new CloudRuntimeException("Unable to find " + vmUuid);
    }
    ServiceOfferingVO offeringVO = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm, null, offeringVO, null, null);
    final Long hostId = vm.getHostId();
    if (hostId == null) {
        s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm);
        throw new CloudRuntimeException("Unable to migrate " + vmUuid);
    }
    final Host host = _hostDao.findById(hostId);
    Long poolId = null;
    final List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
    for (final VolumeVO rootVolumeOfVm : vols) {
        final StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId());
        if (rootDiskPool != null) {
            poolId = rootDiskPool.getId();
        }
    }
    final DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null);
    final ExcludeList excludes = new ExcludeList();
    excludes.addHost(hostId);
    DeployDestination dest = null;
    while (true) {
        try {
            dest = _dpMgr.planDeployment(profile, plan, excludes, planner);
        } catch (final AffinityConflictException e2) {
            s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
            throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
        }
        if (dest != null) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Found destination " + dest + " for migrating to.");
            }
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to find destination for migrating the vm " + profile);
            }
            throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId());
        }
        excludes.addHost(dest.getHost().getId());
        try {
            migrate(vm, srcHostId, dest);
            return;
        } catch (final ResourceUnavailableException e) {
            s_logger.debug("Unable to migrate to unavailable " + dest);
        } catch (final ConcurrentOperationException e) {
            s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
        }
        try {
            advanceStop(vmUuid, true);
            throw new CloudRuntimeException("Unable to migrate " + vm);
        } catch (final ResourceUnavailableException e) {
            s_logger.debug("Unable to stop VM due to " + e.getMessage());
            throw new CloudRuntimeException("Unable to migrate " + vm);
        } catch (final ConcurrentOperationException e) {
            s_logger.debug("Unable to stop VM due to " + e.getMessage());
            throw new CloudRuntimeException("Unable to migrate " + vm);
        } catch (final OperationTimedoutException e) {
            s_logger.debug("Unable to stop VM due to " + e.getMessage());
            throw new CloudRuntimeException("Unable to migrate " + vm);
        }
    }
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) Host(com.cloud.host.Host) AffinityConflictException(com.cloud.exception.AffinityConflictException) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VolumeVO(com.cloud.storage.VolumeVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DeployDestination(com.cloud.deploy.DeployDestination) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException)

Example 19 with DeployDestination

use of com.cloud.deploy.DeployDestination in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateMigrateWithStorage.

private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final HostVO srcHost = _hostDao.findById(srcHostId);
    final HostVO destHost = _hostDao.findById(destHostId);
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId());
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost);
    // Create a map of which volume should go in which storage pool.
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    final Map<Volume, StoragePool> volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
    // a vm and not migrating a vm with storage.
    if (volumeToPoolMap == null || volumeToPoolMap.isEmpty()) {
        throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost + " doesn't involve migrating the volumes.");
    }
    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;
    }
    _networkMgr.prepareNicForMigration(profile, destination);
    volumeMgr.prepareForMigration(profile, destination);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
    final VirtualMachineTO to = hvGuru.implement(profile);
    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(destHostId);
    work = _workDao.persist(work);
    // Put the vm in migrating state.
    vm.setLastHostId(srcHostId);
    vm.setPodIdToDeployIn(destHost.getPodId());
    moveVmToMigratingState(vm, destHostId, work);
    boolean migrated = false;
    try {
        // config drive: Detach the config drive at source host
        // After migration successful attach the config drive in destination host
        // On migration failure VM will be stopped, So configIso will be deleted
        Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            UserVmVO userVm = _userVmDao.findById(vm.getId());
            Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
            if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
                final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
                final String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
                boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
                vmData = _networkModel.generateVmData(userVm.getUserData(), serviceOffering, zoneName, vm.getInstanceName(), vm.getId(), (String) profile.getParameter(VirtualMachineProfile.Param.VmSshPubKey), (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows);
                String vmName = vm.getInstanceName();
                String configDriveIsoRootFolder = "/tmp";
                String isoFile = configDriveIsoRootFolder + "/" + vmName + "/configDrive/" + vmName + ".iso";
                profile.setVmData(vmData);
                profile.setConfigDriveLabel(VmConfigDriveLabel.value());
                profile.setConfigDriveIsoRootFolder(configDriveIsoRootFolder);
                profile.setConfigDriveIsoFile(isoFile);
                // At source host detach the config drive iso.
                AttachOrDettachConfigDriveCommand dettachCommand = new AttachOrDettachConfigDriveCommand(vm.getInstanceName(), vmData, VmConfigDriveLabel.value(), false);
                try {
                    _agentMgr.send(srcHost.getId(), dettachCommand);
                    s_logger.debug("Deleted config drive ISO for  vm " + vm.getInstanceName() + " In host " + srcHost);
                } catch (OperationTimedoutException e) {
                    s_logger.debug("TIme out occured while exeuting command AttachOrDettachConfigDrive " + e.getMessage());
                }
            }
        }
        // Migrate the vm and its volume.
        volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPoolMap);
        // Put the vm back to running state.
        moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
        try {
            if (!checkVmOnHost(vm, destHostId)) {
                s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
                try {
                    _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), 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("VM not found on desintation host. Unable to complete migration for " + vm);
            }
        } catch (final OperationTimedoutException e) {
            s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
        }
        migrated = true;
    } finally {
        if (!migrated) {
            s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
            _alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + dc.getName() + " and pod " + dc.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                vm.setPodIdToDeployIn(srcHost.getPodId());
                stateTransitTo(vm, Event.OperationFailed, srcHostId);
            } catch (final AgentUnavailableException e) {
                s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
            } catch (final NoTransitionException e) {
                s_logger.error("Error while transitioning vm from migrating to running state.", e);
            }
        }
        work.setStep(Step.Done);
        _workDao.update(work.getId(), work);
    }
}
Also used : AlertManager(com.cloud.alert.AlertManager) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) StoragePool(com.cloud.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) Commands(com.cloud.agent.manager.Commands) DataCenterVO(com.cloud.dc.DataCenterVO) Cluster(com.cloud.org.Cluster) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.agent.api.AttachOrDettachConfigDriveCommand) Volume(com.cloud.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.utils.fsm.NoTransitionException)

Example 20 with DeployDestination

use of com.cloud.deploy.DeployDestination in project cloudstack by apache.

the class BrocadeVcsGuestNetworkGuruTest method testReserve.

@Test
public void testReserve() throws InsufficientVirtualNetworkCapacityException, URISyntaxException, InsufficientAddressCapacityException {
    final NetworkVO network = mock(NetworkVO.class);
    when(network.getName()).thenReturn("testnetwork");
    when(network.getState()).thenReturn(State.Implementing);
    when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
    when(network.getBroadcastUri()).thenReturn(new URI("vlan://14"));
    when(network.getDataCenterId()).thenReturn(NETWORK_ID);
    final NicProfile nic = mock(NicProfile.class);
    when(nic.getMacAddress()).thenReturn("macaddress");
    when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start);
    final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class);
    final DeployDestination dest = mock(DeployDestination.class);
    final DataCenterVO dc = mock(DataCenterVO.class);
    when(dest.getDataCenter()).thenReturn(dc);
    when(dcdao.findById((long) anyInt())).thenReturn(dc);
    final HostVO brocadeHost = mock(HostVO.class);
    when(hostdao.findById(anyLong())).thenReturn(brocadeHost);
    when(brocadeHost.getId()).thenReturn(NETWORK_ID);
    when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
    final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class);
    when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID);
    List<BrocadeVcsDeviceVO> devices = new ArrayList();
    devices.add(brocadeDevice);
    when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices);
    final Domain dom = mock(Domain.class);
    when(dom.getName()).thenReturn("domain");
    final Account acc = mock(Account.class);
    when(acc.getAccountName()).thenReturn("accountname");
    final ReservationContext res = mock(ReservationContext.class);
    when(res.getDomain()).thenReturn(dom);
    when(res.getAccount()).thenReturn(acc);
    final AssociateMacToNetworkAnswer answer = mock(AssociateMacToNetworkAnswer.class);
    when(answer.getResult()).thenReturn(true);
    when(agentmgr.easySend(eq(NETWORK_ID), (Command) any())).thenReturn(answer);
    guru.reserve(nic, network, vmProfile, dest, res);
    verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), (Command) any());
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) ArrayList(java.util.ArrayList) NicProfile(com.cloud.vm.NicProfile) URI(java.net.URI) HostVO(com.cloud.host.HostVO) BrocadeVcsDeviceVO(com.cloud.network.BrocadeVcsDeviceVO) ReservationContext(com.cloud.vm.ReservationContext) AssociateMacToNetworkAnswer(com.cloud.agent.api.AssociateMacToNetworkAnswer) DeployDestination(com.cloud.deploy.DeployDestination) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) Domain(com.cloud.domain.Domain) Test(org.junit.Test)

Aggregations

DeployDestination (com.cloud.deploy.DeployDestination)56 DataCenter (com.cloud.dc.DataCenter)27 Account (com.cloud.user.Account)27 Test (org.junit.Test)27 ReservationContext (com.cloud.vm.ReservationContext)26 HostVO (com.cloud.host.HostVO)19 Network (com.cloud.network.Network)18 NetworkVO (com.cloud.network.dao.NetworkVO)18 NetworkOffering (com.cloud.offering.NetworkOffering)18 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)18 Domain (com.cloud.domain.Domain)17 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)15 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)15 URI (java.net.URI)13 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)12 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)11 ArrayList (java.util.ArrayList)11 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)8 Host (com.cloud.host.Host)8 NiciraNvpDeviceVO (com.cloud.network.NiciraNvpDeviceVO)8