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;
}
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;
}
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;
}
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;
}
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");
}
}
Aggregations