use of com.cloud.storage.template.TemplateLocation in project CloudStack-archive by CloudStack-extras.
the class LibvirtComputingResource method execute.
protected CreatePrivateTemplateAnswer execute(CreatePrivateTemplateFromVolumeCommand cmd) {
String secondaryStorageURL = cmd.getSecondaryStorageUrl();
KVMStoragePool secondaryStorage = null;
try {
Connect conn = LibvirtConnection.getConnection();
String templateFolder = cmd.getAccountId() + File.separator + cmd.getTemplateId() + File.separator;
String templateInstallFolder = "/template/tmpl/" + templateFolder;
secondaryStorage = _storagePoolMgr.getStoragePoolByURI(secondaryStorageURL);
KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd.getPrimaryStoragePoolNameLabel());
KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder;
_storage.mkdirs(tmpltPath);
Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
command.add("-f", disk.getPath());
command.add("-t", tmpltPath);
command.add("-n", cmd.getUniqueName() + ".qcow2");
String result = command.execute();
if (result != null) {
s_logger.debug("failed to create template: " + result);
return new CreatePrivateTemplateAnswer(cmd, false, result);
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(tmpltPath, null, cmd.getUniqueName());
TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
loc.create(1, true, cmd.getUniqueName());
loc.addFormat(info);
loc.save();
return new CreatePrivateTemplateAnswer(cmd, true, null, templateInstallFolder + cmd.getUniqueName() + ".qcow2", info.virtualSize, info.size, cmd.getUniqueName(), ImageFormat.QCOW2);
} catch (LibvirtException e) {
s_logger.debug("Failed to get secondary storage pool: " + e.toString());
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (InternalErrorException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (IOException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (ConfigurationException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} catch (CloudRuntimeException e) {
return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
use of com.cloud.storage.template.TemplateLocation in project cosmic by MissionCriticalCloud.
the class NfsSecondaryStorageResource method postUpload.
public String postUpload(final String uuid, final String filename) {
final UploadEntity uploadEntity = uploadEntityStateMap.get(uuid);
final int installTimeoutPerGig = 180 * 60 * 1000;
final String resourcePath = uploadEntity.getInstallPathPrefix();
// template download
final String finalResourcePath = uploadEntity.getTmpltPath();
final UploadEntity.ResourceType resourceType = uploadEntity.getResourceType();
final String fileSavedTempLocation = uploadEntity.getInstallPathPrefix() + "/" + filename;
final String uploadedFileExtension = FilenameUtils.getExtension(filename);
String userSelectedFormat = uploadEntity.getFormat().toString();
if (uploadedFileExtension.equals("zip") || uploadedFileExtension.equals("bz2") || uploadedFileExtension.equals("gz")) {
userSelectedFormat += "." + uploadedFileExtension;
}
final String formatError = ImageStoreUtil.checkTemplateFormat(fileSavedTempLocation, userSelectedFormat);
if (StringUtils.isNotBlank(formatError)) {
final String errorString = "File type mismatch between uploaded file and selected format. Selected file format: " + userSelectedFormat + ". Received: " + formatError;
s_logger.error(errorString);
return errorString;
}
int imgSizeGigs = getSizeInGB(_storage.getSize(fileSavedTempLocation));
final int maxSize = uploadEntity.getMaxSizeInGB();
if (imgSizeGigs > maxSize) {
final String errorMessage = "Maximum file upload size exceeded. Physical file size: " + imgSizeGigs + "GB. Maximum allowed size: " + maxSize + "GB.";
s_logger.error(errorMessage);
return errorMessage;
}
// add one just in case
imgSizeGigs++;
final long timeout = (long) imgSizeGigs * installTimeoutPerGig;
final Script scr = new Script(getScriptLocation(resourceType), timeout, s_logger);
scr.add("-s", Integer.toString(imgSizeGigs));
scr.add("-S", Long.toString(UploadEntity.s_maxTemplateSize));
if (uploadEntity.getDescription() != null && uploadEntity.getDescription().length() > 1) {
scr.add("-d", uploadEntity.getDescription());
}
if (uploadEntity.isHvm()) {
scr.add("-h");
}
final String checkSum = uploadEntity.getChksum();
if (StringUtils.isNotBlank(checkSum)) {
scr.add("-c", checkSum);
}
// add options common to ISO and template
final String extension = uploadEntity.getFormat().getFileExtension();
String templateName = "";
if (extension.equals("iso")) {
templateName = uploadEntity.getUuid().trim().replace(" ", "_");
} else {
try {
templateName = UUID.nameUUIDFromBytes((uploadEntity.getFilename() + System.currentTimeMillis()).getBytes("UTF-8")).toString();
} catch (final UnsupportedEncodingException e) {
templateName = uploadEntity.getUuid().trim().replace(" ", "_");
}
}
// run script to mv the temporary template file to the final template
// file
final String templateFilename = templateName + "." + extension;
uploadEntity.setTemplatePath(finalResourcePath + "/" + templateFilename);
scr.add("-n", templateFilename);
scr.add("-t", resourcePath);
// this is the temporary
scr.add("-f", fileSavedTempLocation);
// template file downloaded
if (uploadEntity.getChksum() != null && uploadEntity.getChksum().length() > 1) {
scr.add("-c", uploadEntity.getChksum());
}
// cleanup
scr.add("-u");
final String result;
result = scr.execute();
if (result != null) {
return result;
}
// Set permissions for the downloaded template
final File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
_storage.setWorldReadableAndWriteable(downloadedTemplate);
// Set permissions for template/volume.properties
String propertiesFile = resourcePath;
if (resourceType == UploadEntity.ResourceType.TEMPLATE) {
propertiesFile += "/template.properties";
} else {
propertiesFile += "/volume.properties";
}
final File templateProperties = new File(propertiesFile);
_storage.setWorldReadableAndWriteable(templateProperties);
final TemplateLocation loc = new TemplateLocation(_storage, resourcePath);
try {
loc.create(uploadEntity.getEntityId(), true, uploadEntity.getFilename());
} catch (final IOException e) {
s_logger.warn("Something is wrong with template location " + resourcePath, e);
loc.purge();
return "Unable to upload due to " + e.getMessage();
}
final Map<String, Processor> processors = _dlMgr.getProcessors();
for (final Processor processor : processors.values()) {
FormatInfo info = null;
try {
info = processor.process(resourcePath, null, templateName);
} catch (final InternalErrorException e) {
s_logger.error("Template process exception ", e);
return e.toString();
}
if (info != null) {
loc.addFormat(info);
uploadEntity.setVirtualSize(info.virtualSize);
uploadEntity.setPhysicalSize(info.size);
break;
}
}
if (!loc.save()) {
s_logger.warn("Cleaning up because we're unable to save the formats");
loc.purge();
}
uploadEntity.setStatus(UploadEntity.Status.COMPLETED);
uploadEntityStateMap.put(uploadEntity.getUuid(), uploadEntity);
return null;
}
use of com.cloud.storage.template.TemplateLocation in project cloudstack by apache.
the class KVMStorageProcessor method createTemplateFromVolumeOrSnapshot.
private Answer createTemplateFromVolumeOrSnapshot(CopyCommand cmd) {
DataTO srcData = cmd.getSrcTO();
final boolean isVolume;
if (srcData instanceof VolumeObjectTO) {
isVolume = true;
} else if (srcData instanceof SnapshotObjectTO) {
isVolume = false;
} else {
return new CopyCmdAnswer("unsupported object type");
}
PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
DataTO destData = cmd.getDestTO();
TemplateObjectTO template = (TemplateObjectTO) destData;
DataStoreTO imageStore = template.getDataStore();
if (!(imageStore instanceof NfsTO)) {
return new CopyCmdAnswer("unsupported protocol");
}
NfsTO nfsImageStore = (NfsTO) imageStore;
KVMStoragePool secondaryStorage = null;
try {
Map<String, String> details = cmd.getOptions();
String path = details != null ? details.get(DiskTO.IQN) : null;
if (path == null) {
new CloudRuntimeException("The 'path' field must be specified.");
}
storagePoolMgr.connectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), path, details);
KVMPhysicalDisk srcDisk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), path);
secondaryStorage = storagePoolMgr.getStoragePoolByURI(nfsImageStore.getUrl());
String templateFolder = template.getPath();
String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateFolder;
storageLayer.mkdirs(tmpltPath);
String templateName = UUID.randomUUID().toString();
s_logger.debug("Converting " + srcDisk.getFormat().toString() + " disk " + srcDisk.getPath() + " into template " + templateName);
String destName = templateFolder + "/" + templateName + ".qcow2";
storagePoolMgr.copyPhysicalDisk(srcDisk, destName, secondaryStorage, cmd.getWaitInMillSeconds());
File templateProp = new File(tmpltPath + "/template.properties");
if (!templateProp.exists()) {
templateProp.createNewFile();
}
String templateContent = "filename=" + templateName + ".qcow2" + System.getProperty("line.separator");
DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
Date date = new Date();
if (isVolume) {
templateContent += "volume.name=" + dateFormat.format(date) + System.getProperty("line.separator");
} else {
templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
}
FileOutputStream templFo = new FileOutputStream(templateProp);
templFo.write(templateContent.getBytes());
templFo.flush();
templFo.close();
Map<String, Object> params = new HashMap<>();
params.put(StorageLayer.InstanceConfigKey, storageLayer);
Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
FormatInfo info = qcow2Processor.process(tmpltPath, null, templateName);
TemplateLocation loc = new TemplateLocation(storageLayer, tmpltPath);
loc.create(1, true, templateName);
loc.addFormat(info);
loc.save();
storagePoolMgr.disconnectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), path);
TemplateObjectTO newTemplate = new TemplateObjectTO();
newTemplate.setPath(templateFolder + File.separator + templateName + ".qcow2");
newTemplate.setSize(info.virtualSize);
newTemplate.setPhysicalSize(info.size);
newTemplate.setFormat(ImageFormat.QCOW2);
newTemplate.setName(templateName);
return new CopyCmdAnswer(newTemplate);
} catch (Exception ex) {
if (isVolume) {
s_logger.debug("Failed to create template from volume: ", ex);
} else {
s_logger.debug("Failed to create template from snapshot: ", ex);
}
return new CopyCmdAnswer(ex.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
use of com.cloud.storage.template.TemplateLocation in project cloudstack by apache.
the class KVMStorageProcessor method createTemplateFromVolume.
@Override
public Answer createTemplateFromVolume(final CopyCommand cmd) {
Map<String, String> details = cmd.getOptions();
if (details != null && details.get(DiskTO.IQN) != null) {
// use the managed-storage approach
return createTemplateFromVolumeOrSnapshot(cmd);
}
final DataTO srcData = cmd.getSrcTO();
final DataTO destData = cmd.getDestTO();
final int wait = cmd.getWaitInMillSeconds();
final TemplateObjectTO template = (TemplateObjectTO) destData;
final DataStoreTO imageStore = template.getDataStore();
final VolumeObjectTO volume = (VolumeObjectTO) srcData;
final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) volume.getDataStore();
if (!(imageStore instanceof NfsTO)) {
return new CopyCmdAnswer("unsupported protocol");
}
final NfsTO nfsImageStore = (NfsTO) imageStore;
KVMStoragePool secondaryStorage = null;
KVMStoragePool primary;
try {
final String templateFolder = template.getPath();
secondaryStorage = storagePoolMgr.getStoragePoolByURI(nfsImageStore.getUrl());
primary = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
final KVMPhysicalDisk disk = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volume.getPath());
final String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateFolder;
storageLayer.mkdirs(tmpltPath);
final String templateName = UUID.randomUUID().toString();
if (primary.getType() != StoragePoolType.RBD) {
final Script command = new Script(_createTmplPath, wait, s_logger);
command.add("-f", disk.getPath());
command.add("-t", tmpltPath);
command.add(NAME_OPTION, templateName + ".qcow2");
final String result = command.execute();
if (result != null) {
s_logger.debug("failed to create template: " + result);
return new CopyCmdAnswer(result);
}
} else {
s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + templateName);
final QemuImgFile srcFile = new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(), primary.getAuthSecret(), disk.getPath()));
srcFile.setFormat(PhysicalDiskFormat.RAW);
final QemuImgFile destFile = new QemuImgFile(tmpltPath + "/" + templateName + ".qcow2");
destFile.setFormat(PhysicalDiskFormat.QCOW2);
final QemuImg q = new QemuImg(cmd.getWaitInMillSeconds());
try {
q.convert(srcFile, destFile);
} catch (final QemuImgException | LibvirtException e) {
final String message = "Failed to create new template while converting " + srcFile.getFileName() + " to " + destFile.getFileName() + " the error was: " + e.getMessage();
throw new QemuImgException(message);
}
final File templateProp = new File(tmpltPath + "/template.properties");
if (!templateProp.exists()) {
templateProp.createNewFile();
}
String templateContent = "filename=" + templateName + ".qcow2" + System.getProperty("line.separator");
final DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
final Date date = new Date();
templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
try (FileOutputStream templFo = new FileOutputStream(templateProp)) {
templFo.write(templateContent.getBytes());
templFo.flush();
} catch (final IOException e) {
throw e;
}
}
final Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, storageLayer);
final Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
final FormatInfo info = qcow2Processor.process(tmpltPath, null, templateName);
final TemplateLocation loc = new TemplateLocation(storageLayer, tmpltPath);
loc.create(1, true, templateName);
loc.addFormat(info);
loc.save();
final TemplateObjectTO newTemplate = new TemplateObjectTO();
newTemplate.setPath(templateFolder + File.separator + templateName + ".qcow2");
newTemplate.setSize(info.virtualSize);
newTemplate.setPhysicalSize(info.size);
newTemplate.setFormat(ImageFormat.QCOW2);
newTemplate.setName(templateName);
return new CopyCmdAnswer(newTemplate);
} catch (final QemuImgException e) {
s_logger.error(e.getMessage());
return new CopyCmdAnswer(e.toString());
} catch (final IOException e) {
s_logger.debug("Failed to createTemplateFromVolume: ", e);
return new CopyCmdAnswer(e.toString());
} catch (final Exception e) {
s_logger.debug("Failed to createTemplateFromVolume: ", e);
return new CopyCmdAnswer(e.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
use of com.cloud.storage.template.TemplateLocation in project cloudstack by apache.
the class LibvirtComputingResourceTest method testCreatePrivateTemplateFromSnapshotCommandInternalErrorException.
@SuppressWarnings("unchecked")
@Test
public void testCreatePrivateTemplateFromSnapshotCommandInternalErrorException() {
final StoragePool pool = Mockito.mock(StoragePool.class);
final String secondaryStoragePoolURL = "nfs:/127.0.0.1/storage/secondary";
final Long dcId = 1l;
final Long accountId = 1l;
final Long volumeId = 1l;
final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
final String backedUpSnapshotName = "snap";
final String origTemplateInstallPath = "/install/path/";
final Long newTemplateId = 2l;
final String templateName = "templ";
final int wait = 0;
final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
final String templatePath = "/template/path";
final String localPath = "/mnt/local";
final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
final StorageLayer storage = Mockito.mock(StorageLayer.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final TemplateLocation location = Mockito.mock(TemplateLocation.class);
final Processor qcow2Processor = Mockito.mock(Processor.class);
when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
String snapshotPath = command.getSnapshotUuid();
final int index = snapshotPath.lastIndexOf("/");
snapshotPath = snapshotPath.substring(0, index);
when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
when(secondaryPool.getLocalPath()).thenReturn(localPath);
when(libvirtComputingResource.getStorage()).thenReturn(storage);
when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
final String templateInstallFolder = "template/tmpl/" + templateFolder;
final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
when(libvirtUtilitiesHelper.generateUUIDName()).thenReturn(tmplName);
try {
when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
when(qcow2Processor.process(tmplPath, null, tmplName)).thenThrow(InternalErrorException.class);
} catch (final ConfigurationException e) {
fail(e.getMessage());
} catch (final InternalErrorException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, libvirtComputingResource);
assertFalse(answer.getResult());
verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
}
Aggregations