Search in sources :

Example 6 with Processor

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();
        }
    }
}
Also used : QCOW2Processor(com.cloud.storage.template.QCOW2Processor) StorageProcessor(com.cloud.storage.resource.StorageProcessor) Processor(com.cloud.storage.template.Processor) HashMap(java.util.HashMap) DataTO(com.cloud.agent.api.to.DataTO) TemplateLocation(com.cloud.storage.template.TemplateLocation) QemuImgException(org.apache.cloudstack.utils.qemu.QemuImgException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) Script(com.cloud.utils.script.Script) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) IOException(java.io.IOException) NfsTO(com.cloud.agent.api.to.NfsTO) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) LibvirtException(org.libvirt.LibvirtException) RbdException(com.ceph.rbd.RbdException) QemuImgException(org.apache.cloudstack.utils.qemu.QemuImgException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) RadosException(com.ceph.rados.exceptions.RadosException) IOException(java.io.IOException) QemuImg(org.apache.cloudstack.utils.qemu.QemuImg) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) QemuImgFile(org.apache.cloudstack.utils.qemu.QemuImgFile) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) FileOutputStream(java.io.FileOutputStream) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) FormatInfo(com.cloud.storage.template.Processor.FormatInfo) QemuImgFile(org.apache.cloudstack.utils.qemu.QemuImgFile) S3Utils.putFile(com.cloud.utils.storage.S3.S3Utils.putFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer)

Example 7 with Processor

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;
}
Also used : QCOW2Processor(com.cloud.storage.template.QCOW2Processor) Processor(com.cloud.storage.template.Processor) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) HashMap(java.util.HashMap)

Example 8 with Processor

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);
}
Also used : TemplateProp(com.cloud.storage.template.TemplateProp) Script(com.cloud.utils.script.Script) OVAProcessor(com.cloud.storage.template.OVAProcessor) VhdProcessor(com.cloud.storage.template.VhdProcessor) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) TARProcessor(com.cloud.storage.template.TARProcessor) Processor(com.cloud.storage.template.Processor) VmdkProcessor(com.cloud.storage.template.VmdkProcessor) RawImageProcessor(com.cloud.storage.template.RawImageProcessor) HashMap(java.util.HashMap) InternalErrorException(com.cloud.exception.InternalErrorException) IOException(java.io.IOException) ConfigurationException(javax.naming.ConfigurationException) TemplateLocation(com.cloud.storage.template.TemplateLocation) VhdProcessor(com.cloud.storage.template.VhdProcessor) TemplateObjectTO(org.apache.cloudstack.storage.to.TemplateObjectTO) FormatInfo(com.cloud.storage.template.Processor.FormatInfo) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer)

Example 9 with Processor

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();
    }
}
Also used : QCOW2Processor(com.cloud.storage.template.QCOW2Processor) OVAProcessor(com.cloud.storage.template.OVAProcessor) VhdProcessor(com.cloud.storage.template.VhdProcessor) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) TARProcessor(com.cloud.storage.template.TARProcessor) Processor(com.cloud.storage.template.Processor) VmdkProcessor(com.cloud.storage.template.VmdkProcessor) RawImageProcessor(com.cloud.storage.template.RawImageProcessor) OVAProcessor(com.cloud.storage.template.OVAProcessor) VmdkProcessor(com.cloud.storage.template.VmdkProcessor) HashMap(java.util.HashMap) VhdProcessor(com.cloud.storage.template.VhdProcessor) RawImageProcessor(com.cloud.storage.template.RawImageProcessor) TARProcessor(com.cloud.storage.template.TARProcessor) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException)

Example 10 with Processor

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;
}
Also used : Script(com.cloud.utils.script.Script) VhdProcessor(com.cloud.storage.template.VhdProcessor) OVAProcessor(com.cloud.storage.template.OVAProcessor) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) TARProcessor(com.cloud.storage.template.TARProcessor) IsoProcessor(com.cloud.storage.template.IsoProcessor) Processor(com.cloud.storage.template.Processor) VmdkProcessor(com.cloud.storage.template.VmdkProcessor) RawImageProcessor(com.cloud.storage.template.RawImageProcessor) HttpTemplateDownloader(com.cloud.storage.template.HttpTemplateDownloader) ScpTemplateDownloader(com.cloud.storage.template.ScpTemplateDownloader) S3TemplateDownloader(com.cloud.storage.template.S3TemplateDownloader) TemplateDownloader(com.cloud.storage.template.TemplateDownloader) LocalTemplateDownloader(com.cloud.storage.template.LocalTemplateDownloader) ResourceType(org.apache.cloudstack.storage.command.DownloadCommand.ResourceType) IOException(java.io.IOException) InternalErrorException(com.cloud.exception.InternalErrorException) TemplateLocation(com.cloud.storage.template.TemplateLocation) FormatInfo(com.cloud.storage.template.Processor.FormatInfo) File(java.io.File)

Aggregations

Processor (com.cloud.storage.template.Processor)17 InternalErrorException (com.cloud.exception.InternalErrorException)15 TemplateLocation (com.cloud.storage.template.TemplateLocation)14 ConfigurationException (javax.naming.ConfigurationException)14 QCOW2Processor (com.cloud.storage.template.QCOW2Processor)12 IOException (java.io.IOException)12 FormatInfo (com.cloud.storage.template.Processor.FormatInfo)11 HashMap (java.util.HashMap)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 Script (com.cloud.utils.script.Script)8 StorageLayer (com.cloud.storage.StorageLayer)7 OVAProcessor (com.cloud.storage.template.OVAProcessor)7 RawImageProcessor (com.cloud.storage.template.RawImageProcessor)7 TARProcessor (com.cloud.storage.template.TARProcessor)7 VhdProcessor (com.cloud.storage.template.VhdProcessor)7 VmdkProcessor (com.cloud.storage.template.VmdkProcessor)7 KVMPhysicalDisk (com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk)6 KVMStoragePool (com.cloud.hypervisor.kvm.storage.KVMStoragePool)6 KVMStoragePoolManager (com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager)6 Answer (com.cloud.agent.api.Answer)4