Search in sources :

Example 21 with ImageFormat

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

the class TemplateAdapterBase method prepare.

@Override
public TemplateProfile prepare(final boolean isIso, final long userId, final String name, final String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHVM, final String url, Boolean isPublic, Boolean featured, Boolean isExtractable, final String format, Long guestOSId, Long zoneId, final HypervisorType hypervisorType, final String chksum, Boolean bootable, final String templateTag, final Account templateOwner, Map details, Boolean sshkeyEnabled, final String imageStoreUuid, final Boolean isDynamicallyScalable, final TemplateType templateType) throws ResourceAllocationException {
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    if (zoneId.longValue() == -1) {
        zoneId = null;
    }
    if (isIso) {
        if (bootable == null) {
            bootable = Boolean.TRUE;
        }
        final GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
        if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
            throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
        }
        if (bootable == false) {
            // Guest os id of None.
            guestOSId = noneGuestOs.getId();
        }
    } else {
        if (bits == null) {
            bits = Integer.valueOf(64);
        }
        if (passwordEnabled == null) {
            passwordEnabled = false;
        }
        if (requiresHVM == null) {
            requiresHVM = true;
        }
    }
    if (isExtractable == null) {
        isExtractable = Boolean.FALSE;
    }
    if (sshkeyEnabled == null) {
        sshkeyEnabled = Boolean.FALSE;
    }
    final boolean isAdmin = _accountMgr.isRootAdmin(templateOwner.getId());
    boolean isRegionStore = false;
    final List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
    if (stores != null && stores.size() > 0) {
        isRegionStore = true;
    }
    if (!isAdmin && zoneId == null && !isRegionStore) {
        // domain admin and user should also be able to register template on a region store
        throw new InvalidParameterValueException("Please specify a valid zone Id. Only admins can create templates in all zones.");
    }
    // check for the url format only when url is not null. url can be null incase of form based upload
    if (url != null && url.toLowerCase().contains("file://")) {
        throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }
    // check whether owner can create public templates
    final boolean allowPublicUserTemplates = TemplateManager.AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    final ImageFormat imgfmt;
    try {
        imgfmt = ImageFormat.valueOf(format.toUpperCase());
    } catch (final IllegalArgumentException e) {
        s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
        throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
    }
    // Check that the resource limit for templates/ISOs won't be exceeded
    final UserVO user = _userDao.findById(userId);
    if (user == null) {
        throw new IllegalArgumentException("Unable to find user with id " + userId);
    }
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
    // If a zoneId is specified, make sure it is valid
    if (zoneId != null) {
        final DataCenterVO zone = _dcDao.findById(zoneId);
        if (zone == null) {
            throw new IllegalArgumentException("Please specify a valid zone.");
        }
        final Account caller = CallContext.current().getCallingAccount();
        if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
        }
    }
    final List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (final VMTemplateVO template : systemvmTmplts) {
        if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) {
            throw new IllegalArgumentException("Cannot use reserved names for templates");
        }
    }
    if (hypervisorType.equals(Hypervisor.HypervisorType.XenServer)) {
        if (details == null || !details.containsKey("hypervisortoolsversion") || details.get("hypervisortoolsversion") == null || ((String) details.get("hypervisortoolsversion")).equalsIgnoreCase("none")) {
            final String hpvs = _configDao.getValue(Config.XenServerPVdriverVersion.key());
            if (hpvs != null) {
                if (details == null) {
                    details = new HashMap<String, String>();
                }
                details.put("hypervisortoolsversion", hpvs);
            }
        }
    }
    final Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    CallContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, imgfmt, guestOSId, zoneId, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, null, isDynamicallyScalable, templateType);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ImageFormat(com.cloud.storage.Storage.ImageFormat) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) GuestOS(com.cloud.storage.GuestOS) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO) TemplateProfile(com.cloud.storage.TemplateProfile)

Example 22 with ImageFormat

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

the class DownloadMonitorImpl method downloadVolumeToStorage.

