Search in sources :

Example 71 with EngineException

use of org.ovirt.engine.core.common.errors.EngineException in project ovirt-engine by oVirt.

the class CreateSnapshotForVmCommand method freezeVm.

/**
 * Freezing the VM is needed for live snapshot with Cinder disks.
 */
private void freezeVm() {
    if (!shouldFreezeOrThawVm()) {
        return;
    }
    VDSReturnValue returnValue;
    try {
        auditLogDirector.log(this, AuditLogType.FREEZE_VM_INITIATED);
        returnValue = runVdsCommand(VDSCommandType.Freeze, new VdsAndVmIDVDSParametersBase(getVds().getId(), getVmId()));
    } catch (EngineException e) {
        handleFreezeVmFailure(e);
        return;
    }
    if (returnValue.getSucceeded()) {
        auditLogDirector.log(this, AuditLogType.FREEZE_VM_SUCCESS);
    } else {
        handleFreezeVmFailure(new EngineException(EngineError.freezeErr));
    }
}
Also used : VdsAndVmIDVDSParametersBase(org.ovirt.engine.core.common.vdscommands.VdsAndVmIDVDSParametersBase) EngineException(org.ovirt.engine.core.common.errors.EngineException) VDSReturnValue(org.ovirt.engine.core.common.vdscommands.VDSReturnValue)

Example 72 with EngineException

use of org.ovirt.engine.core.common.errors.EngineException in project ovirt-engine by oVirt.

the class TryBackToAllSnapshotsOfVmCommand method executeVmCommand.

