Search in sources :

Example 11 with ImageStoreVO

use of org.apache.cloudstack.storage.datastore.db.ImageStoreVO in project cloudstack by apache.

the class ImageStoreHelper method createImageStore.

public ImageStoreVO createImageStore(Map<String, Object> params, Map<String, String> details) {
    ImageStoreVO store = imageStoreDao.findByName((String) params.get("name"));
    if (store != null) {
        return store;
    }
    store = new ImageStoreVO();
    store.setProtocol((String) params.get("protocol"));
    store.setProviderName((String) params.get("providerName"));
    store.setScope((ScopeType) params.get("scope"));
    store.setDataCenterId((Long) params.get("zoneId"));
    String uuid = (String) params.get("uuid");
    if (uuid != null) {
        store.setUuid(uuid);
    } else {
        store.setUuid(UUID.randomUUID().toString());
    }
    store.setUrl((String) params.get("url"));
    store.setName((String) params.get("name"));
    if (store.getName() == null) {
        store.setName(store.getUuid());
    }
    store.setRole((DataStoreRole) params.get("role"));
    if ("cifs".equalsIgnoreCase((String) params.get("protocol")) && details != null) {
        String user = details.get("user");
        String password = details.get("password");
        String domain = details.get("domain");
        String updatedPath = (String) params.get("url");
        if (user == null || password == null) {
            String errMsg = "Missing cifs user and password details. Add them as details parameter.";
            throw new InvalidParameterValueException(errMsg);
        } else {
            try {
                password = DBEncryptionUtil.encrypt(URLEncoder.encode(password, "UTF-8"));
                details.put("password", password);
                updatedPath += "?user=" + user + "&password=" + password + "&domain=" + domain;
            } catch (UnsupportedEncodingException e) {
                throw new CloudRuntimeException("Error while generating the cifs url. " + e.getMessage());
            }
            store.setUrl(updatedPath);
        }
    }
    store = imageStoreDao.persist(store);
    // persist details
    if (details != null) {
        Iterator<String> keyIter = details.keySet().iterator();
        while (keyIter.hasNext()) {
            String key = keyIter.next().toString();
            String value = details.get(key);
            // encrypt swift key or s3 secret key
            if (key.equals(ApiConstants.KEY) || key.equals(ApiConstants.S3_SECRET_KEY)) {
                value = DBEncryptionUtil.encrypt(value);
            }
            ImageStoreDetailVO detail = new ImageStoreDetailVO(store.getId(), key, value, true);
            imageStoreDetailsDao.persist(detail);
        }
    }
    return store;
}
Also used : ImageStoreDetailVO(org.apache.cloudstack.storage.datastore.db.ImageStoreDetailVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO)

Example 12 with ImageStoreVO

use of org.apache.cloudstack.storage.datastore.db.ImageStoreVO in project cloudstack by apache.

the class ImageStoreHelper method createImageStore.

public ImageStoreVO createImageStore(Map<String, Object> params) {
    ImageStoreVO store = imageStoreDao.findByName((String) params.get("name"));
    if (store != null) {
        return store;
    }
    store = new ImageStoreVO();
    store.setProtocol((String) params.get("protocol"));
    store.setProviderName((String) params.get("providerName"));
    store.setScope((ScopeType) params.get("scope"));
    store.setDataCenterId((Long) params.get("zoneId"));
    String uuid = (String) params.get("uuid");
    if (uuid != null) {
        store.setUuid(uuid);
    } else {
        store.setUuid(UUID.randomUUID().toString());
    }
    store.setName((String) params.get("name"));
    if (store.getName() == null) {
        store.setName(store.getUuid());
    }
    store.setUrl((String) params.get("url"));
    store.setRole((DataStoreRole) params.get("role"));
    store = imageStoreDao.persist(store);
    return store;
}
Also used : ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO)

Example 13 with ImageStoreVO

use of org.apache.cloudstack.storage.datastore.db.ImageStoreVO in project cloudstack by apache.

