use of com.cloud.common.storageprocessor.TemplateLocation in project cosmic by MissionCriticalCloud.
the class DownloadManagerImpl method postLocalDownload.
/**
* Post local download activity (install and cleanup). Executed in context of
* downloader thread
*
* @throws IOException
*/
private String postLocalDownload(final String jobId) {
final DownloadJob dnld = this.jobs.get(jobId);
final TemplateDownloader td = dnld.getTemplateDownloader();
// path with mount
final String resourcePath = dnld.getInstallPathPrefix();
// directory
// template download
final String finalResourcePath = dnld.getTmpltPath();
// path on secondary
// storage
final ResourceType resourceType = dnld.getResourceType();
final File originalTemplate = new File(td.getDownloadLocalPath());
final 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(this._storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
// add one just in case
imgSizeGigs++;
final long timeout = (long) imgSizeGigs * this.installTimeoutPerGig;
Script scr = null;
final String script = resourceType == ResourceType.TEMPLATE ? this.createTmpltScr : this.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());
}
// add options common to ISO and template
final String extension = dnld.getFormat().toString().toLowerCase();
String templateName = "";
if (extension.equals("iso")) {
templateName = this.jobs.get(jobId).getTmpltName().trim().replace(" ", "_");
} else {
templateName = java.util.UUID.nameUUIDFromBytes((this.jobs.get(jobId).getTmpltName() + System.currentTimeMillis()).getBytes(StringUtils.getPreferredCharset())).toString();
}
// run script to mv the temporary template file to the final template
// file
final 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");
final String result;
result = scr.execute();
if (result != null) {
return result;
}
// Set permissions for the downloaded template
final File downloadedTemplate = new File(resourcePath + "/" + templateFilename);
this._storage.setWorldReadableAndWriteable(downloadedTemplate);
// Set permissions for template/volume.properties
String propertiesFile = resourcePath;
if (resourceType == ResourceType.TEMPLATE) {
propertiesFile += "/template.properties";
} else {
propertiesFile += "/volume.properties";
}
final File templateProperties = new File(propertiesFile);
this._storage.setWorldReadableAndWriteable(templateProperties);
final TemplateLocation loc = new TemplateLocation(this._storage, resourcePath);
try {
loc.create(dnld.getId(), true, dnld.getTmpltName());
} catch (final IOException e) {
s_logger.warn("Something is wrong with template location " + resourcePath, e);
loc.purge();
return "Unable to download due to " + e.getMessage();
}
final Iterator<Processor> en = this._processors.values().iterator();
while (en.hasNext()) {
final Processor processor = en.next();
TemplateFormatInfo 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) {
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;
}
use of com.cloud.common.storageprocessor.TemplateLocation in project cosmic by MissionCriticalCloud.
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;
final KvmStoragePool primary;
try {
final String templateFolder = template.getPath();
secondaryStorage = this.storagePoolMgr.getStoragePoolByUri(nfsImageStore.getUrl());
primary = this.storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
final KvmPhysicalDisk disk = this.storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), volume.getPath());
final String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateFolder;
this.storageLayer.mkdirs(tmpltPath);
final String templateName = UUID.randomUUID().toString();
if (primary.getType() != StoragePoolType.RBD) {
final Script command = new Script(this.createTmplPath, wait, this.logger);
command.add("-f", disk.getPath());
command.add("-t", tmpltPath);
command.add("-n", templateName + ".qcow2");
final String result = command.execute();
if (result != null) {
this.logger.debug("failed to create template: " + result);
return new CopyCmdAnswer(result);
}
} else {
this.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 (final FileOutputStream templFo = new FileOutputStream(templateProp)) {
templFo.write(templateContent.getBytes());
templFo.flush();
} catch (final IOException e) {
throw e;
}
}
final Map<String, Object> params = new HashMap<>();
params.put(StorageLayer.InstanceConfigKey, this.storageLayer);
final Processor qcow2Processor = new QCOW2Processor();
qcow2Processor.configure("QCOW2 Processor", params);
final TemplateFormatInfo info = qcow2Processor.process(tmpltPath, null, templateName);
final TemplateLocation loc = new TemplateLocation(this.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) {
this.logger.error(e.getMessage());
return new CopyCmdAnswer(e.toString());
} catch (final Exception e) {
this.logger.debug("Failed to createTemplateFromVolume: ", e);
return new CopyCmdAnswer(e.toString());
} finally {
if (secondaryStorage != null) {
secondaryStorage.delete();
}
}
}
use of com.cloud.common.storageprocessor.TemplateLocation in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testCreatePrivateTemplateFromSnapshotCommandIOException.
@Test
public void testCreatePrivateTemplateFromSnapshotCommandIOException() {
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);
final TemplateFormatInfo info = Mockito.mock(TemplateFormatInfo.class);
when(this.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(this.libvirtComputingResource.getStorage()).thenReturn(storage);
when(this.libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
when(this.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(this.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)).thenReturn(info);
when(location.create(1, true, tmplName)).thenThrow(IOException.class);
} catch (final ConfigurationException e) {
fail(e.getMessage());
} catch (final InternalErrorException e) {
fail(e.getMessage());
} catch (final IOException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
assertFalse(answer.getResult());
verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(storagePoolMgr, times(1)).getStoragePoolByUri(command.getSecondaryStorageUrl() + snapshotPath);
verify(storagePoolMgr, times(1)).getStoragePoolByUri(command.getSecondaryStorageUrl());
}
use of com.cloud.common.storageprocessor.TemplateLocation in project cosmic by MissionCriticalCloud.
the class NfsSecondaryStorageResource method copySnapshotToTemplateFromNfsToNfsXenserver.
protected Answer copySnapshotToTemplateFromNfsToNfsXenserver(final CopyCommand cmd, final SnapshotObjectTO srcData, final NfsTO srcDataStore, final TemplateObjectTO destData, final NfsTO destDataStore) {
final String srcMountPoint = getRootDir(srcDataStore.getUrl());
String snapshotPath = srcData.getPath();
final 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;
final String destMountPoint = getRootDir(destDataStore.getUrl());
final String destPath = destMountPoint + File.separator + destData.getPath();
String errMsg = null;
try {
this._storage.mkdir(destPath);
final String templateUuid = UUID.randomUUID().toString();
final String templateName = templateUuid + ".vhd";
final Script command = new Script(this.createTemplateFromSnapshotXenScript, cmd.getWait() * 1000, s_logger);
command.add("-p", snapshotPath);
command.add("-s", snapshotName);
command.add("-n", templateName);
command.add("-t", destPath);
final String result = command.execute();
if (result != null && !result.equalsIgnoreCase("")) {
return new CopyCmdAnswer(result);
}
final Map<String, Object> params = new HashMap<>();
params.put(StorageLayer.InstanceConfigKey, this._storage);
final Processor processor = new VhdProcessor();
processor.configure("Vhd Processor", params);
final TemplateFormatInfo info = processor.process(destPath, null, templateUuid);
final TemplateLocation loc = new TemplateLocation(this._storage, destPath);
loc.create(1, true, templateUuid);
loc.addFormat(info);
loc.save();
final TemplateProp prop = loc.getTemplateInfo();
final 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 (final ConfigurationException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (final InternalErrorException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
} catch (final IOException e) {
s_logger.debug("Failed to create template from snapshot: " + e.toString());
errMsg = e.toString();
}
return new CopyCmdAnswer(errMsg);
}
use of com.cloud.common.storageprocessor.TemplateLocation in project cosmic by MissionCriticalCloud.
the class DownloadManagerImpl method gatherVolumeInfo.
@Override
public Map<Long, TemplateProp> gatherVolumeInfo(final String rootDir) {
final Map<Long, TemplateProp> result = new HashMap<>();
final String volumeDir = rootDir + File.separator + this._volumeDir;
if (!this._storage.exists(volumeDir)) {
this._storage.mkdirs(volumeDir);
}
final List<String> vols = listVolumes(volumeDir);
for (final String vol : vols) {
final String path = vol.substring(0, vol.lastIndexOf(File.separator));
final TemplateLocation loc = new TemplateLocation(this._storage, path);
try {
if (!loc.load()) {
s_logger.warn("Post download installation was not completed for " + path);
// loc.purge();
this._storage.cleanup(path, volumeDir);
continue;
}
} catch (final IOException e) {
s_logger.warn("Unable to load volume location " + path, e);
continue;
}
final TemplateProp vInfo = loc.getTemplateInfo();
result.put(vInfo.getId(), vInfo);
s_logger.debug("Added volume name: " + vInfo.getTemplateName() + ", path: " + vol);
}
return result;
}
Aggregations