use of com.cloud.model.enumeration.ImageFormat in project cosmic by MissionCriticalCloud.
the class TemplateLocation method load.
public boolean load() throws IOException {
try (final FileInputStream strm = new FileInputStream(this._file)) {
this._props.load(strm);
} catch (final IOException e) {
s_logger.warn("Unable to load the template properties", e);
}
for (final ImageFormat format : ImageFormat.values()) {
final String ext = this._props.getProperty(format.toString().toLowerCase());
if (ext != null) {
final TemplateFormatInfo info = new TemplateFormatInfo();
info.format = format;
info.filename = this._props.getProperty(format.toString().toLowerCase() + ".filename");
if (info.filename == null) {
continue;
}
info.size = NumbersUtil.parseLong(this._props.getProperty(format.toString().toLowerCase() + ".size"), -1);
this._props.setProperty("physicalSize", Long.toString(info.size));
info.virtualSize = NumbersUtil.parseLong(this._props.getProperty(format.toString().toLowerCase() + ".virtualsize"), -1);
this._formats.add(info);
if (!checkFormatValidity(info)) {
this._isCorrupted = true;
s_logger.warn("Cleaning up inconsistent information for " + format);
}
}
}
if (this._props.getProperty("uniquename") == null || this._props.getProperty("virtualsize") == null) {
return false;
}
return (this._formats.size() > 0);
}
use of com.cloud.model.enumeration.ImageFormat in project cosmic by MissionCriticalCloud.
the class KvmStorageProcessor method attachOrDetachDisk.
private synchronized String attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KvmPhysicalDisk attachingDisk, final int devId, final DiskControllerType diskControllerType, final ImageFormat diskFormat, final String serial, final VolumeObjectTO volumeObjectTO) throws LibvirtException, InternalErrorException {
final List<LibvirtDiskDef> disks;
Domain dm = null;
LibvirtDiskDef diskdef = null;
final KvmStoragePool attachingPool = attachingDisk.getPool();
try {
dm = conn.domainLookupByName(vmName);
final LibvirtDomainXmlParser parser = new LibvirtDomainXmlParser();
final String domXml = dm.getXMLDesc(0);
parser.parseDomainXml(domXml);
disks = parser.getDisks();
if (!attach) {
for (final LibvirtDiskDef disk : disks) {
final String file = disk.getDiskPath();
if (file != null && file.equalsIgnoreCase(attachingDisk.getPath())) {
diskdef = disk;
break;
}
}
if (diskdef == null) {
throw new InternalErrorException("disk: " + attachingDisk.getPath() + " is not attached before");
}
} else {
diskdef = new LibvirtDiskDef();
if (diskControllerType == DiskControllerType.SCSI) {
diskdef.setQemuDriver(true);
diskdef.setDiscard(LibvirtDiskDef.DiscardType.UNMAP);
}
diskdef.setSerial(serial);
diskdef.setDeviceId(devId);
Optional.ofNullable(volumeObjectTO.getBytesReadRate()).filter(bps -> bps > 0).ifPresent(diskdef::setBytesReadRate);
Optional.ofNullable(volumeObjectTO.getBytesWriteRate()).filter(bps -> bps > 0).ifPresent(diskdef::setBytesWriteRate);
if (volumeObjectTO.getIopsTotalRate() == null) {
Optional.ofNullable(volumeObjectTO.getIopsReadRate()).filter(iops -> iops > 0).ifPresent(diskdef::setIopsReadRate);
Optional.ofNullable(volumeObjectTO.getIopsWriteRate()).filter(iops -> iops > 0).ifPresent(diskdef::setIopsWriteRate);
} else {
Optional.ofNullable(volumeObjectTO.getIopsTotalRate()).filter(iops -> iops > 0).ifPresent(diskdef::setIopsTotalRate);
}
if (attachingPool.getType() == StoragePoolType.RBD) {
diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), attachingPool.getUuid(), devId, diskControllerType, LibvirtDiskDef.DiskProtocol.RBD, ImageFormat.RAW);
} else if (attachingPool.getType() == StoragePoolType.Gluster) {
final String mountpoint = attachingPool.getLocalPath();
final String path = attachingDisk.getPath();
final String glusterVolume = attachingPool.getSourceDir().replace("/", "");
diskdef.defNetworkBasedDisk(glusterVolume + path.replace(mountpoint, ""), attachingPool.getSourceHost(), attachingPool.getSourcePort(), null, null, devId, diskControllerType, LibvirtDiskDef.DiskProtocol.GLUSTER, ImageFormat.QCOW2);
} else if (attachingPool.getType() == StoragePoolType.NetworkFilesystem) {
diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, diskControllerType, diskFormat);
} else if (attachingPool.getType() == StoragePoolType.LVM) {
diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, diskControllerType);
}
}
final String xml = diskdef.toString();
return attachOrDetachDevice(conn, attach, vmName, xml);
} finally {
if (dm != null) {
dm.free();
}
}
}
use of com.cloud.model.enumeration.ImageFormat in project cosmic by MissionCriticalCloud.
the class LaunchPermissionDaoImpl method listPermittedTemplates.
@Override
public List<VMTemplateVO> listPermittedTemplates(final long accountId) {
final TransactionLegacy txn = TransactionLegacy.currentTxn();
final List<VMTemplateVO> permittedTemplates = new ArrayList<>();
PreparedStatement pstmt = null;
try {
final String sql = LIST_PERMITTED_TEMPLATES;
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, accountId);
final ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
final long id = rs.getLong(1);
final String uniqueName = rs.getString(2);
final String name = rs.getString(3);
final boolean isPublic = rs.getBoolean(4);
final String value = rs.getString(5);
final ImageFormat format = ImageFormat.valueOf(value);
final String tmpltType = rs.getString(6);
final int bits = rs.getInt(8);
final String url = rs.getString(9);
final String createdTS = rs.getString(10);
final long templateAccountId = rs.getLong(11);
final String checksum = rs.getString(12);
final String displayText = rs.getString(13);
final boolean enablePassword = rs.getBoolean(14);
final long guestOSId = rs.getLong(15);
final boolean featured = rs.getBoolean(16);
Date createdDate = null;
if (createdTS != null) {
createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS);
}
if (isPublic) {
// if it's public already, skip adding it to
continue;
// permitted templates as this for private
// templates only
}
final VMTemplateVO template = new VMTemplateVO(id, uniqueName, name, format, isPublic, featured, TemplateType.valueOf(tmpltType), url, createdDate, bits, templateAccountId, checksum, displayText, enablePassword, guestOSId, true, null);
permittedTemplates.add(template);
}
} catch (final Exception e) {
s_logger.warn("Error listing permitted templates", e);
}
return permittedTemplates;
}
use of com.cloud.model.enumeration.ImageFormat in project cosmic by MissionCriticalCloud.
the class VolumeApiServiceImpl method allocVolume.
/*
* Just allocate a volume in the database, don't send the createvolume cmd
* to hypervisor. The volume will be finally created only when it's attached
* to a VM.
*/
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", create = true)
public VolumeVO allocVolume(final CreateVolumeCmd cmd) throws ResourceAllocationException {
// FIXME: some of the scheduled event stuff might be missing here...
final Account caller = CallContext.current().getCallingAccount();
final long ownerId = cmd.getEntityOwnerId();
final Account owner = this._accountMgr.getActiveAccountById(ownerId);
Boolean displayVolume = cmd.getDisplayVolume();
// permission check
this._accountMgr.checkAccess(caller, null, true, this._accountMgr.getActiveAccountById(ownerId));
if (displayVolume == null) {
displayVolume = true;
} else {
if (!this._accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot update parameter displayvolume, only admin permitted ");
}
}
// Check that the resource limit for volumes won't be exceeded
this._resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, displayVolume);
Long zoneId = cmd.getZoneId();
final Long diskOfferingId;
final DiskOfferingVO diskOffering;
final StorageProvisioningType provisioningType;
Long size;
Long minIops = null;
Long maxIops = null;
// Volume VO used for extracting the source template id
VolumeVO parentVolume = null;
// validate input parameters before creating the volume
if (cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null || cmd.getSnapshotId() != null && cmd.getDiskOfferingId() != null) {
throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume");
}
if (cmd.getSnapshotId() == null) {
// create a new volume
diskOfferingId = cmd.getDiskOfferingId();
size = cmd.getSize();
final Long sizeInGB = size;
if (size != null) {
if (size > 0) {
// user specify size in GB
size = size * 1024 * 1024 * 1024;
} else {
throw new InvalidParameterValueException("Disk size must be larger than 0");
}
}
// Check that the the disk offering is specified
diskOffering = this._diskOfferingDao.findById(diskOfferingId);
if (diskOffering == null || diskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
throw new InvalidParameterValueException("Please specify a valid disk offering.");
}
if (diskOffering.isCustomized()) {
if (size == null) {
throw new InvalidParameterValueException("This disk offering requires a custom size specified");
}
final Long customDiskOfferingMaxSize = this._volumeMgr.CustomDiskOfferingMaxSize.value();
final Long customDiskOfferingMinSize = this._volumeMgr.CustomDiskOfferingMinSize.value();
if (sizeInGB < customDiskOfferingMinSize || sizeInGB > customDiskOfferingMaxSize) {
throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
}
}
if (!diskOffering.isCustomized() && size != null) {
throw new InvalidParameterValueException("This disk offering does not allow custom size");
}
if (diskOffering.getDomainId() == null) {
// do nothing as offering is public
} else {
this._configMgr.checkDiskOfferingAccess(caller, diskOffering);
}
if (diskOffering.getDiskSize() > 0) {
size = diskOffering.getDiskSize();
}
final Boolean isCustomizedIops = diskOffering.isCustomizedIops();
if (isCustomizedIops != null) {
if (isCustomizedIops) {
minIops = cmd.getMinIops();
maxIops = cmd.getMaxIops();
if (minIops == null && maxIops == null) {
minIops = 0L;
maxIops = 0L;
} else {
if (minIops == null || minIops <= 0) {
throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
}
if (maxIops == null) {
maxIops = 0L;
}
if (minIops > maxIops) {
throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
}
}
} else {
minIops = diskOffering.getMinIops();
maxIops = diskOffering.getMaxIops();
}
}
provisioningType = diskOffering.getProvisioningType();
if (!validateVolumeSizeRange(size)) {
// for validation
throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + this._maxVolumeSizeInGb);
}
} else {
// create volume from snapshot
final Long snapshotId = cmd.getSnapshotId();
final SnapshotVO snapshotCheck = this._snapshotDao.findById(snapshotId);
if (snapshotCheck == null) {
throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
}
if (snapshotCheck.getState() != Snapshot.State.BackedUp) {
throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume " + "creation");
}
parentVolume = this._volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId());
diskOfferingId = snapshotCheck.getDiskOfferingId();
diskOffering = this._diskOfferingDao.findById(diskOfferingId);
if (zoneId == null) {
// if zoneId is not provided, we default to create volume in the same zone as the snapshot zone.
zoneId = snapshotCheck.getDataCenterId();
}
// ; disk offering is used for tags
size = snapshotCheck.getSize();
// purposes
minIops = snapshotCheck.getMinIops();
maxIops = snapshotCheck.getMaxIops();
provisioningType = diskOffering.getProvisioningType();
// check snapshot permissions
this._accountMgr.checkAccess(caller, null, true, snapshotCheck);
// one step operation - create volume in VM's cluster and attach it
// to the VM
final Long vmId = cmd.getVirtualMachineId();
if (vmId != null) {
// Check that the virtual machine ID is valid and it's a user vm
final UserVmVO vm = this._userVmDao.findById(vmId);
if (vm == null || vm.getType() != VirtualMachineType.User) {
throw new InvalidParameterValueException("Please specify a valid User VM.");
}
// Check that the VM is in the correct state
if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
}
// permission check
this._accountMgr.checkAccess(caller, null, false, vm);
}
}
// Check that the resource limit for primary storage won't be exceeded
this._resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, displayVolume, new Long(size));
// Verify that zone exists
final DataCenterVO zone = this._dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
}
// Check if zone is disabled
if (AllocationState.Disabled == zone.getAllocationState() && !this._accountMgr.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
final String userSpecifiedName = getVolumeNameFromCommand(cmd);
DiskControllerType diskControllerType = getDiskControllerType();
if (cmd.getDiskController() != null) {
diskControllerType = DiskControllerType.valueOf(cmd.getDiskController().toUpperCase());
}
ImageFormat fileFormat = ImageFormat.QCOW2;
if (cmd.getFileFormat() != null) {
fileFormat = ImageFormat.valueOf(cmd.getFileFormat().toUpperCase());
}
return commitVolume(cmd, caller, owner, displayVolume, zoneId, diskOfferingId, provisioningType, size, minIops, maxIops, parentVolume, userSpecifiedName, this._uuidMgr.generateUuid(Volume.class, cmd.getCustomId()), diskControllerType, fileFormat);
}
use of com.cloud.model.enumeration.ImageFormat 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