the class ManagementServerImpl method listCapabilities.

@Override
public Map<String, Object> listCapabilities(final ListCapabilitiesCmd cmd) {
    final Map<String, Object> capabilities = new HashMap<String, Object>();
    final Account caller = getCaller();
    boolean securityGroupsEnabled = false;
    boolean elasticLoadBalancerEnabled = false;
    boolean KVMSnapshotEnabled = false;
    String supportELB = "false";
    final List<NetworkVO> networks = _networkDao.listSecurityGroupEnabledNetworks();
    if (networks != null && !networks.isEmpty()) {
        securityGroupsEnabled = true;
        final String elbEnabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key());
        elasticLoadBalancerEnabled = elbEnabled == null ? false : Boolean.parseBoolean(elbEnabled);
        if (elasticLoadBalancerEnabled) {
            final String networkType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key());
            if (networkType != null) {
                supportELB = networkType;
            }
        }
    }
    final long diskOffMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
    final long diskOffMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
    KVMSnapshotEnabled = Boolean.parseBoolean(_configDao.getValue("KVM.snapshot.enabled"));
    final boolean userPublicTemplateEnabled = TemplateManager.AllowPublicUserTemplates.valueIn(caller.getId());
    // add some parameters UI needs to handle API throttling
    final boolean apiLimitEnabled = Boolean.parseBoolean(_configDao.getValue(Config.ApiLimitEnabled.key()));
    final Integer apiLimitInterval = Integer.valueOf(_configDao.getValue(Config.ApiLimitInterval.key()));
    final Integer apiLimitMax = Integer.valueOf(_configDao.getValue(Config.ApiLimitMax.key()));
    final boolean allowUserViewDestroyedVM = (QueryManagerImpl.AllowUserViewDestroyedVM.valueIn(caller.getId()) | _accountService.isAdmin(caller.getId()));
    final boolean allowUserExpungeRecoverVM = (UserVmManager.AllowUserExpungeRecoverVm.valueIn(caller.getId()) | _accountService.isAdmin(caller.getId()));
    // check if region-wide secondary storage is used
    boolean regionSecondaryEnabled = false;
    final List<ImageStoreVO> imgStores = _imgStoreDao.findRegionImageStores();
    if (imgStores != null && imgStores.size() > 0) {
        regionSecondaryEnabled = true;
    }
    capabilities.put("securityGroupsEnabled", securityGroupsEnabled);
    capabilities.put("userPublicTemplateEnabled", userPublicTemplateEnabled);
    capabilities.put("cloudStackVersion", getVersion());
    capabilities.put("supportELB", supportELB);
    capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired());
    capabilities.put("allowusercreateprojects", _projectMgr.allowUserToCreateProject());
    capabilities.put("customDiskOffMinSize", diskOffMinSize);
    capabilities.put("customDiskOffMaxSize", diskOffMaxSize);
    capabilities.put("regionSecondaryEnabled", regionSecondaryEnabled);
    capabilities.put("KVMSnapshotEnabled", KVMSnapshotEnabled);
    capabilities.put("allowUserViewDestroyedVM", allowUserViewDestroyedVM);
    capabilities.put("allowUserExpungeRecoverVM", allowUserExpungeRecoverVM);
    if (apiLimitEnabled) {
        capabilities.put("apiLimitInterval", apiLimitInterval);
        capabilities.put("apiLimitMax", apiLimitMax);
    }
    return capabilities;
}
Also used : Account(com.cloud.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) HashMap(java.util.HashMap) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO)

Example 14 with ImageStoreVO

use of org.apache.cloudstack.storage.datastore.db.ImageStoreVO in project cloudstack by apache.

the class StorageManagerImpl method deleteSecondaryStagingStore.

