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();
}
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);
}
}
use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.
the class FirstFitAllocator method allocateTo.
protected List<Host> allocateTo(final DeploymentPlan plan, final ServiceOffering offering, final VMTemplateVO template, final ExcludeList avoid, List<? extends Host> hosts, final int returnUpTo, final boolean considerReservedCapacity, final Account account) {
if (_allocationAlgorithm.equals("random") || _allocationAlgorithm.equals("userconcentratedpod_random")) {
// Shuffle this so that we don't check the hosts in the same order.
Collections.shuffle(hosts);
} else if (_allocationAlgorithm.equals("userdispersing")) {
hosts = reorderHostsByNumberOfVms(plan, hosts, account);
} else if (_allocationAlgorithm.equals("firstfitleastconsumed")) {
hosts = reorderHostsByCapacity(plan, hosts);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("FirstFitAllocator has " + hosts.size() + " hosts to check for allocation: " + hosts);
}
// We will try to reorder the host lists such that we give priority to hosts that have
// the minimums to support a VM's requirements
hosts = prioritizeHosts(template, offering, hosts);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found " + hosts.size() + " hosts for allocation after prioritization: " + hosts);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Looking for CPU=" + offering.getCpu() + " cores, Ram=" + offering.getRamSize());
}
final long serviceOfferingId = offering.getId();
final List<Host> suitableHosts = new ArrayList<>();
ServiceOfferingDetailsVO offeringDetails = null;
for (final Host host : hosts) {
if (suitableHosts.size() == returnUpTo) {
break;
}
if (avoid.shouldAvoid(host)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host name: " + host.getName() + ", hostId: " + host.getId() + " is in avoid set, skipping this and trying other available hosts");
}
continue;
}
// find number of guest VMs occupying capacity on this host.
if (_capacityMgr.checkIfHostReachMaxGuestLimit(host)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host name: " + host.getName() + ", hostId: " + host.getId() + " already has max Running VMs(count includes system VMs), skipping this and trying other available hosts");
}
avoid.addHost(host.getId());
continue;
}
// Check if GPU device is required by offering and host has the availability
if ((offeringDetails = _serviceOfferingDetailsDao.findDetail(serviceOfferingId, GPU.Keys.vgpuType.toString())) != null) {
final ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(serviceOfferingId, GPU.Keys.pciDevice.toString());
if (!_resourceMgr.isGPUDeviceAvailable(host.getId(), groupName.getValue(), offeringDetails.getValue())) {
s_logger.info("Host name: " + host.getName() + ", hostId: " + host.getId() + " does not have required GPU devices available");
avoid.addHost(host.getId());
continue;
}
}
final int cpu_requested = offering.getCpu();
final long ram_requested = offering.getRamSize() * 1024L * 1024L;
final Cluster cluster = _clusterDao.findById(host.getClusterId());
final ClusterDetailsVO clusterDetailsCpuOvercommit = _clusterDetailsDao.findDetail(cluster.getId(), "cpuOvercommitRatio");
final ClusterDetailsVO clusterDetailsRamOvercommmt = _clusterDetailsDao.findDetail(cluster.getId(), "memoryOvercommitRatio");
final Float cpuOvercommitRatio = Float.parseFloat(clusterDetailsCpuOvercommit.getValue());
final Float memoryOvercommitRatio = Float.parseFloat(clusterDetailsRamOvercommmt.getValue());
final boolean hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu());
final boolean hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, false, cpuOvercommitRatio, memoryOvercommitRatio, considerReservedCapacity);
if (hostHasCpuCapability && hostHasCapacity) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a suitable host, adding to list: " + host.getId());
}
suitableHosts.add(host);
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Not using host " + host.getId() + "; host has cpu capability? " + hostHasCpuCapability + ", host has capacity?" + hostHasCapacity);
}
avoid.addHost(host.getId());
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host Allocator returning " + suitableHosts.size() + " suitable hosts");
}
return suitableHosts;
}
use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.
the class DeploymentPlanningManagerImpl method isEnabledForAllocation.
private boolean isEnabledForAllocation(final long zoneId, final Long podId, final Long clusterId) {
// Check if the zone exists in the system
final Zone zone = zoneRepository.findById(zoneId).orElse(null);
if (zone != null && AllocationState.Disabled == zone.getAllocationState()) {
s_logger.info("Zone is currently disabled, cannot allocate to this zone: " + zoneId);
return false;
}
final Pod pod = _podDao.findById(podId);
if (pod != null && AllocationState.Disabled == pod.getAllocationState()) {
s_logger.info("Pod is currently disabled, cannot allocate to this pod: " + podId);
return false;
}
final Cluster cluster = _clusterDao.findById(clusterId);
if (cluster != null && AllocationState.Disabled == cluster.getAllocationState()) {
s_logger.info("Cluster is currently disabled, cannot allocate to this cluster: " + clusterId);
return false;
}
return true;
}
use of com.cloud.legacymodel.dc.Cluster in project cosmic by MissionCriticalCloud.
the class UpdateClusterCmd method execute.
@Override
public void execute() {
final Cluster cluster = _resourceService.getCluster(getId());
if (cluster == null) {
throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId());
}
final Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate());
if (result != null) {
final ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false);
clusterResponse.setResponseName(getCommandName());
this.setResponseObject(clusterResponse);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update cluster");
}
}
Aggregations