Search in sources :

Example 11 with AsyncTask

use of org.ovirt.engine.core.common.businessentities.AsyncTask in project ovirt-engine by oVirt.

the class CommandAsyncTask method endCommandAction.

private void endCommandAction() {
    CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks();
    ActionReturnValue actionReturnValue = null;
    ExecutionContext context = null;
    boolean endActionRuntimeException = false;
    AsyncTask dbAsyncTask = getParameters().getDbAsyncTask();
    ArrayList<ActionParametersBase> imagesParameters = new ArrayList<>();
    for (EndedTaskInfo taskInfo : entityInfo.getEndedTasksInfo().getTasksInfo()) {
        ActionParametersBase childTaskParameters = taskInfo.getTaskParameters().getDbAsyncTask().getTaskParameters();
        boolean childTaskGroupSuccess = childTaskParameters.getTaskGroupSuccess() && taskInfo.getTaskStatus().getTaskEndedSuccessfully();
        childTaskParameters.setTaskGroupSuccess(childTaskGroupSuccess);
        if (!childTaskParameters.equals(dbAsyncTask.getActionParameters())) {
            imagesParameters.add(childTaskParameters);
        }
    }
    dbAsyncTask.getActionParameters().setImagesParameters(imagesParameters);
    try {
        log.info("CommandAsyncTask::endCommandAction [within thread] context: Attempting to endAction '{}',", dbAsyncTask.getActionParameters().getCommandType());
        try {
            actionReturnValue = coco.endAction(this);
        } catch (EngineException ex) {
            log.error("{}: {}", getErrorMessage(), ex.getMessage());
            log.debug("Exception", ex);
        } catch (RuntimeException ex) {
            log.error(getErrorMessage(), ex);
            endActionRuntimeException = true;
        }
    } catch (RuntimeException Ex2) {
        log.error("CommandAsyncTask::endCommandAction [within thread]: An exception has been thrown (not" + " related to 'endAction' itself)", Ex2);
        endActionRuntimeException = true;
    } finally {
        // if a RuntimeExcpetion occurs we clear the task from db and perform no other action
        if (endActionRuntimeException) {
            handleEndActionRuntimeException(entityInfo, dbAsyncTask);
        } else {
            boolean isTaskGroupSuccess = dbAsyncTask.getActionParameters().getTaskGroupSuccess();
            handleEndActionResult(entityInfo, actionReturnValue, context, isTaskGroupSuccess);
        }
    }
}
Also used : CommandMultiAsyncTasks(org.ovirt.engine.core.bll.CommandMultiAsyncTasks) ExecutionContext(org.ovirt.engine.core.bll.job.ExecutionContext) ActionReturnValue(org.ovirt.engine.core.common.action.ActionReturnValue) AsyncTask(org.ovirt.engine.core.common.businessentities.AsyncTask) ArrayList(java.util.ArrayList) EngineException(org.ovirt.engine.core.common.errors.EngineException) ActionParametersBase(org.ovirt.engine.core.common.action.ActionParametersBase) EndedTaskInfo(org.ovirt.engine.core.common.asynctasks.EndedTaskInfo)

Example 12 with AsyncTask

use of org.ovirt.engine.core.common.businessentities.AsyncTask in project ovirt-engine by oVirt.

the class SPMAsyncTask method handleEndedTask.

/**
 * Handle ended task operation. Change task state to Ended ,Cleared or
 * Cleared Failed , and log appropriate message.
 */
private void handleEndedTask() {
    AsyncTask asyncTask = getParameters().getDbAsyncTask();
    log.debug("Task of command {} with id '{}' has ended.", asyncTask.getActionType(), getCommandId());
    // last access time to now.
    if (getState() != AsyncTaskState.Ended) {
        setState(AsyncTaskState.Ended);
        setLastStatusAccessTime();
    }
    CommandEntity rootCmdEntity = coco.getCommandEntity(asyncTask.getRootCommandId());
    // if the task's root command has failed
    if (rootCmdEntity != null && !rootCmdEntity.isExecuted()) {
        // mark it as a task of a partially completed command
        // Will result in failure of the command
        setPartiallyCompletedCommandTask(true);
        log.debug("Marking task of command {} with id '{}' as partially completed.", asyncTask.getActionType(), getCommandId());
    }
    // Fail zombie task and task that belongs to a partially submitted command
    if (isZombieTask() || isPartiallyCompletedCommandTask()) {
        log.debug("Task of command {} with id '{}' is a zombie or is partially completed, executing failure logic.", asyncTask.getActionType(), getCommandId());
        getParameters().getDbAsyncTask().getTaskParameters().setTaskGroupSuccess(false);
        ExecutionHandler.getInstance().endTaskStep(parameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED);
        onTaskEndFailure();
    }
    if (hasTaskEndedSuccessfully()) {
        log.debug("Task of command {} with id '{}' has succeeded, executing success logic.", asyncTask.getActionType(), getCommandId());
        ExecutionHandler.getInstance().endTaskStep(parameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FINISHED);
        onTaskEndSuccess();
    } else if (hasTaskEndedInFailure()) {
        log.debug("Task of command {} with id '{}' has failed, executing failure logic.", asyncTask.getActionType(), getCommandId());
        ExecutionHandler.getInstance().endTaskStep(parameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED);
        onTaskEndFailure();
    } else if (!doesTaskExist()) {
        log.debug("Task of command {} with id '{}' does not exist, executing cleanup logic.", asyncTask.getActionType(), getCommandId());
        ExecutionHandler.getInstance().endTaskStep(parameters.getDbAsyncTask().getStepId(), JobExecutionStatus.UNKNOWN);
        onTaskDoesNotExist();
    }
}
Also used : AsyncTask(org.ovirt.engine.core.common.businessentities.AsyncTask) CommandEntity(org.ovirt.engine.core.common.businessentities.CommandEntity)

