Search in sources :

Example 6 with Operation

use of com.evolveum.midpoint.schema.statistics.Operation in project midpoint by Evolveum.

the class NodeCleaner method cleanupNodes.

/**
 * Cleans up dead nodes older than specified age.
 *
 * @param selector If returns false, the respective node will not be removed.
 */
public void cleanupNodes(@NotNull DeadNodeCleanupPolicyType policy, @NotNull Predicate<NodeType> selector, @NotNull RunningTask task, @NotNull OperationResult result) throws SchemaException, ObjectNotFoundException {
    if (policy.getMaxAge() == null) {
        return;
    }
    TimeBoundary timeBoundary = TimeBoundary.compute(policy.getMaxAge());
    XMLGregorianCalendar deleteNodesNotCheckedInAfter = timeBoundary.getBoundary();
    LOGGER.info("Starting cleanup for stopped nodes not checked in after {} (duration '{}').", deleteNodesNotCheckedInAfter, timeBoundary.getPositiveDuration());
    for (PrismObject<NodeType> node : clusterManager.getAllNodes(result)) {
        if (!task.canRun()) {
            result.recordWarning("Interrupted");
            LOGGER.warn("Node cleanup was interrupted.");
            break;
        }
        if (!clusterManager.isCurrentNode(node) && !clusterManager.isCheckingIn(node.asObjectable()) && XmlTypeConverter.compareMillis(node.asObjectable().getLastCheckInTime(), deleteNodesNotCheckedInAfter) <= 0) {
            // This includes last check in time == null
            LOGGER.info("Deleting dead node {}; last check in time = {}", node, node.asObjectable().getLastCheckInTime());
            IterativeOperationStartInfo iterativeOperationStartInfo = new IterativeOperationStartInfo(new IterationItemInformation(node));
            iterativeOperationStartInfo.setSimpleCaller(true);
            Operation op = task.recordIterativeOperationStart(iterativeOperationStartInfo);
            if (ObjectTypeUtil.isIndestructible(node)) {
                LOGGER.debug("Not deleting dead but indestructible node {}", node);
                op.skipped();
                continue;
            }
            try {
                // Selector testing is in try-catch because of possible exceptions during autz evaluation
                if (!selector.test(node.asObjectable())) {
                    LOGGER.debug("Not deleting node {} because it was rejected by the selector", node);
                    op.skipped();
                    continue;
                }
                repositoryService.deleteObject(NodeType.class, node.getOid(), result);
                op.succeeded();
            } catch (Throwable t) {
                op.failed(t);
                LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete dead node {}", t, node);
            }
            task.incrementLegacyProgressAndStoreStatisticsIfTimePassed(result);
        }
    }
}
Also used : XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) TimeBoundary(com.evolveum.midpoint.task.quartzimpl.util.TimeBoundary) IterativeOperationStartInfo(com.evolveum.midpoint.schema.statistics.IterativeOperationStartInfo) NodeType(com.evolveum.midpoint.xml.ns._public.common.common_3.NodeType) Operation(com.evolveum.midpoint.schema.statistics.Operation) IterationItemInformation(com.evolveum.midpoint.schema.statistics.IterationItemInformation)

Example 7 with Operation

use of com.evolveum.midpoint.schema.statistics.Operation in project midpoint by Evolveum.

the class DiscoverConnectorsExecutor method execute.

