Search in sources :

Example 1 with UcfExecutionContext

use of com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method fetchChanges.

@Override
public UcfFetchChangesResult fetchChanges(ResourceObjectDefinition objectDefinition, UcfSyncToken initialTokenValue, AttributesToReturn attrsToReturn, Integer maxChanges, UcfExecutionContext ctx, @NotNull UcfLiveSyncChangeListener changeListener, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SchemaException {
    OperationResult result = parentResult.subresult(OP_FETCH_CHANGES).addArbitraryObjectAsContext("objectClass", objectDefinition).addArbitraryObjectAsParam("initialToken", initialTokenValue).build();
    try {
        SyncToken initialToken = TokenUtil.toConnId(initialTokenValue);
        LOGGER.trace("Initial token: {}", initialToken == null ? null : initialToken.getValue());
        ResourceObjectClassDefinition objectClassDefinition = objectDefinition != null ? objectDefinition.getObjectClassDefinition() : null;
        // get icf object class
        ObjectClass requestConnIdObjectClass;
        if (objectClassDefinition == null) {
            requestConnIdObjectClass = ObjectClass.ALL;
        } else {
            requestConnIdObjectClass = objectClassToConnId(objectClassDefinition);
        }
        OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
        if (objectDefinition != null) {
            convertToIcfAttrsToGet(objectDefinition, attrsToReturn, optionsBuilder);
        }
        OperationOptions options = optionsBuilder.build();
        AtomicInteger deltasProcessed = new AtomicInteger(0);
        Thread callerThread = Thread.currentThread();
        SyncDeltaConverter changeConverter = new SyncDeltaConverter(this, objectDefinition);
        AtomicBoolean allChangesFetched = new AtomicBoolean(true);
        UcfFetchChangesResult fetchChangesResult;
        OperationResult connIdResult = result.subresult(ConnectorFacade.class.getName() + ".sync").addContext("connector", connIdConnectorFacade.getClass()).addArbitraryObjectAsParam("objectClass", requestConnIdObjectClass).addArbitraryObjectAsParam("initialToken", initialToken).build();
        try {
            InternalMonitor.recordConnectorOperation("sync");
            ConnIdOperation operation = recordIcfOperationStart(ctx, ProvisioningOperation.ICF_SYNC, objectDefinition);
            /*
                 * We assume that the only way how changes are _not_ fetched is that we explicitly tell ConnId to stop
                 * fetching them by returning 'false' from the handler.handle() method. (Or an exception occurs in the sync()
                 * method.)
                 *
                 * In other words, we assume that if we tell ConnId to continue feeding changes to us, we are sure that on
                 * successful exit from sync() method all changes were processed.
                 */
            SyncResultsHandler syncHandler = syncDelta -> {
                Thread handlingThread = Thread.currentThread();
                if (!handlingThread.equals(callerThread)) {
                    LOGGER.warn("Live Sync changes are being processed in a thread {} that is different from the invoking one ({}). " + "This can cause issues e.g. with operational statistics reporting.", handlingThread, callerThread);
                }
                recordIcfOperationSuspend(ctx, operation);
                LOGGER.trace("Received sync delta: {}", syncDelta);
                OperationResult handleResult;
                // But - just for sure - let us create subresults in a safe way.
                synchronized (connIdResult) {
                    handleResult = connIdResult.subresult(OP_FETCH_CHANGES + ".handle").addArbitraryObjectAsParam("uid", syncDelta.getUid()).setMinor().build();
                }
                UcfLiveSyncChange change = null;
                try {
                    // Here we again assume we are called in a single thread, and that changes received here are in
                    // the correct order - i.e. in the order in which they are to be processed.
                    int sequentialNumber = deltasProcessed.incrementAndGet();
                    change = changeConverter.createChange(sequentialNumber, syncDelta, handleResult);
                    // The following should not throw any exceptions
                    boolean canContinue = changeListener.onChange(change, handleResult);
                    boolean doContinue = canContinue && canRun(ctx) && (maxChanges == null || maxChanges == 0 || sequentialNumber < maxChanges);
                    if (!doContinue) {
                        allChangesFetched.set(false);
                    }
                    return doContinue;
                } catch (RuntimeException e) {
                    handleResult.recordFatalError(e);
                    // any exception here is not expected
                    LoggingUtils.logUnexpectedException(LOGGER, "Got unexpected exception while handling live sync " + "change, stopping the processing. Sync delta: {}, UCF change: {}", e, syncDelta, change);
                    return false;
                } finally {
                    // Asynchronously processed changes (if used) have their own, separate, operation results
                    // that are tied to the lightweight asynchronous task handlers in ChangeProcessingCoordinator.
                    // 
                    // So we can safely compute/cleanup/summarize results here.
                    handleResult.computeStatusIfUnknown();
                    handleResult.cleanupResult();
                    connIdResult.summarize(true);
                    recordIcfOperationResume(ctx, operation);
                }
            };
            LOGGER.trace("Invoking ConnId sync operation: {}", operation);
            SyncToken finalToken;
            try {
                finalToken = connIdConnectorFacade.sync(requestConnIdObjectClass, initialToken, syncHandler, options);
                // Note that finalToken value is not quite reliable. The SyncApiOp documentation is not clear on its semantics;
                // it is only from SyncTokenResultsHandler (SPI) documentation and SyncImpl class that we know this value is
                // non-null when all changes were fetched. And some of the connectors return null even then.
                LOGGER.trace("connector sync method returned: {}", finalToken);
                connIdResult.computeStatus();
                connIdResult.cleanupResult();
                connIdResult.addReturn(OperationResult.RETURN_COUNT, deltasProcessed.get());
                recordIcfOperationEnd(ctx, operation, null);
            } catch (Throwable ex) {
                recordIcfOperationEnd(ctx, operation, ex);
                Throwable midpointEx = processConnIdException(ex, this, connIdResult);
                connIdResult.computeStatusIfUnknown();
                connIdResult.cleanupResult();
                result.computeStatus();
                // Do some kind of acrobatics to do proper throwing of checked exception
                if (midpointEx instanceof CommunicationException) {
                    throw (CommunicationException) midpointEx;
                } else if (midpointEx instanceof GenericFrameworkException) {
                    throw (GenericFrameworkException) midpointEx;
                } else if (midpointEx instanceof SchemaException) {
                    throw (SchemaException) midpointEx;
                } else if (midpointEx instanceof RuntimeException) {
                    throw (RuntimeException) midpointEx;
                } else if (midpointEx instanceof Error) {
                    throw (Error) midpointEx;
                } else {
                    throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
                }
            }
            if (!canRun(ctx)) {
                result.recordStatus(OperationResultStatus.SUCCESS, "Interrupted by task suspension");
            }
            if (allChangesFetched.get()) {
                // We might consider finalToken value here. I.e. it it's non null, we could declare all changes to be fetched.
                // But as mentioned above, this is not supported explicitly in SyncApiOp. So let's be a bit conservative.
                LOGGER.trace("All changes were fetched; with finalToken = {}", finalToken);
                fetchChangesResult = new UcfFetchChangesResult(true, TokenUtil.toUcf(finalToken));
            } else {
                fetchChangesResult = new UcfFetchChangesResult(false, null);
            }
        } catch (Throwable t) {
            connIdResult.recordFatalError(t);
            throw t;
        } finally {
            connIdResult.computeStatusIfUnknown();
        }
        result.recordSuccess();
        result.addReturn(OperationResult.RETURN_COUNT, deltasProcessed.get());
        return fetchChangesResult;
    } catch (Throwable t) {
        result.recordFatalError(t);
        throw t;
    } finally {
        result.computeStatusIfUnknown();
    }
}
Also used : SetUtils.emptyIfNull(org.apache.commons.collections4.SetUtils.emptyIfNull) ActivationUtil(com.evolveum.midpoint.schema.util.ActivationUtil) org.identityconnectors.framework.common.objects(org.identityconnectors.framework.common.objects) Filter(org.identityconnectors.framework.common.objects.filter.Filter) FilterInterpreter(com.evolveum.midpoint.provisioning.ucf.impl.connid.query.FilterInterpreter) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) APIConfigurationImpl(org.identityconnectors.framework.impl.api.APIConfigurationImpl) OperationResultStatus(com.evolveum.midpoint.schema.result.OperationResultStatus) BooleanUtils(org.apache.commons.lang.BooleanUtils) GuardedString(org.identityconnectors.common.security.GuardedString) ConnectorTestOperation(com.evolveum.midpoint.schema.constants.ConnectorTestOperation) AsynchronousOperationReturnValue(com.evolveum.midpoint.schema.result.AsynchronousOperationReturnValue) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnIdUtil.processConnIdException(com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnIdUtil.processConnIdException) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) XmlTypeConverter(com.evolveum.midpoint.prism.xml.XmlTypeConverter) Holder(com.evolveum.midpoint.util.Holder) ConnectorInfo(org.identityconnectors.framework.api.ConnectorInfo) Statistics(org.identityconnectors.framework.impl.api.local.ObjectPool.Statistics) ObjectPool(org.identityconnectors.framework.impl.api.local.ObjectPool) com.evolveum.midpoint.xml.ns._public.resource.capabilities_3(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3) APIConfiguration(org.identityconnectors.framework.api.APIConfiguration) Nullable(org.jetbrains.annotations.Nullable) ConnIdOperation.getIdentifier(com.evolveum.midpoint.schema.reporting.ConnIdOperation.getIdentifier) Contract(org.jetbrains.annotations.Contract) DebugUtil.lazy(com.evolveum.midpoint.util.DebugUtil.lazy) ConnIdOperation(com.evolveum.midpoint.schema.reporting.ConnIdOperation) ConnectorOperationalContext(org.identityconnectors.framework.impl.api.local.operations.ConnectorOperationalContext) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) SearchResultMetadata(com.evolveum.midpoint.schema.SearchResultMetadata) QName(javax.xml.namespace.QName) ProvisioningOperation(com.evolveum.midpoint.schema.statistics.ProvisioningOperation) NotNull(org.jetbrains.annotations.NotNull) Validate(org.apache.commons.lang.Validate) LocalConnectorInfoImpl(org.identityconnectors.framework.impl.api.local.LocalConnectorInfoImpl) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext) java.util(java.util) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Connector(org.identityconnectors.framework.spi.Connector) Trace(com.evolveum.midpoint.util.logging.Trace) ObjectPoolConfiguration(org.identityconnectors.common.pooling.ObjectPoolConfiguration) LocalizationService(com.evolveum.midpoint.common.LocalizationService) PrettyPrinter(com.evolveum.midpoint.util.PrettyPrinter) ObjectFilter(com.evolveum.midpoint.prism.query.ObjectFilter) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) PoolableConnector(org.identityconnectors.framework.spi.PoolableConnector) CapabilityUtil(com.evolveum.midpoint.schema.CapabilityUtil) ConnectorFacade(org.identityconnectors.framework.api.ConnectorFacade) ConnectorOperationalStatus(com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus) Collections.emptySet(java.util.Collections.emptySet) InternalMonitor(com.evolveum.midpoint.schema.internals.InternalMonitor) ConnectorFacadeFactory(org.identityconnectors.framework.api.ConnectorFacadeFactory) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) ItemName(com.evolveum.midpoint.prism.path.ItemName) com.evolveum.midpoint.provisioning.ucf.api(com.evolveum.midpoint.provisioning.ucf.api) com.evolveum.midpoint.schema.processor(com.evolveum.midpoint.schema.processor) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) Protector(com.evolveum.midpoint.prism.crypto.Protector) ShadowUtil(com.evolveum.midpoint.schema.util.ShadowUtil) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) OrderDirectionType(com.evolveum.prism.xml.ns._public.query_3.OrderDirectionType) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) PrismSchema(com.evolveum.midpoint.prism.schema.PrismSchema) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) ConnIdOperation(com.evolveum.midpoint.schema.reporting.ConnIdOperation) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with UcfExecutionContext

