Search in sources :

Example 76 with ProcessException

use of org.apache.nifi.processor.exception.ProcessException in project nifi by apache.

the class TestPutRiemann method testFailedDeref.

@Test(expected = AssertionError.class)
public void testFailedDeref() {
    TestRunner runner = getTestRunner(true);
    MockFlowFile flowFile = new MockFlowFile(1);
    Map<String, String> attributes = new HashMap<>();
    attributes.put("riemann.metric", "5");
    flowFile.putAttributes(attributes);
    runner.enqueue(flowFile);
    try {
        runner.run();
    } catch (ProcessException e) {
        runner.assertQueueNotEmpty();
        throw e;
    }
}
Also used : MockFlowFile(org.apache.nifi.util.MockFlowFile) ProcessException(org.apache.nifi.processor.exception.ProcessException) HashMap(java.util.HashMap) TestRunner(org.apache.nifi.util.TestRunner) Test(org.junit.Test)

Example 77 with ProcessException

use of org.apache.nifi.processor.exception.ProcessException in project nifi by apache.

the class ScriptedLookupService method reloadScript.

/**
 * Reloads the script RecordReaderFactory. This must be called within the lock.
 *
 * @param scriptBody An input stream associated with the script content
 * @return Whether the script was successfully reloaded
 */
@Override
protected boolean reloadScript(final String scriptBody) {
    // note we are starting here with a fresh listing of validation
    // results since we are (re)loading a new/updated script. any
    // existing validation results are not relevant
    final Collection<ValidationResult> results = new HashSet<>();
    try {
        // get the engine and ensure its invocable
        if (scriptEngine instanceof Invocable) {
            final Invocable invocable = (Invocable) scriptEngine;
            // Find a custom configurator and invoke their eval() method
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap.get(scriptingComponentHelper.getScriptEngineName().toLowerCase());
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptBody, scriptingComponentHelper.getModules());
            } else {
                // evaluate the script
                scriptEngine.eval(scriptBody);
            }
            // get configured LookupService from the script (if it exists)
            final Object obj = scriptEngine.get("lookupService");
            if (obj != null) {
                final ComponentLog logger = getLogger();
                try {
                    // set the logger if the processor wants it
                    invocable.invokeMethod(obj, "setLogger", logger);
                } catch (final NoSuchMethodException nsme) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Scripted LookupService does not contain a setLogger method.");
                    }
                }
                // record the processor for use later
                final LookupService<Object> scriptedLookupService = invocable.getInterface(obj, LookupService.class);
                lookupService.set(scriptedLookupService);
                if (scriptedLookupService != null) {
                    try {
                        scriptedLookupService.initialize(new ControllerServiceInitializationContext() {

                            @Override
                            public String getIdentifier() {
                                return ScriptedLookupService.this.getIdentifier();
                            }

                            @Override
                            public ComponentLog getLogger() {
                                return logger;
                            }

                            @Override
                            public StateManager getStateManager() {
                                return ScriptedLookupService.this.getStateManager();
                            }

                            @Override
                            public ControllerServiceLookup getControllerServiceLookup() {
                                return ScriptedLookupService.super.getControllerServiceLookup();
                            }

                            @Override
                            public String getKerberosServicePrincipal() {
                                return ScriptedLookupService.this.kerberosServicePrincipal;
                            }

                            @Override
                            public File getKerberosServiceKeytab() {
                                return ScriptedLookupService.this.kerberosServiceKeytab;
                            }

                            @Override
                            public File getKerberosConfigurationFile() {
                                return ScriptedLookupService.this.kerberosConfigFile;
                            }
                        });
                    } catch (final Exception e) {
                        logger.error("Unable to initialize scripted LookupService: " + e.getLocalizedMessage(), e);
                        throw new ProcessException(e);
                    }
                }
            } else {
                throw new ScriptException("No LookupService was defined by the script.");
            }
        } else {
            throw new ScriptException("Script engine is not Invocable, cannot be used for ScriptedLookupService");
        }
    } catch (final Exception ex) {
        final ComponentLog logger = getLogger();
        final String message = "Unable to load script: " + ex.getLocalizedMessage();
        logger.error(message, ex);
        results.add(new ValidationResult.Builder().subject("ScriptedLookupServiceValidation").valid(false).explanation("Unable to load script due to " + ex.getLocalizedMessage()).input(scriptingComponentHelper.getScriptPath()).build());
    }
    // store the updated validation results
    validationResults.set(results);
    // return whether there was any issues loading the configured script
    return results.isEmpty();
}
Also used : ControllerServiceInitializationContext(org.apache.nifi.controller.ControllerServiceInitializationContext) ScriptEngineConfigurator(org.apache.nifi.processors.script.ScriptEngineConfigurator) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentLog(org.apache.nifi.logging.ComponentLog) LookupFailureException(org.apache.nifi.lookup.LookupFailureException) ProcessException(org.apache.nifi.processor.exception.ProcessException) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) StateManager(org.apache.nifi.components.state.StateManager) File(java.io.File) ControllerServiceLookup(org.apache.nifi.controller.ControllerServiceLookup) HashSet(java.util.HashSet)