@Override
public void downloadVolumeToStorage(final DataObject volume, final AsyncCompletionCallback<DownloadAnswer> callback) {
    boolean downloadJobExists = false;
    VolumeDataStoreVO volumeHost = null;
    final DataStore store = volume.getDataStore();
    final VolumeInfo volInfo = (VolumeInfo) volume;
    final RegisterVolumePayload payload = (RegisterVolumePayload) volInfo.getpayload();
    final String url = payload.getUrl();
    final String checkSum = payload.getChecksum();
    final ImageFormat format = ImageFormat.valueOf(payload.getFormat());
    volumeHost = _volumeStoreDao.findByStoreVolume(store.getId(), volume.getId());
    if (volumeHost == null) {
        volumeHost = new VolumeDataStoreVO(store.getId(), volume.getId(), new Date(), 0, Status.NOT_DOWNLOADED, null, null, "jobid0000", null, url, checkSum);
        _volumeStoreDao.persist(volumeHost);
    } else if ((volumeHost.getJobId() != null) && (volumeHost.getJobId().length() > 2)) {
        downloadJobExists = true;
    } else {
        // persit url and checksum
        volumeHost.setDownloadUrl(url);
        volumeHost.setChecksum(checkSum);
        _volumeStoreDao.update(volumeHost.getId(), volumeHost);
    }
    final Long maxVolumeSizeInBytes = getMaxVolumeSizeInBytes();
    if (volumeHost != null) {
        start();
        final Volume vol = _volumeDao.findById(volume.getId());
        DownloadCommand dcmd = new DownloadCommand((VolumeObjectTO) (volume.getTO()), maxVolumeSizeInBytes, checkSum, url, format);
        dcmd.setProxy(getHttpProxy());
        if (downloadJobExists) {
            dcmd = new DownloadProgressCommand(dcmd, volumeHost.getJobId(), RequestType.GET_OR_RESTART);
            dcmd.setResourceType(ResourceType.VOLUME);
        }
        final EndPoint ep = _epSelector.select(volume);
        if (ep == null) {
            s_logger.warn("There is no secondary storage VM for image store " + store.getName());
            return;
        }
        final DownloadListener dl = new DownloadListener(ep, store, volume, _timer, this, dcmd, callback);
        // auto-wired those injected fields in DownloadListener
        ComponentContext.inject(dl);
        if (downloadJobExists) {
            dl.setCurrState(volumeHost.getDownloadState());
        }
        try {
            ep.sendMessageAsync(dcmd, new UploadListener.Callback(ep.getId(), dl));
        } catch (final Exception e) {
            s_logger.warn("Unable to start /resume download of volume " + volume.getId() + " to " + store.getName(), e);
            dl.setDisconnected();
            dl.scheduleStatusCheck(RequestType.GET_OR_RESTART);
        }
    }
}
Also used : DownloadCommand(com.cloud.storage.command.DownloadCommand) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) RegisterVolumePayload(com.cloud.storage.RegisterVolumePayload) UploadListener(com.cloud.storage.upload.UploadListener) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ImageFormat(com.cloud.storage.Storage.ImageFormat) DownloadProgressCommand(com.cloud.storage.command.DownloadProgressCommand) Volume(com.cloud.storage.Volume) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) VolumeDataStoreVO(com.cloud.storage.datastore.db.VolumeDataStoreVO)

Example 23 with ImageFormat

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

the class TemplateAdapterBase method prepare.