use of com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext in project midpoint by Evolveum.

the class TestUcfDummyMulti method test210TwoBlockingSearches.

@Test
public void test210TwoBlockingSearches() throws Exception {
    // GIVEN
    UcfExecutionContext ctx = createExecutionContext();
    final ResourceObjectClassDefinition accountDefinition = resourceSchema.findObjectClassDefinitionRequired(ACCOUNT_OBJECT_CLASS_NAME);
    // Determine object class from the schema
    OperationResult result1 = createOperationResult();
    final List<PrismObject<ShadowType>> searchResults1 = new ArrayList<>();
    final ObjectHandler handler1 = (ucfObject, result) -> {
        checkUcfShadow(ucfObject.getResourceObject(), accountDefinition);
        searchResults1.add(ucfObject.getResourceObject());
        return true;
    };
    OperationResult result2 = createOperationResult();
    final List<PrismObject<ShadowType>> searchResults2 = new ArrayList<>();
    final ObjectHandler handler2 = (ucfObject, result) -> {
        checkUcfShadow(ucfObject.getResourceObject(), accountDefinition);
        searchResults2.add(ucfObject.getResourceObject());
        return true;
    };
    dummyResource.setBlockOperations(true);
    // WHEN
    Thread t1 = new Thread(() -> {
        try {
            cc.search(accountDefinition, null, handler1, null, null, null, null, ctx, result1);
        } catch (CommunicationException | GenericFrameworkException | SchemaException | SecurityViolationException | ObjectNotFoundException e) {
            logger.error("Error in the search: {}", e.getMessage(), e);
        }
    });
    t1.setName("search1");
    t1.start();
    // Give the new thread a chance to get blocked
    Thread.sleep(500);
    ConnectorOperationalStatus opStat = cc.getOperationalStatus();
    displayDumpable("stats (blocked 1)", opStat);
    assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumActive());
    assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumIdle());
    assertEquals("Unexpected number of search results", 0, searchResults1.size());
    Thread t2 = new Thread(() -> {
        try {
            cc.search(accountDefinition, null, handler2, null, null, null, null, ctx, result2);
        } catch (CommunicationException | GenericFrameworkException | SchemaException | SecurityViolationException | ObjectNotFoundException e) {
            logger.error("Error in the search: {}", e.getMessage(), e);
        }
    });
    t2.setName("search2");
    t2.start();
    // Give the new thread a chance to get blocked
    Thread.sleep(500);
    opStat = cc.getOperationalStatus();
    displayDumpable("stats (blocked 2)", opStat);
    assertEquals("Wrong pool active", (Integer) 2, opStat.getPoolStatusNumActive());
    assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumIdle());
    assertEquals("Unexpected number of search results", 0, searchResults1.size());
    dummyResource.unblockAll();
    t1.join();
    t2.join();
    dummyResource.setBlockOperations(false);
    // THEN
    assertEquals("Unexpected number of search results 1", 1, searchResults1.size());
    assertEquals("Unexpected number of search results 2", 1, searchResults2.size());
    opStat = cc.getOperationalStatus();
    displayDumpable("stats (final)", opStat);
    assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumActive());
    assertEquals("Wrong pool active", (Integer) 2, opStat.getPoolStatusNumIdle());
    PrismObject<ShadowType> searchResult1 = searchResults1.get(0);
    displayDumpable("Search result 1", searchResult1);
    PrismObject<ShadowType> searchResult2 = searchResults2.get(0);
    displayDumpable("Search result 2", searchResult2);
}
Also used : ResourceObjectClassDefinition(com.evolveum.midpoint.schema.processor.ResourceObjectClassDefinition) AssertJUnit(org.testng.AssertJUnit) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) ResourceAttributeContainer(com.evolveum.midpoint.schema.processor.ResourceAttributeContainer) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Test(org.testng.annotations.Test) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) ObjectHandler(com.evolveum.midpoint.provisioning.ucf.api.ObjectHandler) ACCOUNT_OBJECT_CLASS_NAME(com.evolveum.midpoint.schema.util.SchemaTestConstants.ACCOUNT_OBJECT_CLASS_NAME) ArrayList(java.util.ArrayList) ResourceAttribute(com.evolveum.midpoint.schema.processor.ResourceAttribute) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) PrismTestUtil(com.evolveum.midpoint.prism.util.PrismTestUtil) ResourceObjectClassDefinition(com.evolveum.midpoint.schema.processor.ResourceObjectClassDefinition) Files(com.google.common.io.Files) ConnectorOperationalStatus(com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus) TestUtil(com.evolveum.midpoint.test.util.TestUtil) PrismContainerDefinition(com.evolveum.midpoint.prism.PrismContainerDefinition) DummyAccount(com.evolveum.icf.dummy.resource.DummyAccount) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) ResourceTypeUtil(com.evolveum.midpoint.schema.util.ResourceTypeUtil) PrismObject(com.evolveum.midpoint.prism.PrismObject) File(java.io.File) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) ShadowUtil(com.evolveum.midpoint.schema.util.ShadowUtil) ContextConfiguration(org.springframework.test.context.ContextConfiguration) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext) PrismSchema(com.evolveum.midpoint.prism.schema.PrismSchema) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PrismObject(com.evolveum.midpoint.prism.PrismObject) ObjectHandler(com.evolveum.midpoint.provisioning.ucf.api.ObjectHandler) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ConnectorOperationalStatus(com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext) Test(org.testng.annotations.Test)

