Search in sources :

Example 1 with FormatInfo

use of com.cloud.storage.template.Processor.FormatInfo 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();
        }
    }
}
Also used : Script(com.cloud.utils.script.Script) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) Processor(com.cloud.storage.template.Processor) LibvirtException(org.libvirt.LibvirtException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KVMPhysicalDisk(com.cloud.agent.storage.KVMPhysicalDisk) Connect(org.libvirt.Connect) InternalErrorException(com.cloud.exception.InternalErrorException) IOException(java.io.IOException) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) KVMStoragePool(com.cloud.agent.storage.KVMStoragePool) ConfigurationException(javax.naming.ConfigurationException) TemplateLocation(com.cloud.storage.template.TemplateLocation) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CreatePrivateTemplateAnswer(com.cloud.agent.api.storage.CreatePrivateTemplateAnswer) FormatInfo(com.cloud.storage.template.Processor.FormatInfo)

Example 2 with FormatInfo

use of com.cloud.storage.template.Processor.FormatInfo 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 = 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(_storage.getSize(td.getDownloadLocalPath()) * 1.0d / (1024 * 1024 * 1024));
    // add one just in case
    imgSizeGigs++;
    final long timeout = (long) imgSizeGigs * installTimeoutPerGig;
    Script scr = null;
    final 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
    final 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
    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);
    _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);
    _storage.setWorldReadableAndWriteable(templateProperties);
    final TemplateLocation loc = new TemplateLocation(_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 = _processors.values().iterator();
    while (en.hasNext()) {
        final Processor processor = en.next();
        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) {
            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) ResourceType(com.cloud.storage.command.DownloadCommand.ResourceType) IOException(java.io.IOException) InternalErrorException(com.cloud.exception.InternalErrorException) FormatInfo(com.cloud.storage.template.Processor.FormatInfo) File(java.io.File)

Example 3 with FormatInfo

use of com.cloud.storage.template.Processor.FormatInfo 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;
}
Also used : Script(com.cloud.utils.script.Script) VhdProcessor(com.cloud.storage.template.VhdProcessor) QCOW2Processor(com.cloud.storage.template.QCOW2Processor) TARProcessor(com.cloud.storage.template.TARProcessor) Processor(com.cloud.storage.template.Processor) RawImageProcessor(com.cloud.storage.template.RawImageProcessor) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) InternalErrorException(com.cloud.exception.InternalErrorException) UploadEntity(com.cloud.storage.template.UploadEntity) TemplateLocation(com.cloud.storage.template.TemplateLocation) FormatInfo(com.cloud.storage.template.Processor.FormatInfo) File(java.io.File)

Example 4 with FormatInfo

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

Example 5 with FormatInfo

use of com.cloud.storage.template.Processor.FormatInfo 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();
        }
    }
}
Also used : LibvirtException(org.libvirt.LibvirtException) 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) RbdException(com.ceph.rbd.RbdException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LibvirtException(org.libvirt.LibvirtException) QemuImgException(org.apache.cloudstack.utils.qemu.QemuImgException) FileNotFoundException(java.io.FileNotFoundException) InternalErrorException(com.cloud.exception.InternalErrorException) ConfigurationException(javax.naming.ConfigurationException) RadosException(com.ceph.rados.exceptions.RadosException) 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) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) 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) File(java.io.File) S3Utils.putFile(com.cloud.utils.storage.S3.S3Utils.putFile) SimpleDateFormat(java.text.SimpleDateFormat) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer)

Aggregations

FormatInfo (com.cloud.storage.template.Processor.FormatInfo)28 InternalErrorException (com.cloud.exception.InternalErrorException)22 Processor (com.cloud.storage.template.Processor)21 IOException (java.io.IOException)21 TemplateLocation (com.cloud.storage.template.TemplateLocation)20 ConfigurationException (javax.naming.ConfigurationException)17 Script (com.cloud.utils.script.Script)14 QCOW2Processor (com.cloud.storage.template.QCOW2Processor)13 StorageLayer (com.cloud.storage.StorageLayer)10 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)9 File (java.io.File)9 HashMap (java.util.HashMap)9 FileOutputStream (java.io.FileOutputStream)7 Answer (com.cloud.agent.api.Answer)6 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)6 CreatePrivateTemplateFromSnapshotCommand (com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand)6 CreatePrivateTemplateAnswer (com.cloud.agent.api.storage.CreatePrivateTemplateAnswer)6 RawImageProcessor (com.cloud.storage.template.RawImageProcessor)6 TARProcessor (com.cloud.storage.template.TARProcessor)6 VhdProcessor (com.cloud.storage.template.VhdProcessor)6