@Override
public boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd) {
    final long storeId = cmd.getId();
    // Verify that cache store exists
    ImageStoreVO store = _imageStoreDao.findById(storeId);
    if (store == null) {
        throw new InvalidParameterValueException("Cache store with id " + storeId + " doesn't exist");
    }
    _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
    // Verify that there are no live snapshot, template, volume on the cache
    // store that is currently referenced
    List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listActiveOnCache(storeId);
    if (snapshots != null && snapshots.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete cache store with staging snapshots currently in use!");
    }
    List<VolumeDataStoreVO> volumes = _volumeStoreDao.listActiveOnCache(storeId);
    if (volumes != null && volumes.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete cache store with staging volumes currently in use!");
    }
    List<TemplateDataStoreVO> templates = _templateStoreDao.listActiveOnCache(storeId);
    if (templates != null && templates.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete cache store with staging templates currently in use!");
    }
    // ready to delete
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // first delete from image_store_details table, we need to do that since
            // we are not actually deleting record from main
            // image_data_store table, so delete cascade will not work
            _imageStoreDetailsDao.deleteDetails(storeId);
            _snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.ImageCache);
            _volumeStoreDao.deletePrimaryRecordsForStore(storeId);
            _templateStoreDao.deletePrimaryRecordsForStore(storeId);
            _imageStoreDao.remove(storeId);
        }
    });
    return true;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) SnapshotDataStoreVO(org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO) VolumeDataStoreVO(org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO)

Example 15 with ImageStoreVO

use of org.apache.cloudstack.storage.datastore.db.ImageStoreVO in project cloudstack by apache.

the class TemplateManagerImpl method createPrivateTemplateRecord.