Example 3 with UcfExecutionContext

use of com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext in project midpoint by Evolveum.

the class TestUcfDummyMulti method test110SearchNonBlocking.

@Test
public void test110SearchNonBlocking() throws Exception {
    // GIVEN
    UcfExecutionContext ctx = createExecutionContext();
    final ResourceObjectClassDefinition accountDefinition = resourceSchema.findObjectClassDefinitionRequired(ACCOUNT_OBJECT_CLASS_NAME);
    // Determine object class from the schema
    final List<PrismObject<ShadowType>> searchResults = new ArrayList<>();
    ObjectHandler handler = (ucfObject, result) -> {
        displayDumpable("Search: found", ucfObject);
        checkUcfShadow(ucfObject.getResourceObject(), accountDefinition);
        searchResults.add(ucfObject.getResourceObject());
        return true;
    };
    OperationResult result = createOperationResult();
    // WHEN
    cc.search(accountDefinition, null, handler, null, null, null, null, ctx, result);
    // THEN
    assertEquals("Unexpected number of search results", 1, searchResults.size());
    ConnectorOperationalStatus opStat = cc.getOperationalStatus();
    displayDumpable("stats", opStat);
    assertEquals("Wrong pool active", (Integer) 0, opStat.getPoolStatusNumActive());
    assertEquals("Wrong pool active", (Integer) 1, opStat.getPoolStatusNumIdle());
}
Also used : ResourceObjectClassDefinition(com.evolveum.midpoint.schema.processor.ResourceObjectClassDefinition) AssertJUnit(org.testng.AssertJUnit) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) ResourceAttributeContainer(com.evolveum.midpoint.schema.processor.ResourceAttributeContainer) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Test(org.testng.annotations.Test) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) ObjectHandler(com.evolveum.midpoint.provisioning.ucf.api.ObjectHandler) ACCOUNT_OBJECT_CLASS_NAME(com.evolveum.midpoint.schema.util.SchemaTestConstants.ACCOUNT_OBJECT_CLASS_NAME) ArrayList(java.util.ArrayList) ResourceAttribute(com.evolveum.midpoint.schema.processor.ResourceAttribute) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) PrismTestUtil(com.evolveum.midpoint.prism.util.PrismTestUtil) ResourceObjectClassDefinition(com.evolveum.midpoint.schema.processor.ResourceObjectClassDefinition) Files(com.google.common.io.Files) ConnectorOperationalStatus(com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus) TestUtil(com.evolveum.midpoint.test.util.TestUtil) PrismContainerDefinition(com.evolveum.midpoint.prism.PrismContainerDefinition) DummyAccount(com.evolveum.icf.dummy.resource.DummyAccount) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) Collection(java.util.Collection) Set(java.util.Set) IOException(java.io.IOException) ResourceTypeUtil(com.evolveum.midpoint.schema.util.ResourceTypeUtil) PrismObject(com.evolveum.midpoint.prism.PrismObject) File(java.io.File) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) ShadowUtil(com.evolveum.midpoint.schema.util.ShadowUtil) ContextConfiguration(org.springframework.test.context.ContextConfiguration) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext) PrismSchema(com.evolveum.midpoint.prism.schema.PrismSchema) PrismObject(com.evolveum.midpoint.prism.PrismObject) ObjectHandler(com.evolveum.midpoint.provisioning.ucf.api.ObjectHandler) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ConnectorOperationalStatus(com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext) Test(org.testng.annotations.Test)

