Search in sources :

Example 11 with VMSnapshot

use of com.cloud.legacymodel.storage.VMSnapshot in project cosmic by MissionCriticalCloud.

the class VMSnapshotManagerImpl method createVMSnapshot.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_SNAPSHOT_CREATE, eventDescription = "creating VM snapshot", async = true)
public VMSnapshot createVMSnapshot(final Long vmId, final Long vmSnapshotId, final Boolean quiescevm) {
    final UserVmVO userVm = _userVMDao.findById(vmId);
    if (userVm == null) {
        throw new InvalidParameterValueException("Create vm to snapshot failed due to vm: " + vmId + " is not found");
    }
    final VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
    if (vmSnapshot == null) {
        throw new CloudRuntimeException("VM snapshot id: " + vmSnapshotId + " can not be found");
    }
    // serialize VM operation
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmId);
        try {
            return orchestrateCreateVMSnapshot(vmId, vmSnapshotId, quiescevm);
        } finally {
            _workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<VMSnapshot> outcome = createVMSnapshotThroughJobQueue(vmId, vmSnapshotId, quiescevm);
        final VMSnapshot result;
        try {
            result = outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final ExecutionException e) {
            throw new RuntimeException("Execution exception", e);
        }
        final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            }
        }
        return result;
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) ActionEvent(com.cloud.event.ActionEvent)

Example 12 with VMSnapshot

use of com.cloud.legacymodel.storage.VMSnapshot in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method createVMSnapshotResponse.

@Override
public VMSnapshotResponse createVMSnapshotResponse(final VMSnapshot vmSnapshot) {
    final 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());
    final UserVm vm = ApiDBUtils.findUserVmById(vmSnapshot.getVmId());
    if (vm != null) {
        vmSnapshotResponse.setVirtualMachineid(vm.getUuid());
    }
    if (vmSnapshot.getParent() != null) {
        final VMSnapshot vmSnapshotParent = ApiDBUtils.getVMSnapshotById(vmSnapshot.getParent());
        if (vmSnapshotParent != null) {
            vmSnapshotResponse.setParent(vmSnapshotParent.getUuid());
            vmSnapshotResponse.setParentName(vmSnapshotParent.getDisplayName());
        }
    }
    populateOwner(vmSnapshotResponse, vmSnapshot);
    final Project project = ApiDBUtils.findProjectByProjectAccountId(vmSnapshot.getAccountId());
    if (project != null) {
        vmSnapshotResponse.setProjectId(project.getUuid());
        vmSnapshotResponse.setProjectName(project.getName());
    }
    vmSnapshotResponse.setCurrent(vmSnapshot.getCurrent());
    vmSnapshotResponse.setType(vmSnapshot.getType().toString());
    vmSnapshotResponse.setObjectName("vmsnapshot");
    return vmSnapshotResponse;
}
Also used : Project(com.cloud.projects.Project) UserVm(com.cloud.uservm.UserVm) VMSnapshotResponse(com.cloud.api.response.VMSnapshotResponse) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot)

Example 13 with VMSnapshot

use of com.cloud.legacymodel.storage.VMSnapshot in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method cleanupAccount.