@Override
protected void executeVmCommand() {
    final boolean restoreMemory = isRestoreMemory();
    final Guid newActiveSnapshotId = Guid.newGuid();
    final Snapshot snapshotToBePreviewed = getDstSnapshot();
    final Snapshot previousActiveSnapshot = snapshotDao.get(getVmId(), SnapshotType.ACTIVE);
    final Guid previousActiveSnapshotId = previousActiveSnapshot.getId();
    final List<DiskImage> images = getImagesToPreview();
    // Images list without those that are excluded from preview
    final List<DiskImage> filteredImages = (List<DiskImage>) CollectionUtils.subtract(images, getImagesExcludedFromPreview(images, previousActiveSnapshotId, newActiveSnapshotId));
    if (log.isInfoEnabled()) {
        log.info("Previewing snapshot {} with the disks:\n{}", getSnapshotName(), filteredImages.stream().map(disk -> String.format("%s (%s) to imageId %s", disk.getName(), disk.getId().toString(), disk.getImageId().toString())).collect(Collectors.joining("\n")));
    }
    final List<CinderDisk> cinderDisks = new ArrayList<>();
    TransactionSupport.executeInNewTransaction(() -> {
        getCompensationContext().snapshotEntity(previousActiveSnapshot);
        snapshotDao.remove(previousActiveSnapshotId);
        getSnapshotsManager().addSnapshot(previousActiveSnapshotId, "Active VM before the preview", SnapshotStatus.LOCKED, SnapshotType.PREVIEW, getVm(), true, previousActiveSnapshot.getMemoryDiskId(), previousActiveSnapshot.getMetadataDiskId(), null, null, null, getCompensationContext());
        getSnapshotsManager().addActiveSnapshot(newActiveSnapshotId, getVm(), SnapshotStatus.OK, restoreMemory ? snapshotToBePreviewed.getMemoryDiskId() : null, restoreMemory ? snapshotToBePreviewed.getMetadataDiskId() : null, snapshotToBePreviewed.getCreationDate(), images, getCompensationContext());
        // being executed in the same transaction so we can restore the vm config and end the command.
        if (!filteredImages.isEmpty()) {
            getCompensationContext().stateChanged();
        } else {
            vmStaticDao.incrementDbGeneration(getVm().getId());
            restoreVmConfigFromSnapshot();
        }
        return null;
    });
    initializeSnapshotsLeasesParams();
    if (!filteredImages.isEmpty()) {
        vmHandler.lockVm(getVm().getDynamicData(), getCompensationContext());
        freeLock();
        TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {

            @Override
            public Void runInTransaction() {
                for (DiskImage image : filteredImages) {
                    if (image.getDiskStorageType() == DiskStorageType.CINDER) {
                        cinderDisks.add((CinderDisk) image);
                        continue;
                    }
                    ActionReturnValue actionReturnValue = runInternalActionWithTasksContext(ActionType.TryBackToSnapshot, buildTryBackToSnapshotParameters(newActiveSnapshotId, image));
                    if (actionReturnValue.getSucceeded()) {
                        getTaskIdList().addAll(actionReturnValue.getInternalVdsmTaskIdList());
                    } else if (actionReturnValue.getFault() != null) {
                        // if we have a fault, forward it to the user
                        throw new EngineException(actionReturnValue.getFault().getError(), actionReturnValue.getFault().getMessage());
                    } else {
                        log.error("Cannot create snapshot");
                        throw new EngineException(EngineError.IRS_IMAGE_STATUS_ILLEGAL);
                    }
                }
                if (getParameters().getLeaseAction() == LeaseAction.CREATE_NEW_LEASE) {
                    if (!addVmLease(getParameters().getDstLeaseDomainId(), getVm().getId(), false)) {
                        log.error("Failed to create lease for VM '{}' on storage domain '{}'", getVm().getName(), getParameters().getDstLeaseDomainId());
                        throw new EngineException(EngineError.FailedToCreateLease);
                    }
                }
                if (!cinderDisks.isEmpty() && !tryBackAllCinderDisks(cinderDisks, newActiveSnapshotId)) {
                    throw new EngineException(EngineError.CINDER_ERROR, "Failed to preview a snapshot!");
                }
                return null;
            }

            private ImagesContainterParametersBase buildTryBackToSnapshotParameters(final Guid newActiveSnapshotId, DiskImage image) {
                ImagesContainterParametersBase params = new ImagesContainterParametersBase(image.getImageId());
                params.setParentCommand(ActionType.TryBackToAllSnapshotsOfVm);
                params.setVmSnapshotId(newActiveSnapshotId);
                params.setEntityInfo(getParameters().getEntityInfo());
                params.setParentParameters(getParameters());
                params.setQuotaId(image.getQuotaId());
                return params;
            }
        });
    } else {
        // if there are no disks to restore, no compensation context is saved and the VM Configuration
        // (including clusterCompatibilityVersionOrigin) is already restored at this point. Otherwise,
        // if disks are being restored, the VM Configuration is restored later in endSuccessfully()
        updateClusterCompatibilityVersionToOldCluster(true);
    }
    setSucceeded(true);
}
Also used : ImagesContainterParametersBase(org.ovirt.engine.core.common.action.ImagesContainterParametersBase) ArrayList(java.util.ArrayList) EngineException(org.ovirt.engine.core.common.errors.EngineException) Guid(org.ovirt.engine.core.compat.Guid) Snapshot(org.ovirt.engine.core.common.businessentities.Snapshot) ActionReturnValue(org.ovirt.engine.core.common.action.ActionReturnValue) List(java.util.List) ArrayList(java.util.ArrayList) CinderDisk(org.ovirt.engine.core.common.businessentities.storage.CinderDisk) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage)

Example 73 with EngineException

use of org.ovirt.engine.core.common.errors.EngineException in project ovirt-engine by oVirt.

the class RestoreAllSnapshotsCommand method restoreSnapshotAndRemoveObsoleteSnapshots.

/**
 * Restore the snapshot - if it is not the active snapshot, then the VM configuration will be restored.<br>
 * Additionally, remove all obsolete snapshots (The one after stateless, or the preview chain which was not chosen).
 */