Example 4 with UcfExecutionContext

use of com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext in project midpoint by Evolveum.

the class ResourceObjectConverter method executeProvisioningScripts.

private void executeProvisioningScripts(ProvisioningContext ctx, ProvisioningOperationTypeType provisioningOperationType, BeforeAfterType beforeAfter, OperationProvisioningScriptsType scripts, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException, GenericConnectorException {
    Collection<ExecuteProvisioningScriptOperation> operations = determineExecuteScriptOperations(provisioningOperationType, beforeAfter, scripts, ctx.getResource(), result);
    if (operations == null) {
        return;
    }
    ConnectorInstance connector = ctx.getConnector(ScriptCapabilityType.class, result);
    for (ExecuteProvisioningScriptOperation operation : operations) {
        UcfExecutionContext ucfCtx = new UcfExecutionContext(lightweightIdentifierGenerator, ctx.getResource(), ctx.getTask());
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("PROVISIONING SCRIPT EXECUTION {} {} operation on resource {}", beforeAfter.value(), provisioningOperationType.value(), ctx.getResource());
            }
            Object returnedValue = connector.executeScript(operation, ucfCtx, result);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("PROVISIONING SCRIPT EXECUTION {} {} successful, returned value: {}", beforeAfter.value(), provisioningOperationType.value(), returnedValue);
            }
        } catch (CommunicationException ex) {
            String message = "Could not execute provisioning script. Error communicating with the connector " + connector + ": " + ex.getMessage();
            if (ExceptionUtil.isFatalCriticality(operation.getCriticality(), CriticalityType.FATAL)) {
                result.recordFatalError(message, ex);
                throw new CommunicationException(message, ex);
            } else {
                LOGGER.warn("{}", message);
            }
        } catch (GenericFrameworkException ex) {
            String message = "Could not execute provisioning script. Generic error in connector: " + ex.getMessage();
            if (ExceptionUtil.isFatalCriticality(operation.getCriticality(), CriticalityType.FATAL)) {
                result.recordFatalError(message, ex);
                throw new GenericConnectorException(message, ex);
            } else {
                LOGGER.warn("{}", message);
            }
        } catch (Throwable t) {
            String message = "Could not execute provisioning script. Unexpected error in connector: " + t.getClass().getSimpleName() + ": " + t.getMessage();
            if (ExceptionUtil.isFatalCriticality(operation.getCriticality(), CriticalityType.FATAL)) {
                result.recordFatalError(message, t);
                throw t;
            } else {
                LOGGER.warn("{}", message);
            }
        }
    }
}
Also used : GenericConnectorException(com.evolveum.midpoint.provisioning.api.GenericConnectorException) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext)

