Search in sources :

Example 6 with VMSnapshot

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

the class LibvirtRevertToVMSnapshotCommandWrapper method execute.

@Override
public Answer execute(final RevertToVMSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) {
    final String vmName = cmd.getVmName();
    final List<VolumeObjectTO> listVolumeTo = cmd.getVolumeTOs();
    final VMSnapshot.Type vmSnapshotType = cmd.getTarget().getType();
    final Boolean snapshotMemory = vmSnapshotType == VMSnapshot.Type.DiskAndMemory;
    final PowerState vmState;
    Domain dm = null;
    try {
        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
        final Connect conn = libvirtUtilitiesHelper.getConnection();
        dm = libvirtComputingResource.getDomain(conn, vmName);
        if (dm == null) {
            return new RevertToVMSnapshotAnswer(cmd, false, "Revert to VM Snapshot Failed due to can not find vm: " + vmName);
        }
        final DomainSnapshot snapshot = dm.snapshotLookupByName(cmd.getTarget().getSnapshotName());
        if (snapshot == null) {
            return new RevertToVMSnapshotAnswer(cmd, false, "Cannot find vmSnapshot with name: " + cmd.getTarget().getSnapshotName());
        }
        dm.revertToSnapshot(snapshot, VIR_DOMAIN_SNAPSHOT_REVERT_FORCE | VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING);
        snapshot.free();
        if (!snapshotMemory) {
            dm.destroy();
            if (dm.isPersistent() == 1) {
                dm.undefine();
            }
            vmState = PowerState.PowerOff;
        } else {
            vmState = PowerState.PowerOn;
        }
        return new RevertToVMSnapshotAnswer(cmd, listVolumeTo, vmState);
    } catch (final LibvirtException e) {
        final String msg = " Revert to VM snapshot failed due to " + e.toString();
        s_logger.warn(msg, e);
        return new RevertToVMSnapshotAnswer(cmd, false, msg);
    } finally {
        if (dm != null) {
            try {
                dm.free();
            } catch (final LibvirtException l) {
                s_logger.trace("Ignoring libvirt error.", l);
            }
            ;
        }
    }
}
Also used : RevertToVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.RevertToVMSnapshotAnswer) LibvirtException(org.libvirt.LibvirtException) Connect(org.libvirt.Connect) DomainSnapshot(org.libvirt.DomainSnapshot) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) VolumeObjectTO(com.cloud.legacymodel.to.VolumeObjectTO) Domain(org.libvirt.Domain) PowerState(com.cloud.legacymodel.vm.VirtualMachine.PowerState)

Example 7 with VMSnapshot

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

the class CreateVMSnapshotCmd method execute.

@Override
public void execute() {
    CallContext.current().setEventDetails("VM Id: " + getVmId());
    final VMSnapshot result = _vmSnapshotService.createVMSnapshot(getVmId(), getEntityId(), Boolean.FALSE);
    if (result != null) {
        final VMSnapshotResponse response = _responseGenerator.createVMSnapshotResponse(result);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create vm snapshot due to an internal error creating snapshot for vm " + getVmId());
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) VMSnapshotResponse(com.cloud.api.response.VMSnapshotResponse) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot)

Example 8 with VMSnapshot

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

the class VMSnapshotStrategyTest method testCreateVMSnapshot.

@Test
public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException {
    final Long hostId = 1L;
    final Long vmId = 1L;
    final Long guestOsId = 1L;
    final HypervisorType hypervisorType = HypervisorType.Any;
    final String hypervisorVersion = "default";
    final String guestOsName = "Other";
    final List<VolumeObjectTO> volumeObjectTOs = new ArrayList<>();
    final VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
    final UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
    Mockito.when(userVmVO.getGuestOSId()).thenReturn(guestOsId);
    Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId);
    Mockito.when(vmSnapshotHelper.pickRunningHost(Matchers.anyLong())).thenReturn(hostId);
    Mockito.when(vmSnapshotHelper.getVolumeTOList(Matchers.anyLong())).thenReturn(volumeObjectTOs);
    Mockito.when(userVmDao.findById(Matchers.anyLong())).thenReturn(userVmVO);
    final GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
    Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
    final GuestOSHypervisorVO guestOSHypervisorVO = Mockito.mock(GuestOSHypervisorVO.class);
    Mockito.when(guestOSHypervisorVO.getGuestOsName()).thenReturn(guestOsName);
    Mockito.when(guestOsHypervisorDao.findById(Matchers.anyLong())).thenReturn(guestOSHypervisorVO);
    Mockito.when(guestOsHypervisorDao.findByOsIdAndHypervisor(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(guestOSHypervisorVO);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
    final HostVO hostVO = Mockito.mock(HostVO.class);
    Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(hostVO);
    Mockito.when(hostVO.getHypervisorType()).thenReturn(hypervisorType);
    Mockito.when(hostVO.getHypervisorVersion()).thenReturn(hypervisorVersion);
    Exception e = null;
    try {
        vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
    } catch (final CloudRuntimeException e1) {
        e = e1;
    }
    assertNotNull(e);
    final CreateVMSnapshotAnswer answer = Mockito.mock(CreateVMSnapshotAnswer.class);
    Mockito.when(answer.getResult()).thenReturn(true);
    Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
    Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
    VMSnapshot snapshot = null;
    snapshot = vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
    assertNotNull(snapshot);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) VMSnapshot(com.cloud.legacymodel.storage.VMSnapshot) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) IOException(java.io.IOException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) CreateVMSnapshotAnswer(com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer) Command(com.cloud.legacymodel.communication.command.Command) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VolumeObjectTO(com.cloud.legacymodel.to.VolumeObjectTO) Test(org.junit.Test)

