Search in sources :

Example 1 with ImageFormat

use of com.cloud.storage.Storage.ImageFormat in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method updateTemplateOrIso.

private VMTemplateVO updateTemplateOrIso(final BaseUpdateTemplateOrIsoCmd cmd) {
    final Long id = cmd.getId();
    final String name = cmd.getTemplateName();
    final String displayText = cmd.getDisplayText();
    final String format = cmd.getFormat();
    final Long guestOSId = cmd.getOsTypeId();
    final Boolean passwordEnabled = cmd.getPasswordEnabled();
    final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
    final Boolean isRoutingTemplate = cmd.isRoutingType();
    final Boolean bootable = cmd.getBootable();
    final Boolean requiresHvm = cmd.getRequiresHvm();
    final Integer sortKey = cmd.getSortKey();
    final Map details = cmd.getDetails();
    final Account account = CallContext.current().getCallingAccount();
    final String url = cmd.getUrl();
    // verify that template exists
    VMTemplateVO template = _tmpltDao.findById(id);
    if (template == null || template.getRemoved() != null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
        ex.addProxyObject(String.valueOf(id), "templateId");
        throw ex;
    }
    verifyTemplateId(id);
    // do a permission check
    _accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
    if (cmd.isRoutingType() != null) {
        if (!_accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }
    // update is needed if any of the fields below got filled by the user
    final boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && requiresHvm == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && url == null && details == null);
    if (!updateNeeded) {
        return template;
    }
    template = _tmpltDao.createForUpdate(id);
    if (name != null) {
        template.setName(name);
    }
    if (displayText != null) {
        template.setDisplayText(displayText);
    }
    if (sortKey != null) {
        template.setSortKey(sortKey);
    }
    final ImageFormat imageFormat;
    if (format != null) {
        try {
            imageFormat = ImageFormat.valueOf(format.toUpperCase());
        } catch (final IllegalArgumentException e) {
            throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
        }
        template.setFormat(imageFormat);
    }
    if (guestOSId != null) {
        final long oldGuestOSId = template.getGuestOSId();
        final GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
        if (guestOS == null) {
            throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
        } else {
            template.setGuestOSId(guestOSId);
        }
        if (guestOSId != oldGuestOSId) {
            // vm guest os type need to be updated if template guest os id changes.
            final SearchCriteria<VMInstanceVO> sc = _vmInstanceDao.createSearchCriteria();
            sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
            sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
            final List<VMInstanceVO> vms = _vmInstanceDao.search(sc, null);
            if (vms != null && !vms.isEmpty()) {
                for (final VMInstanceVO vm : vms) {
                    vm.setGuestOSId(guestOSId);
                    _vmInstanceDao.update(vm.getId(), vm);
                }
            }
        }
    }
    if (passwordEnabled != null) {
        template.setEnablePassword(passwordEnabled);
    }
    if (bootable != null) {
        template.setBootable(bootable);
    }
    if (requiresHvm != null) {
        template.setRequiresHvm(requiresHvm);
    }
    if (isDynamicallyScalable != null) {
        template.setDynamicallyScalable(isDynamicallyScalable);
    }
    if (url != null) {
        template.setUrl(url);
    }
    if (isRoutingTemplate != null) {
        if (isRoutingTemplate) {
            template.setTemplateType(TemplateType.ROUTING);
        } else {
            template.setTemplateType(TemplateType.USER);
        }
    }
    if (details != null && !details.isEmpty()) {
        template.setDetails(details);
        _tmpltDao.saveDetails(template);
    }
    _tmpltDao.update(id, template);
    return _tmpltDao.findById(id);
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) GuestOSVO(com.cloud.storage.GuestOSVO) ImageFormat(com.cloud.storage.Storage.ImageFormat) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with ImageFormat

use of com.cloud.storage.Storage.ImageFormat in project cloudstack by apache.

the class LaunchPermissionDaoImpl method listPermittedTemplates.

@Override
public List<VMTemplateVO> listPermittedTemplates(long accountId) {
    TransactionLegacy txn = TransactionLegacy.currentTxn();
    List<VMTemplateVO> permittedTemplates = new ArrayList<VMTemplateVO>();
    PreparedStatement pstmt = null;
    try {
        String sql = LIST_PERMITTED_TEMPLATES;
        pstmt = txn.prepareAutoCloseStatement(sql);
        pstmt.setLong(1, accountId);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            long id = rs.getLong(1);
            String uniqueName = rs.getString(2);
            String name = rs.getString(3);
            boolean isPublic = rs.getBoolean(4);
            String value = rs.getString(5);
            ImageFormat format = ImageFormat.valueOf(value);
            String tmpltType = rs.getString(6);
            boolean requiresHVM = rs.getBoolean(7);
            int bits = rs.getInt(8);
            String url = rs.getString(9);
            String createdTS = rs.getString(10);
            long templateAccountId = rs.getLong(11);
            String checksum = rs.getString(12);
            String displayText = rs.getString(13);
            boolean enablePassword = rs.getBoolean(14);
            long guestOSId = rs.getLong(15);
            boolean featured = rs.getBoolean(16);
            Date createdDate = null;
            if (createdTS != null) {
                createdDate = DateUtil.parseDateString(s_gmtTimeZone, createdTS);
            }
            if (isPublic) {
                // if it's public already, skip adding it to
                continue;
            // permitted templates as this for private
            // templates only
            }
            VMTemplateVO template = new VMTemplateVO(id, uniqueName, name, format, isPublic, featured, TemplateType.valueOf(tmpltType), url, createdDate, requiresHVM, bits, templateAccountId, checksum, displayText, enablePassword, guestOSId, true, null);
            permittedTemplates.add(template);
        }
    } catch (Exception e) {
        s_logger.warn("Error listing permitted templates", e);
    }
    return permittedTemplates;
}
Also used : VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Date(java.util.Date) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ImageFormat(com.cloud.storage.Storage.ImageFormat) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) ResultSet(java.sql.ResultSet)

