Search in sources :

Example 6 with Cluster

use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method migrateVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(final Long vmId, final Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // access check - only root admin can migrate VM
    final Account caller = CallContext.current().getCallingAccount();
    if (!_accountMgr.isRootAdmin(caller.getId())) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
        }
        throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!");
    }
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId);
    }
    // business logic
    if (vm.getState() != State.Running) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
        }
        final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
        throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
    }
    if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.KVM)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm + " is not XenServer/KVM, cannot migrate this VM.");
        }
        throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/KVM only");
    }
    if (isVMUsingLocalStorage(vm)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm + " is using Local Storage, cannot migrate this VM.");
        }
        throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
    }
    // check if migrating to same host
    final long srcHostId = vm.getHostId();
    if (destinationHost.getId() == srcHostId) {
        throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM");
    }
    // check if host is UP
    if (destinationHost.getState() != HostStatus.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
        throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
    }
    if (vm.getType() != VirtualMachineType.User) {
        // for System VMs check that the destination host is within the same
        // cluster
        final HostVO srcHost = _hostDao.findById(srcHostId);
        if (srcHost != null && srcHost.getClusterId() != null && destinationHost.getClusterId() != null) {
            if (srcHost.getClusterId().longValue() != destinationHost.getClusterId().longValue()) {
                throw new InvalidParameterValueException("Cannot migrate the VM, destination host is not in the same cluster as current host of the VM");
            }
        }
    }
    checkHostsDedication(vm, srcHostId, destinationHost.getId());
    // call to core process
    final Zone zone = zoneRepository.findById(destinationHost.getDataCenterId()).orElse(null);
    final HostPodVO pod = _podDao.findById(destinationHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
    final DeployDestination dest = new DeployDestination(zone, pod, cluster, destinationHost);
    // check max guest vm limit for the destinationHost
    final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
    if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Host name: " + destinationHost.getName() + ": " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
        }
        throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
    }
    // Check host tags
    final ServiceOffering serviceOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId());
    if (serviceOffering != null) {
        final String requiredHostTag = serviceOffering.getHostTag();
        final List<String> hostTags = _hostTagsDao.gethostTags(destinationHost.getId());
        boolean foundRequiredHostTag = false;
        for (final String hostTag : hostTags) {
            if (hostTag.equals(requiredHostTag)) {
                foundRequiredHostTag = true;
                break;
            }
        }
        if (!foundRequiredHostTag && requiredHostTag != null) {
            throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " does not have required host tag " + requiredHostTag);
        }
    }
    final UserVmVO uservm = _vmDao.findById(vmId);
    if (uservm != null) {
        collectVmDiskStatistics(uservm);
    }
    _itMgr.migrate(vm.getUuid(), srcHostId, dest);
    final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance.getType().equals(VirtualMachineType.User)) {
        return _vmDao.findById(vmId);
    } else {
        return vmInstance;
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) ServiceOffering(com.cloud.offering.ServiceOffering) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.legacymodel.dc.Cluster) HostPodVO(com.cloud.dc.HostPodVO) HostVO(com.cloud.host.HostVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) ActionEvent(com.cloud.event.ActionEvent)

Example 7 with Cluster