@Override
public TemplateProfile prepare(boolean isIso, long userId, String name, String displayText, Integer bits, Boolean passwordEnabled, Boolean requiresHVM, String url, Boolean isPublic, Boolean featured, Boolean isExtractable, String format, Long guestOSId, List<Long> zoneIdList, HypervisorType hypervisorType, String chksum, Boolean bootable, String templateTag, Account templateOwner, Map details, Boolean sshkeyEnabled, String imageStoreUuid, Boolean isDynamicallyScalable, TemplateType templateType, boolean directDownload, boolean deployAsIs) throws ResourceAllocationException {
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    if (isIso) {
        if (bootable == null) {
            bootable = Boolean.TRUE;
        }
        GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
        if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
            throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
        }
        if (bootable == false) {
            // Guest os id of None.
            guestOSId = noneGuestOs.getId();
        }
    } else {
        if (bits == null) {
            bits = Integer.valueOf(64);
        }
        if (passwordEnabled == null) {
            passwordEnabled = false;
        }
        if (requiresHVM == null) {
            requiresHVM = true;
        }
        if (deployAsIs) {
            s_logger.info("Setting default guest OS for deploy-as-is template while the template registration is not completed");
            guestOSId = getDefaultDeployAsIsGuestOsId();
        }
    }
    if (isExtractable == null) {
        isExtractable = Boolean.FALSE;
    }
    if (sshkeyEnabled == null) {
        sshkeyEnabled = Boolean.FALSE;
    }
    boolean isAdmin = _accountMgr.isRootAdmin(templateOwner.getId());
    boolean isRegionStore = false;
    List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
    if (stores != null && stores.size() > 0) {
        isRegionStore = true;
    }
    if (!isAdmin && zoneIdList == null && !isRegionStore) {
        // domain admin and user should also be able to register template on a region store
        throw new InvalidParameterValueException("Please specify a valid zone Id. Only admins can create templates in all zones.");
    }
    // check for the url format only when url is not null. url can be null incase of form based upload
    if (url != null && url.toLowerCase().contains("file://")) {
        throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }
    // check whether owner can create public templates
    boolean allowPublicUserTemplates = TemplateManager.AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    ImageFormat imgfmt;
    try {
        imgfmt = ImageFormat.valueOf(format.toUpperCase());
    } catch (IllegalArgumentException e) {
        s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
        throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
    }
    // Check that the resource limit for templates/ISOs won't be exceeded
    UserVO user = _userDao.findById(userId);
    if (user == null) {
        throw new IllegalArgumentException("Unable to find user with id " + userId);
    }
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
    // If a zoneId is specified, make sure it is valid
    if (zoneIdList != null) {
        for (Long zoneId : zoneIdList) {
            DataCenterVO zone = _dcDao.findById(zoneId);
            if (zone == null) {
                throw new IllegalArgumentException("Please specify a valid zone.");
            }
            Account caller = CallContext.current().getCallingAccount();
            if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
                throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
            }
        }
    }
    List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (VMTemplateVO template : systemvmTmplts) {
        if (template.getName().equalsIgnoreCase(name) || template.getDisplayText().equalsIgnoreCase(displayText)) {
            throw new IllegalArgumentException("Cannot use reserved names for templates");
        }
    }
    if (hypervisorType.equals(Hypervisor.HypervisorType.XenServer)) {
        if (details == null || !details.containsKey("hypervisortoolsversion") || details.get("hypervisortoolsversion") == null || ((String) details.get("hypervisortoolsversion")).equalsIgnoreCase("none")) {
            String hpvs = _configDao.getValue(Config.XenServerPVdriverVersion.key());
            if (hpvs != null) {
                if (details == null) {
                    details = new HashMap<String, String>();
                }
                details.put("hypervisortoolsversion", hpvs);
            }
        }
    }
    Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    CallContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(id, userId, name, displayText, bits, passwordEnabled, requiresHVM, url, isPublic, featured, isExtractable, imgfmt, guestOSId, zoneIdList, hypervisorType, templateOwner.getAccountName(), templateOwner.getDomainId(), templateOwner.getAccountId(), chksum, bootable, templateTag, details, sshkeyEnabled, null, isDynamicallyScalable, templateType, directDownload, deployAsIs);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ImageFormat(com.cloud.storage.Storage.ImageFormat) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) GuestOS(com.cloud.storage.GuestOS) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO) TemplateProfile(com.cloud.storage.TemplateProfile)

Example 24 with ImageFormat

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

the class CephSnapshotStrategy method revertSnapshot.

@Override
public boolean revertSnapshot(SnapshotInfo snapshotInfo) {
    VolumeInfo volumeInfo = snapshotInfo.getBaseVolume();
    ImageFormat imageFormat = volumeInfo.getFormat();
    if (!ImageFormat.RAW.equals(imageFormat)) {
        s_logger.error(String.format("Does not support revert snapshot of the image format [%s] on Ceph/RBD. Can only rollback snapshots of format RAW", imageFormat));
        return false;
    }
    executeRevertSnapshot(snapshotInfo, volumeInfo);
    return true;
}
Also used : VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) ImageFormat(com.cloud.storage.Storage.ImageFormat)

Example 25 with ImageFormat

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

the class CephSnapshotStrategyTest method revertSnapshotTest.

@Test
public void revertSnapshotTest() {
    ImageFormat[] imageFormatValues = ImageFormat.values();
    for (int i = 0; i < imageFormatValues.length - 1; i++) {
        Mockito.reset(cephSnapshotStrategy);
        SnapshotInfo snapshotInfo = Mockito.mock(SnapshotInfo.class);
        VolumeInfo volumeInfo = Mockito.mock(VolumeInfo.class);
        Mockito.when(snapshotInfo.getBaseVolume()).thenReturn(volumeInfo);
        Mockito.when(volumeInfo.getFormat()).thenReturn(imageFormatValues[i]);
        Mockito.lenient().doNothing().when(cephSnapshotStrategy).executeRevertSnapshot(Mockito.any(), Mockito.any());
        boolean revertResult = cephSnapshotStrategy.revertSnapshot(snapshotInfo);
        if (imageFormatValues[i] == ImageFormat.RAW) {
            Assert.assertTrue(revertResult);
            Mockito.verify(cephSnapshotStrategy).executeRevertSnapshot(Mockito.any(), Mockito.any());
        } else {
            Assert.assertFalse(revertResult);
            Mockito.verify(cephSnapshotStrategy, Mockito.times(0)).executeRevertSnapshot(Mockito.any(), Mockito.any());
        }
    }
}
Also used : SnapshotInfo(org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) ImageFormat(com.cloud.storage.Storage.ImageFormat) Test(org.junit.Test)

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