use of com.cloud.storage.template.Processor in project cloudstack by apache.
the class KVMStorageProcessor method createTemplateFromVolume.
@Override
public Answer createTemplateFromVolume(final CopyCommand 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 = null;
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("-n", 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 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.Processor in project cloudstack by apache.
the class LibvirtUtilitiesHelper method buildQCOW2Processor.
public Processor buildQCOW2Processor(final StorageLayer storage) throws ConfigurationException {
final Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, storage);
final Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
return qcow2Processor;
}
use of com.cloud.storage.template.Processor in project cloudstack by apache.
the class NfsSecondaryStorageResource method copySnapshotToTemplateFromNfsToNfsXenserver.
protected Answer copySnapshotToTemplateFromNfsToNfsXenserver(CopyCommand cmd, SnapshotObjectTO srcData, NfsTO srcDataStore, TemplateObjectTO destData, NfsTO destDataStore) {
String srcMountPoint = getRootDir(srcDataStore.getUrl(), _nfsVersion);
String snapshotPath = srcData.getPath();
int index = snapshotPath.lastIndexOf("/");
String snapshotName = snapshotPath.substring(index + 1);
if (!snapshotName.startsWith("VHD-") && !snapshotName.endsWith(".vhd")) {
snapshotName = snapshotName + ".vhd";
}
snapshotPath = snapshotPath.substring(0, index);
snapshotPath = srcMountPoint + File.separator + snapshotPath;
String destMountPoint = getRootDir(destDataStore.getUrl(), _nfsVersion);
String destPath = destMountPoint + File.separator + destData.getPath();
String errMsg = null;
try {
_storage.mkdir(destPath);
String templateUuid = UUID.randomUUID().toString();
String templateName = templateUuid + ".vhd";
Script command = new Script(createTemplateFromSnapshotXenScript, cmd.getWait() * 1000, s_logger);
command.add("-p", snapshotPath);
command.add("-s", snapshotName);
command.add("-n", templateName);
command.add("-t", destPath);
String result = command.execute();
if (result != null && !result.equalsIgnoreCase("")) {
return new CopyCmdAnswer(result);
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
Processor processor = new VhdProcessor();
processor.configure("Vhd Processor", params);
FormatInfo info = processor.process(destPath, null, templateUuid);
TemplateLocation loc = new TemplateLocation(_storage, destPath);
loc.create(1, true, templateUuid);
loc.addFormat(info);
loc.save();
TemplateProp prop = loc.getTemplateInfo();
TemplateObjectTO newTemplate = new TemplateObjectTO();
newTemplate.setPath(destData.getPath() + File.separator + templateName);
newTemplate.setFormat(ImageFormat.VHD);
newTemplate.setSize(prop.getSize());
newTemplate.setPhysicalSize(prop.getPhysicalSize());
newTemplate.setName(templateUuid);
return new CopyCmdAnswer(newTemplate);
} catch (ConfigurationException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (InternalErrorException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (IOException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
}
return new CopyCmdAnswer(errMsg);
}
use of com.cloud.storage.template.Processor in project cloudstack by apache.
the class NfsSecondaryStorageResource method getVirtualSize.
protected long getVirtualSize(File file, ImageFormat format) {
Processor processor = null;
try {
if (format == null) {
return file.length();
} else if (format == ImageFormat.QCOW2) {
processor = new QCOW2Processor();
} else if (format == ImageFormat.OVA) {
processor = new OVAProcessor();
} else if (format == ImageFormat.VHD) {
processor = new VhdProcessor();
} else if (format == ImageFormat.RAW) {
processor = new RawImageProcessor();
} else if (format == ImageFormat.VMDK) {
processor = new VmdkProcessor();
}
if (format == ImageFormat.TAR) {
processor = new TARProcessor();
}
if (processor == null) {
return file.length();
}
Map<String, Object> params = new HashMap<String, Object>();
params.put(StorageLayer.InstanceConfigKey, _storage);
processor.configure("template processor", params);
return processor.getVirtualSize(file);
} catch (Exception e) {
s_logger.warn("Failed to get virtual size of file " + file.getPath() + ", returning file size instead: ", e);
return file.length();
}
}
use of com.cloud.storage.template.Processor in project cloudstack by apache.
the class DownloadManagerImpl method postLocalDownload.
/**
* Post local download activity (install and cleanup). Executed in context of
* downloader thread
*
* @throws IOException
*/
private String postLocalDownload(String jobId) {
DownloadJob dnld = jobs.get(jobId);
TemplateDownloader td = dnld.getTemplateDownloader();
// path with mount
String resourcePath = dnld.getInstallPathPrefix();
// directory
// template download
String finalResourcePath = dnld.getTmpltPath();
// path on secondary
// storage
ResourceType resourceType = dnld.getResourceType();
File originalTemplate = new File(td.getDownloadLocalPath());
String checkSum = computeCheckSum(originalTemplate);
if (checkSum == null) {
s_logger.warn("Something wrong happened when try to calculate the checksum of downloaded template!");
}
dnld.setCheckSum(checkSum);
int imgSizeGigs = (int) Math.ceil(_storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
// add one just in case
imgSizeGigs++;
long timeout = (long) imgSizeGigs * installTimeoutPerGig;
Script scr = null;
String script = resourceType == ResourceType.TEMPLATE ? createTmpltScr : createVolScr;
scr = new Script(script, timeout, s_logger);
scr.add("-s", Integer.toString(imgSizeGigs));
scr.add("-S", Long.toString(td.getMaxTemplateSizeInBytes()));
if (dnld.getDescription() != null && dnld.getDescription().length() > 1) {
scr.add("-d", dnld.getDescription());
}
if (dnld.isHvm()) {
scr.add("-h");
}
// add options common to ISO and template
String extension = dnld.getFormat().getFileExtension();
String templateName = "";
if (extension.equals("iso")) {
templateName = jobs.get(jobId).getTmpltName().trim().replace(" ", "_");
} else {
templateName = java.util.UUID.nameUUIDFromBytes((jobs.get(jobId).getTmpltName() + System.currentTimeMillis()).getBytes(StringUtils.getPreferredCharset())).toString();
}
// run script to mv the temporary template file to the final template
// file
String templateFilename = templateName + "." + extension;
dnld.setTmpltPath(finalResourcePath + "/" + templateFilename);
scr.add("-n", templateFilename);
scr.add("-t", resourcePath);
// this is the temporary
scr.add("-f", td.getDownloadLocalPath());
// template file downloaded
if (dnld.getChecksum() != null && dnld.getChecksum().length() > 1) {
scr.add("-c", dnld.getChecksum());
}
// cleanup
scr.add("-u");
String result;
result = scr.execute();
if (result != null) {
return result;
}
// Set permissions for the downloaded template
File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
_storage.setWorldReadableAndWriteable(downloadedTemplate);
// Set permissions for template/volume.properties
String propertiesFile = resourcePath;
if (resourceType == ResourceType.TEMPLATE) {
propertiesFile += "/template.properties";
} else {
propertiesFile += "/volume.properties";
}
File templateProperties = new File(propertiesFile);
_storage.setWorldReadableAndWriteable(templateProperties);
TemplateLocation loc = new TemplateLocation(_storage, resourcePath);
try {
loc.create(dnld.getId(), true, dnld.getTmpltName());
} catch (IOException e) {
s_logger.warn("Something is wrong with template location " + resourcePath, e);
loc.purge();
return "Unable to download due to " + e.getMessage();
}
Iterator<Processor> en = _processors.values().iterator();
while (en.hasNext()) {
Processor processor = en.next();
FormatInfo info = null;
try {
info = processor.process(resourcePath, null, templateName);
} catch (InternalErrorException e) {
s_logger.error("Template process exception ", e);
return e.toString();
}
if (info != null) {
if (!loc.addFormat(info)) {
loc.purge();
return "Unable to install due to invalid file format";
}
dnld.setTemplatesize(info.virtualSize);
dnld.setTemplatePhysicalSize(info.size);
break;
}
}
if (!loc.save()) {
s_logger.warn("Cleaning up because we're unable to save the formats");
loc.purge();
}
return null;
}
Aggregations