Search in sources :

Example 11 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class BSFClient method connect.

/**
 * {@inheritDoc}
 */
@Override
public void connect(final InetAddress address, final int port, final int timeout) throws IOException, Exception {
    m_results = new HashMap<String, String>();
    BSFManager bsfManager = new BSFManager();
    File file = new File(m_fileName);
    Map<String, Object> map = getParametersMap();
    try {
        if (m_langClass == null) {
            m_langClass = BSFManager.getLangFromFilename(m_fileName);
        }
        if (m_bsfEngine != null && m_langClass != null && m_fileExtensions.length > 0) {
            BSFManager.registerScriptingEngine(m_langClass, m_bsfEngine, m_fileExtensions);
        }
        if (file.exists() && file.canRead()) {
            String code = IOUtils.getStringFromReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
            // Declare some beans that can be used inside the script
            bsfManager.declareBean("map", map, Map.class);
            bsfManager.declareBean("ip_addr", address.getHostAddress(), String.class);
            // TODO: I'm not sure how to deal with it on detectors. Is the node exists before running detectors? If so, I need NodeDao here.
            // bsfManager.declareBean("node_id",svc.getNodeId(),int.class );
            // bsfManager.declareBean("node_label", svc.getNodeLabel(), String.class);
            bsfManager.declareBean("svc_name", m_serviceName, String.class);
            bsfManager.declareBean("results", m_results, Map.class);
            bsfManager.declareBean("port", port, Integer.class);
            bsfManager.declareBean("timeout", timeout, Integer.class);
            for (final Entry<String, Object> entry : map.entrySet()) {
                bsfManager.declareBean(entry.getKey(), entry.getValue(), String.class);
            }
            LOG.info("Executing {} for {}", m_langClass, file.getAbsoluteFile());
            if ("eval".equals(m_runType)) {
                m_results.put("status", bsfManager.eval(m_langClass, "BSFDetector", 0, 0, code).toString());
            } else if ("exec".equals(m_runType)) {
                bsfManager.exec(m_langClass, "BSFDetector", 0, 0, code);
            } else {
                LOG.warn("Invalid run-type parameter value '{}' for service '{}'. Only 'eval' and 'exec' are supported.", m_runType, m_serviceName);
                throw new RuntimeException("Invalid run-type '" + m_runType + "'");
            }
            if ("exec".equals(m_runType) && !m_results.containsKey("status")) {
                LOG.warn("The exec script '{}' for service '{}' never put a 'status' entry in the 'results' bean. Exec scripts should put this entry with a value of 'OK' for up.", m_fileName, m_serviceName);
            }
        } else {
            LOG.warn("Cannot locate or read BSF script file '{}'. Marking service '{}' down.", m_fileName, m_serviceName);
        }
    } catch (BSFException e) {
        m_results.clear();
        LOG.warn("BSFDetector poll for service '{}' failed with BSFException: {}", m_serviceName, e.getMessage(), e);
    } catch (FileNotFoundException e) {
        m_results.clear();
        LOG.warn("Could not find BSF script file '{}'. Marking service '{}' down.", m_fileName, m_serviceName);
    } catch (IOException e) {
        m_results.clear();
        LOG.warn("BSFDetector poll for service '{}' failed with IOException: {}", m_serviceName, e.getMessage(), e);
    } catch (Throwable e) {
        m_results.clear();
        LOG.warn("BSFDetector poll for service '{}' failed with unexpected throwable: {}", m_serviceName, e.getMessage(), e);
    } finally {
        BSFManagerTerminator.terminate(bsfManager);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) BSFManager(org.apache.bsf.BSFManager) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BSFException(org.apache.bsf.BSFException) File(java.io.File)

Example 12 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class BSFNotificationStrategy method executeScript.

private static synchronized int executeScript(String fileName, BSFNotificationStrategy obj) {
    String lang = obj.getLangClass();
    String engine = obj.getBsfEngine();
    String runType = obj.getBsfRunType();
    String[] extensions = obj.getFileExtensions();
    LOG.info("Loading notification script from file '{}'", fileName);
    File scriptFile = new File(fileName);
    int ret = -1;
    try {
        if (lang == null)
            lang = BSFManager.getLangFromFilename(fileName);
        // Declare some beans that can be used inside the script
        HashMap<String, String> results = new HashMap<String, String>();
        s_bsfManager.declareBean("results", results, Map.class);
        declareBeans(obj);
        if (engine != null && lang != null && extensions != null && extensions.length > 0) {
            // We register the scripting engine again no matter what since
            // BSFManager doesn't let us know what engine is currently registered
            // for this language and it might not be the same as what we want.
            LOG.debug("Registering scripting engine '{}' for '{}'", engine, lang);
            BSFManager.registerScriptingEngine(lang, engine, extensions);
        }
        if (scriptFile.exists() && scriptFile.canRead()) {
            String code = IOUtils.getStringFromReader(new InputStreamReader(new FileInputStream(scriptFile), StandardCharsets.UTF_8));
            // Check foot before firing
            obj.checkAberrantScriptBehaviors(code);
            // Execute the script
            if ("eval".equals(runType)) {
                results.put("status", s_bsfManager.eval(lang, "BSFNotificationStrategy", 0, 0, code).toString());
            } else if ("exec".equals(runType)) {
                s_bsfManager.exec(lang, "BSFNotificationStrategy", 0, 0, code);
            } else {
                LOG.warn("Invalid run-type parameter value '{}' for BSF notification script '{}'. Only 'eval' and 'exec' are supported.", runType, scriptFile);
            }
            // Check whether the script finished successfully
            if ("OK".equals(results.get("status"))) {
                LOG.info("Execution succeeded and successful status passed back for script '{}'", scriptFile);
                ret = 0;
            } else {
                LOG.warn("Execution succeeded for script '{}', but script did not indicate successful notification by putting an entry into the 'results' bean with key 'status' and value 'OK'", scriptFile);
                ret = -1;
            }
        } else {
            LOG.warn("Cannot locate or read BSF script file '{}'. Returning failure indication.", fileName);
            ret = -1;
        }
    } catch (BSFException e) {
        LOG.warn("Execution of script '{}' failed with BSFException: {}", scriptFile, e.getMessage(), e);
        ret = -1;
    } catch (FileNotFoundException e) {
        LOG.warn("Could not find BSF script file '{}'.", fileName);
        ret = -1;
    } catch (IOException e) {
        LOG.warn("Execution of script '{}' failed with IOException: {}", scriptFile, e.getMessage(), e);
        ret = -1;
    } catch (Throwable e) {
        // Catch any RuntimeException throws
        LOG.warn("Execution of script '{}' failed with unexpected throwable: {}", scriptFile, e.getMessage(), e);
        ret = -1;
    } finally {
        undeclareBean("results");
        undeclareBeans(obj);
    }
    LOG.debug("Finished running BSF script notification.");
    return ret;
}
Also used : BSFException(org.apache.bsf.BSFException) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 13 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class BSFNorthbounder method process.

/**
 * Process.
 *
 * @param alarm the alarm
 * @throws NorthbounderException the northbounder exception
 */
private void process(NorthboundAlarm alarm) throws NorthbounderException {
    m_manager.registerBean("alarm", alarm);
    try {
        LOG.debug("processing alarm {} with engine {}", alarm, getName());
        m_manager.exec(m_engine.getLanguage(), "", 0, 0, m_engine.getOnAlarm());
    } catch (BSFException e) {
        throw new NorthbounderException("Cannot execute script", e);
    } finally {
        m_manager.unregisterBean("alarm");
    }
}
Also used : BSFException(org.apache.bsf.BSFException) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException)

