use of com.cloud.vm.snapshot.VMSnapshot in project cloudstack by apache.
the class CitrixRevertToVMSnapshotCommandWrapper method execute.
@Override
public Answer execute(final RevertToVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String vmName = command.getVmName();
final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
final VMSnapshot.Type vmSnapshotType = command.getTarget().getType();
final Boolean snapshotMemory = vmSnapshotType == VMSnapshot.Type.DiskAndMemory;
final Connection conn = citrixResourceBase.getConnection();
PowerState vmState = null;
VM vm = null;
try {
final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
if (vmSnapshots == null || vmSnapshots.size() == 0) {
return new RevertToVMSnapshotAnswer(command, false, "Cannot find vmSnapshot with name: " + command.getTarget().getSnapshotName());
}
final VM vmSnapshot = vmSnapshots.iterator().next();
// find target VM or creating a work VM
try {
vm = citrixResourceBase.getVM(conn, vmName);
} catch (final Exception e) {
vm = citrixResourceBase.createWorkingVM(conn, vmName, command.getGuestOSType(), command.getPlatformEmulator(), listVolumeTo);
}
if (vm == null) {
return new RevertToVMSnapshotAnswer(command, false, "Revert to VM Snapshot Failed due to can not find vm: " + vmName);
}
// call plugin to execute revert
citrixResourceBase.revertToSnapshot(conn, vmSnapshot, vmName, vm.getUuid(conn), snapshotMemory, citrixResourceBase.getHost().getUuid());
vm = citrixResourceBase.getVM(conn, vmName);
final Set<VBD> vbds = vm.getVBDs(conn);
final Map<String, VDI> vdiMap = new HashMap<String, VDI>();
// get vdi:vbdr to a map
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.type == Types.VbdType.DISK) {
final VDI vdi = vbdr.VDI;
vdiMap.put(vbdr.userdevice, vdi);
}
}
if (!snapshotMemory) {
vm.destroy(conn);
vmState = PowerState.PowerOff;
} else {
vmState = PowerState.PowerOn;
}
// after revert, VM's volumes path have been changed, need to report to manager
for (final VolumeObjectTO volumeTo : listVolumeTo) {
final Long deviceId = volumeTo.getDeviceId();
final VDI vdi = vdiMap.get(deviceId.toString());
volumeTo.setPath(vdi.getUuid(conn));
}
return new RevertToVMSnapshotAnswer(command, listVolumeTo, vmState);
} catch (final Exception e) {
s_logger.error("revert vm " + vmName + " to snapshot " + command.getTarget().getSnapshotName() + " failed due to " + e.getMessage());
return new RevertToVMSnapshotAnswer(command, false, e.getMessage());
}
}
use of com.cloud.vm.snapshot.VMSnapshot in project cloudstack by apache.
the class AccountManagerImpl method cleanupAccount.
protected boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
// cleanup the users from the account
List<UserVO> users = _userDao.listByAccount(accountId);
for (UserVO user : users) {
if (!_userDao.remove(user.getId())) {
s_logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
accountCleanupNeeded = true;
}
}
// delete global load balancer rules for the account.
List<org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(accountId);
if (gslbRules != null && !gslbRules.isEmpty()) {
_gslbService.revokeAllGslbRulesForAccount(caller, accountId);
}
// delete the account from project accounts
_projectAccountDao.removeAccountFromProjects(accountId);
if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
// delete the account from group
_messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
}
// delete all vm groups belonging to accont
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) {
if (!_vmMgr.deleteVmGroup(group.getId())) {
s_logger.error("Unable to delete group: " + group.getId());
accountCleanupNeeded = true;
}
}
// Delete the snapshots dir for the account. Have to do this before destroying the VMs.
boolean success = _snapMgr.deleteSnapshotDirsForAccount(accountId);
if (success) {
s_logger.debug("Successfully deleted snapshots directories for all volumes under account " + accountId + " across all zones");
}
// clean up templates
List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
boolean allTemplatesDeleted = true;
for (VMTemplateVO template : userTemplates) {
if (template.getRemoved() == null) {
try {
allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
} catch (Exception e) {
s_logger.warn("Failed to delete template while removing account: " + template.getName() + " due to: ", e);
allTemplatesDeleted = false;
}
}
}
if (!allTemplatesDeleted) {
s_logger.warn("Failed to delete templates while removing account id=" + accountId);
accountCleanupNeeded = true;
}
// Destroy VM Snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
for (VMSnapshot vmSnapshot : vmSnapshots) {
try {
_vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
} catch (Exception e) {
s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
}
}
// Destroy the account's VMs
List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
}
for (UserVmVO vm : vms) {
if (vm.getState() != VirtualMachine.State.Destroyed && vm.getState() != VirtualMachine.State.Expunging) {
try {
_vmMgr.destroyVm(vm.getId(), false);
} catch (Exception e) {
e.printStackTrace();
s_logger.warn("Failed destroying instance " + vm.getUuid() + " as part of account deletion.");
}
}
// should pass in order to perform further cleanup
if (!_vmMgr.expunge(vm, callerUserId, caller)) {
s_logger.error("Unable to expunge vm: " + vm.getId());
accountCleanupNeeded = true;
}
}
// Mark the account's volumes as destroyed
List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
for (VolumeVO volume : volumes) {
try {
volumeService.deleteVolume(volume.getId(), caller);
} catch (Exception ex) {
s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
}
// delete remote access vpns and associated users
List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
for (VpnUserVO vpnUser : vpnUsers) {
_remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
}
try {
for (RemoteAccessVpnVO vpn : remoteAccessVpns) {
_remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, false);
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
// Cleanup security groups
int numRemoved = _securityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
// Cleanup affinity groups
int numAGRemoved = _affinityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numAGRemoved + " affinity groups for account " + accountId);
// Delete all the networks
boolean networksDeleted = true;
s_logger.debug("Deleting networks for account " + account.getId());
List<NetworkVO> networks = _networkDao.listByOwner(accountId);
if (networks != null) {
for (NetworkVO network : networks) {
ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller);
if (!_networkMgr.destroyNetwork(network.getId(), context, false)) {
s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
networksDeleted = false;
} else {
s_logger.debug("Network " + network.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
}
// Delete all VPCs
boolean vpcsDeleted = true;
s_logger.debug("Deleting vpcs for account " + account.getId());
List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
for (Vpc vpc : vpcs) {
if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) {
s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
vpcsDeleted = false;
} else {
s_logger.debug("VPC " + vpc.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
if (networksDeleted && vpcsDeleted) {
// release ip addresses belonging to the account
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (IpAddress ip : ipsToRelease) {
s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
if (!_ipAddrMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
accountCleanupNeeded = true;
}
}
}
// Delete Site 2 Site VPN customer gateway
s_logger.debug("Deleting site-to-site VPN customer gateways for account " + accountId);
if (!_vpnMgr.deleteCustomerGatewayByAccount(accountId)) {
s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId);
}
// Delete autoscale resources if any
try {
_autoscaleMgr.cleanUpAutoScaleResources(accountId);
} catch (CloudRuntimeException ex) {
s_logger.warn("Failed to cleanup AutoScale resources as a part of account id=" + accountId + " cleanup due to exception:", ex);
accountCleanupNeeded = true;
}
// up successfully
if (networksDeleted) {
if (!_configMgr.releaseAccountSpecificVirtualRanges(accountId)) {
accountCleanupNeeded = true;
} else {
s_logger.debug("Account specific Virtual IP ranges " + " are successfully released as a part of account id=" + accountId + " cleanup.");
}
}
// release account specific guest vlans
List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
for (AccountGuestVlanMapVO map : maps) {
_dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
}
int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
// release account specific acquired portable IP's. Since all the portable IP's must have been already
// disassociated with VPC/guest network (due to deletion), so just mark portable IP as free.
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (IpAddress ip : ipsToRelease) {
if (ip.isPortable()) {
s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
_ipAddrMgr.releasePortableIpAddress(ip.getId());
}
}
// release dedication if any
List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
s_logger.debug("Releasing dedicated resources for account " + accountId);
for (DedicatedResourceVO dr : dedicatedResources) {
if (!_dedicatedDao.remove(dr.getId())) {
s_logger.warn("Fail to release dedicated resources for account " + accountId);
}
}
}
// Updating and deleting the resourceLimit and resourceCount should be the last step in cleanupAccount
// process.
// Update resource count for this account and for parent domains.
List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
for (ResourceCountVO resourceCount : resourceCounts) {
_resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
}
// Delete resource count and resource limits entries set for this account (if there are any).
_resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
_resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
// Delete ssh keypairs
List<SSHKeyPairVO> sshkeypairs = _sshKeyPairDao.listKeyPairs(accountId, account.getDomainId());
for (SSHKeyPairVO keypair : sshkeypairs) {
_sshKeyPairDao.remove(keypair.getId());
}
return true;
} catch (Exception ex) {
s_logger.warn("Failed to cleanup account " + account + " due to ", ex);
accountCleanupNeeded = true;
return true;
} finally {
s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed."));
if (accountCleanupNeeded) {
_accountDao.markForCleanup(accountId);
} else {
account.setNeedsCleanup(false);
_accountDao.update(accountId, account);
}
}
}
use of com.cloud.vm.snapshot.VMSnapshot in project cloudstack by apache.
the class ApiResponseHelper method createVMSnapshotResponse.
@Override
public VMSnapshotResponse createVMSnapshotResponse(VMSnapshot vmSnapshot) {
VMSnapshotResponse vmSnapshotResponse = new VMSnapshotResponse();
vmSnapshotResponse.setId(vmSnapshot.getUuid());
vmSnapshotResponse.setName(vmSnapshot.getName());
vmSnapshotResponse.setState(vmSnapshot.getState());
vmSnapshotResponse.setCreated(vmSnapshot.getCreated());
vmSnapshotResponse.setDescription(vmSnapshot.getDescription());
vmSnapshotResponse.setDisplayName(vmSnapshot.getDisplayName());
UserVm vm = ApiDBUtils.findUserVmById(vmSnapshot.getVmId());
if (vm != null) {
vmSnapshotResponse.setVirtualMachineId(vm.getUuid());
vmSnapshotResponse.setVirtualMachineName(StringUtils.isEmpty(vm.getDisplayName()) ? vm.getHostName() : vm.getDisplayName());
vmSnapshotResponse.setHypervisor(vm.getHypervisorType());
DataCenterVO datacenter = ApiDBUtils.findZoneById(vm.getDataCenterId());
if (datacenter != null) {
vmSnapshotResponse.setZoneId(datacenter.getUuid());
vmSnapshotResponse.setZoneName(datacenter.getName());
}
}
if (vmSnapshot.getParent() != null) {
VMSnapshot vmSnapshotParent = ApiDBUtils.getVMSnapshotById(vmSnapshot.getParent());
if (vmSnapshotParent != null) {
vmSnapshotResponse.setParent(vmSnapshotParent.getUuid());
vmSnapshotResponse.setParentName(vmSnapshotParent.getDisplayName());
}
}
populateOwner(vmSnapshotResponse, vmSnapshot);
Project project = ApiDBUtils.findProjectByProjectAccountId(vmSnapshot.getAccountId());
if (project != null) {
vmSnapshotResponse.setProjectId(project.getUuid());
vmSnapshotResponse.setProjectName(project.getName());
}
Account account = ApiDBUtils.findAccountById(vmSnapshot.getAccountId());
if (account != null) {
vmSnapshotResponse.setAccountName(account.getAccountName());
}
DomainVO domain = ApiDBUtils.findDomainById(vmSnapshot.getDomainId());
if (domain != null) {
vmSnapshotResponse.setDomainId(domain.getUuid());
vmSnapshotResponse.setDomainName(domain.getName());
}
List<? extends ResourceTag> tags = _resourceTagDao.listBy(vmSnapshot.getId(), ResourceObjectType.VMSnapshot);
List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
for (ResourceTag tag : tags) {
ResourceTagResponse tagResponse = createResourceTagResponse(tag, false);
CollectionUtils.addIgnoreNull(tagResponses, tagResponse);
}
vmSnapshotResponse.setTags(new HashSet<>(tagResponses));
vmSnapshotResponse.setHasAnnotation(annotationDao.hasAnnotations(vmSnapshot.getUuid(), AnnotationService.EntityType.VM_SNAPSHOT.name(), _accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())));
vmSnapshotResponse.setCurrent(vmSnapshot.getCurrent());
vmSnapshotResponse.setType(vmSnapshot.getType().toString());
vmSnapshotResponse.setObjectName("vmsnapshot");
return vmSnapshotResponse;
}
use of com.cloud.vm.snapshot.VMSnapshot in project cloudstack by apache.
the class StorageSystemSnapshotStrategy method takeHypervisorSnapshot.
private VMSnapshot takeHypervisorSnapshot(VolumeInfo volumeInfo) {
VirtualMachine virtualMachine = volumeInfo.getAttachedVM();
if (virtualMachine != null && VirtualMachine.State.Running.equals(virtualMachine.getState())) {
String vmSnapshotName = UUID.randomUUID().toString().replace("-", "");
VMSnapshotVO vmSnapshotVO = new VMSnapshotVO(virtualMachine.getAccountId(), virtualMachine.getDomainId(), virtualMachine.getId(), vmSnapshotName, vmSnapshotName, vmSnapshotName, virtualMachine.getServiceOfferingId(), VMSnapshot.Type.Disk, null);
VMSnapshot vmSnapshot = vmSnapshotDao.persist(vmSnapshotVO);
if (vmSnapshot == null) {
throw new CloudRuntimeException("Unable to allocate a VM snapshot object");
}
vmSnapshot = vmSnapshotService.createVMSnapshot(virtualMachine.getId(), vmSnapshot.getId(), true);
if (vmSnapshot == null) {
throw new CloudRuntimeException("Unable to create a hypervisor-side snapshot");
}
try {
Thread.sleep(60000);
} catch (Exception ex) {
s_logger.warn(ex.getMessage(), ex);
}
return vmSnapshot;
}
// We didn't need to take a hypervisor-side snapshot. Return 'null' to indicate this.
return null;
}
use of com.cloud.vm.snapshot.VMSnapshot in project cloudstack by apache.
the class ScaleIOVMSnapshotStrategy method publishUsageEvent.
private void publishUsageEvent(String type, VMSnapshot vmSnapshot, UserVm userVm, VolumeObjectTO volumeTo) {
VolumeVO volume = volumeDao.findById(volumeTo.getId());
Long diskOfferingId = volume.getDiskOfferingId();
Long offeringId = null;
if (diskOfferingId != null) {
DiskOfferingVO offering = diskOfferingDao.findById(diskOfferingId);
if (offering != null && !offering.isComputeOnly()) {
offeringId = offering.getId();
}
}
Map<String, String> details = new HashMap<>();
if (vmSnapshot != null) {
details.put(UsageEventVO.DynamicParameters.vmSnapshotId.name(), String.valueOf(vmSnapshot.getId()));
}
// save volume's id into templateId field
UsageEventUtils.publishUsageEvent(// save volume's id into templateId field
type, // save volume's id into templateId field
vmSnapshot.getAccountId(), // save volume's id into templateId field
userVm.getDataCenterId(), // save volume's id into templateId field
userVm.getId(), // save volume's id into templateId field
vmSnapshot.getName(), // save volume's id into templateId field
offeringId, // save volume's id into templateId field
volume.getId(), volumeTo.getSize(), VMSnapshot.class.getName(), vmSnapshot.getUuid(), details);
}
Aggregations