Example 5 with UcfExecutionContext

use of com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext in project midpoint by Evolveum.

the class ResourceManager method executeScript.

public Object executeScript(String resourceOid, ProvisioningScriptType script, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
    PrismObject<ResourceType> resource = getResource(resourceOid, null, task, result);
    ConnectorSpec connectorSpec = selectConnectorSpec(resource, ScriptCapabilityType.class);
    if (connectorSpec == null) {
        throw new UnsupportedOperationException("No connector supports script capability");
    }
    ConnectorInstance connectorInstance = connectorManager.getConfiguredConnectorInstance(connectorSpec, false, result);
    ExecuteProvisioningScriptOperation scriptOperation = ProvisioningUtil.convertToScriptOperation(script, "script on " + resource, prismContext);
    try {
        UcfExecutionContext ucfCtx = new UcfExecutionContext(lightweightIdentifierGenerator, resource.asObjectable(), task);
        return connectorInstance.executeScript(scriptOperation, ucfCtx, result);
    } catch (GenericFrameworkException e) {
        // Not expected. Transform to system exception
        result.recordFatalError("Generic provisioning framework error", e);
        throw new SystemException("Generic provisioning framework error: " + e.getMessage(), e);
    }
}
Also used : ConnectorInstance(com.evolveum.midpoint.provisioning.ucf.api.ConnectorInstance) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) ExecuteProvisioningScriptOperation(com.evolveum.midpoint.provisioning.ucf.api.ExecuteProvisioningScriptOperation) UcfExecutionContext(com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext)

