use of com.cloud.affinity.AffinityGroupVO in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method createVirtualMachine.
@DB
private UserVm createVirtualMachine(final Zone zone, final ServiceOffering serviceOffering, final VirtualMachineTemplate tmplt, String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final List<NetworkVO> networkList, final String group, final HTTPMethod httpmethod, final String userData, final String sshKeyPair, final HypervisorType hypervisor, final Account caller, final Map<Long, IpAddresses> requestedIps, final IpAddresses defaultIps, final Boolean isDisplayVm, final String keyboard, final List<Long> affinityGroupIdList, final Map<String, String> customParameters, final String customId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
_accountMgr.checkAccess(caller, null, true, owner);
if (owner.getState() == Account.State.disabled) {
throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
}
final VMTemplateVO template = _templateDao.findById(tmplt.getId());
if (template != null) {
_templateDao.loadDetails(template);
}
final long accountId = owner.getId();
assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be " + "specified together";
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
}
// check if zone is dedicated
final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
if (dedicatedZone != null) {
final DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
if (domain == null) {
throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
}
// check that caller can operate with domain
_configMgr.checkZoneAccess(caller, zone);
// check that vm owner can create vm in the domain
_configMgr.checkZoneAccess(owner, zone);
}
ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
// check if account/domain is with in resource limits to create a new vm
final boolean isIso = Storage.ImageFormat.ISO == template.getFormat();
long size = 0;
// custom root disk size, resizes base template to larger size
if (customParameters.containsKey("rootdisksize")) {
final Long rootDiskSize = NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1);
if (rootDiskSize <= 0) {
throw new InvalidParameterValueException("Root disk size should be a positive number.");
}
size = rootDiskSize * GB_TO_BYTES;
}
if (diskOfferingId != null) {
final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
if (diskOffering != null && diskOffering.isCustomized()) {
if (diskSize == null) {
throw new InvalidParameterValueException("This disk offering requires a custom size specified");
}
final Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
final Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
if (diskSize < customDiskOfferingMinSize || diskSize > customDiskOfferingMaxSize) {
throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
}
size += diskSize * GB_TO_BYTES;
}
size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
}
resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, isIso || diskOfferingId == null ? 1 : 2);
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
// check that the affinity groups exist
if (affinityGroupIdList != null) {
for (final Long affinityGroupId : affinityGroupIdList) {
final AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
if (ag == null) {
throw new InvalidParameterValueException("Unable to find affinity group " + ag);
} else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
} else {
// verify permissions
if (ag.getAclType() == ACLType.Domain) {
_accountMgr.checkAccess(caller, null, false, owner, ag);
// make sure the owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
}
}
} else {
_accountMgr.checkAccess(caller, null, true, owner, ag);
// make sure the owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (ag.getDomainId() != owner.getDomainId()) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
}
}
}
}
}
}
final HypervisorType hypervisorType;
if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
if (hypervisor == null || hypervisor == HypervisorType.None) {
throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
}
hypervisorType = hypervisor;
} else {
if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
}
hypervisorType = template.getHypervisorType();
}
// check if we have available pools for vm deployment
final long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
if (availablePools < 1) {
throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
}
if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
}
final List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
}
if (isIso && !template.isBootable()) {
throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
}
// Check templates permissions
_accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
// check if the user data is correct
validateUserData(userData, httpmethod);
// Find an SSH public key corresponding to the key pair name, if one is
// given
String sshPublicKey = null;
if (sshKeyPair != null && !sshKeyPair.equals("")) {
final SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
if (pair == null) {
throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
}
sshPublicKey = pair.getPublicKey();
}
final List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<>();
final LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<>();
short defaultNetworkNumber = 0;
boolean vpcNetwork = false;
for (final NetworkVO network : networkList) {
if (network.getDataCenterId() != zone.getId()) {
if (!network.isStrechedL2Network()) {
throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
}
final NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
final Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
if (physicalNetworkId == null) {
throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
}
final String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
}
}
// relax the check if the caller is admin account
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
if (!(network.getGuestType() == Network.GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
}
}
IpAddresses requestedIpPair = null;
if (requestedIps != null && !requestedIps.isEmpty()) {
requestedIpPair = requestedIps.get(network.getId());
}
if (requestedIpPair == null) {
requestedIpPair = new IpAddresses(null, null);
} else {
_networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair);
}
NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());
if (defaultNetworkNumber == 0) {
defaultNetworkNumber++;
// if user requested specific ip for default network, add it
if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
_networkModel.checkRequestedIpAddresses(network.getId(), defaultIps);
profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
} else if (defaultIps.getMacAddress() != null) {
profile = new NicProfile(null, null, defaultIps.getMacAddress());
}
profile.setDefaultNic(true);
if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
if (userData != null && !userData.isEmpty()) {
throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
if (sshPublicKey != null && !sshPublicKey.isEmpty()) {
throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
if (template.getEnablePassword()) {
throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
}
}
}
networks.add(new Pair<>(network, profile));
networkNicMap.put(network.getUuid(), profile);
}
// gateway for the vm
if (defaultNetworkNumber == 0) {
throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
} else if (defaultNetworkNumber > 1) {
throw new InvalidParameterValueException("Only 1 default network per vm is supported");
}
final long id = _vmDao.getNextInSequence(Long.class, "id");
if (hostName != null) {
// Check is hostName is RFC compliant
checkNameForRFCCompliance(hostName);
}
final String instanceName;
final String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
if (hostName == null) {
// Generate name using uuid and instance.name global config
hostName = generateHostName(uuidName);
}
if (hostName != null) {
// Check is hostName is RFC compliant
checkNameForRFCCompliance(hostName);
}
instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
// Check if VM with instanceName already exists.
final VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
}
checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
long userId = CallContext.current().getCallingUserId();
if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
if (!userVOs.isEmpty()) {
userId = userVOs.get(0).getId();
}
}
final UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters);
// Assign instance to the group
try {
if (group != null) {
final boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
if (!addToGroup) {
throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
}
}
} catch (final Exception ex) {
throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
}
if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
_affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
}
CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
return vm;
}
use of com.cloud.affinity.AffinityGroupVO in project cosmic by MissionCriticalCloud.
the class HostJoinDaoImpl method newHostResponse.
@Override
public HostResponse newHostResponse(final HostJoinVO host, final EnumSet<HostDetails> details) {
final HostResponse hostResponse = new HostResponse();
hostResponse.setId(host.getUuid());
hostResponse.setCapabilities(host.getCapabilities());
hostResponse.setClusterId(host.getClusterUuid());
hostResponse.setCpuSockets(host.getCpuSockets());
hostResponse.setCpuNumber(host.getCpus());
hostResponse.setZoneId(host.getZoneUuid());
hostResponse.setDisconnectedOn(host.getDisconnectedOn());
hostResponse.setHypervisor(host.getHypervisorType());
hostResponse.setHostType(host.getType());
hostResponse.setLastPinged(new Date(host.getLastPinged()));
hostResponse.setManagementServerId(host.getManagementServerId());
hostResponse.setName(host.getName());
hostResponse.setPodId(host.getPodUuid());
hostResponse.setRemoved(host.getRemoved());
hostResponse.setState(host.getStatus());
hostResponse.setIpAddress(host.getPrivateIpAddress());
hostResponse.setVersion(host.getVersion());
hostResponse.setCreated(host.getCreated());
final DedicatedResourceVO dedicatedResourceVO = dedicatedResourceDao.findByHostId(host.getId());
if (dedicatedResourceVO != null) {
hostResponse.setDedicated(true);
final DomainVO domainVO = domainDao.findById(dedicatedResourceVO.getDomainId());
if (domainVO != null) {
hostResponse.setDomainId(domainVO.getUuid());
hostResponse.setDomainName(domainVO.getName());
}
final AccountVO accountVO = accountDao.findById(dedicatedResourceVO.getAccountId());
if (accountVO != null) {
hostResponse.setAccountId(accountVO.getUuid());
hostResponse.setAccountName(accountVO.getAccountName());
}
final AffinityGroupVO affinityGroupVO = affinityGroupDao.findById(dedicatedResourceVO.getAffinityGroupId());
if (affinityGroupVO != null) {
hostResponse.setAffinityGroupId(affinityGroupVO.getUuid());
hostResponse.setAffinityGroupName(affinityGroupVO.getName());
}
}
final List<HostGpuGroupsVO> gpuGroups = ApiDBUtils.getGpuGroups(host.getId());
if (gpuGroups != null && !gpuGroups.isEmpty()) {
final List<GpuResponse> gpus = new ArrayList<>();
for (final HostGpuGroupsVO entry : gpuGroups) {
final GpuResponse gpuResponse = new GpuResponse();
gpuResponse.setGpuGroupName(entry.getGroupName());
final List<VGPUTypesVO> vgpuTypes = ApiDBUtils.getVgpus(entry.getId());
if (vgpuTypes != null && !vgpuTypes.isEmpty()) {
final List<VgpuResponse> vgpus = new ArrayList<>();
for (final VGPUTypesVO vgpuType : vgpuTypes) {
final VgpuResponse vgpuResponse = new VgpuResponse();
vgpuResponse.setName(vgpuType.getVgpuType());
vgpuResponse.setVideoRam(vgpuType.getVideoRam());
vgpuResponse.setMaxHeads(vgpuType.getMaxHeads());
vgpuResponse.setMaxResolutionX(vgpuType.getMaxResolutionX());
vgpuResponse.setMaxResolutionY(vgpuType.getMaxResolutionY());
vgpuResponse.setMaxVgpuPerPgpu(vgpuType.getMaxVgpuPerPgpu());
vgpuResponse.setRemainingCapacity(vgpuType.getRemainingCapacity());
vgpuResponse.setmaxCapacity(vgpuType.getMaxCapacity());
vgpus.add(vgpuResponse);
}
gpuResponse.setVgpu(vgpus);
}
gpus.add(gpuResponse);
}
hostResponse.setGpuGroups(gpus);
}
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
hostResponse.setOsCategoryId(host.getOsCategoryUuid());
hostResponse.setOsCategoryName(host.getOsCategoryName());
hostResponse.setZoneName(host.getZoneName());
hostResponse.setPodName(host.getPodName());
if (host.getClusterId() > 0) {
hostResponse.setClusterName(host.getClusterName());
hostResponse.setClusterType(host.getClusterType().toString());
}
}
final DecimalFormat decimalFormat = new DecimalFormat("#.##");
if (host.getType() == Host.Type.Routing) {
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) {
// set allocated capacities
final Long mem = host.getMemReservedCapacity() + host.getMemUsedCapacity();
final Long cpu = host.getCpuReservedCapacity() + host.getCpuUsedCapacity();
hostResponse.setMemoryAllocated(mem);
hostResponse.setMemoryTotal(host.getTotalMemory());
final String hostTags = host.getTag();
hostResponse.setHostTags(host.getTag());
final String haTag = ApiDBUtils.getHaTag();
if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) {
if (haTag.equalsIgnoreCase(hostTags)) {
hostResponse.setHaHost(true);
} else {
hostResponse.setHaHost(false);
}
} else {
hostResponse.setHaHost(false);
}
hostResponse.setHypervisorVersion(host.getHypervisorVersion());
final String cpuAlloc = Float.toString(((float) cpu / (host.getCpus() * CapacityManager.CpuOverprovisioningFactor.valueIn(host.getClusterId()))) * 100f) + "%";
hostResponse.setCpuAllocated(cpuAlloc);
final String cpuWithOverprovisioning = Float.toString(host.getCpus() * CapacityManager.CpuOverprovisioningFactor.valueIn(host.getClusterId()));
hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning);
}
if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) {
// set CPU/RAM/Network stats
final String cpuUsed;
final HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId());
if (hostStats != null) {
final float cpuUtil = (float) hostStats.getCpuUtilization();
cpuUsed = decimalFormat.format(cpuUtil) + "%";
hostResponse.setCpuUsed(cpuUsed);
hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue());
hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue());
hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue());
}
}
if (details.contains(HostDetails.all) && host.getHypervisorType() == Hypervisor.HypervisorType.KVM) {
// only kvm has the requirement to return host details
try {
final HostVO h = hostDao.findById(host.getId());
hostDao.loadDetails(h);
final Map<String, String> hostVoDetails;
hostVoDetails = h.getDetails();
hostResponse.setDetails(hostVoDetails);
hostResponse.setHypervisorVersion(h.getDetail("Host.OS") + " " + h.getDetail("Host.OS.Version") + " with kernel " + h.getDetail("Host.OS.Kernel.Version"));
} catch (final Exception e) {
s_logger.debug("failed to get host details", e);
}
}
} else if (host.getType() == Host.Type.SecondaryStorage) {
final StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId());
if (secStorageStats != null) {
hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes());
hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed());
}
}
hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host.getId()));
if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) {
final Set<com.cloud.host.Status.Event> possibleEvents = host.getStatus().getPossibleEvents();
if ((possibleEvents != null) && !possibleEvents.isEmpty()) {
String events = "";
final Iterator<com.cloud.host.Status.Event> iter = possibleEvents.iterator();
while (iter.hasNext()) {
final com.cloud.host.Status.Event event = iter.next();
events += event.toString();
if (iter.hasNext()) {
events += "; ";
}
}
hostResponse.setEvents(events);
}
}
hostResponse.setResourceState(host.getResourceState().toString());
// set async job
if (host.getJobId() != null) {
hostResponse.setJobId(host.getJobUuid());
hostResponse.setJobStatus(host.getJobStatus());
}
hostResponse.setObjectName("host");
return hostResponse;
}
use of com.cloud.affinity.AffinityGroupVO in project cosmic by MissionCriticalCloud.
the class HostJoinDaoImpl method newHostForMigrationResponse.
@Override
public HostForMigrationResponse newHostForMigrationResponse(final HostJoinVO host, final EnumSet<HostDetails> details) {
final HostForMigrationResponse hostResponse = new HostForMigrationResponse();
hostResponse.setId(host.getUuid());
hostResponse.setCapabilities(host.getCapabilities());
hostResponse.setClusterId(host.getClusterUuid());
hostResponse.setCpuNumber(host.getCpus());
hostResponse.setZoneId(host.getZoneUuid());
hostResponse.setDisconnectedOn(host.getDisconnectedOn());
hostResponse.setHypervisor(host.getHypervisorType());
hostResponse.setHostType(host.getType());
hostResponse.setLastPinged(new Date(host.getLastPinged()));
hostResponse.setManagementServerId(host.getManagementServerId());
hostResponse.setName(host.getName());
hostResponse.setPodId(host.getPodUuid());
hostResponse.setRemoved(host.getRemoved());
hostResponse.setState(host.getStatus());
hostResponse.setIpAddress(host.getPrivateIpAddress());
hostResponse.setVersion(host.getVersion());
hostResponse.setCreated(host.getCreated());
final DedicatedResourceVO dedicatedResourceVO = dedicatedResourceDao.findByHostId(host.getId());
if (dedicatedResourceVO != null) {
hostResponse.setDedicated(true);
final DomainVO domainVO = domainDao.findById(dedicatedResourceVO.getDomainId());
if (domainVO != null) {
hostResponse.setDomainId(domainVO.getUuid());
hostResponse.setDomainName(domainVO.getName());
}
final AccountVO accountVO = accountDao.findById(dedicatedResourceVO.getAccountId());
if (accountVO != null) {
hostResponse.setAccountId(accountVO.getUuid());
hostResponse.setAccountName(accountVO.getAccountName());
}
final AffinityGroupVO affinityGroupVO = affinityGroupDao.findById(dedicatedResourceVO.getAffinityGroupId());
if (affinityGroupVO != null) {
hostResponse.setAffinityGroupId(affinityGroupVO.getUuid());
hostResponse.setAffinityGroupName(affinityGroupVO.getName());
}
}
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) {
hostResponse.setOsCategoryId(host.getOsCategoryUuid());
hostResponse.setOsCategoryName(host.getOsCategoryName());
hostResponse.setZoneName(host.getZoneName());
hostResponse.setPodName(host.getPodName());
if (host.getClusterId() > 0) {
hostResponse.setClusterName(host.getClusterName());
hostResponse.setClusterType(host.getClusterType().toString());
}
}
final DecimalFormat decimalFormat = new DecimalFormat("#.##");
if (host.getType() == Host.Type.Routing) {
if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) {
// set allocated capacities
final Long mem = host.getMemReservedCapacity() + host.getMemUsedCapacity();
final Long cpu = host.getCpuReservedCapacity() + host.getCpuReservedCapacity();
hostResponse.setMemoryAllocated(mem);
hostResponse.setMemoryTotal(host.getTotalMemory());
final String hostTags = host.getTag();
hostResponse.setHostTags(host.getTag());
final String haTag = ApiDBUtils.getHaTag();
if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) {
if (haTag.equalsIgnoreCase(hostTags)) {
hostResponse.setHaHost(true);
} else {
hostResponse.setHaHost(false);
}
} else {
hostResponse.setHaHost(false);
}
hostResponse.setHypervisorVersion(host.getHypervisorVersion());
final String cpuAlloc = decimalFormat.format(((float) cpu / (float) host.getCpus()) * 100f) + "%";
hostResponse.setCpuAllocated(cpuAlloc);
final String cpuWithOverprovisioning = Float.toString(host.getCpus() * ApiDBUtils.getCpuOverprovisioningFactor(host.getClusterId()));
hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning);
}
if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) {
// set CPU/RAM/Network stats
final String cpuUsed;
final HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId());
if (hostStats != null) {
final float cpuUtil = (float) hostStats.getCpuUtilization();
cpuUsed = decimalFormat.format(cpuUtil) + "%";
hostResponse.setCpuUsed(cpuUsed);
hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue());
hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue());
hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue());
}
}
} else if (host.getType() == Host.Type.SecondaryStorage) {
final StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId());
if (secStorageStats != null) {
hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes());
hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed());
}
}
hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host.getId()));
if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) {
final Set<com.cloud.host.Status.Event> possibleEvents = host.getStatus().getPossibleEvents();
if ((possibleEvents != null) && !possibleEvents.isEmpty()) {
String events = "";
final Iterator<com.cloud.host.Status.Event> iter = possibleEvents.iterator();
while (iter.hasNext()) {
final com.cloud.host.Status.Event event = iter.next();
events += event.toString();
if (iter.hasNext()) {
events += "; ";
}
}
hostResponse.setEvents(events);
}
}
hostResponse.setResourceState(host.getResourceState().toString());
// set async job
hostResponse.setJobId(host.getJobUuid());
hostResponse.setJobStatus(host.getJobStatus());
hostResponse.setObjectName("host");
return hostResponse;
}
Aggregations