use of com.cloud.storage.VMTemplateZoneVO in project cloudstack by apache.
the class TemplateServiceImpl method createChildDataDiskTemplate.
private boolean createChildDataDiskTemplate(DatadiskTO dataDiskTemplate, VMTemplateVO template, TemplateInfo parentTemplate, DataStore imageStore, int diskCount) throws ExecutionException, InterruptedException {
// Make an entry in vm_template table
Storage.ImageFormat format = dataDiskTemplate.isIso() ? Storage.ImageFormat.ISO : template.getFormat();
String suffix = dataDiskTemplate.isIso() ? "-IsoDiskTemplate-" : "-DataDiskTemplate-";
TemplateType ttype = dataDiskTemplate.isIso() ? TemplateType.ISODISK : TemplateType.DATADISK;
final long templateId = _templateDao.getNextInSequence(Long.class, "id");
long guestOsId = dataDiskTemplate.isIso() ? 1 : 0;
String templateName = dataDiskTemplate.isIso() ? dataDiskTemplate.getPath().substring(dataDiskTemplate.getPath().lastIndexOf(File.separator) + 1) : template.getName() + suffix + diskCount;
VMTemplateVO templateVO = new VMTemplateVO(templateId, templateName, format, false, false, false, ttype, template.getUrl(), template.requiresHvm(), template.getBits(), template.getAccountId(), null, templateName, false, guestOsId, false, template.getHypervisorType(), null, null, false, false, false, false);
if (dataDiskTemplate.isIso()) {
templateVO.setUniqueName(templateName);
}
templateVO.setParentTemplateId(template.getId());
templateVO.setSize(dataDiskTemplate.getVirtualSize());
templateVO = _templateDao.persist(templateVO);
// Make sync call to create Datadisk templates in image store
TemplateApiResult result = null;
TemplateInfo dataDiskTemplateInfo = imageFactory.getTemplate(templateVO.getId(), imageStore);
AsyncCallFuture<TemplateApiResult> future = createDatadiskTemplateAsync(parentTemplate, dataDiskTemplateInfo, dataDiskTemplate.getPath(), dataDiskTemplate.getDiskId(), dataDiskTemplate.getFileSize(), dataDiskTemplate.isBootable());
result = future.get();
if (result.isSuccess()) {
// Make an entry in template_zone_ref table
if (imageStore.getScope().getScopeType() == ScopeType.REGION) {
associateTemplateToZone(templateId, null);
} else if (imageStore.getScope().getScopeType() == ScopeType.ZONE) {
Long zoneId = ((ImageStoreEntity) imageStore).getDataCenterId();
VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
_vmTemplateZoneDao.persist(templateZone);
}
_resourceLimitMgr.incrementResourceCount(template.getAccountId(), ResourceType.secondary_storage, templateVO.getSize());
} else {
// Delete the Datadisk templates that were already created as they are now invalid
s_logger.debug("Since creation of Datadisk template: " + templateVO.getId() + " failed, delete other Datadisk templates that were created as part of parent" + " template download");
TemplateInfo parentTemplateInfo = imageFactory.getTemplate(templateVO.getParentTemplateId(), imageStore);
cleanupDatadiskTemplates(parentTemplateInfo);
}
return result.isSuccess();
}
use of com.cloud.storage.VMTemplateZoneVO in project cloudstack by apache.
the class TemplateManagerImpl method createPrivateTemplate.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true)
public VirtualMachineTemplate createPrivateTemplate(CreateTemplateCmd command) throws CloudRuntimeException {
final long templateId = command.getEntityId();
Long volumeId = command.getVolumeId();
Long snapshotId = command.getSnapshotId();
VMTemplateVO privateTemplate = null;
final Long accountId = CallContext.current().getCallingAccountId();
SnapshotVO snapshot = null;
VolumeVO volume = null;
Account caller = CallContext.current().getCallingAccount();
try {
TemplateInfo tmplInfo = _tmplFactory.getTemplate(templateId, DataStoreRole.Image);
long zoneId = 0;
if (snapshotId != null) {
snapshot = _snapshotDao.findById(snapshotId);
zoneId = snapshot.getDataCenterId();
} else if (volumeId != null) {
volume = _volumeDao.findById(volumeId);
zoneId = volume.getDataCenterId();
}
DataStore store = _dataStoreMgr.getImageStoreWithFreeCapacity(zoneId);
if (store == null) {
throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
}
AsyncCallFuture<TemplateApiResult> future = null;
if (snapshotId != null) {
DataStoreRole dataStoreRole = ApiResponseHelper.getDataStoreRole(snapshot, _snapshotStoreDao, _dataStoreMgr);
SnapshotInfo snapInfo = _snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (dataStoreRole == DataStoreRole.Image) {
if (snapInfo == null) {
snapInfo = _snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId);
}
// We need to copy the snapshot onto secondary.
SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
snapshotStrategy.backupSnapshot(snapInfo);
// Attempt to grab it again.
snapInfo = _snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId + " on secondary and could not create backup");
}
}
_accountMgr.checkAccess(caller, null, true, snapInfo);
DataStore snapStore = snapInfo.getDataStore();
if (snapStore != null) {
// pick snapshot image store to create template
store = snapStore;
}
}
future = _tmpltSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store);
} else if (volumeId != null) {
VolumeInfo volInfo = _volFactory.getVolume(volumeId);
if (volInfo == null) {
throw new InvalidParameterValueException("No such volume exist");
}
_accountMgr.checkAccess(caller, null, true, volInfo);
future = _tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
} else {
throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
}
CommandResult result = null;
try {
result = future.get();
if (result.isFailed()) {
privateTemplate = null;
s_logger.debug("Failed to create template" + result.getResult());
throw new CloudRuntimeException("Failed to create template" + result.getResult());
}
// create entries in template_zone_ref table
if (_dataStoreMgr.isRegionStore(store)) {
// template created on region store
_tmpltSvr.associateTemplateToZone(templateId, null);
} else {
VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
_tmpltZoneDao.persist(templateZone);
}
privateTemplate = _tmpltDao.findById(templateId);
TemplateDataStoreVO srcTmpltStore = _tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), zoneId, privateTemplate.getId(), privateTemplate.getName(), null, privateTemplate.getSourceTemplateId(), srcTmpltStore.getPhysicalSize(), privateTemplate.getSize());
_usageEventDao.persist(usageEvent);
} catch (InterruptedException e) {
s_logger.debug("Failed to create template", e);
throw new CloudRuntimeException("Failed to create template", e);
} catch (ExecutionException e) {
s_logger.debug("Failed to create template", e);
throw new CloudRuntimeException("Failed to create template", e);
}
} finally {
if (privateTemplate == null) {
final VolumeVO volumeFinal = volume;
final SnapshotVO snapshotFinal = snapshot;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// template_store_ref entries should have been removed using our
// DataObject.processEvent command in case of failure, but clean
// it up here to avoid
// some leftovers which will cause removing template from
// vm_template table fail.
_tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template_zone_ref record
_tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template record
_tmpltDao.expunge(templateId);
// decrement resource count
if (accountId != null) {
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volumeFinal != null ? volumeFinal.getSize() : snapshotFinal.getSize()));
}
}
});
}
}
if (privateTemplate != null) {
return privateTemplate;
} else {
throw new CloudRuntimeException("Failed to create a template");
}
}
use of com.cloud.storage.VMTemplateZoneVO in project cloudstack by apache.
the class TemplateManagerImpl method attachIso.
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_ATTACH, eventDescription = "attaching ISO", async = true)
public boolean attachIso(long isoId, long vmId, boolean forced) {
Account caller = CallContext.current().getCallingAccount();
Long userId = CallContext.current().getCallingUserId();
// Verify input parameters
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
VMTemplateVO iso = _tmpltDao.findById(isoId);
if (iso == null || iso.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find an ISO with id " + isoId);
}
if (!TemplateType.PERHOST.equals(iso.getTemplateType())) {
VMTemplateZoneVO exists = _tmpltZoneDao.findByZoneTemplate(vm.getDataCenterId(), isoId);
if (null == exists) {
throw new InvalidParameterValueException("ISO is not available in the zone the VM is in.");
}
}
// check permissions
// check if caller has access to VM and ISO
// and also check if the VM's owner has access to the ISO.
_accountMgr.checkAccess(caller, null, false, iso, vm);
Account vmOwner = _accountDao.findById(vm.getAccountId());
_accountMgr.checkAccess(vmOwner, null, false, iso, vm);
State vmState = vm.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
if (XS_TOOLS_ISO.equals(iso.getUniqueName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer) {
throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
}
if (VMWARE_TOOLS_ISO.equals(iso.getUniqueName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
}
boolean result = attachISOToVM(vmId, userId, isoId, true, forced);
if (result) {
return result;
} else {
throw new CloudRuntimeException("Failed to attach iso");
}
}
use of com.cloud.storage.VMTemplateZoneVO in project cloudstack by apache.
the class HypervisorTemplateAdapter method cleanupTemplate.
boolean cleanupTemplate(VMTemplateVO template, boolean success) {
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByTemplateId(template.getId());
List<Long> zoneIds = templateZones.stream().map(VMTemplateZoneVO::getZoneId).collect(Collectors.toList());
if (zoneIds.size() > 0) {
return success;
}
template.setRemoved(new Date());
template.setState(State.Inactive);
templateDao.update(template.getId(), template);
return success;
}
use of com.cloud.storage.VMTemplateZoneVO in project cloudstack by apache.
the class HypervisorTemplateAdapter method delete.
@Override
@DB
public boolean delete(TemplateProfile profile) {
boolean success = false;
VMTemplateVO template = profile.getTemplate();
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
if (profile.getZoneIdList() != null && profile.getZoneIdList().size() > 1)
throw new CloudRuntimeException("Operation is not supported for more than one zone id at a time");
Long zoneId = null;
if (profile.getZoneIdList() != null)
zoneId = profile.getZoneIdList().get(0);
// find all eligible image stores for this template
List<DataStore> imageStores = templateMgr.getImageStoreByTemplate(template.getId(), zoneId);
if (imageStores == null || imageStores.size() == 0) {
// already destroyed on image stores
success = true;
s_logger.info("Unable to find image store still having template: " + template.getName() + ", so just mark the template removed");
} else {
// Make sure the template is downloaded to all found image stores
for (DataStore store : imageStores) {
long storeId = store.getId();
List<TemplateDataStoreVO> templateStores = _tmpltStoreDao.listByTemplateStore(template.getId(), storeId);
for (TemplateDataStoreVO templateStore : templateStores) {
if (templateStore.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
String errorMsg = "Please specify a template that is not currently being downloaded.";
s_logger.debug("Template: " + template.getName() + " is currently being downloaded to secondary storage host: " + store.getName() + "; cant' delete it.");
throw new CloudRuntimeException(errorMsg);
}
}
}
String eventType = "";
if (template.getFormat().equals(ImageFormat.ISO)) {
eventType = EventTypes.EVENT_ISO_DELETE;
} else {
eventType = EventTypes.EVENT_TEMPLATE_DELETE;
}
for (DataStore imageStore : imageStores) {
// publish zone-wide usage event
Long sZoneId = ((ImageStoreEntity) imageStore).getDataCenterId();
if (sZoneId != null) {
UsageEventUtils.publishUsageEvent(eventType, template.getAccountId(), sZoneId, template.getId(), null, VirtualMachineTemplate.class.getName(), template.getUuid());
}
boolean dataDiskDeletetionResult = true;
List<VMTemplateVO> dataDiskTemplates = templateDao.listByParentTemplatetId(template.getId());
if (dataDiskTemplates != null && dataDiskTemplates.size() > 0) {
s_logger.info("Template: " + template.getId() + " has Datadisk template(s) associated with it. Delete Datadisk templates before deleting the template");
for (VMTemplateVO dataDiskTemplate : dataDiskTemplates) {
s_logger.info("Delete Datadisk template: " + dataDiskTemplate.getId() + " from image store: " + imageStore.getName());
AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(dataDiskTemplate.getId(), imageStore));
try {
TemplateApiResult result = future.get();
dataDiskDeletetionResult = result.isSuccess();
if (!dataDiskDeletetionResult) {
s_logger.warn("Failed to delete datadisk template: " + dataDiskTemplate + " from image store: " + imageStore.getName() + " due to: " + result.getResult());
break;
}
// Remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, dataDiskTemplate.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
// Mark datadisk template as Inactive
List<DataStore> iStores = templateMgr.getImageStoreByTemplate(dataDiskTemplate.getId(), null);
if (iStores == null || iStores.size() == 0) {
dataDiskTemplate.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.update(dataDiskTemplate.getId(), dataDiskTemplate);
}
// Decrement total secondary storage space used by the account
_resourceLimitMgr.recalculateResourceCount(dataDiskTemplate.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
} catch (Exception e) {
s_logger.debug("Delete datadisk template failed", e);
throw new CloudRuntimeException("Delete datadisk template failed", e);
}
}
}
// remove from template_zone_ref
if (dataDiskDeletetionResult) {
s_logger.info("Delete template: " + template.getId() + " from image store: " + imageStore.getName());
AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(template.getId(), imageStore));
try {
TemplateApiResult result = future.get();
success = result.isSuccess();
if (!success) {
s_logger.warn("Failed to delete the template: " + template + " from the image store: " + imageStore.getName() + " due to: " + result.getResult());
break;
}
// remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
} catch (InterruptedException | ExecutionException e) {
s_logger.debug("Delete template Failed", e);
throw new CloudRuntimeException("Delete template Failed", e);
}
} else {
s_logger.warn("Template: " + template.getId() + " won't be deleted from image store: " + imageStore.getName() + " because deletion of one of the Datadisk" + " templates that belonged to the template failed");
}
}
}
if (success) {
if ((imageStores != null && imageStores.size() > 1) && (profile.getZoneIdList() != null)) {
// if template is stored in more than one image stores, and the zone id is not null, then don't delete other templates.
return cleanupTemplate(template, success);
}
// delete all cache entries for this template
List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
for (TemplateInfo tmplOnCache : cacheTmpls) {
s_logger.info("Delete template: " + tmplOnCache.getId() + " from image cache store: " + tmplOnCache.getDataStore().getName());
tmplOnCache.delete();
}
// find all eligible image stores for this template
List<DataStore> iStores = templateMgr.getImageStoreByTemplate(template.getId(), null);
if (iStores == null || iStores.size() == 0) {
// remove any references from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByTemplateId(template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
// Mark template as Inactive.
template.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.remove(template.getId());
_tmpltDao.update(template.getId(), template);
// Decrement the number of templates and total secondary storage
// space used by the account
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
_resourceLimitMgr.recalculateResourceCount(template.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// remove its related ACL permission
Pair<Class<?>, Long> tmplt = new Pair<Class<?>, Long>(VirtualMachineTemplate.class, template.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
// Remove template details
templateDetailsDao.removeDetails(template.getId());
// Remove deploy-as-is details (if any)
templateDeployAsIsDetailsDao.removeDetails(template.getId());
// Remove comments (if any)
AnnotationService.EntityType entityType = template.getFormat().equals(ImageFormat.ISO) ? AnnotationService.EntityType.ISO : AnnotationService.EntityType.TEMPLATE;
annotationDao.removeByEntityType(entityType.name(), template.getUuid());
}
return success;
}
Aggregations