Example 3 with ImageFormat

use of com.cloud.storage.Storage.ImageFormat in project cloudstack by apache.

the class KVMStorageProcessor method copyVolumeFromImageCacheToPrimary.

@Override
public Answer copyVolumeFromImageCacheToPrimary(final CopyCommand cmd) {
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    final DataStoreTO srcStore = srcData.getDataStore();
    final DataStoreTO destStore = destData.getDataStore();
    final VolumeObjectTO srcVol = (VolumeObjectTO) srcData;
    final ImageFormat srcFormat = srcVol.getFormat();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) destStore;
    if (!(srcStore instanceof NfsTO)) {
        return new CopyCmdAnswer("can only handle nfs storage");
    }
    final NfsTO nfsStore = (NfsTO) srcStore;
    final String srcVolumePath = srcData.getPath();
    final String secondaryStorageUrl = nfsStore.getUrl();
    KVMStoragePool secondaryStoragePool = null;
    KVMStoragePool primaryPool = null;
    try {
        try {
            primaryPool = storagePoolMgr.getStoragePool(primaryStore.getPoolType(), primaryStore.getUuid());
        } catch (final CloudRuntimeException e) {
            if (e.getMessage().contains("not found")) {
                primaryPool = storagePoolMgr.createStoragePool(primaryStore.getUuid(), primaryStore.getHost(), primaryStore.getPort(), primaryStore.getPath(), null, primaryStore.getPoolType());
            } else {
                return new CopyCmdAnswer(e.getMessage());
            }
        }
        Map<String, String> details = cmd.getOptions2();
        String path = details != null ? details.get(DiskTO.IQN) : null;
        storagePoolMgr.connectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), path, details);
        final String volumeName = UUID.randomUUID().toString();
        final int index = srcVolumePath.lastIndexOf(File.separator);
        final String volumeDir = srcVolumePath.substring(0, index);
        String srcVolumeName = srcVolumePath.substring(index + 1);
        secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + File.separator + volumeDir);
        if (!srcVolumeName.endsWith(".qcow2") && srcFormat == ImageFormat.QCOW2) {
            srcVolumeName = srcVolumeName + ".qcow2";
        }
        final KVMPhysicalDisk volume = secondaryStoragePool.getPhysicalDisk(srcVolumeName);
        volume.setFormat(PhysicalDiskFormat.valueOf(srcFormat.toString()));
        final KVMPhysicalDisk newDisk = storagePoolMgr.copyPhysicalDisk(volume, path != null ? path : volumeName, primaryPool, cmd.getWaitInMillSeconds());
        storagePoolMgr.disconnectPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), path);
        final VolumeObjectTO newVol = new VolumeObjectTO();
        newVol.setFormat(ImageFormat.valueOf(newDisk.getFormat().toString().toUpperCase()));
        newVol.setPath(path != null ? path : volumeName);
        return new CopyCmdAnswer(newVol);
    } catch (final CloudRuntimeException e) {
        s_logger.debug("Failed to copyVolumeFromImageCacheToPrimary: ", e);
        return new CopyCmdAnswer(e.toString());
    } finally {
        if (secondaryStoragePool != null) {
            storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
        }
    }
}
Also used : PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) NfsTO(com.cloud.agent.api.to.NfsTO) ImageFormat(com.cloud.storage.Storage.ImageFormat) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer)

Example 4 with ImageFormat

use of com.cloud.storage.Storage.ImageFormat in project cloudstack by apache.

the class KVMStorageProcessor method copyVolumeFromPrimaryToSecondary.

