use of com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult in project cosmic by MissionCriticalCloud.
the class HypervisorTemplateAdapter method delete.
@Override
@DB
public boolean delete(final TemplateProfile profile) {
boolean success = true;
final VMTemplateVO template = profile.getTemplate();
// find all eligible image stores for this template
final List<DataStore> imageStores = templateMgr.getImageStoreByTemplate(template.getId(), profile.getZoneId());
if (imageStores == null || imageStores.size() == 0) {
// already destroyed on image stores
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 (final DataStore store : imageStores) {
final long storeId = store.getId();
final List<TemplateDataStoreVO> templateStores = _tmpltStoreDao.listByTemplateStore(template.getId(), storeId);
for (final TemplateDataStoreVO templateStore : templateStores) {
if (templateStore.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
final 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);
}
}
}
for (final DataStore imageStore : imageStores) {
// publish zone-wide usage event
final Long sZoneId = ((ImageStoreEntity) imageStore).getDataCenterId();
s_logger.info("Delete template from image store: " + imageStore.getName());
final AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(template.getId(), imageStore));
try {
final 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
final List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, template.getId());
if (templateZones != null) {
for (final VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
// mark all the occurrences of this template in the given store as destroyed.
templateDataStoreDao.removeByTemplateStore(template.getId(), imageStore.getId());
} catch (final InterruptedException | ExecutionException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
}
}
}
if (success) {
if ((imageStores.size() > 1) && (profile.getZoneId() != 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 success;
}
// delete all cache entries for this template
final List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
for (final TemplateInfo tmplOnCache : cacheTmpls) {
s_logger.info("Delete template from image cache store: " + tmplOnCache.getDataStore().getName());
tmplOnCache.delete();
}
// find all eligible image stores for this template
final List<DataStore> iStores = templateMgr.getImageStoreByTemplate(template.getId(), null);
if (iStores == null || iStores.size() == 0) {
// Mark template as Inactive.
template.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.update(template.getId(), template);
// Decrement the number of templates and total secondary storage
// space used by the account
final Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
_resourceLimitMgr.recalculateResourceCount(template.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// remove its related ACL permission
final Pair<Class<?>, Long> tmplt = new Pair<>(VirtualMachineTemplate.class, template.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
}
return success;
}
use of com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult in project cosmic by MissionCriticalCloud.
the class HypervisorTemplateAdapterTest method testEmitDeleteEventUuid.
@Test
public void testEmitDeleteEventUuid() throws InterruptedException, ExecutionException {
// All the mocks required for this test to work.
final ImageStoreEntity store = mock(ImageStoreEntity.class);
when(store.getId()).thenReturn(1l);
when(store.getDataCenterId()).thenReturn(1l);
when(store.getName()).thenReturn("Test Store");
final TemplateDataStoreVO dataStoreVO = mock(TemplateDataStoreVO.class);
when(dataStoreVO.getDownloadState()).thenReturn(Status.DOWNLOADED);
final TemplateInfo info = mock(TemplateInfo.class);
when(info.getDataStore()).thenReturn(store);
final VMTemplateVO template = mock(VMTemplateVO.class);
when(template.getId()).thenReturn(1l);
when(template.getName()).thenReturn("Test Template");
when(template.getFormat()).thenReturn(ImageFormat.QCOW2);
when(template.getAccountId()).thenReturn(1l);
// TODO possibly return this from method for comparison, if things work how i want
when(template.getUuid()).thenReturn("Test UUID");
final TemplateProfile profile = mock(TemplateProfile.class);
when(profile.getTemplate()).thenReturn(template);
when(profile.getZoneId()).thenReturn(1l);
final TemplateApiResult result = mock(TemplateApiResult.class);
when(result.isSuccess()).thenReturn(true);
when(result.isFailed()).thenReturn(false);
final AsyncCallFuture<TemplateApiResult> future = mock(AsyncCallFuture.class);
when(future.get()).thenReturn(result);
final AccountVO acct = mock(AccountVO.class);
when(acct.getId()).thenReturn(1l);
when(acct.getDomainId()).thenReturn(1l);
when(_templateMgr.getImageStoreByTemplate(anyLong(), anyLong())).thenReturn(Collections.singletonList((DataStore) store));
when(_templateStoreDao.listByTemplateStore(anyLong(), anyLong())).thenReturn(Collections.singletonList(dataStoreVO));
when(_dataFactory.getTemplate(anyLong(), any(DataStore.class))).thenReturn(info);
when(_dataFactory.listTemplateOnCache(anyLong())).thenReturn(Collections.singletonList(info));
when(_templateService.deleteTemplateAsync(any(TemplateInfo.class))).thenReturn(future);
when(_accountDao.findById(anyLong())).thenReturn(acct);
when(_accountDao.findByIdIncludingRemoved(anyLong())).thenReturn(acct);
_adapter.delete(profile);
Assert.assertNotNull(events);
Assert.assertEquals(0, events.size());
}
use of com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method createPrivateTemplate.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true)
public VirtualMachineTemplate createPrivateTemplate(final CreateTemplateCmd command) throws CloudRuntimeException {
final long templateId = command.getEntityId();
final Long volumeId = command.getVolumeId();
final Long snapshotId = command.getSnapshotId();
VMTemplateVO privateTemplate = null;
final Long accountId = CallContext.current().getCallingAccountId();
SnapshotVO snapshot = null;
VolumeVO volume = null;
try {
final 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.getImageStore(zoneId);
if (store == null) {
throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
}
final AsyncCallFuture<TemplateApiResult> future;
if (snapshotId != null) {
final 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.
final 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");
}
}
final 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) {
final VolumeInfo volInfo = _volFactory.getVolume(volumeId);
future = _tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
} else {
throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
}
final CommandResult result;
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 {
final VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
_tmpltZoneDao.persist(templateZone);
}
privateTemplate = _tmpltDao.findById(templateId);
} catch (final InterruptedException | 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(final 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.engine.subsystem.api.storage.TemplateService.TemplateApiResult in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method prepareTemplateForCreate.
@Override
@DB
public VMTemplateStoragePoolVO prepareTemplateForCreate(final VMTemplateVO templ, final StoragePool pool) {
final VMTemplateVO template = _tmpltDao.findById(templ.getId(), true);
final long poolId = pool.getId();
final long templateId = template.getId();
final VMTemplateStoragePoolVO templateStoragePoolRef;
final TemplateDataStoreVO templateStoreRef;
templateStoragePoolRef = _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
if (templateStoragePoolRef != null) {
templateStoragePoolRef.setMarkedForGC(false);
_tmpltPoolDao.update(templateStoragePoolRef.getId(), templateStoragePoolRef);
if (templateStoragePoolRef.getDownloadState() == Status.DOWNLOADED) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Template " + templateId + " has already been downloaded to pool " + poolId);
}
return templateStoragePoolRef;
}
}
templateStoreRef = _tmplStoreDao.findByTemplateZoneDownloadStatus(templateId, pool.getDataCenterId(), VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
if (templateStoreRef == null) {
s_logger.error("Unable to find a secondary storage host who has completely downloaded the template.");
return null;
}
final List<StoragePoolHostVO> vos = _poolHostDao.listByHostStatus(poolId, com.cloud.host.Status.Up);
if (vos == null || vos.isEmpty()) {
throw new CloudRuntimeException("Cannot download " + templateId + " to poolId " + poolId + " since there is no host in the Up state connected to this pool");
}
if (templateStoragePoolRef == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Downloading template " + templateId + " to pool " + poolId);
}
final DataStore srcSecStore = _dataStoreMgr.getDataStore(templateStoreRef.getDataStoreId(), DataStoreRole.Image);
final TemplateInfo srcTemplate = _tmplFactory.getTemplate(templateId, srcSecStore);
final AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.prepareTemplateOnPrimary(srcTemplate, pool);
try {
final TemplateApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("prepare template failed:" + result.getResult());
return null;
}
return _tmpltPoolDao.findByPoolTemplate(poolId, templateId);
} catch (final Exception ex) {
s_logger.debug("failed to copy template from image store:" + srcSecStore.getName() + " to primary storage");
}
}
return null;
}
use of com.cloud.engine.subsystem.api.storage.TemplateService.TemplateApiResult in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method copy.
@Override
@DB
public boolean copy(final long userId, final VMTemplateVO template, final DataStore srcSecStore, final DataCenterVO dstZone) throws StorageUnavailableException, ResourceAllocationException {
final long tmpltId = template.getId();
final long dstZoneId = dstZone.getId();
// find all eligible image stores for the destination zone
final List<DataStore> dstSecStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(dstZoneId));
if (dstSecStores == null || dstSecStores.isEmpty()) {
throw new StorageUnavailableException("Destination zone is not ready, no image store associated", DataCenter.class, dstZone.getId());
}
final AccountVO account = _accountDao.findById(template.getAccountId());
// find the size of the template to be copied
final TemplateDataStoreVO srcTmpltStore = _tmplStoreDao.findByStoreTemplate(srcSecStore.getId(), tmpltId);
_resourceLimitMgr.checkResourceLimit(account, ResourceType.template);
_resourceLimitMgr.checkResourceLimit(account, ResourceType.secondary_storage, new Long(srcTmpltStore.getSize()).longValue());
// Event details
final String copyEventType;
if (template.getFormat().equals(ImageFormat.ISO)) {
copyEventType = EventTypes.EVENT_ISO_COPY;
} else {
copyEventType = EventTypes.EVENT_TEMPLATE_COPY;
}
final TemplateInfo srcTemplate = _tmplFactory.getTemplate(template.getId(), srcSecStore);
// for that zone
for (final DataStore dstSecStore : dstSecStores) {
final TemplateDataStoreVO dstTmpltStore = _tmplStoreDao.findByStoreTemplate(dstSecStore.getId(), tmpltId);
if (dstTmpltStore != null && dstTmpltStore.getDownloadState() == Status.DOWNLOADED) {
// already downloaded on this image store
return true;
}
if (dstTmpltStore != null && dstTmpltStore.getDownloadState() != Status.DOWNLOAD_IN_PROGRESS) {
_tmplStoreDao.removeByTemplateStore(tmpltId, dstSecStore.getId());
}
final AsyncCallFuture<TemplateApiResult> future = _tmpltSvr.copyTemplate(srcTemplate, dstSecStore);
try {
final TemplateApiResult result = future.get();
if (result.isFailed()) {
s_logger.debug("copy template failed for image store " + dstSecStore.getName() + ":" + result.getResult());
// try next image store
continue;
}
_tmpltDao.addTemplateToZone(template, dstZoneId);
return true;
} catch (final Exception ex) {
s_logger.debug("failed to copy template to image store:" + dstSecStore.getName() + " ,will try next one");
}
}
return false;
}
Aggregations