protected void restoreSnapshotAndRemoveObsoleteSnapshots(Snapshot targetSnapshot) {
    Guid activeSnapshotId = snapshotDao.getId(getVmId(), SnapshotType.ACTIVE);
    List<DiskImage> imagesFromActiveSnapshot = diskImageDao.getAllSnapshotsForVmSnapshot(activeSnapshotId);
    Snapshot previewedSnapshot = snapshotDao.get(getVmId(), SnapshotType.PREVIEW);
    if (previewedSnapshot != null) {
        VM vmFromConf = snapshotVmConfigurationHelper.getVmFromConfiguration(previewedSnapshot.getVmConfiguration(), previewedSnapshot.getVmId(), previewedSnapshot.getId());
        List<DiskImage> previewedImagesFromDB = diskImageDao.getAllSnapshotsForVmSnapshot(previewedSnapshot.getId());
        imagesFromPreviewSnapshot.addAll(ImagesHandler.imagesIntersection(vmFromConf.getImages(), previewedImagesFromDB));
    }
    List<DiskImage> intersection = ImagesHandler.imagesIntersection(imagesFromActiveSnapshot, imagesFromPreviewSnapshot);
    switch(targetSnapshot.getType()) {
        case PREVIEW:
            snapshotDao.updateStatus(snapshotDao.getId(getVmId(), SnapshotType.REGULAR, SnapshotStatus.IN_PREVIEW), SnapshotStatus.OK);
            getParameters().setImages((List<DiskImage>) CollectionUtils.union(imagesFromPreviewSnapshot, intersection));
            imagesFromPreviewSnapshot.forEach(image -> {
                if (image.getDiskStorageType() != DiskStorageType.CINDER) {
                    imagesToRestore.add(image);
                } else {
                    List<DiskImage> cinderDiskFromPreviewSnapshot = intersection.stream().filter(diskImage -> diskImage.getId().equals(image.getId())).collect(Collectors.toList());
                    if (!cinderDiskFromPreviewSnapshot.isEmpty()) {
                        imagesToRestore.add(cinderDiskFromPreviewSnapshot.get(0));
                    }
                }
            });
            updateSnapshotIdForSkipRestoreImages(ImagesHandler.imagesSubtract(imagesFromActiveSnapshot, imagesToRestore), targetSnapshot.getId());
            restoreConfiguration(targetSnapshot);
            break;
        case STATELESS:
            imagesToRestore = getParameters().getImages();
            restoreConfiguration(targetSnapshot);
            break;
        case REGULAR:
            prepareToDeletePreviewBranch(imagesFromActiveSnapshot);
            // Set the active snapshot's images as target images for restore, because they are what we keep.
            getParameters().setImages(imagesFromActiveSnapshot);
            imagesFromActiveSnapshot.forEach(image -> {
                List<DiskImage> cinderDiskFromPreviewSnapshot = imagesFromPreviewSnapshot.stream().filter(diskImage -> diskImage.getId().equals(image.getId())).collect(Collectors.toList());
                if (!cinderDiskFromPreviewSnapshot.isEmpty()) {
                    if (image.getDiskStorageType() == DiskStorageType.IMAGE) {
                        imagesToRestore.add(image);
                    } else if (image.getDiskStorageType() == DiskStorageType.CINDER) {
                        CinderDisk cinderVolume = getInitialCinderVolumeToDelete(image);
                        if (cinderVolume != null) {
                            imagesToRestore.add(cinderVolume);
                        }
                    }
                }
            });
            updateSnapshotIdForSkipRestoreImages(ImagesHandler.imagesSubtract(imagesFromActiveSnapshot, imagesToRestore), activeSnapshotId);
            break;
        default:
            throw new EngineException(EngineError.ENGINE, "No support for restoring to snapshot type: " + targetSnapshot.getType());
    }
}
Also used : LockMessagesMatchUtil(org.ovirt.engine.core.bll.LockMessagesMatchUtil) CinderDisk(org.ovirt.engine.core.common.businessentities.storage.CinderDisk) EngineException(org.ovirt.engine.core.common.errors.EngineException) SnapshotDao(org.ovirt.engine.core.dao.SnapshotDao) VmDynamicDao(org.ovirt.engine.core.dao.VmDynamicDao) ActionReturnValue(org.ovirt.engine.core.common.action.ActionReturnValue) RestoreAllSnapshotsParameters(org.ovirt.engine.core.common.action.RestoreAllSnapshotsParameters) VmStaticDao(org.ovirt.engine.core.dao.VmStaticDao) CommandContext(org.ovirt.engine.core.bll.context.CommandContext) ActionType(org.ovirt.engine.core.common.action.ActionType) Future(java.util.concurrent.Future) DisksFilter(org.ovirt.engine.core.bll.storage.disk.image.DisksFilter) Map(java.util.Map) Snapshot(org.ovirt.engine.core.common.businessentities.Snapshot) Instance(javax.enterprise.inject.Instance) DiskImagesValidator(org.ovirt.engine.core.bll.validator.storage.DiskImagesValidator) DiskStorageType(org.ovirt.engine.core.common.businessentities.storage.DiskStorageType) EngineMessage(org.ovirt.engine.core.common.errors.EngineMessage) Set(java.util.Set) Collectors(java.util.stream.Collectors) ConcurrentChildCommandsExecutionCallback(org.ovirt.engine.core.bll.ConcurrentChildCommandsExecutionCallback) SnapshotType(org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType) Objects(java.util.Objects) ONLY_NOT_SHAREABLE(org.ovirt.engine.core.bll.storage.disk.image.DisksFilter.ONLY_NOT_SHAREABLE) List(java.util.List) VmValidator(org.ovirt.engine.core.bll.validator.VmValidator) Optional(java.util.Optional) MultipleStorageDomainsValidator(org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator) AuditLogType(org.ovirt.engine.core.common.AuditLogType) VdcObjectType(org.ovirt.engine.core.common.VdcObjectType) QuotaConsumptionParameter(org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter) VmLeaseVDSParameters(org.ovirt.engine.core.common.vdscommands.VmLeaseVDSParameters) QuotaStorageDependent(org.ovirt.engine.core.bll.quota.QuotaStorageDependent) EntityInfo(org.ovirt.engine.core.common.asynctasks.EntityInfo) LockProperties(org.ovirt.engine.core.common.action.LockProperties) Guid(org.ovirt.engine.core.compat.Guid) RestoreAllCinderSnapshotsParameters(org.ovirt.engine.core.common.action.RestoreAllCinderSnapshotsParameters) SnapshotActionEnum(org.ovirt.engine.core.common.businessentities.SnapshotActionEnum) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage) OvfUtils(org.ovirt.engine.core.utils.OvfUtils) ArrayList(java.util.ArrayList) CommandCoordinatorUtil(org.ovirt.engine.core.bll.tasks.CommandCoordinatorUtil) ImageStatus(org.ovirt.engine.core.common.businessentities.storage.ImageStatus) HashSet(java.util.HashSet) Inject(javax.inject.Inject) CollectionUtils(org.apache.commons.collections.CollectionUtils) DiskImageDao(org.ovirt.engine.core.dao.DiskImageDao) ONLY_ACTIVE(org.ovirt.engine.core.bll.storage.disk.image.DisksFilter.ONLY_ACTIVE) VmCommand(org.ovirt.engine.core.bll.VmCommand) Pair(org.ovirt.engine.core.common.utils.Pair) RestoreFromSnapshotParameters(org.ovirt.engine.core.common.action.RestoreFromSnapshotParameters) ImagesHandler(org.ovirt.engine.core.bll.storage.disk.image.ImagesHandler) StoragePoolValidator(org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator) SnapshotStatus(org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotStatus) LockingGroup(org.ovirt.engine.core.common.locks.LockingGroup) EndProcedure(org.ovirt.engine.core.common.action.ActionParametersBase.EndProcedure) ImagesContainterParametersBase(org.ovirt.engine.core.common.action.ImagesContainterParametersBase) VDSReturnValue(org.ovirt.engine.core.common.vdscommands.VDSReturnValue) Scope(org.ovirt.engine.core.common.action.LockProperties.Scope) Typed(javax.enterprise.inject.Typed) QuotaStorageConsumptionParameter(org.ovirt.engine.core.bll.quota.QuotaStorageConsumptionParameter) EngineError(org.ovirt.engine.core.common.errors.EngineError) ExecutionException(java.util.concurrent.ExecutionException) VM(org.ovirt.engine.core.common.businessentities.VM) CommandCallback(org.ovirt.engine.core.bll.tasks.interfaces.CommandCallback) PermissionSubject(org.ovirt.engine.core.bll.utils.PermissionSubject) RemoveImageParameters(org.ovirt.engine.core.common.action.RemoveImageParameters) VDSCommandType(org.ovirt.engine.core.common.vdscommands.VDSCommandType) Collections(java.util.Collections) VmInterfaceManager(org.ovirt.engine.core.bll.network.VmInterfaceManager) ImageDao(org.ovirt.engine.core.dao.ImageDao) Snapshot(org.ovirt.engine.core.common.businessentities.Snapshot) VM(org.ovirt.engine.core.common.businessentities.VM) EngineException(org.ovirt.engine.core.common.errors.EngineException) Guid(org.ovirt.engine.core.compat.Guid) CinderDisk(org.ovirt.engine.core.common.businessentities.storage.CinderDisk) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage)

