]> git.basschouten.com Git - openhab-addons.git/blob
cf1c45464e90a4dd073c931ad60e1bda14485dfb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.ScriptEngineFactory.*;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.nio.channels.SeekableByteChannel;
20 import java.nio.file.AccessMode;
21 import java.nio.file.FileSystems;
22 import java.nio.file.LinkOption;
23 import java.nio.file.NoSuchFileException;
24 import java.nio.file.OpenOption;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.nio.file.attribute.FileAttribute;
28 import java.time.Duration;
29 import java.time.ZonedDateTime;
30 import java.util.Collections;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.function.Consumer;
34 import java.util.function.Function;
35
36 import javax.script.ScriptContext;
37 import javax.script.ScriptException;
38
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.graalvm.polyglot.Context;
41 import org.graalvm.polyglot.Engine;
42 import org.graalvm.polyglot.HostAccess;
43 import org.graalvm.polyglot.Value;
44 import org.openhab.automation.jsscripting.internal.fs.DelegatingFileSystem;
45 import org.openhab.automation.jsscripting.internal.fs.PrefixedSeekableByteChannel;
46 import org.openhab.automation.jsscripting.internal.fs.ReadOnlySeekableByteArrayChannel;
47 import org.openhab.automation.jsscripting.internal.fs.watch.JSDependencyTracker;
48 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable;
49 import org.openhab.core.automation.module.script.ScriptExtensionAccessor;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
54
55 /**
56  * GraalJS ScriptEngine implementation
57  *
58  * @author Jonathan Gilbert - Initial contribution
59  * @author Dan Cunningham - Script injections
60  * @author Florian Hotze - Create lock object for multi-thread synchronization; Inject the {@link JSRuntimeFeatures}
61  *         into the JS context; Fix memory leak caused by HostObject by making HostAccess reference static
62  */
63 public class OpenhabGraalJSScriptEngine
64         extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<GraalJSScriptEngine> {
65
66     private static final Logger LOGGER = LoggerFactory.getLogger(OpenhabGraalJSScriptEngine.class);
67     private static final String GLOBAL_REQUIRE = "require(\"@jsscripting-globals\");";
68     private static final String REQUIRE_WRAPPER_NAME = "__wraprequire__";
69     /** Final CommonJS search path for our library */
70     private static final Path NODE_DIR = Paths.get("node_modules");
71     /** Provides unlimited host access as well as custom translations from JS to Java Objects */
72     private static final HostAccess HOST_ACCESS = HostAccess.newBuilder(HostAccess.ALL)
73             // Translate JS-Joda ZonedDateTime to java.time.ZonedDateTime
74             .targetTypeMapping(Value.class, ZonedDateTime.class, (v) -> v.hasMember("withFixedOffsetZone"), v -> {
75                 return ZonedDateTime.parse(v.invokeMember("withFixedOffsetZone").invokeMember("toString").asString());
76             }, HostAccess.TargetMappingPrecedence.LOW)
77
78             // Translate JS-Joda Duration to java.time.Duration
79             .targetTypeMapping(Value.class, Duration.class,
80                     // picking two members to check as Duration has many common function names
81                     (v) -> v.hasMember("minusDuration") && v.hasMember("toNanos"), v -> {
82                         return Duration.ofNanos(v.invokeMember("toNanos").asLong());
83                     }, HostAccess.TargetMappingPrecedence.LOW)
84             .build();
85
86     /** Shared lock object for synchronization of multi-thread access */
87     private final Object lock = new Object();
88     private final JSRuntimeFeatures jsRuntimeFeatures;
89
90     // these fields start as null because they are populated on first use
91     private String engineIdentifier;
92     private Consumer<String> scriptDependencyListener;
93
94     private boolean initialized = false;
95     private final String globalScript;
96
97     /**
98      * Creates an implementation of ScriptEngine (& Invocable), wrapping the contained engine, that tracks the script
99      * lifecycle and provides hooks for scripts to do so too.
100      */
101     public OpenhabGraalJSScriptEngine(@Nullable String injectionCode, JSScriptServiceUtil jsScriptServiceUtil) {
102         super(null); // delegate depends on fields not yet initialised, so we cannot set it immediately
103         this.globalScript = GLOBAL_REQUIRE + (injectionCode != null ? injectionCode : "");
104         this.jsRuntimeFeatures = jsScriptServiceUtil.getJSRuntimeFeatures(lock);
105
106         LOGGER.debug("Initializing GraalJS script engine...");
107
108         delegate = GraalJSScriptEngine.create(
109                 Engine.newBuilder().allowExperimentalOptions(true).option("engine.WarnInterpreterOnly", "false")
110                         .build(),
111                 Context.newBuilder("js").allowExperimentalOptions(true).allowAllAccess(true)
112                         .allowHostAccess(HOST_ACCESS).option("js.commonjs-require-cwd", JSDependencyTracker.LIB_PATH)
113                         .option("js.nashorn-compat", "true") // to ease migration
114                         .option("js.ecmascript-version", "2021") // nashorn compat will enforce es5 compatibility, we
115                                                                  // want ecma2021
116                         .option("js.commonjs-require", "true") // enable CommonJS module support
117                         .hostClassLoader(getClass().getClassLoader())
118                         .fileSystem(new DelegatingFileSystem(FileSystems.getDefault().provider()) {
119                             @Override
120                             public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
121                                     FileAttribute<?>... attrs) throws IOException {
122                                 if (scriptDependencyListener != null) {
123                                     scriptDependencyListener.accept(path.toString());
124                                 }
125
126                                 if (path.toString().endsWith(".js")) {
127                                     SeekableByteChannel sbc = null;
128                                     if (isRootNodePath(path)) {
129                                         InputStream is = getClass().getResourceAsStream(nodeFileToResource(path));
130                                         if (is == null) {
131                                             throw new IOException("Could not read " + path.toString());
132                                         }
133                                         sbc = new ReadOnlySeekableByteArrayChannel(is.readAllBytes());
134                                     } else {
135                                         sbc = super.newByteChannel(path, options, attrs);
136                                     }
137                                     return new PrefixedSeekableByteChannel(
138                                             ("require=" + REQUIRE_WRAPPER_NAME + "(require);").getBytes(), sbc);
139                                 } else {
140                                     return super.newByteChannel(path, options, attrs);
141                                 }
142                             }
143
144                             @Override
145                             public void checkAccess(Path path, Set<? extends AccessMode> modes,
146                                     LinkOption... linkOptions) throws IOException {
147                                 if (isRootNodePath(path)) {
148                                     if (getClass().getResource(nodeFileToResource(path)) == null) {
149                                         throw new NoSuchFileException(path.toString());
150                                     }
151                                 } else {
152                                     super.checkAccess(path, modes, linkOptions);
153                                 }
154                             }
155
156                             @Override
157                             public Map<String, Object> readAttributes(Path path, String attributes,
158                                     LinkOption... options) throws IOException {
159                                 if (isRootNodePath(path)) {
160                                     return Collections.singletonMap("isRegularFile", true);
161                                 }
162                                 return super.readAttributes(path, attributes, options);
163                             }
164
165                             @Override
166                             public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException {
167                                 if (isRootNodePath(path)) {
168                                     return path;
169                                 }
170                                 return super.toRealPath(path, linkOptions);
171                             }
172                         }));
173     }
174
175     @Override
176     protected void beforeInvocation() {
177         if (initialized) {
178             return;
179         }
180
181         ScriptContext ctx = delegate.getContext();
182
183         // these are added post-construction, so we need to fetch them late
184         this.engineIdentifier = (String) ctx.getAttribute(CONTEXT_KEY_ENGINE_IDENTIFIER);
185         if (this.engineIdentifier == null) {
186             throw new IllegalStateException("Failed to retrieve engine identifier from engine bindings");
187         }
188
189         ScriptExtensionAccessor scriptExtensionAccessor = (ScriptExtensionAccessor) ctx
190                 .getAttribute(CONTEXT_KEY_EXTENSION_ACCESSOR);
191         if (scriptExtensionAccessor == null) {
192             throw new IllegalStateException("Failed to retrieve script extension accessor from engine bindings");
193         }
194
195         scriptDependencyListener = (Consumer<String>) ctx
196                 .getAttribute("oh.dependency-listener"/* CONTEXT_KEY_DEPENDENCY_LISTENER */);
197         if (scriptDependencyListener == null) {
198             LOGGER.warn(
199                     "Failed to retrieve script script dependency listener from engine bindings. Script dependency tracking will be disabled.");
200         }
201
202         ScriptExtensionModuleProvider scriptExtensionModuleProvider = new ScriptExtensionModuleProvider(
203                 scriptExtensionAccessor, lock);
204
205         Function<Function<Object[], Object>, Function<String, Object>> wrapRequireFn = originalRequireFn -> moduleName -> scriptExtensionModuleProvider
206                 .locatorFor(delegate.getPolyglotContext(), engineIdentifier).locateModule(moduleName)
207                 .map(m -> (Object) m).orElseGet(() -> originalRequireFn.apply(new Object[] { moduleName }));
208
209         delegate.getBindings(ScriptContext.ENGINE_SCOPE).put(REQUIRE_WRAPPER_NAME, wrapRequireFn);
210         // Injections into the JS runtime
211         delegate.put("require", wrapRequireFn.apply((Function<Object[], Object>) delegate.get("require")));
212         jsRuntimeFeatures.getFeatures().forEach((key, obj) -> {
213             LOGGER.debug("Injecting {} into the JS runtime...", key);
214             delegate.put(key, obj);
215         });
216
217         initialized = true;
218
219         try {
220             eval(globalScript);
221         } catch (ScriptException e) {
222             LOGGER.error("Could not inject global script", e);
223         }
224     }
225
226     @Override
227     public Object invokeFunction(String s, Object... objects) throws ScriptException, NoSuchMethodException {
228         // Synchronize multi-thread access to avoid exceptions when reloading a script file while the script is running
229         synchronized (lock) {
230             return super.invokeFunction(s, objects);
231         }
232     }
233
234     @Override
235     public void close() {
236         jsRuntimeFeatures.close();
237         delegate.close();
238     }
239
240     /**
241      * Tests if this is a root node directory, `/node_modules`, `C:\node_modules`, etc...
242      *
243      * @param path a root path
244      * @return whether the given path is a node root directory
245      */
246     private boolean isRootNodePath(Path path) {
247         return path.startsWith(path.getRoot().resolve(NODE_DIR));
248     }
249
250     /**
251      * Converts a root node path to a class resource path for loading local modules
252      * Ex: C:\node_modules\foo.js -> /node_modules/foo.js
253      *
254      * @param path a root path, e.g. C:\node_modules\foo.js
255      * @return the class resource path for loading local modules
256      */
257     private String nodeFileToResource(Path path) {
258         return "/" + path.subpath(0, path.getNameCount()).toString().replace('\\', '/');
259     }
260 }