Aggregations

UcfExecutionContext (com.evolveum.midpoint.provisioning.ucf.api.UcfExecutionContext)7 PrismSchema (com.evolveum.midpoint.prism.schema.PrismSchema)5 SchemaConstants (com.evolveum.midpoint.schema.constants.SchemaConstants)5 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)5 ConnectorOperationalStatus (com.evolveum.midpoint.schema.statistics.ConnectorOperationalStatus)5 ShadowUtil (com.evolveum.midpoint.schema.util.ShadowUtil)5 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)5 DummyAccount (com.evolveum.icf.dummy.resource.DummyAccount)4 SchemaRegistry (com.evolveum.midpoint.prism.schema.SchemaRegistry)4 PrismTestUtil (com.evolveum.midpoint.prism.util.PrismTestUtil)4 GenericFrameworkException (com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException)4 ObjectHandler (com.evolveum.midpoint.provisioning.ucf.api.ObjectHandler)4 ResourceTypeUtil (com.evolveum.midpoint.schema.util.ResourceTypeUtil)4 ACCOUNT_OBJECT_CLASS_NAME (com.evolveum.midpoint.schema.util.SchemaTestConstants.ACCOUNT_OBJECT_CLASS_NAME)4 TestUtil (com.evolveum.midpoint.test.util.TestUtil)4 ArrayList (java.util.ArrayList)4 Collection (java.util.Collection)4 List (java.util.List)4 Set (java.util.Set)4 ContextConfiguration (org.springframework.test.context.ContextConfiguration)4