@Override
public PipelineData execute(ActionExpressionType expression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException, SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ExpressionEvaluationException {
    boolean rebind = expressionHelper.getArgumentAsBoolean(expression.getParameter(), PARAM_REBIND_RESOURCES, input, context, false, PARAM_REBIND_RESOURCES, globalResult);
    PipelineData output = PipelineData.createEmpty();
    for (PipelineItem item : input.getData()) {
        PrismValue value = item.getValue();
        OperationResult result = operationsHelper.createActionResult(item, this, globalResult);
        context.checkTaskStop();
        if (value instanceof PrismObjectValue && ((PrismObjectValue) value).asObjectable() instanceof ConnectorHostType) {
            PrismObject<ConnectorHostType> connectorHostTypePrismObject = ((PrismObjectValue) value).asPrismObject();
            Set<ConnectorType> newConnectors;
            Operation op = operationsHelper.recordStart(context, connectorHostTypePrismObject.asObjectable());
            Throwable exception = null;
            try {
                newConnectors = modelService.discoverConnectors(connectorHostTypePrismObject.asObjectable(), context.getTask(), result);
                operationsHelper.recordEnd(context, op, null, result);
            } catch (CommunicationException | SecurityViolationException | SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException | RuntimeException e) {
                operationsHelper.recordEnd(context, op, e, result);
                exception = processActionException(e, NAME, value, context);
                newConnectors = Collections.emptySet();
            }
            context.println((exception != null ? "Attempted to discover " : "Discovered " + newConnectors.size()) + " new connector(s) from " + connectorHostTypePrismObject + exceptionSuffix(exception));
            for (ConnectorType connectorType : newConnectors) {
                output.addValue(connectorType.asPrismObject().getValue(), item.getResult(), item.getVariables());
            }
            try {
                if (rebind) {
                    rebindConnectors(newConnectors, context, result);
                }
            } catch (ScriptExecutionException e) {
                // noinspection ThrowableNotThrown
                // TODO better message
                processActionException(e, NAME, value, context);
            }
        } else {
            // noinspection ThrowableNotThrown
            processActionException(new ScriptExecutionException("Input item is not a PrismObject<ConnectorHost>"), NAME, value, context);
        }
        operationsHelper.trimAndCloneResult(result, item.getResult());
    }
    // TODO configurable output (either connector hosts or discovered connectors)
    return output;
}
Also used : ConnectorHostType(com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorHostType) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ConnectorType(com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ScriptExecutionException(com.evolveum.midpoint.util.exception.ScriptExecutionException) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Operation(com.evolveum.midpoint.schema.statistics.Operation) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException)

Example 8 with Operation

use of com.evolveum.midpoint.schema.statistics.Operation in project midpoint by Evolveum.

the class ReencryptExecutor method execute.

@Override
public PipelineData execute(ActionExpressionType expression, PipelineData input, ExecutionContext context, OperationResult globalResult) throws ScriptExecutionException, SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException, SecurityViolationException, ExpressionEvaluationException {
    Protector protector = prismContext.getDefaultProtector();
    boolean dryRun = operationsHelper.getDryRun(expression, input, context, globalResult);
    PipelineData output = PipelineData.createEmpty();
    for (PipelineItem item : input.getData()) {
        PrismValue value = item.getValue();
        OperationResult result = operationsHelper.createActionResult(item, this, globalResult);
        context.checkTaskStop();
        if (value instanceof PrismObjectValue) {
            @SuppressWarnings({ "unchecked", "raw" }) PrismObject<? extends ObjectType> prismObject = ((PrismObjectValue) value).asPrismObject();
            ObjectType objectBean = prismObject.asObjectable();
            Operation op = operationsHelper.recordStart(context, objectBean);
            try {
                Collection<? extends ItemDelta<?, ?>> modifications = CryptoUtil.computeReencryptModifications(protector, prismObject);
                if (!modifications.isEmpty()) {
                    result.addArbitraryObjectCollectionAsParam("modifications", modifications);
                    if (dryRun) {
                        context.println("Would reencrypt (this is dry run) " + prismObject.toString() + ": " + modifications.size() + " modification(s)");
                    } else {
                        cacheRepositoryService.modifyObject(objectBean.getClass(), objectBean.getOid(), modifications, result);
                        context.println("Reencrypted " + prismObject + ": " + modifications.size() + " modification(s)");
                    }
                }
                result.computeStatus();
                operationsHelper.recordEnd(context, op, null, result);
            } catch (Throwable ex) {
                result.recordFatalError("Couldn't reencrypt object", ex);
                operationsHelper.recordEnd(context, op, ex, result);
                Throwable exception = processActionException(ex, NAME, value, context);
                context.println("Couldn't reencrypt " + prismObject.toString() + drySuffix(dryRun) + exceptionSuffix(exception));
            }
            PrismPropertyValue<String> oidVal = prismContext.itemFactory().createPropertyValue(objectBean.getOid());
            output.add(new PipelineItem(oidVal, item.getResult()));
        } else {
            // noinspection ThrowableNotThrown
            processActionException(new ScriptExecutionException("Item is not a PrismObject"), NAME, value, context);
        }
        operationsHelper.trimAndCloneResult(result, item.getResult());
    }
    return output;
}
Also used : ScriptExecutionException(com.evolveum.midpoint.util.exception.ScriptExecutionException) PipelineData(com.evolveum.midpoint.model.impl.scripting.PipelineData) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Operation(com.evolveum.midpoint.schema.statistics.Operation) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) PipelineItem(com.evolveum.midpoint.model.api.PipelineItem) Protector(com.evolveum.midpoint.prism.crypto.Protector)