Example 78 with ProcessException

use of org.apache.nifi.processor.exception.ProcessException in project nifi by apache.

the class ExecuteScript method onTrigger.

/**
 * Evaluates the given script body (or file) using the current session, context, and flowfile. The script
 * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script
 * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a
 * FlowFile, the original FlowFile will be routed to no-flowfile
 *
 * @param context        the current process context
 * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which
 *                       can be used for accessing FlowFiles, etc.
 * @throws ProcessException if the scripted processor's onTrigger() method throws an exception
 */
@Override
public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }
    ProcessSession session = sessionFactory.createSession();
    try {
        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("session", session);
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("REL_SUCCESS", REL_SUCCESS);
            bindings.put("REL_FAILURE", REL_FAILURE);
            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }
            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap.get(scriptingComponentHelper.getScriptEngineName().toLowerCase());
            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }
            // Commit this session for the user. This plus the outermost catch statement mimics the behavior
            // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base
            // class with InvokeScriptedProcessor
            session.commit();
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        session.rollback(true);
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }
}
Also used : ProcessSession(org.apache.nifi.processor.ProcessSession) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ComponentLog(org.apache.nifi.logging.ComponentLog) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) SimpleBindings(javax.script.SimpleBindings) Map(java.util.Map)

Example 79 with ProcessException

use of org.apache.nifi.processor.exception.ProcessException in project nifi by apache.

the class ExecuteScript method setup.

/**
 * Performs setup operations when the processor is scheduled to run. This includes evaluating the processor's
 * properties, as well as reloading the script (from file or the "Script Body" property)
 *
 * @param context the context in which to perform the setup operations
 */
@OnScheduled
public void setup(final ProcessContext context) {
    scriptingComponentHelper.setupVariables(context);
    // Create a script engine for each possible task
    int maxTasks = context.getMaxConcurrentTasks();
    scriptingComponentHelper.setup(maxTasks, getLogger());
    scriptToRun = scriptingComponentHelper.getScriptBody();
    try {
        if (scriptToRun == null && scriptingComponentHelper.getScriptPath() != null) {
            try (final FileInputStream scriptStream = new FileInputStream(scriptingComponentHelper.getScriptPath())) {
                scriptToRun = IOUtils.toString(scriptStream, Charset.defaultCharset());
            }
        }
    } catch (IOException ioe) {
        throw new ProcessException(ioe);
    }
}
Also used : ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) OnScheduled(org.apache.nifi.annotation.lifecycle.OnScheduled)

Example 80 with ProcessException

use of org.apache.nifi.processor.exception.ProcessException in project nifi by apache.

the class InvokeScriptedProcessor method reloadScript.

/**
 * Reloads the script Processor. This must be called within the lock.
 *
 * @param scriptBody An input stream associated with the script content
 * @return Whether the script was successfully reloaded
 */