Example 13 with AsyncTask

use of org.ovirt.engine.core.common.businessentities.AsyncTask in project ovirt-engine by oVirt.

the class MaintenanceNumberOfVdssCommand method validate.

@Override
protected boolean validate() {
    boolean result = true;
    Map<Guid, Cluster> clusters = new HashMap<>();
    Set<Guid> clustersAsSet = new HashSet<>();
    Set<Guid> vdsWithRunningVMs = new HashSet<>();
    List<String> hostNotRespondingList = new ArrayList<>();
    List<String> hostsWithNonMigratableVms = new ArrayList<>();
    List<String> hostsWithVmsWithPluggedDiskSnapshots = new ArrayList<>();
    List<String> nonMigratableVms = new ArrayList<>();
    for (Guid vdsId : getParameters().getVdsIdList()) {
        VDS vds = vdsDao.get(vdsId);
        if (vds == null) {
            log.error("ResourceManager::vdsMaintenance could not find VDS '{}'", vdsId);
            result = failValidation(EngineMessage.VDS_INVALID_SERVER_ID);
            continue;
        }
        // TODO make a more efficient call but normally the command just loads one cluster anyway
        if (!clusters.containsKey(vds.getClusterId())) {
            final Cluster cluster = clusterDao.get(vds.getClusterId());
            clusters.put(cluster.getId(), cluster);
        }
        if (!vdssToMaintenance.containsKey(vdsId)) {
            vdssToMaintenance.put(vdsId, vds);
            if (vds.getSpmStatus() == VdsSpmStatus.SPM) {
                addSharedLockEntry(vds);
            }
        }
        if (getParameters().isStopGlusterService() && !vds.getClusterSupportsGlusterService()) {
            result = failValidation(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_SERVICE_MAINTENANCE_NOT_SUPPORTED_FOR_CLUSTER);
            break;
        }
    }
    result = result && acquireLockInternal();
    if (result) {
        // tasks running
        for (Guid vdsId : getParameters().getVdsIdList()) {
            VDS vds = vdssToMaintenance.get(vdsId);
            if (vds != null) {
                if ((vds.getStatus() != VDSStatus.Maintenance) && (vds.getStatus() != VDSStatus.NonResponsive) && (vds.getStatus() != VDSStatus.Up) && (vds.getStatus() != VDSStatus.Error) && (vds.getStatus() != VDSStatus.PreparingForMaintenance) && (vds.getStatus() != VDSStatus.Down) && (vds.getStatus() != VDSStatus.NonOperational && (vds.getStatus() != VDSStatus.InstallFailed))) {
                    result = failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_IS_NOT_OPERATIONAL);
                } else {
                    List<VM> vms = vmDao.getAllRunningForVds(vdsId);
                    if (!vms.isEmpty()) {
                        vdsWithRunningVMs.add(vdsId);
                    }
                    clustersAsSet.add(vds.getClusterId());
                    List<String> nonMigratableVmDescriptionsToFrontEnd = new ArrayList<>();
                    for (VM vm : vms) {
                        // And they need safe place for migration
                        if (vm.isHostedEngine()) {
                            List<VDS> clusterVdses = vdsDao.getAllForClusterWithStatus(vds.getClusterId(), VDSStatus.Up);
                            if (!HostedEngineHelper.haveHostsAvailableforHE(clusterVdses, getParameters().getVdsIdList())) {
                                failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_NO_ALTERNATE_HOST_FOR_HOSTED_ENGINE);
                                return false;
                            }
                        }
                        // other non-migratable VMs are reported
                        if (vm.getMigrationSupport() != MigrationSupport.MIGRATABLE && !vm.isHostedEngine()) {
                            nonMigratableVmDescriptionsToFrontEnd.add(vm.getName());
                        }
                    }
                    List<AsyncTask> asyncTasks = null;
                    if (nonMigratableVmDescriptionsToFrontEnd.size() > 0) {
                        hostsWithNonMigratableVms.add(vds.getName());
                        nonMigratableVms.addAll(nonMigratableVmDescriptionsToFrontEnd);
                        // The non migratable VM names will be comma separated
                        log.error("VDS '{}' contains non migratable VMs", vdsId);
                        result = false;
                    } else if (!validate(new MultipleVmsValidator(vms).vmNotHavingPluggedDiskSnapshots(EngineMessage.VDS_CANNOT_MAINTENANCE_VM_HAS_PLUGGED_DISK_SNAPSHOT))) {
                        hostsWithVmsWithPluggedDiskSnapshots.add(vds.getName());
                        result = false;
                    } else if (vds.getStatus() == VDSStatus.Maintenance) {
                        result = failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_IS_IN_MAINTENANCE);
                    } else if (vds.getSpmStatus() == VdsSpmStatus.Contending) {
                        result = failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_SPM_CONTENDING);
                    } else if (vds.getStatus() == VDSStatus.NonResponsive && vds.getVmCount() > 0) {
                        result = false;
                        hostNotRespondingList.add(vds.getName());
                    } else if (vds.getStatus() == VDSStatus.NonResponsive && vds.getSpmStatus() != VdsSpmStatus.None) {
                        result = failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_VDS_IS_NOT_RESPONDING_AND_IS_SPM);
                    } else if (vds.getSpmStatus() == VdsSpmStatus.SPM && vds.getStatus() == VDSStatus.Up && ((asyncTasks = asyncTaskDao.getAsyncTaskIdsByStoragePoolId(vds.getStoragePoolId()))).size() > 0) {
                        String runningTasks = asyncTasks.stream().map(AsyncTask::toString).collect(Collectors.joining("\n"));
                        log.warn("There are running tasks on the SPM: '{}'", runningTasks);
                        result = failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_SPM_WITH_RUNNING_TASKS);
                    } else if (!validateNoRunningJobs(vds)) {
                        result = false;
                    } else if (!validateNoActiveImageTransfers(vds)) {
                        result = false;
                    } else if (!clusters.get(vds.getClusterId()).isInUpgradeMode()) {
                        result = handlePositiveEnforcingAffinityGroup(vdsId, vms);
                    }
                }
            }
        }
        // If one of the host is non responsive with running VM's, add a Validate message.
        handleNonResponsiveHosts(hostNotRespondingList);
        // If one of the vms is non migratable, add a Validate message.
        handleNonMigratableVms(hostsWithNonMigratableVms, nonMigratableVms);
        handleHostsWithVmsWithPluggedDiskSnapshots(hostsWithVmsWithPluggedDiskSnapshots);
        if (result) {
            // Remove all redundant clusters in clusters list, by adding it to a
            // set.
            // For each cluster check for each host that belongs to it, if its a
            // part of the parameters and
            // if there are running hosts for it - if it is up and is not in the
            // parameters -migration will be possible
            // to be performed, and there is no point to continue the check for
            // the given cluster - otherwise,
            // if the host is up and in the parameters - it may be that the
            // cluster is problematic (no hosts in up
            // state that we will be able to migrate VMs to)
            // In the end - if the clusters list is not empty - this is an
            // error, use the "problematic clusters list" to format an error to
            // the client
            List<String> problematicClusters = new ArrayList<>();
            List<String> allHostsWithRunningVms = new ArrayList<>();
            for (Guid clusterID : clustersAsSet) {
                List<VDS> vdsList = vdsDao.getAllForCluster(clusterID);
                boolean vdsForMigrationExists = checkIfThereIsVDSToHoldMigratedVMs(getParameters().getVdsIdList(), vdsList);
                if (!vdsForMigrationExists) {
                    List<String> candidateHostsWithRunningVms = new ArrayList<>();
                    for (VDS vdsInCluster : vdsList) {
                        if (vdsWithRunningVMs.contains(vdsInCluster.getId())) {
                            candidateHostsWithRunningVms.add(vdsInCluster.getName());
                        }
                    }
                    // cluster
                    if (!candidateHostsWithRunningVms.isEmpty()) {
                        addClusterDetails(clusterID, problematicClusters);
                        allHostsWithRunningVms.addAll(candidateHostsWithRunningVms);
                    }
                }
            }
            // If there are problematic clusters
            result = problematicClusters.isEmpty();
            if (!result) {
                addValidationMessage(EngineMessage.CANNOT_MAINTENANCE_VDS_RUN_VMS_NO_OTHER_RUNNING_VDS);
                String commaDelimitedClusters = StringUtils.join(problematicClusters, ",");
                getReturnValue().getValidationMessages().add(String.format("$ClustersList %1$s", commaDelimitedClusters));
                getReturnValue().getValidationMessages().add(String.format("$HostsList %1$s", StringUtils.join(allHostsWithRunningVms, ",")));
            }
        }
        if (result && !getParameters().isForceMaintenance()) {
            result = validateGlusterParams(clustersAsSet);
        }
    }
    return result;
}
Also used : VDS(org.ovirt.engine.core.common.businessentities.VDS) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AsyncTask(org.ovirt.engine.core.common.businessentities.AsyncTask) Cluster(org.ovirt.engine.core.common.businessentities.Cluster) Guid(org.ovirt.engine.core.compat.Guid) VM(org.ovirt.engine.core.common.businessentities.VM) MultipleVmsValidator(org.ovirt.engine.core.bll.validator.MultipleVmsValidator) HashSet(java.util.HashSet)