protected boolean cleanupAccount(final AccountVO account, final long callerUserId, final Account caller) {
    final long accountId = account.getId();
    boolean accountCleanupNeeded = false;
    try {
        // cleanup the users from the account
        final List<UserVO> users = _userDao.listByAccount(accountId);
        for (final 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 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
        final List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
        for (final 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.
        final 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
        final List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
        boolean allTemplatesDeleted = true;
        for (final VMTemplateVO template : userTemplates) {
            if (template.getRemoved() == null) {
                try {
                    allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
                } catch (final 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
        final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
        for (final VMSnapshot vmSnapshot : vmSnapshots) {
            try {
                _vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
            } catch (final Exception e) {
                s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
            }
        }
        // Destroy the account's VMs
        final List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
        }
        // no need to catch exception at this place as expunging vm should pass in order to perform further cleanup
        for (final UserVmVO vm : vms) {
            if (!_vmMgr.expunge(vm, callerUserId, caller)) {
                s_logger.error("Unable to expunge vm: " + vm.getId());
                accountCleanupNeeded = true;
            }
        }
        // Mark the account's volumes as destroyed
        final List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
        for (final VolumeVO volume : volumes) {
            if (!volume.getState().equals(Volume.State.Destroy)) {
                try {
                    volumeService.deleteVolume(volume.getId(), caller);
                } catch (final 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
        final List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
        final List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
        for (final VpnUserVO vpnUser : vpnUsers) {
            _remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
        }
        try {
            for (final RemoteAccessVpnVO vpn : remoteAccessVpns) {
                _remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller);
            }
        } catch (final 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 affinity groups
        final 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());
        final List<NetworkVO> networks = _networkDao.listByOwner(accountId);
        if (networks != null) {
            for (final NetworkVO network : networks) {
                final 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());
        final List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
        for (final 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
            final List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
            for (final 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);
        }
        // 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
        final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
        for (final AccountGuestVlanMapVO map : maps) {
            _dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
        }
        final int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
        s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
        // release dedication if any
        final List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for account " + accountId);
            for (final 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.
        final List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
        for (final 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);
        return true;
    } catch (final 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);
        }
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) VpnUserVO(com.cloud.network.VpnUserVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) Vpc(com.cloud.legacymodel.network.vpc.Vpc) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) VolumeVO(com.cloud.storage.VolumeVO) NetworkVO(com.cloud.network.dao.NetworkVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) CloudAuthenticationException(com.cloud.legacymodel.exceptions.CloudAuthenticationException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InstanceGroupVO(com.cloud.vm.InstanceGroupVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VpnUserVO(com.cloud.network.VpnUserVO) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ResourceCountVO(com.cloud.configuration.ResourceCountVO) IpAddress(com.cloud.network.IpAddress) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Example 14 with VMSnapshot

use of com.cloud.legacymodel.storage.VMSnapshot in project cosmic by MissionCriticalCloud.

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<>();
        // 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());
    }
}
Also used : RevertToVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RevertToVMSnapshotAnswer) HashMap(java.util.HashMap) Connection(com.xensource.xenapi.Connection) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) VM(com.xensource.xenapi.VM) VolumeObjectTO(com.cloud.legacymodel.to.VolumeObjectTO) VBD(com.xensource.xenapi.VBD) VDI(com.xensource.xenapi.VDI) PowerState(com.cloud.legacymodel.vm.VirtualMachine.PowerState)

Aggregations

VMSnapshot (com.cloud.legacymodel.storage.VMSnapshot)14 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)8 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)6 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)5 UserVmVO (com.cloud.vm.UserVmVO)5 Account (com.cloud.legacymodel.user.Account)4 ExecutionException (java.util.concurrent.ExecutionException)4 VMSnapshotResponse (com.cloud.api.response.VMSnapshotResponse)3 ActionEvent (com.cloud.event.ActionEvent)3 AsyncJobExecutionContext (com.cloud.framework.jobs.AsyncJobExecutionContext)3 VmWorkJobVO (com.cloud.framework.jobs.impl.VmWorkJobVO)3 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)3 VolumeObjectTO (com.cloud.legacymodel.to.VolumeObjectTO)3 UserVm (com.cloud.uservm.UserVm)3 RevertToVMSnapshotAnswer (com.cloud.legacymodel.communication.answer.RevertToVMSnapshotAnswer)2 AgentUnavailableException (com.cloud.legacymodel.exceptions.AgentUnavailableException)2 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)2 OperationTimedoutException (com.cloud.legacymodel.exceptions.OperationTimedoutException)2 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)2 PowerState (com.cloud.legacymodel.vm.VirtualMachine.PowerState)2