Example 9 with VMSnapshot

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

the class VMSnapshotManagerImpl method deleteVMSnapshot.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_SNAPSHOT_DELETE, eventDescription = "delete vm snapshots", async = true)
public boolean deleteVMSnapshot(final Long vmSnapshotId) {
    final Account caller = getCaller();
    final VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
    if (vmSnapshot == null) {
        throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId);
    }
    _accountMgr.checkAccess(caller, null, true, vmSnapshot);
    // check VM snapshot states, only allow to delete vm snapshots in created and error state
    if (VMSnapshot.State.Ready != vmSnapshot.getState() && VMSnapshot.State.Expunging != vmSnapshot.getState() && VMSnapshot.State.Error != vmSnapshot.getState()) {
        throw new InvalidParameterValueException("Can't delete the vm snapshotshot " + vmSnapshotId + " due to it is not in Created or Error, or Expunging State");
    }
    // check if there are other active VM snapshot tasks
    if (hasActiveVMSnapshotTasks(vmSnapshot.getVmId())) {
        final List<VMSnapshotVO> expungingSnapshots = _vmSnapshotDao.listByInstanceId(vmSnapshot.getVmId(), VMSnapshot.State.Expunging);
        if (expungingSnapshots.size() > 0 && expungingSnapshots.get(0).getId() == vmSnapshot.getId()) {
            s_logger.debug("Target VM snapshot already in expunging state, go on deleting it: " + vmSnapshot.getDisplayName());
        } else {
            throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later");
        }
    }
    // serialize VM operation
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmSnapshot.getVmId());
        try {
            return orchestrateDeleteVMSnapshot(vmSnapshotId);
        } finally {
            _workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<VMSnapshot> outcome = deleteVMSnapshotThroughJobQueue(vmSnapshot.getVmId(), vmSnapshotId);
        VMSnapshot result = null;
        try {
            result = outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final ExecutionException e) {
            throw new RuntimeException("Execution excetion", 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);
            }
        }
        if (jobResult instanceof Boolean) {
            return (Boolean) jobResult;
        }
        return false;
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) 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) ExecutionException(java.util.concurrent.ExecutionException) ActionEvent(com.cloud.event.ActionEvent)

Example 10 with VMSnapshot

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

the class VMSnapshotManagerImpl method revertToSnapshot.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_SNAPSHOT_REVERT, eventDescription = "revert to VM snapshot", async = true)
public UserVm revertToSnapshot(final Long vmSnapshotId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException {
    // check if VM snapshot exists in DB
    final VMSnapshotVO vmSnapshotVo = _vmSnapshotDao.findById(vmSnapshotId);
    if (vmSnapshotVo == null) {
        throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId);
    }
    final Long vmId = vmSnapshotVo.getVmId();
    final UserVmVO userVm = _userVMDao.findById(vmId);
    // check if VM exists
    if (userVm == null) {
        throw new InvalidParameterValueException("Revert vm to snapshot: " + vmSnapshotId + " failed due to vm: " + vmId + " is not found");
    }
    // check if there are other active VM snapshot tasks
    if (hasActiveVMSnapshotTasks(vmId)) {
        throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later");
    }
    final Account caller = getCaller();
    _accountMgr.checkAccess(caller, null, true, vmSnapshotVo);
    // VM should be in running or stopped states
    if (userVm.getState() != VirtualMachine.State.Running && userVm.getState() != VirtualMachine.State.Stopped) {
        throw new InvalidParameterValueException("VM Snapshot reverting failed due to vm is not in the state of Running or Stopped.");
    }
    if (userVm.getState() == VirtualMachine.State.Running && vmSnapshotVo.getType() == VMSnapshot.Type.Disk || userVm.getState() == VirtualMachine.State.Stopped && vmSnapshotVo.getType() == VMSnapshot.Type.DiskAndMemory) {
        throw new InvalidParameterValueException("VM Snapshot revert not allowed. This will result in VM state change. You can revert running VM to disk and memory type snapshot and stopped VM to disk type" + " snapshot");
    }
    // if snapshot is not created, error out
    if (vmSnapshotVo.getState() != VMSnapshot.State.Ready) {
        throw new InvalidParameterValueException("VM Snapshot reverting failed due to vm snapshot is not in the state of Created.");
    }
    // serialize VM operation
    final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        final VmWorkJobVO placeHolder;
        placeHolder = createPlaceHolderWork(vmSnapshotVo.getVmId());
        try {
            return orchestrateRevertToVMSnapshot(vmSnapshotId);
        } finally {
            _workJobDao.expunge(placeHolder.getId());
        }
    } else {
        final Outcome<VMSnapshot> outcome = revertToVMSnapshotThroughJobQueue(vmSnapshotVo.getVmId(), vmSnapshotId);
        VMSnapshot result = null;
        try {
            result = outcome.get();
        } catch (final InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (final ExecutionException e) {
            throw new RuntimeException("Execution excetion", e);
        }
        final Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof InsufficientCapacityException) {
                throw (InsufficientCapacityException) jobResult;
            } else if (jobResult instanceof ResourceUnavailableException) {
                throw (ResourceUnavailableException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            }
        }
        return userVm;
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) 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) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ExecutionException(java.util.concurrent.ExecutionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ActionEvent(com.cloud.event.ActionEvent)

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