Search in sources :

Example 6 with Cluster

use of com.cloud.org.Cluster in project cloudstack by apache.

the class UpdateClusterCmd method execute.

@Override
public void execute() {
    Cluster cluster = _resourceService.getCluster(getId());
    if (cluster == null) {
        throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId());
    }
    Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate());
    if (result != null) {
        ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false);
        clusterResponse.setResponseName(getCommandName());
        this.setResponseObject(clusterResponse);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update cluster");
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Cluster(com.cloud.org.Cluster) ClusterResponse(org.apache.cloudstack.api.response.ClusterResponse)

Example 7 with Cluster

use of com.cloud.org.Cluster in project cloudstack by apache.

the class AddClusterCmd method execute.

@Override
public void execute() {
    try {
        List<? extends Cluster> result = _resourceService.discoverCluster(this);
        ListResponse<ClusterResponse> response = new ListResponse<ClusterResponse>();
        List<ClusterResponse> clusterResponses = new ArrayList<ClusterResponse>();
        if (result != null && result.size() > 0) {
            for (Cluster cluster : result) {
                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());
        this.setResponseObject(response);
    } catch (DiscoveryException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    } catch (ResourceInUseException ex) {
        s_logger.warn("Exception: ", ex);
        ServerApiException e = new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
        for (String proxyObj : ex.getIdProxyList()) {
            e.addProxyObject(proxyObj);
        }
        throw e;
    }
}
Also used : ListResponse(org.apache.cloudstack.api.response.ListResponse) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceInUseException(com.cloud.exception.ResourceInUseException) ArrayList(java.util.ArrayList) ClusterResponse(org.apache.cloudstack.api.response.ClusterResponse) Cluster(com.cloud.org.Cluster) DiscoveryException(com.cloud.exception.DiscoveryException)

Example 8 with Cluster

use of com.cloud.org.Cluster 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 9 with Cluster

use of com.cloud.org.Cluster 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 10 with Cluster

use of com.cloud.org.Cluster in project cloudstack by apache.

the class UserVmManagerImpl method migrateVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // access check - only root admin can migrate VM
    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!");
    }
    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);
        }
        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.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm) && !vm.getHypervisorType().equals(HypervisorType.Hyperv) && !vm.getHypervisorType().equals(HypervisorType.LXC) && !vm.getHypervisorType().equals(HypervisorType.Simulator) && !vm.getHypervisorType().equals(HypervisorType.Ovm3)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(vm + " is not XenServer/VMware/KVM/Ovm/Hyperv, cannot migrate this VM.");
        }
        throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 only");
    }
    if (vm.getType().equals(VirtualMachine.Type.User) && vm.getHypervisorType().equals(HypervisorType.LXC)) {
        throw new InvalidParameterValueException("Unsupported Hypervisor Type for User VM migration, we support XenServer/VMware/KVM/Ovm/Hyperv/Ovm3 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
    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() != com.cloud.host.Status.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() != VirtualMachine.Type.User) {
        // for System VMs check that the destination host is within the same
        // cluster
        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
    DataCenterVO dcVO = _dcDao.findById(destinationHost.getDataCenterId());
    HostPodVO pod = _podDao.findById(destinationHost.getPodId());
    Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
    DeployDestination dest = new DeployDestination(dcVO, pod, cluster, destinationHost);
    // check max guest vm limit for the destinationHost
    HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
    if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
        }
        throw new VirtualMachineMigrationException("Destination host, hostId: " + destinationHost.getId() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
    }
    UserVmVO uservm = _vmDao.findById(vmId);
    if (uservm != null) {
        collectVmDiskStatistics(uservm);
    }
    _itMgr.migrate(vm.getUuid(), srcHostId, dest);
    VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
    if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
        return _vmDao.findById(vmId);
    } else {
        return vmInstance;
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) Cluster(com.cloud.org.Cluster) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) HostPodVO(com.cloud.dc.HostPodVO) HostVO(com.cloud.host.HostVO) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

Cluster (com.cloud.org.Cluster)26 ArrayList (java.util.ArrayList)13 HostVO (com.cloud.host.HostVO)8 ServerApiException (org.apache.cloudstack.api.ServerApiException)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)6 DataCenter (com.cloud.dc.DataCenter)5 Pod (com.cloud.dc.Pod)5 DeployDestination (com.cloud.deploy.DeployDestination)5 DataCenterVO (com.cloud.dc.DataCenterVO)4 DiscoveryException (com.cloud.exception.DiscoveryException)4 ResourceInUseException (com.cloud.exception.ResourceInUseException)4 Host (com.cloud.host.Host)4 StoragePool (com.cloud.storage.StoragePool)4 ClusterResponse (org.apache.cloudstack.api.response.ClusterResponse)4 ClusterResponse (com.cloud.api.response.ClusterResponse)3 ClusterDetailsVO (com.cloud.dc.ClusterDetailsVO)3 ClusterVO (com.cloud.dc.ClusterVO)3 List (java.util.List)3 ServerApiException (com.cloud.api.ServerApiException)2