use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method copyTemplate.
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_COPY, eventDescription = "copying template", async = true)
public VirtualMachineTemplate copyTemplate(final CopyTemplateCmd cmd) throws StorageUnavailableException, ResourceAllocationException {
final Long templateId = cmd.getId();
final Long userId = CallContext.current().getCallingUserId();
final Long sourceZoneId = cmd.getSourceZoneId();
final Long destZoneId = cmd.getDestinationZoneId();
final Account caller = CallContext.current().getCallingAccount();
// Verify parameters
final VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null || template.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find template with id");
}
final DataStore srcSecStore;
if (sourceZoneId != null) {
// template is on zone-wide secondary storage
srcSecStore = getImageStore(sourceZoneId, templateId);
} else {
// template is on region store
srcSecStore = getImageStore(templateId);
}
if (srcSecStore == null) {
throw new InvalidParameterValueException("There is no template " + templateId + " ready on image store.");
}
if (template.isCrossZones()) {
// sync template from cache store to region store if it is not there, for cases where we are going to migrate existing NFS to S3.
_tmpltSvr.syncTemplateToRegionStore(templateId, srcSecStore);
s_logger.debug("Template " + templateId + " is cross-zone, don't need to copy");
return template;
}
if (sourceZoneId != null) {
if (sourceZoneId.equals(destZoneId)) {
throw new InvalidParameterValueException("Please specify different source and destination zones.");
}
final DataCenterVO sourceZone = _dcDao.findById(sourceZoneId);
if (sourceZone == null) {
throw new InvalidParameterValueException("Please specify a valid source zone.");
}
}
final DataCenterVO dstZone = _dcDao.findById(destZoneId);
if (dstZone == null) {
throw new InvalidParameterValueException("Please specify a valid destination zone.");
}
final DataStore dstSecStore = getImageStore(destZoneId, templateId);
if (dstSecStore != null) {
s_logger.debug("There is template " + templateId + " in secondary storage " + dstSecStore.getName() + " in zone " + destZoneId + " , don't need to copy");
return template;
}
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
final boolean success = copy(userId, template, srcSecStore, dstZone);
if (success) {
// increase resource count
final long accountId = template.getAccountId();
if (template.getSize() != null) {
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.secondary_storage, template.getSize());
}
return template;
} else {
throw new CloudRuntimeException("Failed to copy template");
}
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class TemplateManagerImpl method updateTemplateOrIso.
private VMTemplateVO updateTemplateOrIso(final BaseUpdateTemplateOrIsoCmd cmd) {
final Long id = cmd.getId();
final String name = cmd.getTemplateName();
final String displayText = cmd.getDisplayText();
final String format = cmd.getFormat();
final Long guestOSId = cmd.getOsTypeId();
final Boolean passwordEnabled = cmd.getPasswordEnabled();
final Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
final Boolean isRoutingTemplate = cmd.isRoutingType();
final Boolean bootable = cmd.getBootable();
final Boolean requiresHvm = cmd.getRequiresHvm();
final Integer sortKey = cmd.getSortKey();
final Map details = cmd.getDetails();
final Account account = CallContext.current().getCallingAccount();
final String url = cmd.getUrl();
// verify that template exists
VMTemplateVO template = _tmpltDao.findById(id);
if (template == null || template.getRemoved() != null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
ex.addProxyObject(String.valueOf(id), "templateId");
throw ex;
}
verifyTemplateId(id);
// do a permission check
_accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
if (cmd.isRoutingType() != null) {
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
}
}
// update is needed if any of the fields below got filled by the user
final boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && requiresHvm == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && url == null && details == null);
if (!updateNeeded) {
return template;
}
template = _tmpltDao.createForUpdate(id);
if (name != null) {
template.setName(name);
}
if (displayText != null) {
template.setDisplayText(displayText);
}
if (sortKey != null) {
template.setSortKey(sortKey);
}
final ImageFormat imageFormat;
if (format != null) {
try {
imageFormat = ImageFormat.valueOf(format.toUpperCase());
} catch (final IllegalArgumentException e) {
throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
template.setFormat(imageFormat);
}
if (guestOSId != null) {
final long oldGuestOSId = template.getGuestOSId();
final GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
if (guestOS == null) {
throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
} else {
template.setGuestOSId(guestOSId);
}
if (guestOSId != oldGuestOSId) {
// vm guest os type need to be updated if template guest os id changes.
final SearchCriteria<VMInstanceVO> sc = _vmInstanceDao.createSearchCriteria();
sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
final List<VMInstanceVO> vms = _vmInstanceDao.search(sc, null);
if (vms != null && !vms.isEmpty()) {
for (final VMInstanceVO vm : vms) {
vm.setGuestOSId(guestOSId);
_vmInstanceDao.update(vm.getId(), vm);
}
}
}
}
if (passwordEnabled != null) {
template.setEnablePassword(passwordEnabled);
}
if (bootable != null) {
template.setBootable(bootable);
}
if (requiresHvm != null) {
template.setRequiresHvm(requiresHvm);
}
if (isDynamicallyScalable != null) {
template.setDynamicallyScalable(isDynamicallyScalable);
}
if (url != null) {
template.setUrl(url);
}
if (isRoutingTemplate != null) {
if (isRoutingTemplate) {
template.setTemplateType(TemplateType.ROUTING);
} else {
template.setTemplateType(TemplateType.USER);
}
}
if (details != null && !details.isEmpty()) {
template.setDetails(details);
_tmpltDao.saveDetails(template);
}
_tmpltDao.update(id, template);
return _tmpltDao.findById(id);
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class SnapshotManagerImpl method takeSnapshot.
@Override
@DB
public SnapshotInfo takeSnapshot(final VolumeInfo volume) throws ResourceAllocationException {
final CreateSnapshotPayload payload = (CreateSnapshotPayload) volume.getpayload();
final Long snapshotId = payload.getSnapshotId();
final Account snapshotOwner = payload.getAccount();
final SnapshotInfo snapshot = snapshotFactory.getSnapshot(snapshotId, volume.getDataStore());
snapshot.addPayload(payload);
try {
final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.TAKE);
if (snapshotStrategy == null) {
throw new CloudRuntimeException("Can't find snapshot strategy to deal with snapshot:" + snapshotId);
}
snapshotStrategy.takeSnapshot(snapshot);
try {
SnapshotDataStoreVO snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Image);
if (snapshotStoreRef == null) {
// The snapshot was not backed up to secondary. Find the snap on primary
snapshotStoreRef = _snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Primary);
if (snapshotStoreRef == null) {
throw new CloudRuntimeException("Could not find snapshot");
}
}
// Correct the resource count of snapshot in case of delta snapshots.
_resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize() - snapshotStoreRef.getPhysicalSize()));
} catch (final Exception e) {
s_logger.debug("post process snapshot failed", e);
}
} catch (final Exception e) {
s_logger.debug("Failed to create snapshot", e);
_resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.snapshot);
_resourceLimitMgr.decrementResourceCount(snapshotOwner.getId(), ResourceType.secondary_storage, new Long(volume.getSize()));
throw new CloudRuntimeException("Failed to create snapshot", e);
}
return snapshot;
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class SnapshotManagerImpl method listSnapshots.
@Override
public Pair<List<? extends Snapshot>, Integer> listSnapshots(final ListSnapshotsCmd cmd) {
final Long volumeId = cmd.getVolumeId();
final String name = cmd.getSnapshotName();
final Long id = cmd.getId();
final String keyword = cmd.getKeyword();
final String snapshotTypeStr = cmd.getSnapshotType();
final String intervalTypeStr = cmd.getIntervalType();
final Map<String, String> tags = cmd.getTags();
final Long zoneId = cmd.getZoneId();
final Account caller = CallContext.current().getCallingAccount();
final List<Long> permittedAccounts = new ArrayList<>();
// Verify parameters
if (volumeId != null) {
final VolumeVO volume = _volsDao.findById(volumeId);
if (volume != null) {
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
}
}
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
final Long domainId = domainIdRecursiveListProject.first();
final Boolean isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
final Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
final SearchBuilder<SnapshotVO> sb = _snapshotDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
// exclude those Destroyed snapshot, not showing on UI
sb.and("statusNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
sb.and("volumeId", sb.entity().getVolumeId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("snapshotTypeEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.IN);
sb.and("snapshotTypeNEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.NEQ);
sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
if (tags != null && !tags.isEmpty()) {
final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
final SearchCriteria<SnapshotVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sc.setParameters("statusNEQ", Snapshot.State.Destroyed);
if (volumeId != null) {
sc.setParameters("volumeId", volumeId);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Snapshot.toString());
for (final String key : tags.keySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
count++;
}
}
if (zoneId != null) {
sc.setParameters("dataCenterId", zoneId);
}
if (name != null) {
sc.setParameters("name", "%" + name + "%");
}
if (id != null) {
sc.setParameters("id", id);
}
if (keyword != null) {
final SearchCriteria<SnapshotVO> ssc = _snapshotDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (snapshotTypeStr != null) {
final Type snapshotType = SnapshotVO.getSnapshotType(snapshotTypeStr);
if (snapshotType == null) {
throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr);
}
if (snapshotType == Type.RECURRING) {
sc.setParameters("snapshotTypeEQ", Type.HOURLY.ordinal(), Type.DAILY.ordinal(), Type.WEEKLY.ordinal(), Type.MONTHLY.ordinal());
} else {
sc.setParameters("snapshotTypeEQ", snapshotType.ordinal());
}
} else if (intervalTypeStr != null && volumeId != null) {
final Type type = SnapshotVO.getSnapshotType(intervalTypeStr);
if (type == null) {
throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr);
}
sc.setParameters("snapshotTypeEQ", type.ordinal());
} else {
// Show only MANUAL and RECURRING snapshot types
sc.setParameters("snapshotTypeNEQ", Snapshot.Type.TEMPLATE.ordinal());
}
final Pair<List<SnapshotVO>, Integer> result = _snapshotDao.searchAndCount(sc, searchFilter);
return new Pair<>(result.first(), result.second());
}
use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.
the class SnapshotManagerImpl method backupSnapshotFromVmSnapshot.
@Override
public Snapshot backupSnapshotFromVmSnapshot(final Long snapshotId, final Long vmId, final Long volumeId, final Long vmSnapshotId) {
final VMInstanceVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to vm:" + vmId + " doesn't exist");
}
if (!HypervisorType.KVM.equals(vm.getHypervisorType())) {
throw new InvalidParameterValueException("Unsupported hypervisor type " + vm.getHypervisorType() + ". This supports KVM only");
}
final VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
if (vmSnapshot == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to vmSnapshot:" + vmSnapshotId + " doesn't exist");
}
// check vmsnapshot permissions
final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, null, true, vmSnapshot);
final SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
if (snapshot == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to snapshot:" + snapshotId + " doesn't exist");
}
final VolumeInfo volume = volFactory.getVolume(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
}
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
}
final DataStore store = volume.getDataStore();
final SnapshotDataStoreVO parentSnapshotDataStoreVO = _snapshotStoreDao.findParent(store.getRole(), store.getId(), volumeId);
if (parentSnapshotDataStoreVO != null) {
// Double check the snapshot is removed or not
final SnapshotVO parentSnap = _snapshotDao.findById(parentSnapshotDataStoreVO.getSnapshotId());
if (parentSnap != null && parentSnapshotDataStoreVO.getInstallPath() != null && parentSnapshotDataStoreVO.getInstallPath().equals(vmSnapshot.getName())) {
throw new InvalidParameterValueException("Creating snapshot failed due to snapshot : " + parentSnap.getUuid() + " is created from the same vm snapshot");
}
}
SnapshotInfo snapshotInfo = this.snapshotFactory.getSnapshot(snapshotId, store);
snapshotInfo = (SnapshotInfo) store.create(snapshotInfo);
final SnapshotDataStoreVO snapshotOnPrimaryStore = this._snapshotStoreDao.findBySnapshot(snapshot.getId(), store.getRole());
snapshotOnPrimaryStore.setState(ObjectInDataStoreStateMachine.State.Ready);
snapshotOnPrimaryStore.setInstallPath(vmSnapshot.getName());
_snapshotStoreDao.update(snapshotOnPrimaryStore.getId(), snapshotOnPrimaryStore);
snapshot.setState(Snapshot.State.CreatedOnPrimary);
_snapshotDao.update(snapshot.getId(), snapshot);
snapshotInfo = this.snapshotFactory.getSnapshot(snapshotId, store);
final Long snapshotOwnerId = vm.getAccountId();
try {
final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
if (snapshotStrategy == null) {
throw new CloudRuntimeException("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
}
snapshotInfo = snapshotStrategy.backupSnapshot(snapshotInfo);
} catch (final Exception e) {
s_logger.debug("Failed to backup snapshot from vm snapshot", e);
_resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.snapshot);
_resourceLimitMgr.decrementResourceCount(snapshotOwnerId, ResourceType.secondary_storage, volume.getSize());
throw new CloudRuntimeException("Failed to backup snapshot from vm snapshot", e);
}
return snapshotInfo;
}
Aggregations