Search in sources :

Example 1 with TemplateLocation

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();
        }
    }
}
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 TemplateLocation

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;
}
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 3 with TemplateLocation

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();
        }
    }
}
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 4 with TemplateLocation

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();
        }
    }
}
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)

Example 5 with TemplateLocation

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());
}
Also used : KVMStoragePoolManager(com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager) KVMStoragePool(com.cloud.hypervisor.kvm.storage.KVMStoragePool) StoragePool(com.cloud.storage.StoragePool) NfsStoragePool(com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool) StorageLayer(com.cloud.storage.StorageLayer) Processor(com.cloud.storage.template.Processor) KVMPhysicalDisk(com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk) InternalErrorException(com.cloud.exception.InternalErrorException) LibvirtUtilitiesHelper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) AttachAnswer(org.apache.cloudstack.storage.command.AttachAnswer) Answer(com.cloud.agent.api.Answer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) LibvirtRequestWrapper(com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper) KVMStoragePool(com.cloud.hypervisor.kvm.storage.KVMStoragePool) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TemplateLocation(com.cloud.storage.template.TemplateLocation) CreatePrivateTemplateFromSnapshotCommand(com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

TemplateLocation (com.cloud.storage.template.TemplateLocation)25 InternalErrorException (com.cloud.exception.InternalErrorException)24 Processor (com.cloud.storage.template.Processor)24 ConfigurationException (javax.naming.ConfigurationException)21 FormatInfo (com.cloud.storage.template.Processor.FormatInfo)20 IOException (java.io.IOException)19 QCOW2Processor (com.cloud.storage.template.QCOW2Processor)14 Script (com.cloud.utils.script.Script)13 StorageLayer (com.cloud.storage.StorageLayer)12 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)11 HashMap (java.util.HashMap)11 File (java.io.File)9 Answer (com.cloud.agent.api.Answer)8 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)8 CreatePrivateTemplateFromSnapshotCommand (com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand)8 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)8 LibvirtUtilitiesHelper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper)8 StoragePool (com.cloud.storage.StoragePool)8 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 RawImageProcessor (com.cloud.storage.template.RawImageProcessor)7