use of com.cloud.storage.DiskOfferingVO in project cloudstack by apache.
the class DatabaseConfig method saveServiceOffering.
@DB
protected void saveServiceOffering() {
long id = Long.parseLong(_currentObjectParams.get("id"));
String name = _currentObjectParams.get("name");
String displayText = _currentObjectParams.get("displayText");
ProvisioningType provisioningType = ProvisioningType.valueOf(_currentObjectParams.get("provisioningType"));
int cpu = Integer.parseInt(_currentObjectParams.get("cpu"));
int ramSize = Integer.parseInt(_currentObjectParams.get("ramSize"));
int speed = Integer.parseInt(_currentObjectParams.get("speed"));
String useLocalStorageValue = _currentObjectParams.get("useLocalStorage");
// int nwRate = Integer.parseInt(_currentObjectParams.get("nwRate"));
// int mcRate = Integer.parseInt(_currentObjectParams.get("mcRate"));
boolean ha = Boolean.parseBoolean(_currentObjectParams.get("enableHA"));
boolean mirroring = Boolean.parseBoolean(_currentObjectParams.get("mirrored"));
boolean useLocalStorage;
if (useLocalStorageValue != null) {
if (Boolean.parseBoolean(useLocalStorageValue)) {
useLocalStorage = true;
} else {
useLocalStorage = false;
}
} else {
useLocalStorage = false;
}
DiskOfferingVO diskOfferingVO = new DiskOfferingVO(name, displayText, provisioningType, false, null, false, false, true);
ServiceOfferingVO serviceOffering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, ha, displayText, false, null, false);
Long bytesReadRate = Long.parseLong(_currentObjectParams.get("bytesReadRate"));
if ((bytesReadRate != null) && (bytesReadRate > 0))
diskOfferingVO.setBytesReadRate(bytesReadRate);
Long bytesWriteRate = Long.parseLong(_currentObjectParams.get("bytesWriteRate"));
if ((bytesWriteRate != null) && (bytesWriteRate > 0))
diskOfferingVO.setBytesWriteRate(bytesWriteRate);
Long iopsReadRate = Long.parseLong(_currentObjectParams.get("iopsReadRate"));
if ((iopsReadRate != null) && (iopsReadRate > 0))
diskOfferingVO.setIopsReadRate(iopsReadRate);
Long iopsWriteRate = Long.parseLong(_currentObjectParams.get("iopsWriteRate"));
if ((iopsWriteRate != null) && (iopsWriteRate > 0))
diskOfferingVO.setIopsWriteRate(iopsWriteRate);
DiskOfferingDaoImpl DiskOfferinDao = ComponentContext.inject(DiskOfferingDaoImpl.class);
try {
DiskOfferinDao.persist(diskOfferingVO);
} catch (Exception e) {
s_logger.error("error creating disk offering", e);
}
serviceOffering.setDiskOfferingId(diskOfferingVO.getId());
ServiceOfferingDaoImpl serviceOfferingDao = ComponentContext.inject(ServiceOfferingDaoImpl.class);
try {
serviceOfferingDao.persist(serviceOffering);
} catch (Exception e) {
s_logger.error("error creating service offering", e);
}
/*
String insertSql = "INSERT INTO `cloud`.`service_offering` (id, name, cpu, ram_size, speed, nw_rate, mc_rate, created, ha_enabled, mirrored, display_text, guest_ip_type, use_local_storage) " +
"VALUES (" + id + ",'" + name + "'," + cpu + "," + ramSize + "," + speed + "," + nwRate + "," + mcRate + ",now()," + ha + "," + mirroring + ",'" + displayText + "','" + guestIpType + "','" + useLocalStorage + "')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.error("error creating service offering", ex);
return;
}
*/
}
use of com.cloud.storage.DiskOfferingVO in project cloudstack by apache.
the class UnmanagedVMsManagerImpl method importVirtualMachineInternal.
private UserVm importVirtualMachineInternal(final UnmanagedInstanceTO unmanagedInstance, final String instanceName, final DataCenter zone, final Cluster cluster, final HostVO host, final VirtualMachineTemplate template, final String displayName, final String hostName, final Account caller, final Account owner, final Long userId, final ServiceOfferingVO serviceOffering, final Map<String, Long> dataDiskOfferingMap, final Map<String, Long> nicNetworkMap, final Map<String, Network.IpAddresses> callerNicIpAddressMap, final Map<String, String> details, final boolean migrateAllowed, final boolean forced) {
UserVm userVm = null;
ServiceOfferingVO validatedServiceOffering = null;
try {
validatedServiceOffering = getUnmanagedInstanceServiceOffering(unmanagedInstance, serviceOffering, owner, zone, details);
} catch (Exception e) {
LOGGER.error("Service offering for VM import not compatible", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import VM: %s. %s", unmanagedInstance.getName(), StringUtils.defaultString(e.getMessage())));
}
String internalCSName = unmanagedInstance.getInternalCSName();
if (StringUtils.isEmpty(internalCSName)) {
internalCSName = instanceName;
}
Map<String, String> allDetails = new HashMap<>(details);
if (validatedServiceOffering.isDynamic()) {
allDetails.put(VmDetailConstants.CPU_NUMBER, String.valueOf(validatedServiceOffering.getCpu()));
allDetails.put(VmDetailConstants.MEMORY, String.valueOf(validatedServiceOffering.getRamSize()));
if (serviceOffering.getSpeed() == null) {
allDetails.put(VmDetailConstants.CPU_SPEED, String.valueOf(validatedServiceOffering.getSpeed()));
}
}
if (!migrateAllowed && !hostSupportsServiceOffering(host, validatedServiceOffering)) {
throw new InvalidParameterValueException(String.format("Service offering: %s is not compatible with host: %s of unmanaged VM: %s", serviceOffering.getUuid(), host.getUuid(), instanceName));
}
// Check disks and supplied disk offerings
List<UnmanagedInstanceTO.Disk> unmanagedInstanceDisks = unmanagedInstance.getDisks();
if (CollectionUtils.isEmpty(unmanagedInstanceDisks)) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("No attached disks found for the unmanaged VM: %s", instanceName));
}
Pair<UnmanagedInstanceTO.Disk, List<UnmanagedInstanceTO.Disk>> rootAndDataDisksPair = getRootAndDataDisks(unmanagedInstanceDisks, dataDiskOfferingMap);
final UnmanagedInstanceTO.Disk rootDisk = rootAndDataDisksPair.first();
final List<UnmanagedInstanceTO.Disk> dataDisks = rootAndDataDisksPair.second();
if (rootDisk == null || StringUtils.isEmpty(rootDisk.getController())) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM import failed. Unable to retrieve root disk details for VM: %s ", instanceName));
}
allDetails.put(VmDetailConstants.ROOT_DISK_CONTROLLER, rootDisk.getController());
try {
checkUnmanagedDiskAndOfferingForImport(rootDisk, null, validatedServiceOffering, owner, zone, cluster, migrateAllowed);
if (CollectionUtils.isNotEmpty(dataDisks)) {
// Data disk(s) present
checkUnmanagedDiskAndOfferingForImport(dataDisks, dataDiskOfferingMap, owner, zone, cluster, migrateAllowed);
allDetails.put(VmDetailConstants.DATA_DISK_CONTROLLER, dataDisks.get(0).getController());
}
resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.volume, unmanagedInstanceDisks.size());
} catch (ResourceAllocationException e) {
LOGGER.error(String.format("Volume resource allocation error for owner: %s", owner.getUuid()), e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Volume resource allocation error for owner: %s. %s", owner.getUuid(), StringUtils.defaultString(e.getMessage())));
}
// Check NICs and supplied networks
Map<String, Network.IpAddresses> nicIpAddressMap = getNicIpAddresses(unmanagedInstance.getNics(), callerNicIpAddressMap);
Map<String, Long> allNicNetworkMap = getUnmanagedNicNetworkMap(unmanagedInstance.getNics(), nicNetworkMap, nicIpAddressMap, zone, hostName, owner);
if (!CollectionUtils.isEmpty(unmanagedInstance.getNics())) {
allDetails.put(VmDetailConstants.NIC_ADAPTER, unmanagedInstance.getNics().get(0).getAdapterType());
}
VirtualMachine.PowerState powerState = VirtualMachine.PowerState.PowerOff;
if (unmanagedInstance.getPowerState().equals(UnmanagedInstanceTO.PowerState.PowerOn)) {
powerState = VirtualMachine.PowerState.PowerOn;
}
try {
userVm = userVmManager.importVM(zone, host, template, internalCSName, displayName, owner, null, caller, true, null, owner.getAccountId(), userId, validatedServiceOffering, null, hostName, cluster.getHypervisorType(), allDetails, powerState);
} catch (InsufficientCapacityException ice) {
LOGGER.error(String.format("Failed to import vm name: %s", instanceName), ice);
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ice.getMessage());
}
if (userVm == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import vm name: %s", instanceName));
}
List<Pair<DiskProfile, StoragePool>> diskProfileStoragePoolList = new ArrayList<>();
try {
if (rootDisk.getCapacity() == null || rootDisk.getCapacity() == 0) {
throw new InvalidParameterValueException(String.format("Root disk ID: %s size is invalid", rootDisk.getDiskId()));
}
Long minIops = null;
if (details.containsKey("minIops")) {
minIops = Long.parseLong(details.get("minIops"));
}
Long maxIops = null;
if (details.containsKey("maxIops")) {
maxIops = Long.parseLong(details.get("maxIops"));
}
DiskOfferingVO diskOffering = diskOfferingDao.findById(serviceOffering.getDiskOfferingId());
diskProfileStoragePoolList.add(importDisk(rootDisk, userVm, cluster, diskOffering, Volume.Type.ROOT, String.format("ROOT-%d", userVm.getId()), (rootDisk.getCapacity() / Resource.ResourceType.bytesToGiB), minIops, maxIops, template, owner, null));
for (UnmanagedInstanceTO.Disk disk : dataDisks) {
if (disk.getCapacity() == null || disk.getCapacity() == 0) {
throw new InvalidParameterValueException(String.format("Disk ID: %s size is invalid", rootDisk.getDiskId()));
}
DiskOffering offering = diskOfferingDao.findById(dataDiskOfferingMap.get(disk.getDiskId()));
diskProfileStoragePoolList.add(importDisk(disk, userVm, cluster, offering, Volume.Type.DATADISK, String.format("DATA-%d-%s", userVm.getId(), disk.getDiskId()), (disk.getCapacity() / Resource.ResourceType.bytesToGiB), offering.getMinIops(), offering.getMaxIops(), template, owner, null));
}
} catch (Exception e) {
LOGGER.error(String.format("Failed to import volumes while importing vm: %s", instanceName), e);
cleanupFailedImportVM(userVm);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import volumes while importing vm: %s. %s", instanceName, StringUtils.defaultString(e.getMessage())));
}
try {
boolean firstNic = true;
for (UnmanagedInstanceTO.Nic nic : unmanagedInstance.getNics()) {
Network network = networkDao.findById(allNicNetworkMap.get(nic.getNicId()));
Network.IpAddresses ipAddresses = nicIpAddressMap.get(nic.getNicId());
importNic(nic, userVm, network, ipAddresses, firstNic, forced);
firstNic = false;
}
} catch (Exception e) {
LOGGER.error(String.format("Failed to import NICs while importing vm: %s", instanceName), e);
cleanupFailedImportVM(userVm);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import NICs while importing vm: %s. %s", instanceName, StringUtils.defaultString(e.getMessage())));
}
if (migrateAllowed) {
userVm = migrateImportedVM(host, template, validatedServiceOffering, userVm, owner, diskProfileStoragePoolList);
}
publishVMUsageUpdateResourceCount(userVm, validatedServiceOffering);
return userVm;
}
use of com.cloud.storage.DiskOfferingVO in project cloudstack by apache.
the class QueryManagerImpl method searchForServiceOfferingsInternal.
private Pair<List<ServiceOfferingJoinVO>, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) {
// Note
// The filteredOfferings method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will filteredOfferings all offerings
// 2. For domainAdmin and regular users, we will filteredOfferings everything in
// their domains+parent domains ... all the way
// till
// root
Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", SortKeyAscending.value(), cmd.getStartIndex(), cmd.getPageSizeVal());
searchFilter.addOrderBy(ServiceOfferingJoinVO.class, "id", true);
Account caller = CallContext.current().getCallingAccount();
Object name = cmd.getServiceOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long vmId = cmd.getVirtualMachineId();
Long domainId = cmd.getDomainId();
Boolean isSystem = cmd.getIsSystem();
String vmTypeStr = cmd.getSystemVmType();
ServiceOfferingVO currentVmOffering = null;
Boolean isRecursive = cmd.isRecursive();
Long zoneId = cmd.getZoneId();
Integer cpuNumber = cmd.getCpuNumber();
Integer memory = cmd.getMemory();
Integer cpuSpeed = cmd.getCpuSpeed();
SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
if (!_accountMgr.isRootAdmin(caller.getId()) && isSystem) {
throw new InvalidParameterValueException("Only ROOT admins can access system's offering");
}
// domain
if (domainId != null && !_accountMgr.isRootAdmin(caller.getId())) {
// child of so's domain
if (!isPermissible(caller.getDomainId(), domainId)) {
throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering");
}
}
if (vmId != null) {
VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
ex.addProxyObject(vmId.toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
currentVmOffering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
if (!currentVmOffering.isDynamic()) {
sc.addAnd("id", SearchCriteria.Op.NEQ, currentVmOffering.getId());
}
if (currentVmOffering.getDiskOfferingStrictness()) {
sc.addAnd("diskOfferingId", Op.EQ, currentVmOffering.getDiskOfferingId());
sc.addAnd("diskOfferingStrictness", Op.EQ, true);
} else {
sc.addAnd("diskOfferingStrictness", Op.EQ, false);
}
boolean isRootVolumeUsingLocalStorage = virtualMachineManager.isRootVolumeOnLocalStorage(vmId);
// 1. Only return offerings with the same storage type than the storage pool where the VM's root volume is allocated
sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, isRootVolumeUsingLocalStorage);
// 2.In case vm is running return only offerings greater than equal to current offering compute and offering's dynamic scalability should match
if (vmInstance.getState() == VirtualMachine.State.Running) {
Integer vmCpu = currentVmOffering.getCpu();
Integer vmMemory = currentVmOffering.getRamSize();
Integer vmSpeed = currentVmOffering.getSpeed();
if ((vmCpu == null || vmMemory == null || vmSpeed == null) && VirtualMachine.Type.User.equals(vmInstance.getType())) {
UserVmVO userVmVO = _userVmDao.findById(vmId);
_userVmDao.loadDetails(userVmVO);
Map<String, String> details = userVmVO.getDetails();
vmCpu = NumbersUtil.parseInt(details.get(ApiConstants.CPU_NUMBER), 0);
if (vmSpeed == null) {
vmSpeed = NumbersUtil.parseInt(details.get(ApiConstants.CPU_SPEED), 0);
}
vmMemory = NumbersUtil.parseInt(details.get(ApiConstants.MEMORY), 0);
}
if (vmCpu != null && vmCpu > 0) {
sc.addAnd("cpu", Op.SC, getMinimumCpuServiceOfferingJoinSearchCriteria(vmCpu));
}
if (vmSpeed != null && vmSpeed > 0) {
sc.addAnd("speed", Op.SC, getMinimumCpuSpeedServiceOfferingJoinSearchCriteria(vmSpeed));
}
if (vmMemory != null && vmMemory > 0) {
sc.addAnd("ramSize", Op.SC, getMinimumMemoryServiceOfferingJoinSearchCriteria(vmMemory));
}
sc.addAnd("dynamicScalingEnabled", Op.EQ, currentVmOffering.isDynamicScalingEnabled());
}
}
// boolean includePublicOfferings = false;
if ((_accountMgr.isNormalUser(caller.getId()) || _accountMgr.isDomainAdmin(caller.getId())) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// For non-root users.
if (isSystem) {
throw new InvalidParameterValueException("Only root admins can access system's offering");
}
if (isRecursive) {
// domain + all sub-domains
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
throw new InvalidParameterValueException("Only ROOT admins and Domain admins can list service offerings with isrecursive=true");
}
}
} else {
// for root users
if (caller.getDomainId() != 1 && isSystem) {
// NON ROOT admin
throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering");
}
if (domainId != null) {
sc.addAnd("domainId", Op.FIND_IN_SET, String.valueOf(domainId));
}
}
if (keyword != null) {
SearchCriteria<ServiceOfferingJoinVO> ssc = _srvOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (isSystem != null) {
// note that for non-root users, isSystem is always false when
// control comes to here
sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (vmTypeStr != null) {
sc.addAnd("vmType", SearchCriteria.Op.EQ, vmTypeStr);
}
if (zoneId != null) {
SearchBuilder<ServiceOfferingJoinVO> sb = _srvOfferingJoinDao.createSearchBuilder();
sb.and("zoneId", sb.entity().getZoneId(), Op.FIND_IN_SET);
sb.or("zId", sb.entity().getZoneId(), Op.NULL);
sb.done();
SearchCriteria<ServiceOfferingJoinVO> zoneSC = sb.create();
zoneSC.setParameters("zoneId", String.valueOf(zoneId));
sc.addAnd("zoneId", SearchCriteria.Op.SC, zoneSC);
}
if (cpuNumber != null) {
SearchCriteria<ServiceOfferingJoinVO> cpuConstraintSearchCriteria = _srvOfferingJoinDao.createSearchCriteria();
cpuConstraintSearchCriteria.addAnd("minCpu", Op.LTEQ, cpuNumber);
cpuConstraintSearchCriteria.addAnd("maxCpu", Op.GTEQ, cpuNumber);
SearchCriteria<ServiceOfferingJoinVO> cpuSearchCriteria = _srvOfferingJoinDao.createSearchCriteria();
cpuSearchCriteria.addOr("minCpu", Op.NULL);
cpuSearchCriteria.addOr("constraints", Op.SC, cpuConstraintSearchCriteria);
cpuSearchCriteria.addOr("minCpu", Op.GTEQ, cpuNumber);
sc.addAnd("cpuConstraints", SearchCriteria.Op.SC, cpuSearchCriteria);
}
if (memory != null) {
SearchCriteria<ServiceOfferingJoinVO> memoryConstraintSearchCriteria = _srvOfferingJoinDao.createSearchCriteria();
memoryConstraintSearchCriteria.addAnd("minMemory", Op.LTEQ, memory);
memoryConstraintSearchCriteria.addAnd("maxMemory", Op.GTEQ, memory);
SearchCriteria<ServiceOfferingJoinVO> memSearchCriteria = _srvOfferingJoinDao.createSearchCriteria();
memSearchCriteria.addOr("minMemory", Op.NULL);
memSearchCriteria.addOr("memconstraints", Op.SC, memoryConstraintSearchCriteria);
memSearchCriteria.addOr("minMemory", Op.GTEQ, memory);
sc.addAnd("memoryConstraints", SearchCriteria.Op.SC, memSearchCriteria);
}
if (cpuSpeed != null) {
SearchCriteria<ServiceOfferingJoinVO> cpuSpeedSearchCriteria = _srvOfferingJoinDao.createSearchCriteria();
cpuSpeedSearchCriteria.addOr("speed", Op.NULL);
cpuSpeedSearchCriteria.addOr("speed", Op.GTEQ, cpuSpeed);
sc.addAnd("cpuspeedconstraints", SearchCriteria.Op.SC, cpuSpeedSearchCriteria);
}
// Fetch the offering ids from the details table since theres no smart way to filter them in the join ... yet!
if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
Domain callerDomain = _domainDao.findById(caller.getDomainId());
List<Long> domainIds = findRelatedDomainIds(callerDomain, isRecursive);
List<Long> ids = _srvOfferingDetailsDao.findOfferingIdsByDomainIds(domainIds);
SearchBuilder<ServiceOfferingJoinVO> sb = _srvOfferingJoinDao.createSearchBuilder();
if (ids != null && !ids.isEmpty()) {
sb.and("id", sb.entity().getId(), Op.IN);
}
sb.or("domainId", sb.entity().getDomainId(), Op.NULL);
sb.done();
SearchCriteria<ServiceOfferingJoinVO> scc = sb.create();
if (ids != null && !ids.isEmpty()) {
scc.setParameters("id", ids.toArray());
}
sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
}
if (currentVmOffering != null) {
DiskOfferingVO diskOffering = _diskOfferingDao.findByIdIncludingRemoved(currentVmOffering.getDiskOfferingId());
List<String> storageTags = com.cloud.utils.StringUtils.csvTagsToList(diskOffering.getTags());
if (!storageTags.isEmpty() && VolumeApiServiceImpl.MatchStoragePoolTagsWithDiskOffering.value()) {
SearchBuilder<ServiceOfferingJoinVO> sb = _srvOfferingJoinDao.createSearchBuilder();
for (String tag : storageTags) {
sb.and(tag, sb.entity().getTags(), Op.FIND_IN_SET);
}
sb.done();
SearchCriteria<ServiceOfferingJoinVO> scc = sb.create();
for (String tag : storageTags) {
scc.setParameters(tag, tag);
}
sc.addAnd("storageTags", SearchCriteria.Op.SC, scc);
}
List<String> hostTags = com.cloud.utils.StringUtils.csvTagsToList(currentVmOffering.getHostTag());
if (!hostTags.isEmpty()) {
SearchBuilder<ServiceOfferingJoinVO> sb = _srvOfferingJoinDao.createSearchBuilder();
for (String tag : hostTags) {
sb.and(tag, sb.entity().getHostTag(), Op.FIND_IN_SET);
}
sb.done();
SearchCriteria<ServiceOfferingJoinVO> scc = sb.create();
for (String tag : hostTags) {
scc.setParameters(tag, tag);
}
sc.addAnd("hostTags", SearchCriteria.Op.SC, scc);
}
}
return _srvOfferingJoinDao.searchAndCount(sc, searchFilter);
}
use of com.cloud.storage.DiskOfferingVO in project cloudstack by apache.
the class ConfigurationServerImpl method createDefaultDiskOffering.
private DiskOfferingVO createDefaultDiskOffering(String name, String description, ProvisioningType provisioningType, int numGibibytes, String tags, boolean isCustomized, boolean isSystemUse) {
long diskSize = numGibibytes;
diskSize = diskSize * 1024 * 1024 * 1024;
tags = cleanupTags(tags);
DiskOfferingVO newDiskOffering = new DiskOfferingVO(name, description, provisioningType, diskSize, tags, isCustomized, null, null, null);
newDiskOffering.setUniqueName("Cloud.Com-" + name);
// leaving the above reference to cloud.com in as it is an identifier and has no real world relevance
newDiskOffering = _diskOfferingDao.persistDefaultDiskOffering(newDiskOffering);
return newDiskOffering;
}
use of com.cloud.storage.DiskOfferingVO in project cloudstack by apache.
the class ManagementServerImpl method listHostsForMigrationOfVM.
@Override
public Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>> listHostsForMigrationOfVM(final Long vmId, final Long startIndex, final Long pageSize, final String keyword) {
final Account caller = getCaller();
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) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the VM with given id");
throw ex;
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not running, cannot migrate the vm" + vm);
}
final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, cannot " + "migrate the vm with specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
UserVmDetailVO userVmDetailVO = _UserVmDetailsDao.findDetail(vm.getId(), ApiConstants.BootType.UEFI.toString());
if (userVmDetailVO != null) {
s_logger.info(" Live Migration of UEFI enabled VM : " + vm.getInstanceName() + " is not supported");
if ("legacy".equalsIgnoreCase(userVmDetailVO.getValue()) || "secure".equalsIgnoreCase(userVmDetailVO.getValue())) {
// Return empty list.
return new Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>>(new Pair<List<? extends Host>, Integer>(new ArrayList<HostVO>(), new Integer(0)), new ArrayList<Host>(), new HashMap<Host, Boolean>());
}
}
if (_serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
s_logger.info(" Live Migration of GPU enabled VM : " + vm.getInstanceName() + " is not supported");
// Return empty list.
return new Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>>(new Pair<List<? extends Host>, Integer>(new ArrayList<HostVO>(), new Integer(0)), new ArrayList<Host>(), new HashMap<Host, Boolean>());
}
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/Ovm3, 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");
}
final long srcHostId = vm.getHostId();
final Host srcHost = _hostDao.findById(srcHostId);
if (srcHost == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm);
}
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id");
ex.addProxyObject(String.valueOf(srcHostId), "hostId");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
String srcHostVersion = srcHost.getHypervisorVersion();
if (HypervisorType.KVM.equals(srcHost.getHypervisorType()) && srcHostVersion == null) {
srcHostVersion = "";
}
// Check if the vm can be migrated with storage.
boolean canMigrateWithStorage = false;
if (VirtualMachine.Type.User.equals(vm.getType()) || HypervisorType.VMware.equals(vm.getHypervisorType())) {
canMigrateWithStorage = _hypervisorCapabilitiesDao.isStorageMotionSupported(srcHost.getHypervisorType(), srcHostVersion);
}
// Check if the vm is using any disks on local storage.
final VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm, null, _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()), null, null);
final List<VolumeVO> volumes = _volumeDao.findCreatedByInstance(vmProfile.getId());
boolean usesLocal = false;
for (final VolumeVO volume : volumes) {
final DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
final DiskProfile diskProfile = new DiskProfile(volume, diskOffering, vmProfile.getHypervisorType());
if (diskProfile.useLocalStorage()) {
usesLocal = true;
break;
}
}
if (!canMigrateWithStorage && usesLocal) {
throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
}
final Type hostType = srcHost.getType();
Pair<List<HostVO>, Integer> allHostsPair = null;
List<HostVO> allHosts = null;
List<HostVO> hostsForMigrationWithStorage = null;
final Map<Host, Boolean> requiresStorageMotion = new HashMap<Host, Boolean>();
DataCenterDeployment plan = null;
if (canMigrateWithStorage) {
Long podId = !VirtualMachine.Type.User.equals(vm.getType()) ? srcHost.getPodId() : null;
allHostsPair = searchForServers(startIndex, pageSize, null, hostType, null, srcHost.getDataCenterId(), podId, null, null, keyword, null, null, srcHost.getHypervisorType(), null, srcHost.getId());
allHosts = allHostsPair.first();
hostsForMigrationWithStorage = new ArrayList<>(allHosts);
for (final VolumeVO volume : volumes) {
StoragePool storagePool = _poolDao.findById(volume.getPoolId());
Long volClusterId = storagePool.getClusterId();
for (Iterator<HostVO> iterator = hostsForMigrationWithStorage.iterator(); iterator.hasNext(); ) {
final Host host = iterator.next();
String hostVersion = host.getHypervisorVersion();
if (HypervisorType.KVM.equals(host.getHypervisorType()) && hostVersion == null) {
hostVersion = "";
}
if (volClusterId != null) {
if (storagePool.isLocal() || !host.getClusterId().equals(volClusterId) || usesLocal) {
if (storagePool.isManaged()) {
// At the time being, we do not support storage migration of a volume from managed storage unless the managed storage
// is at the zone level and the source and target storage pool is the same.
// If the source and target storage pool is the same and it is managed, then we still have to perform a storage migration
// because we need to create a new target volume and copy the contents of the source volume into it before deleting the
// source volume.
iterator.remove();
} else {
boolean hostSupportsStorageMigration = (srcHostVersion != null && srcHostVersion.equals(hostVersion)) || _hypervisorCapabilitiesDao.isStorageMotionSupported(host.getHypervisorType(), hostVersion);
if (hostSupportsStorageMigration && hasSuitablePoolsForVolume(volume, host, vmProfile)) {
requiresStorageMotion.put(host, true);
} else {
iterator.remove();
}
}
}
} else {
if (storagePool.isManaged()) {
if (srcHost.getClusterId() != host.getClusterId()) {
if (storagePool.getPoolType() == Storage.StoragePoolType.PowerFlex) {
// Simply, changing volume access to host should work: grant access on dest host and revoke access on source host
continue;
}
// If the volume's storage pool is managed and at the zone level, then we still have to perform a storage migration
// because we need to create a new target volume and copy the contents of the source volume into it before deleting
// the source volume.
requiresStorageMotion.put(host, true);
}
}
}
}
}
plan = new DataCenterDeployment(srcHost.getDataCenterId(), podId, null, null, null, null);
} else {
final Long cluster = srcHost.getClusterId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Searching for all hosts in cluster " + cluster + " for migrating VM " + vm);
}
allHostsPair = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, keyword, null, null, null, null, srcHost.getId());
allHosts = allHostsPair.first();
plan = new DataCenterDeployment(srcHost.getDataCenterId(), srcHost.getPodId(), srcHost.getClusterId(), null, null, null);
}
final Pair<List<? extends Host>, Integer> otherHosts = new Pair<List<? extends Host>, Integer>(allHosts, allHostsPair.second());
List<Host> suitableHosts = new ArrayList<Host>();
final ExcludeList excludes = new ExcludeList();
excludes.addHost(srcHostId);
if (dpdkHelper.isVMDpdkEnabled(vm.getId())) {
excludeNonDPDKEnabledHosts(plan, excludes);
}
// call affinitygroup chain
final long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
if (vmGroupCount > 0) {
for (final AffinityGroupProcessor processor : _affinityProcessors) {
processor.process(vmProfile, plan, excludes);
}
}
if (vm.getType() == VirtualMachine.Type.User || vm.getType() == VirtualMachine.Type.DomainRouter) {
final DataCenterVO dc = _dcDao.findById(srcHost.getDataCenterId());
_dpMgr.checkForNonDedicatedResources(vmProfile, dc, excludes);
}
for (final HostAllocator allocator : hostAllocators) {
if (canMigrateWithStorage) {
suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, hostsForMigrationWithStorage, HostAllocator.RETURN_UPTO_ALL, false);
} else {
suitableHosts = allocator.allocateTo(vmProfile, plan, Host.Type.Routing, excludes, HostAllocator.RETURN_UPTO_ALL, false);
}
if (suitableHosts != null && !suitableHosts.isEmpty()) {
break;
}
}
if (s_logger.isDebugEnabled()) {
if (suitableHosts.isEmpty()) {
s_logger.debug("No suitable hosts found");
} else {
s_logger.debug("Hosts having capacity and suitable for migration: " + suitableHosts);
}
}
return new Ternary<Pair<List<? extends Host>, Integer>, List<? extends Host>, Map<Host, Boolean>>(otherHosts, suitableHosts, requiresStorageMotion);
}
Aggregations