2 * Copyright (c) 2010-2022 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.ScriptEngineFactory.*;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.InputStreamReader;
20 import java.io.Reader;
21 import java.nio.channels.SeekableByteChannel;
22 import java.nio.file.AccessMode;
23 import java.nio.file.FileSystems;
24 import java.nio.file.LinkOption;
25 import java.nio.file.NoSuchFileException;
26 import java.nio.file.OpenOption;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.nio.file.attribute.FileAttribute;
30 import java.time.Duration;
31 import java.time.ZonedDateTime;
32 import java.util.Collections;
35 import java.util.concurrent.locks.Lock;
36 import java.util.concurrent.locks.ReentrantLock;
37 import java.util.function.Consumer;
38 import java.util.function.Function;
40 import javax.script.ScriptContext;
41 import javax.script.ScriptException;
43 import org.eclipse.jdt.annotation.Nullable;
44 import org.graalvm.polyglot.Context;
45 import org.graalvm.polyglot.Engine;
46 import org.graalvm.polyglot.HostAccess;
47 import org.graalvm.polyglot.Source;
48 import org.graalvm.polyglot.Value;
49 import org.openhab.automation.jsscripting.internal.fs.DelegatingFileSystem;
50 import org.openhab.automation.jsscripting.internal.fs.PrefixedSeekableByteChannel;
51 import org.openhab.automation.jsscripting.internal.fs.ReadOnlySeekableByteArrayChannel;
52 import org.openhab.automation.jsscripting.internal.fs.watch.JSDependencyTracker;
53 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable;
54 import org.openhab.core.automation.module.script.ScriptExtensionAccessor;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
61 * GraalJS ScriptEngine implementation
63 * @author Jonathan Gilbert - Initial contribution
64 * @author Dan Cunningham - Script injections
65 * @author Florian Hotze - Create lock object for multi-thread synchronization; Inject the {@link JSRuntimeFeatures}
66 * into the JS context; Fix memory leak caused by HostObject by making HostAccess reference static; Switch to
67 * {@link Lock} for multi-thread synchronization; globals & openhab-js injection code caching
69 public class OpenhabGraalJSScriptEngine
70 extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<GraalJSScriptEngine> {
72 private static final Logger LOGGER = LoggerFactory.getLogger(OpenhabGraalJSScriptEngine.class);
73 private static Source GLOBAL_SOURCE;
77 GLOBAL_SOURCE = Source.newBuilder("js", getFileAsReader("node_modules/@jsscripting-globals.js"),
78 "@jsscripting-globals.js").cached(true).build();
79 } catch (IOException e) {
80 throw new RuntimeException("Failed to load @jsscripting-globals.js", e);
84 private static Source OPENHAB_JS_SOURCE;
88 OPENHAB_JS_SOURCE = Source
89 .newBuilder("js", getFileAsReader("node_modules/@openhab-globals.js"), "@openhab-globals.js")
90 .cached(true).build();
91 } catch (IOException e) {
92 throw new RuntimeException("Failed to load @openhab-globals.js", e);
95 private static String OPENHAB_JS_INJECTION_CODE = "Object.assign(this, require('openhab'));";
97 private static final String REQUIRE_WRAPPER_NAME = "__wraprequire__";
98 /** Final CommonJS search path for our library */
99 private static final Path NODE_DIR = Paths.get("node_modules");
100 /** Shared Polyglot {@link Engine} across all instances of {@link OpenhabGraalJSScriptEngine} */
101 private static final Engine ENGINE = Engine.newBuilder().allowExperimentalOptions(true)
102 .option("engine.WarnInterpreterOnly", "false").build();
103 /** Provides unlimited host access as well as custom translations from JS to Java Objects */
104 private static final HostAccess HOST_ACCESS = HostAccess.newBuilder(HostAccess.ALL)
105 // Translate JS-Joda ZonedDateTime to java.time.ZonedDateTime
106 .targetTypeMapping(Value.class, ZonedDateTime.class, (v) -> v.hasMember("withFixedOffsetZone"), v -> {
107 return ZonedDateTime.parse(v.invokeMember("withFixedOffsetZone").invokeMember("toString").asString());
108 }, HostAccess.TargetMappingPrecedence.LOW)
110 // Translate JS-Joda Duration to java.time.Duration
111 .targetTypeMapping(Value.class, Duration.class,
112 // picking two members to check as Duration has many common function names
113 (v) -> v.hasMember("minusDuration") && v.hasMember("toNanos"), v -> {
114 return Duration.ofNanos(v.invokeMember("toNanos").asLong());
115 }, HostAccess.TargetMappingPrecedence.LOW)
118 /** {@link Lock} synchronization of multi-thread access */
119 private final Lock lock = new ReentrantLock();
120 private final JSRuntimeFeatures jsRuntimeFeatures;
122 // these fields start as null because they are populated on first use
123 private String engineIdentifier;
124 private @Nullable Consumer<String> scriptDependencyListener;
126 private boolean initialized = false;
127 private final boolean injectionEnabled;
128 private final boolean useIncludedLibrary;
131 * Creates an implementation of ScriptEngine (& Invocable), wrapping the contained engine, that tracks the script
132 * lifecycle and provides hooks for scripts to do so too.
134 public OpenhabGraalJSScriptEngine(boolean injectionEnabled, boolean useIncludedLibrary,
135 JSScriptServiceUtil jsScriptServiceUtil) {
136 super(null); // delegate depends on fields not yet initialised, so we cannot set it immediately
137 this.injectionEnabled = injectionEnabled;
138 this.useIncludedLibrary = useIncludedLibrary;
139 this.jsRuntimeFeatures = jsScriptServiceUtil.getJSRuntimeFeatures(lock);
141 LOGGER.debug("Initializing GraalJS script engine...");
143 delegate = GraalJSScriptEngine.create(ENGINE,
144 Context.newBuilder("js").allowExperimentalOptions(true).allowAllAccess(true)
145 .allowHostAccess(HOST_ACCESS).option("js.commonjs-require-cwd", JSDependencyTracker.LIB_PATH)
146 .option("js.nashorn-compat", "true") // Enable Nashorn compat mode as openhab-js relies on
148 // https://github.com/oracle/graaljs/blob/master/docs/user/NashornMigrationGuide.md#accessors
149 .option("js.ecmascript-version", "2022") // If Nashorn compat is enabled, it will enforce ES5
150 // compatibility, we want ECMA2022
151 .option("js.commonjs-require", "true") // Enable CommonJS module support
152 .hostClassLoader(getClass().getClassLoader())
153 .fileSystem(new DelegatingFileSystem(FileSystems.getDefault().provider()) {
155 public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
156 FileAttribute<?>... attrs) throws IOException {
157 Consumer<String> localScriptDependencyListener = scriptDependencyListener;
158 if (localScriptDependencyListener != null) {
159 localScriptDependencyListener.accept(path.toString());
162 if (path.toString().endsWith(".js")) {
163 SeekableByteChannel sbc = null;
164 if (isRootNodePath(path)) {
165 InputStream is = getClass().getResourceAsStream(nodeFileToResource(path));
167 throw new IOException("Could not read " + path.toString());
169 sbc = new ReadOnlySeekableByteArrayChannel(is.readAllBytes());
171 sbc = super.newByteChannel(path, options, attrs);
173 return new PrefixedSeekableByteChannel(
174 ("require=" + REQUIRE_WRAPPER_NAME + "(require);").getBytes(), sbc);
176 return super.newByteChannel(path, options, attrs);
181 public void checkAccess(Path path, Set<? extends AccessMode> modes,
182 LinkOption... linkOptions) throws IOException {
183 if (isRootNodePath(path)) {
184 if (getClass().getResource(nodeFileToResource(path)) == null) {
185 throw new NoSuchFileException(path.toString());
188 super.checkAccess(path, modes, linkOptions);
193 public Map<String, Object> readAttributes(Path path, String attributes,
194 LinkOption... options) throws IOException {
195 if (isRootNodePath(path)) {
196 return Collections.singletonMap("isRegularFile", true);
198 return super.readAttributes(path, attributes, options);
202 public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException {
203 if (isRootNodePath(path)) {
206 return super.toRealPath(path, linkOptions);
212 protected void beforeInvocation() {
213 super.beforeInvocation();
221 ScriptContext ctx = delegate.getContext();
223 throw new IllegalStateException("Failed to retrieve script context");
226 // these are added post-construction, so we need to fetch them late
227 this.engineIdentifier = (String) ctx.getAttribute(CONTEXT_KEY_ENGINE_IDENTIFIER);
228 if (this.engineIdentifier == null) {
229 throw new IllegalStateException("Failed to retrieve engine identifier from engine bindings");
232 ScriptExtensionAccessor scriptExtensionAccessor = (ScriptExtensionAccessor) ctx
233 .getAttribute(CONTEXT_KEY_EXTENSION_ACCESSOR);
234 if (scriptExtensionAccessor == null) {
235 throw new IllegalStateException("Failed to retrieve script extension accessor from engine bindings");
238 scriptDependencyListener = (Consumer<String>) ctx
239 .getAttribute("oh.dependency-listener"/* CONTEXT_KEY_DEPENDENCY_LISTENER */);
240 if (scriptDependencyListener == null) {
242 "Failed to retrieve script script dependency listener from engine bindings. Script dependency tracking will be disabled.");
245 ScriptExtensionModuleProvider scriptExtensionModuleProvider = new ScriptExtensionModuleProvider(
246 scriptExtensionAccessor, lock);
248 // Wrap the "require" function to also allow loading modules from the ScriptExtensionModuleProvider
249 Function<Function<Object[], Object>, Function<String, Object>> wrapRequireFn = originalRequireFn -> moduleName -> scriptExtensionModuleProvider
250 .locatorFor(delegate.getPolyglotContext(), engineIdentifier).locateModule(moduleName)
251 .map(m -> (Object) m).orElseGet(() -> originalRequireFn.apply(new Object[] { moduleName }));
252 delegate.getBindings(ScriptContext.ENGINE_SCOPE).put(REQUIRE_WRAPPER_NAME, wrapRequireFn);
253 delegate.put("require", wrapRequireFn.apply((Function<Object[], Object>) delegate.get("require")));
255 // Injections into the JS runtime
256 jsRuntimeFeatures.getFeatures().forEach((key, obj) -> {
257 LOGGER.debug("Injecting {} into the JS runtime...", key);
258 delegate.put(key, obj);
264 LOGGER.debug("Evaluating cached global script...");
265 delegate.getPolyglotContext().eval(GLOBAL_SOURCE);
266 if (this.injectionEnabled) {
267 if (this.useIncludedLibrary) {
268 LOGGER.debug("Evaluating cached openhab-js injection...");
269 delegate.getPolyglotContext().eval(OPENHAB_JS_SOURCE);
271 LOGGER.debug("Evaluating openhab-js injection from the file system...");
272 eval(OPENHAB_JS_INJECTION_CODE);
275 LOGGER.debug("Successfully initialized GraalJS script engine.");
276 } catch (ScriptException e) {
277 LOGGER.error("Could not inject global script", e);
282 protected Object afterInvocation(Object obj) {
284 return super.afterInvocation(obj);
288 protected Exception afterThrowsInvocation(Exception e) {
290 return super.afterThrowsInvocation(e);
294 public void close() {
295 jsRuntimeFeatures.close();
299 * Tests if this is a root node directory, `/node_modules`, `C:\node_modules`, etc...
301 * @param path a root path
302 * @return whether the given path is a node root directory
304 private boolean isRootNodePath(Path path) {
305 return path.startsWith(path.getRoot().resolve(NODE_DIR));
309 * Converts a root node path to a class resource path for loading local modules
310 * Ex: C:\node_modules\foo.js -> /node_modules/foo.js
312 * @param path a root path, e.g. C:\node_modules\foo.js
313 * @return the class resource path for loading local modules
315 private String nodeFileToResource(Path path) {
316 return "/" + path.subpath(0, path.getNameCount()).toString().replace('\\', '/');
320 * @param fileName filename relative to the resources folder
321 * @return file as {@link InputStreamReader}
323 private static Reader getFileAsReader(String fileName) throws IOException {
324 InputStream ioStream = OpenhabGraalJSScriptEngine.class.getClassLoader().getResourceAsStream(fileName);
326 if (ioStream == null) {
327 throw new IOException(fileName + " not found");
330 return new InputStreamReader(ioStream);