2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.jsscripting.internal;
15 import java.util.Arrays;
16 import java.util.stream.Collectors;
18 import javax.script.Invocable;
19 import javax.script.ScriptContext;
20 import javax.script.ScriptEngine;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.graalvm.polyglot.PolyglotException;
24 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
31 * @author Jonathan Gilbert - Initial contribution
32 * @author Florian Hotze - Improve logger name, Fix memory leak caused by exception logging
34 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable>
35 extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<T> {
37 private static final String SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER = "openhab-transformation-script-";
38 private static final int STACK_TRACE_LENGTH = 5;
40 private @Nullable Logger logger;
42 public DebuggingGraalScriptEngine(T delegate) {
47 protected void beforeInvocation() {
48 super.beforeInvocation();
55 public Exception afterThrowsInvocation(Exception e) {
56 Throwable cause = e.getCause();
57 // OPS4J Pax Logging holds a reference to the exception, which causes the OpenhabGraalJSScriptEngine to not be
58 // removed from heap by garbage collection and causing a memory leak.
59 // Therefore, don't pass the exceptions itself to the logger, but only their message!
60 if (cause instanceof IllegalArgumentException) {
61 logger.error("Failed to execute script: {}", stringifyThrowable(cause));
62 } else if (cause instanceof PolyglotException) {
63 logger.error("Failed to execute script: {}", stringifyThrowable(cause));
68 private String stringifyThrowable(Throwable throwable) {
69 String message = throwable.getMessage();
70 StackTraceElement[] stackTraceElements = throwable.getStackTrace();
71 String stackTrace = Arrays.stream(stackTraceElements).limit(STACK_TRACE_LENGTH)
72 .map(t -> " at " + t.toString()).collect(Collectors.joining(System.lineSeparator()))
73 + System.lineSeparator() + " ... " + stackTraceElements.length + " more";
74 return (message != null) ? message + System.lineSeparator() + stackTrace : stackTrace;
78 * Initializes the logger.
79 * This cannot be done on script engine creation because the context variables are not yet initialized.
80 * Therefore, the logger needs to be initialized on the first use after script engine creation.
82 private void initializeLogger() {
83 ScriptContext ctx = delegate.getContext();
84 Object fileName = ctx.getAttribute("javax.script.filename");
85 Object ruleUID = ctx.getAttribute("ruleUID");
86 Object ohEngineIdentifier = ctx.getAttribute("oh.engine-identifier");
88 String identifier = "stack";
89 if (fileName != null) {
90 identifier = fileName.toString().replaceAll("^.*[/\\\\]", "");
91 } else if (ruleUID != null) {
92 identifier = ruleUID.toString();
93 } else if (ohEngineIdentifier != null) {
94 if (ohEngineIdentifier.toString().startsWith(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER)) {
95 identifier = ohEngineIdentifier.toString().replaceAll(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER,
100 logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);