use of com.cloud.model.enumeration.OptimiseFor in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method updateVirtualMachine.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_UPDATE, eventDescription = "updating Vm")
public UserVm updateVirtualMachine(final UpdateVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException {
final String displayName = cmd.getDisplayName();
final String group = cmd.getGroup();
final Boolean ha = cmd.getHaEnable();
final Boolean isDisplayVm = cmd.getDisplayVm();
final Long id = cmd.getId();
final Long osTypeId = cmd.getOsTypeId();
final String userData = cmd.getUserData();
final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
final String hostName = cmd.getHostName();
final Map<String, String> details = cmd.getDetails();
final Account caller = CallContext.current().getCallingAccount();
final OptimiseFor optimiseFor = cmd.getOptimiseFor();
final String manufacturerString = cmd.getManufacturerString();
final Boolean requiresRestart = cmd.getRequiresRestart();
final MaintenancePolicy maintenancePolicy = cmd.getMaintenancePolicy();
final Long bootMenuTimeout = cmd.getBootMenuTimeout();
final String bootOrder = cmd.getBootOrder();
final ComplianceStatus complianceStatus = cmd.getComplianceStatus();
// Input validation and permission checks
final UserVmVO vmInstance = _vmDao.findById(id);
if (vmInstance == null) {
throw new InvalidParameterValueException("unable to find virtual machine with id " + id);
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
// If the flag is specified and is changed
if (isDisplayVm != null && isDisplayVm != vmInstance.isDisplayVm()) {
// update vm
vmInstance.setDisplayVm(isDisplayVm);
// Resource limit changes
final ServiceOffering offering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId());
_resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.user_vm, isDisplayVm);
_resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.cpu, isDisplayVm, new Long(offering.getCpu()));
_resourceLimitMgr.changeResourceCount(vmInstance.getAccountId(), ResourceType.memory, isDisplayVm, new Long(offering.getRamSize()));
// take care of the root volume as well.
final List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(id, VolumeType.ROOT);
if (!rootVols.isEmpty()) {
_volumeService.updateDisplay(rootVols.get(0), isDisplayVm);
}
// take care of the data volumes as well.
final List<VolumeVO> dataVols = _volsDao.findByInstanceAndType(id, VolumeType.DATADISK);
for (final Volume dataVol : dataVols) {
_volumeService.updateDisplay(dataVol, isDisplayVm);
}
}
if (details != null && !details.isEmpty()) {
_vmDao.loadDetails(vmInstance);
for (final Map.Entry<String, String> entry : details.entrySet()) {
if (entry instanceof Map.Entry) {
vmInstance.setDetail(entry.getKey(), entry.getValue());
}
}
_vmDao.saveDetails(vmInstance);
}
return updateVirtualMachine(id, displayName, group, ha, isDisplayVm, osTypeId, userData, isDynamicallyScalable, cmd.getHttpMethod(), cmd.getCustomId(), hostName, cmd.getInstanceName(), manufacturerString, optimiseFor, requiresRestart, maintenancePolicy, bootMenuTimeout, bootOrder, complianceStatus);
}
use of com.cloud.model.enumeration.OptimiseFor in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method createPrivateTemplate.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true)
public VirtualMachineTemplate createPrivateTemplate(final CreateTemplateCmd command) throws CloudRuntimeException {
final long templateId = command.getEntityId();
Long volumeId = command.getVolumeId();
final Long snapshotId = command.getSnapshotId();
VMTemplateVO privateTemplate = null;
final Long accountId = CallContext.current().getCallingAccountId();
SnapshotVO snapshot = null;
VolumeVO volume = null;
OptimiseFor optimiseFor = command.getOptimiseFor();
String manufacturerString = command.getManufacturerString();
String cpuFlags = command.getCpuFlags();
Boolean macLearning = command.getMacLearning();
MaintenancePolicy maintenancePolicy = command.getMaintenancePolicy();
try {
final TemplateInfo tmplInfo = this._tmplFactory.getTemplate(templateId, DataStoreRole.Image);
long zoneId = 0;
if (snapshotId != null) {
snapshot = this._snapshotDao.findById(snapshotId);
zoneId = snapshot.getDataCenterId();
} else if (volumeId != null) {
volume = this._volumeDao.findById(volumeId);
zoneId = volume.getDataCenterId();
}
DataStore store = this._dataStoreMgr.getImageStore(zoneId);
if (store == null) {
throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
}
final AsyncCallFuture<TemplateApiResult> future;
if (snapshotId != null) {
final DataStoreRole dataStoreRole = ApiResponseHelper.getDataStoreRole(snapshot, this._snapshotStoreDao, this._dataStoreMgr);
SnapshotInfo snapInfo = this._snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (dataStoreRole == DataStoreRole.Image) {
if (snapInfo == null) {
snapInfo = this._snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId);
}
if (volumeId == null) {
volumeId = snapInfo.getVolumeId();
}
// We need to copy the snapshot onto secondary.
final SnapshotStrategy snapshotStrategy = this._storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
snapshotStrategy.backupSnapshot(snapInfo);
// Attempt to grab it again.
snapInfo = this._snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId + " on secondary and could not create backup");
}
}
final DataStore snapStore = snapInfo.getDataStore();
if (snapStore != null) {
// pick snapshot image store to create template
store = snapStore;
}
}
future = this._tmpltSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store);
} else if (volumeId != null) {
final VolumeInfo volInfo = this._volFactory.getVolume(volumeId);
future = this._tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
} else {
throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
}
if (volume != null) {
final VMInstanceVO vm = this._vmInstanceDao.findById(volume.getInstanceId());
if (vm != null) {
if (optimiseFor == null) {
optimiseFor = vm.getOptimiseFor();
}
if (manufacturerString == null) {
manufacturerString = vm.getManufacturerString();
}
if (cpuFlags == null) {
cpuFlags = vm.getCpuFlags();
}
if (macLearning == null) {
macLearning = vm.getMacLearning();
}
if (maintenancePolicy == null) {
maintenancePolicy = vm.getMaintenancePolicy();
}
}
}
final CommandResult result;
try {
result = future.get();
if (result.isFailed()) {
s_logger.debug("Failed to create template" + result.getResult());
throw new CloudRuntimeException("Failed to create template" + result.getResult());
}
// create entries in template_zone_ref table
if (this._dataStoreMgr.isRegionStore(store)) {
// template created on region store
this._tmpltSvr.associateTemplateToZone(templateId, null);
} else {
final VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
this._tmpltZoneDao.persist(templateZone);
}
if (optimiseFor == null) {
optimiseFor = OptimiseFor.Generic;
}
if (maintenancePolicy == null) {
maintenancePolicy = MaintenancePolicy.LiveMigrate;
}
privateTemplate = this._tmpltDao.findById(templateId);
privateTemplate.setCpuFlags(cpuFlags);
privateTemplate.setMacLearning(macLearning);
privateTemplate.setManufacturerString(manufacturerString);
privateTemplate.setOptimiseFor(optimiseFor);
privateTemplate.setMaintenancePolicy(maintenancePolicy);
this._tmpltDao.persist(privateTemplate);
} catch (final InterruptedException | ExecutionException e) {
s_logger.debug("Failed to create template", e);
throw new CloudRuntimeException("Failed to create template", e);
}
} finally {
if (privateTemplate == null) {
final VolumeVO volumeFinal = volume;
final SnapshotVO snapshotFinal = snapshot;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
// template_store_ref entries should have been removed using our
// DataObject.processEvent command in case of failure, but clean
// it up here to avoid
// some leftovers which will cause removing template from
// vm_template table fail.
TemplateManagerImpl.this._tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template_zone_ref record
TemplateManagerImpl.this._tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template record
TemplateManagerImpl.this._tmpltDao.expunge(templateId);
// decrement resource count
if (accountId != null) {
TemplateManagerImpl.this._resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
TemplateManagerImpl.this._resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volumeFinal != null ? volumeFinal.getSize() : snapshotFinal.getSize()));
}
}
});
}
}
if (privateTemplate != null) {
return privateTemplate;
} else {
throw new CloudRuntimeException("Failed to create a template");
}
}
use of com.cloud.model.enumeration.OptimiseFor in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method updateTemplateOrIso.
private VMTemplateVO updateTemplateOrIso(final BaseUpdateTemplateOrIsoCmd cmd) {
final Long id = cmd.getId();
final String name = cmd.getTemplateName();
final String displayText = cmd.getDisplayText();
final String format = cmd.getFormat();
final Long guestOSId = cmd.getOsTypeId();
final Boolean passwordEnabled = cmd.getPasswordEnabled();
final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
final Boolean isRoutingTemplate = cmd.isRoutingType();
final Boolean bootable = cmd.getBootable();
final Integer sortKey = cmd.getSortKey();
final Map details = cmd.getDetails();
final Account account = CallContext.current().getCallingAccount();
final String url = cmd.getUrl();
final OptimiseFor optimiseFor = cmd.getOptimiseFor();
final String manufacturerString = cmd.getManufacturerString();
final String cpuFlags = cmd.getCpuFlags();
final Boolean macLearning = cmd.getMacLearning();
final MaintenancePolicy maintenancePolicy = cmd.getMaintenancePolicy();
final Boolean isRemoteGatewayTemplate = cmd.getIsRemoteGatewayTemplate();
// verify that template exists
VMTemplateVO template = this._tmpltDao.findById(id);
if (template == null || template.getRemoved() != null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
ex.addProxyObject(String.valueOf(id), "templateId");
throw ex;
}
verifyTemplateId(id);
// do a permission check
this._accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
if (cmd.isRoutingType() != null) {
if (!this._accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
}
}
// update is needed if any of the fields below got filled by the user
final boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && optimiseFor == null && manufacturerString == null && isRemoteGatewayTemplate == null && cpuFlags == null && macLearning == null && passwordEnabled == null && bootable == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && url == null && details == null);
if (!updateNeeded) {
return template;
}
template = this._tmpltDao.createForUpdate(id);
if (name != null) {
template.setName(name);
}
if (displayText != null) {
template.setDisplayText(displayText);
}
if (sortKey != null) {
template.setSortKey(sortKey);
}
if (optimiseFor != null) {
template.setOptimiseFor(optimiseFor);
}
if (manufacturerString != null) {
template.setManufacturerString(manufacturerString);
}
if (cpuFlags != null) {
template.setCpuFlags(cpuFlags);
}
if (macLearning != null) {
template.setMacLearning(macLearning);
}
if (maintenancePolicy != null) {
template.setMaintenancePolicy(maintenancePolicy);
}
if (isRemoteGatewayTemplate != null) {
template.setRemoteGatewayTemplate(isRemoteGatewayTemplate);
}
final ImageFormat imageFormat;
if (format != null) {
try {
imageFormat = ImageFormat.valueOf(format.toUpperCase());
} catch (final IllegalArgumentException e) {
throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
template.setFormat(imageFormat);
}
if (guestOSId != null) {
final long oldGuestOSId = template.getGuestOSId();
final GuestOSVO guestOS = this._guestOSDao.findById(guestOSId);
if (guestOS == null) {
throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
} else {
template.setGuestOSId(guestOSId);
}
if (guestOSId != oldGuestOSId) {
// vm guest os type need to be updated if template guest os id changes.
final SearchCriteria<VMInstanceVO> sc = this._vmInstanceDao.createSearchCriteria();
sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
final List<VMInstanceVO> vms = this._vmInstanceDao.search(sc, null);
if (vms != null && !vms.isEmpty()) {
for (final VMInstanceVO vm : vms) {
vm.setGuestOSId(guestOSId);
this._vmInstanceDao.update(vm.getId(), vm);
}
}
}
}
if (passwordEnabled != null) {
template.setEnablePassword(passwordEnabled);
}
if (bootable != null) {
template.setBootable(bootable);
}
if (isDynamicallyScalable != null) {
template.setDynamicallyScalable(isDynamicallyScalable);
}
if (url != null) {
template.setUrl(url);
}
if (isRoutingTemplate != null) {
if (isRoutingTemplate) {
template.setTemplateType(TemplateType.ROUTING);
} else {
template.setTemplateType(TemplateType.USER);
}
}
if (details != null && !details.isEmpty()) {
template.setDetails(details);
this._tmpltDao.saveDetails(template);
}
this._tmpltDao.update(id, template);
return this._tmpltDao.findById(id);
}
use of com.cloud.model.enumeration.OptimiseFor in project cosmic by MissionCriticalCloud.
the class TemplateAdapterBase method prepare.
@Override
public TemplateProfile prepare(final boolean isIso, final long userId, final String name, final String displayText, Integer bits, Boolean passwordEnabled, final String url, Boolean isPublic, Boolean featured, Boolean isExtractable, final String format, Long guestOSId, Long zoneId, final HypervisorType hypervisorType, final String chksum, Boolean bootable, final String templateTag, final Account templateOwner, Map details, Boolean sshkeyEnabled, final String imageStoreUuid, final Boolean isDynamicallyScalable, final TemplateType templateType, final String manufacturerString, final OptimiseFor optimiseFor, final MaintenancePolicy maintenancePolicy, Boolean isRemoteGatewayTemplate) throws ResourceAllocationException {
if (isPublic == null) {
isPublic = Boolean.FALSE;
}
if (zoneId.longValue() == -1) {
zoneId = null;
}
if (isIso) {
if (bootable == null) {
bootable = Boolean.TRUE;
}
final GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
if ((guestOSId == null || noneGuestOs == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
}
if (bootable == false) {
// Guest os id of None.
guestOSId = noneGuestOs.getId();
}
} else {
if (bits == null) {
bits = Integer.valueOf(64);
}
if (passwordEnabled == null) {
passwordEnabled = false;
}
}
if (isExtractable == null) {
isExtractable = Boolean.FALSE;
}
if (sshkeyEnabled == null) {
sshkeyEnabled = Boolean.FALSE;
}
if (isRemoteGatewayTemplate == null) {
isRemoteGatewayTemplate = Boolean.FALSE;
}
final boolean isAdmin = _accountMgr.isRootAdmin(templateOwner.getId());
boolean isRegionStore = false;
final List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
if (stores != null && stores.size() > 0) {
isRegionStore = true;
}
if (!isAdmin && zoneId == null && !isRegionStore) {
// domain admin and user should also be able to register template on a region store
throw new InvalidParameterValueException("Please specify a valid zone Id. Only admins can create templates in all zones.");
}
// check for the url format only when url is not null. url can be null incase of form based upload
if (url != null && url.toLowerCase().contains("file://")) {
throw new InvalidParameterValueException("File:// type urls are currently unsupported");
}
// check whether owner can create public templates
final boolean allowPublicUserTemplates = TemplateManager.AllowPublicUserTemplates.valueIn(templateOwner.getId());
if (!isAdmin && !allowPublicUserTemplates && isPublic) {
throw new InvalidParameterValueException("Only private templates/ISO can be created.");
}
if (!isAdmin || featured == null) {
featured = Boolean.FALSE;
}
final ImageFormat imgfmt;
try {
imgfmt = ImageFormat.valueOf(format.toUpperCase());
} catch (final IllegalArgumentException e) {
s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
// Check that the resource limit for templates/ISOs won't be exceeded
final UserVO user = _userDao.findById(userId);
if (user == null) {
throw new IllegalArgumentException("Unable to find user with id " + userId);
}
_resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
// If a zoneId is specified, make sure it is valid
if (zoneId != null) {
final DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new IllegalArgumentException("Please specify a valid zone.");
}
final Account caller = CallContext.current().getCallingAccount();
if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
}
final List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
for (final VMTemplateVO template : systemvmTmplts) {
if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) {
throw new IllegalArgumentException("Cannot use reserved names for templates");
}
}
if (hypervisorType.equals(HypervisorType.XenServer)) {
if (details == null || !details.containsKey("hypervisortoolsversion") || details.get("hypervisortoolsversion") == null || ((String) details.get("hypervisortoolsversion")).equalsIgnoreCase("none")) {
final String hpvs = _configDao.getValue(Config.XenServerPVdriverVersion.key());
if (hpvs != null) {
if (details == null) {
details = new HashMap<String, String>();
}
details.put("hypervisortoolsversion", hpvs);
}
}
}
// When template contains Win, it should be set to OptimiseFor Windows
OptimiseFor correctedOptimiseFor = optimiseFor;
if (name != null && name.toLowerCase().contains("win") && optimiseFor != OptimiseFor.Windows) {
s_logger.debug("Template name '" + name + "' contains 'win' so setting OptimiseFor to Windows");
correctedOptimiseFor = OptimiseFor.Windows;
}
final Long id = _tmpltDao.getNextInSequence(Long.class, "id");
CallContext.current().setEventDetails("Id: " + id + " name: " + name);
return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, url, isPublic, featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, null, isDynamicallyScalable, templateType, manufacturerString, correctedOptimiseFor, maintenancePolicy, isRemoteGatewayTemplate);
}
Aggregations