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 static org.openhab.core.automation.module.script.ScriptTransformationService.OPENHAB_TRANSFORMATION_SCRIPT;
17 import java.util.Arrays;
18 import java.util.stream.Collectors;
20 import javax.script.Compilable;
21 import javax.script.Invocable;
22 import javax.script.ScriptContext;
23 import javax.script.ScriptEngine;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.graalvm.polyglot.PolyglotException;
27 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndCompilableAndAutoCloseable;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
34 * @author Jonathan Gilbert - Initial contribution
35 * @author Florian Hotze - Improve logger name, Fix memory leak caused by exception logging
37 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable & Compilable>
38 extends InvocationInterceptingScriptEngineWithInvocableAndCompilableAndAutoCloseable<T> {
40 private static final int STACK_TRACE_LENGTH = 5;
42 private @Nullable Logger logger;
44 public DebuggingGraalScriptEngine(T delegate) {
49 protected void beforeInvocation() {
50 super.beforeInvocation();
57 public Exception afterThrowsInvocation(Exception e) {
58 Throwable cause = e.getCause();
59 // OPS4J Pax Logging holds a reference to the exception, which causes the OpenhabGraalJSScriptEngine to not be
60 // removed from heap by garbage collection and causing a memory leak.
61 // Therefore, don't pass the exceptions itself to the logger, but only their message!
62 if (cause instanceof IllegalArgumentException) {
63 logger.error("Failed to execute script: {}", stringifyThrowable(cause));
64 } else if (cause instanceof PolyglotException) {
65 logger.error("Failed to execute script: {}", stringifyThrowable(cause));
70 private String stringifyThrowable(Throwable throwable) {
71 String message = throwable.getMessage();
72 StackTraceElement[] stackTraceElements = throwable.getStackTrace();
73 String stackTrace = Arrays.stream(stackTraceElements).limit(STACK_TRACE_LENGTH)
74 .map(t -> " at " + t.toString()).collect(Collectors.joining(System.lineSeparator()))
75 + System.lineSeparator() + " ... " + stackTraceElements.length + " more";
76 return (message != null) ? message + System.lineSeparator() + stackTrace : stackTrace;
80 * Initializes the logger.
81 * This cannot be done on script engine creation because the context variables are not yet initialized.
82 * Therefore, the logger needs to be initialized on the first use after script engine creation.
84 private void initializeLogger() {
85 ScriptContext ctx = delegate.getContext();
86 Object fileName = ctx.getAttribute("javax.script.filename");
87 Object ruleUID = ctx.getAttribute("ruleUID");
88 Object ohEngineIdentifier = ctx.getAttribute("oh.engine-identifier");
90 String identifier = "stack";
91 if (fileName != null) {
92 identifier = fileName.toString().replaceAll("^.*[/\\\\]", "");
93 } else if (ruleUID != null) {
94 identifier = ruleUID.toString();
95 } else if (ohEngineIdentifier != null) {
96 if (ohEngineIdentifier.toString().startsWith(OPENHAB_TRANSFORMATION_SCRIPT)) {
97 identifier = ohEngineIdentifier.toString().replaceAll(OPENHAB_TRANSFORMATION_SCRIPT, "transformation.");
101 logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);