Example 9 with Operation

use of com.evolveum.midpoint.schema.statistics.Operation in project midpoint by Evolveum.

the class CaseCleaner method cleanupCases.

public void cleanupCases(@NotNull CleanupPolicyType policy, @NotNull RunningTask executionTask, @NotNull OperationResult result) throws CommonException {
    DeletionCounters counters = new DeletionCounters();
    TimeBoundary timeBoundary = TimeBoundary.compute(policy.getMaxAge());
    XMLGregorianCalendar deleteCasesClosedUpTo = timeBoundary.boundary;
    LOGGER.debug("Starting cleanup for closed cases deleting up to {} (duration '{}').", deleteCasesClosedUpTo, timeBoundary.positiveDuration);
    ObjectQuery obsoleteCasesQuery = prismContext.queryFor(CaseType.class).item(CaseType.F_STATE).eq(SchemaConstants.CASE_STATE_CLOSED).and().item(CaseType.F_CLOSE_TIMESTAMP).le(deleteCasesClosedUpTo).and().item(CaseType.F_PARENT_REF).isNull().build();
    List<PrismObject<CaseType>> rootObsoleteCases = modelService.searchObjects(CaseType.class, obsoleteCasesQuery, null, executionTask, result);
    LOGGER.debug("Found {} case tree(s) to be cleaned up", rootObsoleteCases.size());
    boolean interrupted = false;
    for (PrismObject<CaseType> rootObsoleteCase : rootObsoleteCases) {
        if (!executionTask.canRun()) {
            result.recordWarning("Interrupted");
            LOGGER.warn("Task cleanup was interrupted.");
            interrupted = true;
            break;
        }
        IterativeOperationStartInfo startInfo = new IterativeOperationStartInfo(new IterationItemInformation(rootObsoleteCase));
        startInfo.setSimpleCaller(true);
        Operation op = executionTask.recordIterativeOperationStart(startInfo);
        try {
            if (ObjectTypeUtil.isIndestructible(rootObsoleteCase)) {
                LOGGER.trace("Not deleting root case {} because it's marked as indestructible", rootObsoleteCase);
                op.skipped();
            } else {
                deleteCaseWithChildren(rootObsoleteCase, counters, executionTask, result);
                op.succeeded();
            }
        } catch (Throwable t) {
            op.failed(t);
            LoggingUtils.logException(LOGGER, "Couldn't delete children cases for {}", t, rootObsoleteCase);
        }
        executionTask.incrementLegacyProgressAndStoreStatisticsIfTimePassed(result);
    }
    LOGGER.info("Case cleanup procedure " + (interrupted ? "was interrupted" : "finished") + ". Successfully deleted {} cases; there were problems with deleting {} cases.", counters.deleted, counters.problems);
    String suffix = interrupted ? " Interrupted." : "";
    if (counters.problems == 0) {
        result.createSubresult(OP_STATISTICS).recordStatus(SUCCESS, "Successfully deleted " + counters.deleted + " case(s)." + suffix);
    } else {
        result.createSubresult(OP_STATISTICS).recordPartialError("Successfully deleted " + counters.deleted + " case(s), " + "there was problems with deleting " + counters.problems + " cases." + suffix);
    }
}
Also used : Operation(com.evolveum.midpoint.schema.statistics.Operation) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) PrismObject(com.evolveum.midpoint.prism.PrismObject) CaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType) IterativeOperationStartInfo(com.evolveum.midpoint.schema.statistics.IterativeOperationStartInfo) IterationItemInformation(com.evolveum.midpoint.schema.statistics.IterationItemInformation)