@Override
public Answer copyVolumeFromPrimaryToSecondary(final CopyCommand cmd) {
    final DataTO srcData = cmd.getSrcTO();
    final DataTO destData = cmd.getDestTO();
    final VolumeObjectTO srcVol = (VolumeObjectTO) srcData;
    final VolumeObjectTO destVol = (VolumeObjectTO) destData;
    final ImageFormat srcFormat = srcVol.getFormat();
    final ImageFormat destFormat = destVol.getFormat();
    final DataStoreTO srcStore = srcData.getDataStore();
    final DataStoreTO destStore = destData.getDataStore();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcStore;
    if (!(destStore instanceof NfsTO)) {
        return new CopyCmdAnswer("can only handle nfs storage");
    }
    final NfsTO nfsStore = (NfsTO) destStore;
    final String srcVolumePath = srcData.getPath();
    final String destVolumePath = destData.getPath();
    final String secondaryStorageUrl = nfsStore.getUrl();
    KVMStoragePool secondaryStoragePool = null;
    try {
        final String volumeName = UUID.randomUUID().toString();
        final String destVolumeName = volumeName + "." + destFormat.getFileExtension();
        final KVMPhysicalDisk volume = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), srcVolumePath);
        volume.setFormat(PhysicalDiskFormat.valueOf(srcFormat.toString()));
        secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl);
        secondaryStoragePool.createFolder(destVolumePath);
        storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
        secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + File.separator + destVolumePath);
        storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, secondaryStoragePool, cmd.getWaitInMillSeconds());
        final VolumeObjectTO newVol = new VolumeObjectTO();
        newVol.setPath(destVolumePath + File.separator + destVolumeName);
        newVol.setFormat(destFormat);
        return new CopyCmdAnswer(newVol);
    } catch (final CloudRuntimeException e) {
        s_logger.debug("Failed to copyVolumeFromPrimaryToSecondary: ", e);
        return new CopyCmdAnswer(e.toString());
    } finally {
        if (secondaryStoragePool != null) {
            storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
        }
    }
}
Also used : PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) DataStoreTO(com.cloud.agent.api.to.DataStoreTO) DataTO(com.cloud.agent.api.to.DataTO) PrimaryDataStoreTO(org.apache.cloudstack.storage.to.PrimaryDataStoreTO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) NfsTO(com.cloud.agent.api.to.NfsTO) CopyCmdAnswer(org.apache.cloudstack.storage.command.CopyCmdAnswer) ImageFormat(com.cloud.storage.Storage.ImageFormat)

Example 5 with ImageFormat

use of com.cloud.storage.Storage.ImageFormat in project cloudstack by apache.

the class LibvirtComputingResourceTest method testPrimaryStorageDownloadCommandNOTemplateDisk.

@Test(expected = NullPointerException.class)
public void testPrimaryStorageDownloadCommandNOTemplateDisk() {
    final StoragePool pool = Mockito.mock(StoragePool.class);
    final List<KVMPhysicalDisk> disks = new ArrayList<KVMPhysicalDisk>();
    final String name = "Test";
    final String url = "http://template/";
    final ImageFormat format = ImageFormat.QCOW2;
    final long accountId = 1l;
    final int wait = 0;
    final PrimaryStorageDownloadCommand command = new PrimaryStorageDownloadCommand(name, url, format, accountId, pool, wait);
    final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
    final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
    final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
    final KVMPhysicalDisk tmplVol = Mockito.mock(KVMPhysicalDisk.class);
    final KVMPhysicalDisk primaryVol = Mockito.mock(KVMPhysicalDisk.class);
    final KVMPhysicalDisk disk = new KVMPhysicalDisk("/path", "disk.qcow2", primaryPool);
    disks.add(disk);
    final int index = url.lastIndexOf("/");
    final String mountpoint = url.substring(0, index);
    when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
    when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
    when(secondaryPool.listPhysicalDisks()).thenReturn(disks);
    when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
    when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
    final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
    assertNotNull(wrapper);
    final Answer answer = wrapper.execute(command, libvirtComputingResource);
    assertFalse(answer.getResult());
    verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
}
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) KVMPhysicalDisk(com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk) PrimaryStorageDownloadCommand(com.cloud.agent.api.storage.PrimaryStorageDownloadCommand) ArrayList(java.util.ArrayList) ImageFormat(com.cloud.storage.Storage.ImageFormat) 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) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

ImageFormat (com.cloud.storage.Storage.ImageFormat)30 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 Test (org.junit.Test)9 Answer (com.cloud.agent.api.Answer)8 CheckRouterAnswer (com.cloud.agent.api.CheckRouterAnswer)8 PrimaryStorageDownloadCommand (com.cloud.agent.api.storage.PrimaryStorageDownloadCommand)8 LibvirtRequestWrapper (com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper)8 StoragePool (com.cloud.storage.StoragePool)8 ArrayList (java.util.ArrayList)8 DataStoreTO (com.cloud.agent.api.to.DataStoreTO)7 DataTO (com.cloud.agent.api.to.DataTO)7 VMTemplateVO (com.cloud.storage.VMTemplateVO)7 NfsTO (com.cloud.agent.api.to.NfsTO)6 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)5 Account (com.cloud.user.Account)5 UnsupportedAnswer (com.cloud.agent.api.UnsupportedAnswer)4 NfsStoragePool (com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool)4 IOException (java.io.IOException)4 Date (java.util.Date)4