use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.

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 Zone zone = _zoneRepository.findById(destHost.getDataCenterId()).orElse(null);
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(zone, 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 (VirtualMachineType.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachineType.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);
    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
        final Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            final UserVmVO userVm = _userVmDao.findById(vm.getId());
            final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            final 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();
                final 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, network);
                final String vmName = vm.getInstanceName();
                final String configDriveIsoRootFolder = "/tmp";
                final 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.
                final 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 (final 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 " + zone.getName() + " and pod " + zone.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                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.legacymodel.exceptions.OperationTimedoutException) StoragePool(com.cloud.legacymodel.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) Commands(com.cloud.agent.manager.Commands) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.legacymodel.dc.Cluster) Nic(com.cloud.legacymodel.network.Nic) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.legacymodel.communication.command.AttachOrDettachConfigDriveCommand) Volume(com.cloud.legacymodel.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException)

Example 8 with Cluster

use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.

the class AddClusterCmdTest method testExecuteForResult.

@Test
public void testExecuteForResult() throws Exception {
    resourceService = Mockito.mock(ResourceService.class);
    responseGenerator = Mockito.mock(ResponseGenerator.class);
    addClusterCmd._resourceService = resourceService;
    addClusterCmd._responseGenerator = responseGenerator;
    final Cluster cluster = Mockito.mock(Cluster.class);
    final Cluster[] clusterArray = new Cluster[] { cluster };
    Mockito.doReturn(Arrays.asList(clusterArray)).when(resourceService).discoverCluster(addClusterCmd);
    addClusterCmd.execute();
}
Also used : ResponseGenerator(com.cloud.api.ResponseGenerator) ResourceService(com.cloud.resource.ResourceService) Cluster(com.cloud.legacymodel.dc.Cluster) Test(org.junit.Test)

Example 9 with Cluster

use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.

the class AddClusterCmd method execute.

@Override
public void execute() {
    try {
        final List<? extends Cluster> result = _resourceService.discoverCluster(this);
        final ListResponse<ClusterResponse> response = new ListResponse<>();
        final List<ClusterResponse> clusterResponses = new ArrayList<>();
        if (result != null && result.size() > 0) {
            for (final Cluster cluster : result) {
                final ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false);
                clusterResponses.add(clusterResponse);
            }
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add cluster");
        }
        response.setResponses(clusterResponses);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } catch (final DiscoveryException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    } catch (final ResourceInUseException ex) {
        s_logger.warn("Exception: ", ex);
        final ServerApiException e = new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
        for (final String proxyObj : ex.getIdProxyList()) {
            e.addProxyObject(proxyObj);
        }
        throw e;
    }
}
Also used : ListResponse(com.cloud.api.response.ListResponse) ServerApiException(com.cloud.api.ServerApiException) ResourceInUseException(com.cloud.legacymodel.exceptions.ResourceInUseException) ArrayList(java.util.ArrayList) ClusterResponse(com.cloud.api.response.ClusterResponse) Cluster(com.cloud.legacymodel.dc.Cluster) DiscoveryException(com.cloud.legacymodel.exceptions.DiscoveryException)

Example 10 with Cluster

use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.

the class ListClustersCmd method execute.

// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
@Override
public void execute() {
    final Pair<List<? extends Cluster>, Integer> result = _mgr.searchForClusters(this);
    final ListResponse<ClusterResponse> response = new ListResponse<>();
    final List<ClusterResponse> clusterResponses = new ArrayList<>();
    for (final Cluster cluster : result.first()) {
        final ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, showCapacities);
        clusterResponse.setObjectName("cluster");
        clusterResponses.add(clusterResponse);
    }
    response.setResponses(clusterResponses, result.second());
    response.setResponseName(getCommandName());
    this.setResponseObject(response);
}
Also used : ListResponse(com.cloud.api.response.ListResponse) ArrayList(java.util.ArrayList) Cluster(com.cloud.legacymodel.dc.Cluster) ClusterResponse(com.cloud.api.response.ClusterResponse) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Cluster (com.cloud.legacymodel.dc.Cluster)16 HostVO (com.cloud.host.HostVO)7 Zone (com.cloud.db.model.Zone)6 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)6 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)5 ArrayList (java.util.ArrayList)5 DeployDestination (com.cloud.deploy.DeployDestination)4 Pod (com.cloud.legacymodel.dc.Pod)4 StoragePool (com.cloud.legacymodel.storage.StoragePool)4 ClusterResponse (com.cloud.api.response.ClusterResponse)3 HostPodVO (com.cloud.dc.HostPodVO)3 Host (com.cloud.legacymodel.dc.Host)3 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)3 DiscoveryException (com.cloud.legacymodel.exceptions.DiscoveryException)3 NoTransitionException (com.cloud.legacymodel.exceptions.NoTransitionException)3 ResourceInUseException (com.cloud.legacymodel.exceptions.ResourceInUseException)3 Volume (com.cloud.legacymodel.storage.Volume)3 StoragePoolHostVO (com.cloud.storage.StoragePoolHostVO)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3