]> git.basschouten.com Git - openhab-addons.git/blob
76f1afb2dd54483c33b893d4589cdf4fb2783744
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.automation.jsscripting.internal;
14
15 import static org.openhab.core.automation.module.script.ScriptTransformationService.OPENHAB_TRANSFORMATION_SCRIPT;
16
17 import java.util.Arrays;
18 import java.util.stream.Collectors;
19
20 import javax.script.Compilable;
21 import javax.script.Invocable;
22 import javax.script.ScriptContext;
23 import javax.script.ScriptEngine;
24
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;
30
31 /**
32  * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
33  *
34  * @author Jonathan Gilbert - Initial contribution
35  * @author Florian Hotze - Improve logger name, Fix memory leak caused by exception logging
36  */
37 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable & Compilable>
38         extends InvocationInterceptingScriptEngineWithInvocableAndCompilableAndAutoCloseable<T> {
39
40     private static final int STACK_TRACE_LENGTH = 5;
41
42     private @Nullable Logger logger;
43
44     public DebuggingGraalScriptEngine(T delegate) {
45         super(delegate);
46     }
47
48     @Override
49     protected void beforeInvocation() {
50         super.beforeInvocation();
51         if (logger == null) {
52             initializeLogger();
53         }
54     }
55
56     @Override
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));
66         }
67         return e;
68     }
69
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;
77     }
78
79     /**
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.
83      */
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");
89
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.");
98             }
99         }
100
101         logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);
102     }
103 }