]> git.basschouten.com Git - openhab-addons.git/blob
508e9cf26aa7f6b6c489e1d338aa09f584cc97dd
[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 java.util.Arrays;
16 import java.util.stream.Collectors;
17
18 import javax.script.Invocable;
19 import javax.script.ScriptContext;
20 import javax.script.ScriptEngine;
21
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;
27
28 /**
29  * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
30  *
31  * @author Jonathan Gilbert - Initial contribution
32  * @author Florian Hotze - Improve logger name, Fix memory leak caused by exception logging
33  */
34 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable>
35         extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<T> {
36
37     private static final String SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER = "openhab-transformation-script-";
38     private static final int STACK_TRACE_LENGTH = 5;
39
40     private @Nullable Logger logger;
41
42     public DebuggingGraalScriptEngine(T delegate) {
43         super(delegate);
44     }
45
46     @Override
47     protected void beforeInvocation() {
48         super.beforeInvocation();
49         if (logger == null) {
50             initializeLogger();
51         }
52     }
53
54     @Override
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));
64         }
65         return e;
66     }
67
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;
75     }
76
77     /**
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.
81      */
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");
87
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,
96                         "transformation.");
97             }
98         }
99
100         logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);
101     }
102 }