Example 14 with BSFException

use of org.apache.bsf.BSFException in project groovy-core by groovy.

the class GroovyEngine method exec.

/**
     * Execute a script.
     */
public void exec(String source, int lineNo, int columnNo, Object script) throws BSFException {
    try {
        // use evaluate to pass in the BSF variables
        source = convertToValidJavaClassname(source);
        getEvalShell().evaluate(script.toString(), source);
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
    }
}
Also used : BSFException(org.apache.bsf.BSFException) BSFException(org.apache.bsf.BSFException)

Example 15 with BSFException

use of org.apache.bsf.BSFException in project opennms by OpenNMS.

the class Executor method start.

public synchronized void start() {
    for (final Engine engine : m_config.getEngines()) {
        LOG.debug("Registering engine: {}", engine.getLanguage());
        String[] extensions = null;
        if (engine.getExtensions().isPresent()) {
            StringTokenizer st = new StringTokenizer(engine.getExtensions().get());
            extensions = new String[st.countTokens()];
            int j = 0;
            while (st.hasMoreTokens()) {
                extensions[j++] = st.nextToken();
            }
        }
        BSFManager.registerScriptingEngine(engine.getLanguage(), engine.getClassName(), extensions);
    }
    m_scriptManager = new BSFManager();
    m_scriptManager.registerBean("log", LOG);
    // Run all start scripts
    for (final StartScript startScript : m_config.getStartScripts()) {
        if (startScript.getContent().isPresent()) {
            try {
                m_scriptManager.exec(startScript.getLanguage(), "", 0, 0, startScript.getContent().get());
            } catch (BSFException e) {
                LOG.error("Start script failed: " + startScript, e);
            }
        } else {
            LOG.warn("Start script has no script content: " + startScript);
        }
    }
    // Start the thread pool
    m_executorService = Executors.newFixedThreadPool(1, new LogPreservingThreadFactory("Scriptd-Executor", 1));
    // started
    try {
        m_broadcastEventProcessor = new BroadcastEventProcessor(this);
    } catch (Throwable e) {
        LOG.error("Failed to setup event reader", e);
        throw new UndeclaredThrowableException(e);
    }
    LOG.debug("Scriptd executor started");
}
Also used : StringTokenizer(java.util.StringTokenizer) StartScript(org.opennms.netmgt.config.scriptd.StartScript) BSFException(org.apache.bsf.BSFException) LogPreservingThreadFactory(org.opennms.core.concurrent.LogPreservingThreadFactory) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) BSFManager(org.apache.bsf.BSFManager) Engine(org.opennms.netmgt.config.scriptd.Engine)

Aggregations

BSFException (org.apache.bsf.BSFException)22 BSFManager (org.apache.bsf.BSFManager)8 File (java.io.File)5 IOException (java.io.IOException)5 FileInputStream (java.io.FileInputStream)4 FileNotFoundException (java.io.FileNotFoundException)3 InputStreamReader (java.io.InputStreamReader)3 BSFEngine (org.apache.bsf.BSFEngine)3 Script (groovy.lang.Script)2 HashMap (java.util.HashMap)2 SampleResult (org.apache.jmeter.samplers.SampleResult)2 NorthbounderException (org.opennms.netmgt.alarmd.api.NorthbounderException)2 BufferedInputStream (java.io.BufferedInputStream)1 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)1 LinkedHashMap (java.util.LinkedHashMap)1 StringTokenizer (java.util.StringTokenizer)1 EvaluatorException (org.mozilla.javascript.EvaluatorException)1 JavaScriptException (org.mozilla.javascript.JavaScriptException)1 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)1 WrappedException (org.mozilla.javascript.WrappedException)1