use of com.cloud.storage.SnapshotVO in project cloudstack by apache.
the class StorageSystemDataMotionStrategy method handleCreateVolumeFromSnapshotOnSecondaryStorage.
/**
* Creates a volume on the storage from a snapshot that resides on the secondary storage (archived snapshot).
* @param snapshotInfo snapshot on secondary
* @param volumeInfo volume to be created on the storage
* @param callback for async
*/
private void handleCreateVolumeFromSnapshotOnSecondaryStorage(SnapshotInfo snapshotInfo, VolumeInfo volumeInfo, AsyncCompletionCallback<CopyCommandResult> callback) {
// at this point, the snapshotInfo and volumeInfo should have the same disk offering ID (so either one should be OK to get a DiskOfferingVO instance)
DiskOfferingVO diskOffering = _diskOfferingDao.findByIdIncludingRemoved(volumeInfo.getDiskOfferingId());
SnapshotVO snapshot = _snapshotDao.findById(snapshotInfo.getId());
// update the volume's hv_ss_reserve (hypervisor snapshot reserve) from a disk offering (used for managed storage)
_volumeService.updateHypervisorSnapshotReserveForVolume(diskOffering, volumeInfo.getId(), snapshot.getHypervisorType());
CopyCmdAnswer copyCmdAnswer = null;
String errMsg = null;
HostVO hostVO = null;
try {
// create a volume on the storage
AsyncCallFuture<VolumeApiResult> future = _volumeService.createVolumeAsync(volumeInfo, volumeInfo.getDataStore());
VolumeApiResult result = future.get();
if (result.isFailed()) {
LOGGER.error("Failed to create a volume: " + result.getResult());
throw new CloudRuntimeException(result.getResult());
}
volumeInfo = _volumeDataFactory.getVolume(volumeInfo.getId(), volumeInfo.getDataStore());
volumeInfo.processEvent(Event.MigrationRequested);
volumeInfo = _volumeDataFactory.getVolume(volumeInfo.getId(), volumeInfo.getDataStore());
hostVO = getHost(snapshotInfo.getDataCenterId(), false);
// copy the volume from secondary via the hypervisor
copyCmdAnswer = performCopyOfVdi(volumeInfo, snapshotInfo, hostVO);
if (copyCmdAnswer == null || !copyCmdAnswer.getResult()) {
if (copyCmdAnswer != null && !StringUtils.isEmpty(copyCmdAnswer.getDetails())) {
errMsg = copyCmdAnswer.getDetails();
} else {
errMsg = "Unable to create volume from snapshot";
}
}
} catch (Exception ex) {
errMsg = ex.getMessage() != null ? ex.getMessage() : "Copy operation failed in 'StorageSystemDataMotionStrategy.handleCreateVolumeFromSnapshotBothOnStorageSystem'";
}
CopyCommandResult result = new CopyCommandResult(null, copyCmdAnswer);
result.setResult(errMsg);
callback.complete(result);
}
use of com.cloud.storage.SnapshotVO in project cloudstack by apache.
the class XenserverSnapshotStrategy method deleteSnapshot.
@Override
public boolean deleteSnapshot(Long snapshotId) {
SnapshotVO snapshotVO = snapshotDao.findById(snapshotId);
if (snapshotVO.getState() == Snapshot.State.Allocated) {
snapshotDao.remove(snapshotId);
return true;
}
if (snapshotVO.getState() == Snapshot.State.Destroyed) {
return true;
}
if (Snapshot.State.Error.equals(snapshotVO.getState())) {
List<SnapshotDataStoreVO> storeRefs = snapshotStoreDao.findBySnapshotId(snapshotId);
for (SnapshotDataStoreVO ref : storeRefs) {
snapshotStoreDao.expunge(ref.getId());
}
snapshotDao.remove(snapshotId);
return true;
}
if (snapshotVO.getState() == Snapshot.State.CreatedOnPrimary) {
s_logger.debug("delete snapshot on primary storage:");
snapshotVO.setState(Snapshot.State.Destroyed);
snapshotDao.update(snapshotId, snapshotVO);
return true;
}
if (!Snapshot.State.BackedUp.equals(snapshotVO.getState()) && !Snapshot.State.Error.equals(snapshotVO.getState())) {
throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is in " + snapshotVO.getState() + " Status");
}
// first mark the snapshot as destroyed, so that ui can't see it, but we
// may not destroy the snapshot on the storage, as other snapshots may
// depend on it.
SnapshotInfo snapshotOnImage = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Image);
if (snapshotOnImage == null) {
s_logger.debug("Can't find snapshot on backup storage, delete it in db");
snapshotDao.remove(snapshotId);
return true;
}
SnapshotObject obj = (SnapshotObject) snapshotOnImage;
try {
obj.processEvent(Snapshot.Event.DestroyRequested);
} catch (NoTransitionException e) {
s_logger.debug("Failed to set the state to destroying: ", e);
return false;
}
try {
boolean result = deleteSnapshotChain(snapshotOnImage);
obj.processEvent(Snapshot.Event.OperationSucceeded);
if (result) {
//snapshot is deleted on backup storage, need to delete it on primary storage
SnapshotDataStoreVO snapshotOnPrimary = snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Primary);
if (snapshotOnPrimary != null) {
SnapshotInfo snapshotOnPrimaryInfo = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
long volumeId = snapshotOnPrimary.getVolumeId();
VolumeVO volumeVO = volumeDao.findById(volumeId);
if (((PrimaryDataStoreImpl) snapshotOnPrimaryInfo.getDataStore()).getPoolType() == StoragePoolType.RBD && volumeVO != null) {
snapshotSvr.deleteSnapshot(snapshotOnPrimaryInfo);
}
snapshotOnPrimary.setState(State.Destroyed);
snapshotStoreDao.update(snapshotOnPrimary.getId(), snapshotOnPrimary);
}
}
} catch (Exception e) {
s_logger.debug("Failed to delete snapshot: ", e);
try {
obj.processEvent(Snapshot.Event.OperationFailed);
} catch (NoTransitionException e1) {
s_logger.debug("Failed to change snapshot state: " + e.toString());
}
return false;
}
return true;
}
use of com.cloud.storage.SnapshotVO in project cloudstack by apache.
the class XenserverSnapshotStrategy method revertSnapshot.
@Override
public boolean revertSnapshot(SnapshotInfo snapshot) {
if (canHandle(snapshot, SnapshotOperation.REVERT) == StrategyPriority.CANT_HANDLE) {
throw new CloudRuntimeException("Reverting not supported. Create a template or volume based on the snapshot instead.");
}
SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());
if (snapshotVO == null) {
throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
}
try {
VolumeInfo volumeInfo = snapshot.getBaseVolume();
StoragePool store = (StoragePool) volumeInfo.getDataStore();
if (store != null && store.getStatus() != StoragePoolStatus.Up) {
snapshot.processEvent(Event.OperationFailed);
throw new CloudRuntimeException("store is not in up state");
}
volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested);
boolean result = false;
try {
result = snapshotSvr.revertSnapshot(snapshot);
if (!result) {
s_logger.debug("Failed to revert snapshot: " + snapshot.getId());
throw new CloudRuntimeException("Failed to revert snapshot: " + snapshot.getId());
}
} finally {
if (result) {
volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
} else {
volumeInfo.stateTransit(Volume.Event.OperationFailed);
}
}
return result;
} finally {
if (snapshotVO != null) {
snapshotDao.releaseFromLockTable(snapshot.getId());
}
}
}
use of com.cloud.storage.SnapshotVO in project cloudstack by apache.
the class XenserverSnapshotStrategy method takeSnapshot.
@Override
@DB
public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) {
Object payload = snapshot.getPayload();
if (payload != null) {
CreateSnapshotPayload createSnapshotPayload = (CreateSnapshotPayload) payload;
if (createSnapshotPayload.getQuiescevm()) {
throw new InvalidParameterValueException("can't handle quiescevm equal true for volume snapshot");
}
}
SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());
if (snapshotVO == null) {
throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
}
try {
VolumeInfo volumeInfo = snapshot.getBaseVolume();
volumeInfo.stateTransit(Volume.Event.SnapshotRequested);
SnapshotResult result = null;
try {
result = snapshotSvr.takeSnapshot(snapshot);
if (result.isFailed()) {
s_logger.debug("Failed to take snapshot: " + result.getResult());
throw new CloudRuntimeException(result.getResult());
}
} finally {
if (result != null && result.isSuccess()) {
volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
} else {
volumeInfo.stateTransit(Volume.Event.OperationFailed);
}
}
snapshot = result.getSnapshot();
DataStore primaryStore = snapshot.getDataStore();
boolean backupFlag = Boolean.parseBoolean(configDao.getValue(Config.BackupSnapshotAfterTakingSnapshot.toString()));
SnapshotInfo backupedSnapshot;
if (backupFlag) {
backupedSnapshot = backupSnapshot(snapshot);
} else {
// Fake it to get the transitions to fire in the proper order
s_logger.debug("skipping backup of snapshot due to configuration " + Config.BackupSnapshotAfterTakingSnapshot.toString());
SnapshotObject snapObj = (SnapshotObject) snapshot;
try {
snapObj.processEvent(Snapshot.Event.OperationNotPerformed);
} catch (NoTransitionException e) {
s_logger.debug("Failed to change state: " + snapshot.getId() + ": " + e.toString());
throw new CloudRuntimeException(e.toString());
}
backupedSnapshot = snapshot;
}
try {
SnapshotInfo parent = snapshot.getParent();
if (backupedSnapshot != null && parent != null && primaryStore instanceof PrimaryDataStoreImpl) {
if (((PrimaryDataStoreImpl) primaryStore).getPoolType() != StoragePoolType.RBD) {
Long parentSnapshotId = parent.getId();
while (parentSnapshotId != null && parentSnapshotId != 0L) {
SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), parentSnapshotId);
if (snapshotDataStoreVO != null) {
parentSnapshotId = snapshotDataStoreVO.getParentSnapshotId();
snapshotStoreDao.remove(snapshotDataStoreVO.getId());
} else {
parentSnapshotId = null;
}
}
}
SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), snapshot.getId());
if (snapshotDataStoreVO != null) {
snapshotDataStoreVO.setParentSnapshotId(0L);
snapshotStoreDao.update(snapshotDataStoreVO.getId(), snapshotDataStoreVO);
}
}
} catch (Exception e) {
s_logger.debug("Failed to clean up snapshots on primary storage", e);
}
return backupedSnapshot;
} finally {
if (snapshotVO != null) {
snapshotDao.releaseFromLockTable(snapshot.getId());
}
}
}
use of com.cloud.storage.SnapshotVO in project cloudstack by apache.
the class UsageServiceImpl method getUsageRecords.
@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(GetUsageRecordsCmd cmd) {
Long accountId = cmd.getAccountId();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
Account userAccount = null;
Account caller = CallContext.current().getCallingAccount();
Long usageType = cmd.getUsageType();
Long projectId = cmd.getProjectId();
String usageId = cmd.getUsageId();
if (projectId != null) {
if (accountId != null) {
throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
}
Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
accountId = project.getProjectAccountId();
}
//if accountId is not specified, use accountName and domainId
if ((accountId == null) && (accountName != null) && (domainId != null)) {
if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
if (accounts.size() > 0) {
userAccount = accounts.get(0);
}
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
} else {
throw new PermissionDeniedException("Invalid Domain Id or Account");
}
}
boolean isAdmin = false;
boolean isDomainAdmin = false;
//If accountId couldn't be found using accountName and domainId, get it from userContext
if (accountId == null) {
accountId = caller.getId();
//If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
if (_accountService.isRootAdmin(caller.getId())) {
isAdmin = true;
} else if (_accountService.isDomainAdmin(caller.getId())) {
isDomainAdmin = true;
}
s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
}
Date startDate = cmd.getStartDate();
Date endDate = cmd.getEndDate();
if (startDate.after(endDate)) {
throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
}
TimeZone usageTZ = getUsageTimezone();
Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ);
Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ);
if (s_logger.isDebugEnabled()) {
s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
}
Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
}
if (isDomainAdmin) {
SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
List<DomainVO> domains = _domainDao.search(sdc, null);
List<Long> domainIds = new ArrayList<Long>();
for (DomainVO domain : domains) domainIds.add(domain.getId());
sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray());
}
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
if (usageType != null) {
sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
}
if (usageId != null) {
if (usageType == null) {
throw new InvalidParameterValueException("Usageid must be specified together with usageType");
}
Long usageDbId = null;
switch(usageType.intValue()) {
case UsageTypes.NETWORK_BYTES_RECEIVED:
case UsageTypes.NETWORK_BYTES_SENT:
case UsageTypes.RUNNING_VM:
case UsageTypes.ALLOCATED_VM:
case UsageTypes.VM_SNAPSHOT:
VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId);
if (vm != null) {
usageDbId = vm.getId();
}
if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) {
HostVO host = _hostDao.findByUuidIncludingRemoved(usageId);
if (host != null) {
usageDbId = host.getId();
}
}
break;
case UsageTypes.SNAPSHOT:
SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId);
if (snap != null) {
usageDbId = snap.getId();
}
break;
case UsageTypes.TEMPLATE:
case UsageTypes.ISO:
VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId);
if (tmpl != null) {
usageDbId = tmpl.getId();
}
break;
case UsageTypes.LOAD_BALANCER_POLICY:
LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId);
if (lb != null) {
usageDbId = lb.getId();
}
break;
case UsageTypes.PORT_FORWARDING_RULE:
PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId);
if (pf != null) {
usageDbId = pf.getId();
}
break;
case UsageTypes.VOLUME:
case UsageTypes.VM_DISK_IO_READ:
case UsageTypes.VM_DISK_IO_WRITE:
case UsageTypes.VM_DISK_BYTES_READ:
case UsageTypes.VM_DISK_BYTES_WRITE:
VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId);
if (volume != null) {
usageDbId = volume.getId();
}
break;
case UsageTypes.VPN_USERS:
VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId);
if (vpnUser != null) {
usageDbId = vpnUser.getId();
}
break;
case UsageTypes.SECURITY_GROUP:
SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId);
if (sg != null) {
usageDbId = sg.getId();
}
break;
case UsageTypes.IP_ADDRESS:
IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId);
if (ip != null) {
usageDbId = ip.getId();
}
break;
default:
break;
}
if (usageDbId != null) {
sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId);
} else {
// return an empty list if usageId was not found
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
}
if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
} else {
// return an empty list if we fail to validate the dates
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
Pair<List<UsageVO>, Integer> usageRecords = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
try {
usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter);
} finally {
txn.close();
// switch back to VMOPS_DB
TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
swap.close();
}
return new Pair<List<? extends Usage>, Integer>(usageRecords.first(), usageRecords.second());
}
Aggregations