Example 14 with AsyncTask

use of org.ovirt.engine.core.common.businessentities.AsyncTask in project ovirt-engine by oVirt.

the class AsyncTaskDaoTest method testRemove.

/**
 * Ensures that removing a ad_group works as expected.
 */
@Test
public void testRemove() {
    AsyncTask result = dao.get(existingAsyncTask.getTaskId());
    assertNotNull(result);
    assertEquals(1, dao.remove(existingAsyncTask.getTaskId()));
    result = dao.get(existingAsyncTask.getTaskId());
    assertNull(result);
    assertEquals(0, dao.remove(existingAsyncTask.getTaskId()));
    // The removed task is associated with an entity, try to fetch
    // tasks for the entity, and see no task is returned
    List<Guid> taskIds = dao.getAsyncTaskIdsByEntity(FixturesTool.ENTITY_WITH_TASKS_ID);
    assertNotNull(taskIds);
    assertTrue(taskIds.isEmpty());
}
Also used : AsyncTask(org.ovirt.engine.core.common.businessentities.AsyncTask) Guid(org.ovirt.engine.core.compat.Guid) Test(org.junit.Test)

Example 15 with AsyncTask

use of org.ovirt.engine.core.common.businessentities.AsyncTask in project ovirt-engine by oVirt.