Example 10 with Operation

use of com.evolveum.midpoint.schema.statistics.Operation in project midpoint by Evolveum.

the class MockComponentActivityRun method runLocally.

@Override
@NotNull
protected ActivityRunResult runLocally(OperationResult result) throws CommonException {
    CompositeMockWorkDefinition workDef = activity.getWorkDefinition();
    int steps = workDef.getSteps();
    long delay = workDef.getDelay();
    LOGGER.info("Mock activity starting: id={}, steps={}, delay={}, sub-activity={}:\n{}", workDef.getMessage(), steps, delay, getMockSubActivity(), debugDumpLazily());
    String itemName = workDef.getMessage() + ":" + getMockSubActivity();
    Operation operation = activityState.getLiveItemProcessingStatistics().recordOperationStart(new IterativeOperationStartInfo(new IterationItemInformation(itemName, null, null, null)));
    RunningTask task = taskRun.getRunningTask();
    if (delay > 0) {
        LOGGER.trace("Sleeping for {} msecs", delay);
        MiscUtil.sleepWatchfully(System.currentTimeMillis() + delay, 100, task::canRun);
    }
    result.recordSuccess();
    getRecorder().recordExecution(itemName);
    QualifiedItemProcessingOutcomeType qualifiedOutcome = new QualifiedItemProcessingOutcomeType(getPrismContext()).outcome(ItemProcessingOutcomeType.SUCCESS);
    operation.done(qualifiedOutcome, null);
    incrementProgress(qualifiedOutcome);
    LOGGER.info("Mock activity finished: id={}, sub-activity={}:\n{}", workDef.getMessage(), getMockSubActivity(), debugDumpLazily());
    return standardRunResult();
}
Also used : QualifiedItemProcessingOutcomeType(com.evolveum.midpoint.xml.ns._public.common.common_3.QualifiedItemProcessingOutcomeType) RunningTask(com.evolveum.midpoint.task.api.RunningTask) IterativeOperationStartInfo(com.evolveum.midpoint.schema.statistics.IterativeOperationStartInfo) Operation(com.evolveum.midpoint.schema.statistics.Operation) IterationItemInformation(com.evolveum.midpoint.schema.statistics.IterationItemInformation) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Operation (com.evolveum.midpoint.schema.statistics.Operation)11 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)6 PipelineItem (com.evolveum.midpoint.model.api.PipelineItem)5 IterationItemInformation (com.evolveum.midpoint.schema.statistics.IterationItemInformation)5 IterativeOperationStartInfo (com.evolveum.midpoint.schema.statistics.IterativeOperationStartInfo)5 PipelineData (com.evolveum.midpoint.model.impl.scripting.PipelineData)3 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)3 ScriptExecutionException (com.evolveum.midpoint.util.exception.ScriptExecutionException)3 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)3 PrismObject (com.evolveum.midpoint.prism.PrismObject)2 PrismValue (com.evolveum.midpoint.prism.PrismValue)2 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)2 RunningTask (com.evolveum.midpoint.task.api.RunningTask)2 TimeBoundary (com.evolveum.midpoint.task.quartzimpl.util.TimeBoundary)2 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)2 QualifiedItemProcessingOutcomeType (com.evolveum.midpoint.xml.ns._public.common.common_3.QualifiedItemProcessingOutcomeType)2 NotNull (org.jetbrains.annotations.NotNull)2 ValidationResult (com.evolveum.midpoint.model.api.validator.ValidationResult)1 PrismObjectValue (com.evolveum.midpoint.prism.PrismObjectValue)1 Protector (com.evolveum.midpoint.prism.crypto.Protector)1