@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true)
public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, Account templateOwner) throws ResourceAllocationException {
    Account caller = CallContext.current().getCallingAccount();
    boolean isAdmin = (_accountMgr.isAdmin(caller.getId()));
    _accountMgr.checkAccess(caller, null, true, templateOwner);
    String name = cmd.getTemplateName();
    if ((name == null) || (name.length() > 32)) {
        throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters");
    }
    if (cmd.getTemplateTag() != null) {
        if (!_accountService.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    // do some parameter defaulting
    Integer bits = cmd.getBits();
    Boolean requiresHvm = cmd.getRequiresHvm();
    Boolean passwordEnabled = cmd.isPasswordEnabled();
    Boolean isPublic = cmd.isPublic();
    Boolean featured = cmd.isFeatured();
    int bitsValue = ((bits == null) ? 64 : bits.intValue());
    boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm.booleanValue());
    boolean passwordEnabledValue = ((passwordEnabled == null) ? false : passwordEnabled.booleanValue());
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    boolean isDynamicScalingEnabled = cmd.isDynamicallyScalable();
    // check whether template owner can create public templates
    boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created.");
    }
    Long volumeId = cmd.getVolumeId();
    Long snapshotId = cmd.getSnapshotId();
    if ((volumeId == null) && (snapshotId == null)) {
        throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.");
    }
    if ((volumeId != null) && (snapshotId != null)) {
        throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")");
    }
    HypervisorType hyperType;
    VolumeVO volume = null;
    SnapshotVO snapshot = null;
    VMTemplateVO privateTemplate = null;
    if (volumeId != null) {
        // create template from volume
        volume = _volumeDao.findById(volumeId);
        if (volume == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
        }
        // check permissions
        _accountMgr.checkAccess(caller, null, true, volume);
        // created
        if (!_volumeMgr.volumeInactive(volume)) {
            String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first";
            if (s_logger.isInfoEnabled()) {
                s_logger.info(msg);
            }
            throw new CloudRuntimeException(msg);
        }
        hyperType = _volumeDao.getHypervisorType(volumeId);
        if (HypervisorType.LXC.equals(hyperType)) {
            throw new InvalidParameterValueException("Template creation is not supported for LXC volume: " + volumeId);
        }
    } else {
        // create template from snapshot
        snapshot = _snapshotDao.findById(snapshotId);
        if (snapshot == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId);
        }
        // Volume could be removed so find including removed to record source template id.
        volume = _volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId());
        // check permissions
        _accountMgr.checkAccess(caller, null, true, snapshot);
        if (snapshot.getState() != Snapshot.State.BackedUp) {
            throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for template creation");
        }
        /*
             * // bug #11428. Operation not supported if vmware and snapshots
             * parent volume = ROOT if(snapshot.getHypervisorType() ==
             * HypervisorType.VMware && snapshotVolume.getVolumeType() ==
             * Type.DATADISK){ throw new UnsupportedServiceException(
             * "operation not supported, snapshot with id " + snapshotId +
             * " is created from Data Disk"); }
             */
        hyperType = snapshot.getHypervisorType();
    }
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : snapshot.getSize()).longValue());
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    Long guestOSId = cmd.getOsTypeId();
    GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
    if (guestOS == null) {
        throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
    }
    Long nextTemplateId = _tmpltDao.getNextInSequence(Long.class, "id");
    String description = cmd.getDisplayText();
    boolean isExtractable = false;
    Long sourceTemplateId = null;
    if (volume != null) {
        VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
        if (volume.getIsoId() != null && volume.getIsoId() != 0) {
            sourceTemplateId = volume.getIsoId();
        } else if (volume.getTemplateId() != null) {
            sourceTemplateId = volume.getTemplateId();
        }
    }
    String templateTag = cmd.getTemplateTag();
    if (templateTag != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding template tag: " + templateTag);
        }
    }
    privateTemplate = new VMTemplateVO(nextTemplateId, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, requiresHvmValue, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true, hyperType, templateTag, cmd.getDetails(), false, isDynamicScalingEnabled);
    if (sourceTemplateId != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("This template is getting created from other template, setting source template Id to: " + sourceTemplateId);
        }
    }
    // for region wide storage, set cross zones flag
    List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
    if (!CollectionUtils.isEmpty(stores)) {
        privateTemplate.setCrossZones(true);
    }
    privateTemplate.setSourceTemplateId(sourceTemplateId);
    VMTemplateVO template = _tmpltDao.persist(privateTemplate);
    // Increment the number of templates
    if (template != null) {
        Map<String, String> details = new HashMap<String, String>();
        if (sourceTemplateId != null) {
            VMTemplateVO sourceTemplate = _tmpltDao.findById(sourceTemplateId);
            if (sourceTemplate != null && sourceTemplate.getDetails() != null) {
                details.putAll(sourceTemplate.getDetails());
            }
        }
        if (volume != null) {
            Long vmId = volume.getInstanceId();
            if (vmId != null) {
                UserVmVO userVm = _userVmDao.findById(vmId);
                if (userVm != null) {
                    _userVmDao.loadDetails(userVm);
                    details.putAll(userVm.getDetails());
                }
            }
        }
        if (cmd.getDetails() != null) {
            // new password will be generated during vm deployment from password enabled template
            details.remove("Encrypted.Password");
            details.putAll(cmd.getDetails());
        }
        if (!details.isEmpty()) {
            privateTemplate.setDetails(details);
            _tmpltDao.saveDetails(privateTemplate);
        }
        _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
        _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : snapshot.getSize()));
    }
    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

ImageStoreVO (org.apache.cloudstack.storage.datastore.db.ImageStoreVO)38 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)14 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)12 Account (com.cloud.user.Account)10 DataCenterVO (com.cloud.dc.DataCenterVO)9 HashMap (java.util.HashMap)9 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 ArrayList (java.util.ArrayList)8 ClusterVO (com.cloud.dc.ClusterVO)6 HostPodVO (com.cloud.dc.HostPodVO)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 Map (java.util.Map)5 HostVO (com.cloud.host.HostVO)4 DataStoreRole (com.cloud.storage.DataStoreRole)4 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)3 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)3 URISyntaxException (java.net.URISyntaxException)3 DataStoreProvider (org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider)3 Test (org.testng.annotations.Test)3 ClusterDetailsVO (com.cloud.dc.ClusterDetailsVO)2