private boolean reloadScript(final String scriptBody) {
    // note we are starting here with a fresh listing of validation
    // results since we are (re)loading a new/updated script. any
    // existing validation results are not relevant
    final Collection<ValidationResult> results = new HashSet<>();
    try {
        // get the engine and ensure its invocable
        if (scriptEngine instanceof Invocable) {
            final Invocable invocable = (Invocable) scriptEngine;
            // Find a custom configurator and invoke their eval() method
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap.get(scriptingComponentHelper.getScriptEngineName().toLowerCase());
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptBody, scriptingComponentHelper.getModules());
            } else {
                // evaluate the script
                scriptEngine.eval(scriptBody);
            }
            // get configured processor from the script (if it exists)
            final Object obj = scriptEngine.get("processor");
            if (obj != null) {
                final ComponentLog logger = getLogger();
                try {
                    // set the logger if the processor wants it
                    invocable.invokeMethod(obj, "setLogger", logger);
                } catch (final NoSuchMethodException nsme) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Configured script Processor does not contain a setLogger method.");
                    }
                }
                // record the processor for use later
                final Processor scriptProcessor = invocable.getInterface(obj, Processor.class);
                processor.set(scriptProcessor);
                if (scriptProcessor != null) {
                    try {
                        scriptProcessor.initialize(new ProcessorInitializationContext() {

                            @Override
                            public String getIdentifier() {
                                return InvokeScriptedProcessor.this.getIdentifier();
                            }

                            @Override
                            public ComponentLog getLogger() {
                                return logger;
                            }

                            @Override
                            public ControllerServiceLookup getControllerServiceLookup() {
                                return InvokeScriptedProcessor.super.getControllerServiceLookup();
                            }

                            @Override
                            public NodeTypeProvider getNodeTypeProvider() {
                                return InvokeScriptedProcessor.super.getNodeTypeProvider();
                            }

                            @Override
                            public String getKerberosServicePrincipal() {
                                return InvokeScriptedProcessor.this.kerberosServicePrincipal;
                            }

                            @Override
                            public File getKerberosServiceKeytab() {
                                return InvokeScriptedProcessor.this.kerberosServiceKeytab;
                            }

                            @Override
                            public File getKerberosConfigurationFile() {
                                return InvokeScriptedProcessor.this.kerberosConfigFile;
                            }
                        });
                    } catch (final Exception e) {
                        logger.error("Unable to initialize scripted Processor: " + e.getLocalizedMessage(), e);
                        throw new ProcessException(e);
                    }
                }
            } else {
                throw new ScriptException("No processor was defined by the script.");
            }
        }
    } catch (final Exception ex) {
        final ComponentLog logger = getLogger();
        final String message = "Unable to load script: " + ex.getLocalizedMessage();
        logger.error(message, ex);
        results.add(new ValidationResult.Builder().subject("ScriptValidation").valid(false).explanation("Unable to load script due to " + ex.getLocalizedMessage()).input(scriptingComponentHelper.getScriptPath()).build());
    }
    // store the updated validation results
    validationResults.set(results);
    // return whether there was any issues loading the configured script
    return results.isEmpty();
}
Also used : AbstractSessionFactoryProcessor(org.apache.nifi.processor.AbstractSessionFactoryProcessor) Processor(org.apache.nifi.processor.Processor) NodeTypeProvider(org.apache.nifi.controller.NodeTypeProvider) ValidationResult(org.apache.nifi.components.ValidationResult) ComponentLog(org.apache.nifi.logging.ComponentLog) ProcessorInitializationContext(org.apache.nifi.processor.ProcessorInitializationContext) ProcessException(org.apache.nifi.processor.exception.ProcessException) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) ProcessException(org.apache.nifi.processor.exception.ProcessException) File(java.io.File) ControllerServiceLookup(org.apache.nifi.controller.ControllerServiceLookup) HashSet(java.util.HashSet)

Aggregations

ProcessException (org.apache.nifi.processor.exception.ProcessException)274 FlowFile (org.apache.nifi.flowfile.FlowFile)169 IOException (java.io.IOException)162 InputStream (java.io.InputStream)79 HashMap (java.util.HashMap)78 ComponentLog (org.apache.nifi.logging.ComponentLog)78 OutputStream (java.io.OutputStream)62 ArrayList (java.util.ArrayList)55 Map (java.util.Map)52 PropertyDescriptor (org.apache.nifi.components.PropertyDescriptor)39 InputStreamCallback (org.apache.nifi.processor.io.InputStreamCallback)38 StopWatch (org.apache.nifi.util.StopWatch)37 HashSet (java.util.HashSet)36 ProcessSession (org.apache.nifi.processor.ProcessSession)35 Relationship (org.apache.nifi.processor.Relationship)33 List (java.util.List)31 OutputStreamCallback (org.apache.nifi.processor.io.OutputStreamCallback)29 AtomicReference (java.util.concurrent.atomic.AtomicReference)28 Set (java.util.Set)26 ProcessContext (org.apache.nifi.processor.ProcessContext)25