Example 74 with EngineException

use of org.ovirt.engine.core.common.errors.EngineException in project ovirt-engine by oVirt.

the class RestoreFromSnapshotCommand method performImageVdsmOperation.

@Override
protected boolean performImageVdsmOperation() {
    VDSReturnValue vdsReturnValue = null;
    try {
        Guid storagePoolId = getDiskImage().getStoragePoolId() != null ? getDiskImage().getStoragePoolId() : Guid.Empty;
        Guid storageDomainId = getDiskImage().getStorageIds() != null && !getDiskImage().getStorageIds().isEmpty() ? getDiskImage().getStorageIds().get(0) : Guid.Empty;
        Guid imageGroupId = getDiskImage().getId() != null ? getDiskImage().getId() : Guid.Empty;
        Guid taskId = persistAsyncTaskPlaceHolder(ActionType.RestoreAllSnapshots);
        vdsReturnValue = runVdsCommand(VDSCommandType.DestroyImage, postDeleteActionHandler.fixParameters(new DestroyImageVDSCommandParameters(storagePoolId, storageDomainId, imageGroupId, _imagesToDelete, getDiskImage().isWipeAfterDelete(), storageDomainDao.get(storageDomainId).getDiscardAfterDelete(), true)));
        if (vdsReturnValue.getSucceeded()) {
            getReturnValue().getInternalVdsmTaskIdList().add(createTask(taskId, vdsReturnValue.getCreationInfo(), ActionType.RestoreAllSnapshots, VdcObjectType.Storage, storageDomainId));
        }
    }// Don't throw an exception when cannot destroy image in the VDSM.
     catch (EngineException e) {
        // Set fault for parent command RestoreAllSnapshotCommand to use, if decided to fail the command.
        getReturnValue().setFault(new EngineFault(e, e.getVdsError().getCode()));
        log.info("Image '{}' not exist in Irs", getDiskImage().getImageId());
    }
    return vdsReturnValue != null ? vdsReturnValue.getSucceeded() : false;
}
Also used : DestroyImageVDSCommandParameters(org.ovirt.engine.core.common.vdscommands.DestroyImageVDSCommandParameters) EngineFault(org.ovirt.engine.core.common.errors.EngineFault) EngineException(org.ovirt.engine.core.common.errors.EngineException) Guid(org.ovirt.engine.core.compat.Guid) VDSReturnValue(org.ovirt.engine.core.common.vdscommands.VDSReturnValue)