the class AsyncTaskDaoTest method testSaveOrUpdate.

@Test
public void testSaveOrUpdate() {
    existingAsyncTask.setstatus(AsyncTaskStatusEnum.aborting);
    existingAsyncTask.setresult(AsyncTaskResultEnum.failure);
    existingAsyncTask.setActionType(ActionType.AddDisk);
    List<AsyncTask> tasks = dao.getAll();
    assertNotNull(tasks);
    int tasksNumber = tasks.size();
    dao.saveOrUpdate(existingAsyncTask);
    tasks = dao.getAll();
    assertEquals(tasksNumber, tasks.size());
    AsyncTask taskFromDb = dao.get(existingAsyncTask.getTaskId());
    assertNotNull(taskFromDb);
    assertEquals(taskFromDb, existingAsyncTask);
    dao.saveOrUpdate(newAsyncTask);
    tasks = dao.getAll();
    assertNotNull(tasks);
    assertEquals(tasksNumber + 1, tasks.size());
    taskFromDb = dao.get(newAsyncTask.getTaskId());
    assertEquals(taskFromDb, newAsyncTask);
}
Also used : AsyncTask(org.ovirt.engine.core.common.businessentities.AsyncTask) Test(org.junit.Test)

Aggregations

AsyncTask (org.ovirt.engine.core.common.businessentities.AsyncTask)24 Test (org.junit.Test)8 Guid (org.ovirt.engine.core.compat.Guid)7 ActionParametersBase (org.ovirt.engine.core.common.action.ActionParametersBase)5 ArrayList (java.util.ArrayList)4 AsyncTaskCreationInfo (org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo)2 EngineException (org.ovirt.engine.core.common.errors.EngineException)2 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Before (org.junit.Before)1 CommandMultiAsyncTasks (org.ovirt.engine.core.bll.CommandMultiAsyncTasks)1 ExecutionContext (org.ovirt.engine.core.bll.job.ExecutionContext)1 CommandCoordinator (org.ovirt.engine.core.bll.tasks.interfaces.CommandCoordinator)1 SPMTask (org.ovirt.engine.core.bll.tasks.interfaces.SPMTask)1 MultipleVmsValidator (org.ovirt.engine.core.bll.validator.MultipleVmsValidator)1 ActionReturnValue (org.ovirt.engine.core.common.action.ActionReturnValue)1 ActionType (org.ovirt.engine.core.common.action.ActionType)1