Example 75 with EngineException

use of org.ovirt.engine.core.common.errors.EngineException in project ovirt-engine by oVirt.

the class RefreshGlusterHooksCommandTest method executeCommandWhenFailed.

@Test
public void executeCommandWhenFailed() {
    setupMocks();
    doThrow(new EngineException(EngineError.GlusterHookListException)).when(hookSyncJob).refreshHooksInCluster(getCluster(), true);
    try {
        cmd.executeCommand();
        fail("Expected EngineException");
    } catch (EngineException e) {
        assertEquals(EngineError.GlusterHookListException, e.getErrorCode());
        assertEquals(AuditLogType.GLUSTER_HOOK_REFRESH_FAILED, cmd.getAuditLogTypeValue());
    }
}
Also used : EngineException(org.ovirt.engine.core.common.errors.EngineException) Test(org.junit.Test) BaseCommandTest(org.ovirt.engine.core.bll.BaseCommandTest)

Aggregations

EngineException (org.ovirt.engine.core.common.errors.EngineException)107 Guid (org.ovirt.engine.core.compat.Guid)30 ActionReturnValue (org.ovirt.engine.core.common.action.ActionReturnValue)25 VDSReturnValue (org.ovirt.engine.core.common.vdscommands.VDSReturnValue)25 DiskImage (org.ovirt.engine.core.common.businessentities.storage.DiskImage)18 ArrayList (java.util.ArrayList)17 VDS (org.ovirt.engine.core.common.businessentities.VDS)11 HashMap (java.util.HashMap)7 Pair (org.ovirt.engine.core.common.utils.Pair)7 HashSet (java.util.HashSet)6 List (java.util.List)6 Callable (java.util.concurrent.Callable)6 Snapshot (org.ovirt.engine.core.common.businessentities.Snapshot)6 IOException (java.io.IOException)5 EntityInfo (org.ovirt.engine.core.common.asynctasks.EntityInfo)5 Map (java.util.Map)4 PersistentHostSetupNetworksParameters (org.ovirt.engine.core.common.action.PersistentHostSetupNetworksParameters)4 Cluster (org.ovirt.engine.core.common.businessentities.Cluster)4 Set (java.util.Set)3 VdsActionParameters (org.ovirt.engine.core.common.action.VdsActionParameters)3