]> git.basschouten.com Git - openhab-addons.git/blob
704097662a6986b7864e455603d9fa6df8acdaa9
[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 Script Engine 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
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
72     // shared lock object for synchronization of multi-thread access
73     private final Object lock = new Object();
74     private final JSRuntimeFeatures jsRuntimeFeatures;
75
76     // these fields start as null because they are populated on first use
77     private String engineIdentifier;
78     private Consumer<String> scriptDependencyListener;
79
80     private boolean initialized = false;
81     private final String globalScript;
82
83     /**
84      * Creates an implementation of ScriptEngine (& Invocable), wrapping the contained engine, that tracks the script
85      * lifecycle and provides hooks for scripts to do so too.
86      */
87     public OpenhabGraalJSScriptEngine(@Nullable String injectionCode, JSScriptServiceUtil jsScriptServiceUtil) {
88         super(null); // delegate depends on fields not yet initialised, so we cannot set it immediately
89         this.globalScript = GLOBAL_REQUIRE + (injectionCode != null ? injectionCode : "");
90         this.jsRuntimeFeatures = jsScriptServiceUtil.getJSRuntimeFeatures(lock);
91
92         LOGGER.debug("Initializing GraalJS script engine...");
93
94         // Custom translate JS Objects - > Java Objects
95         HostAccess hostAccess = HostAccess.newBuilder(HostAccess.ALL)
96                 // Translate JS-Joda ZonedDateTime to java.time.ZonedDateTime
97                 .targetTypeMapping(Value.class, ZonedDateTime.class, (v) -> v.hasMember("withFixedOffsetZone"), v -> {
98                     return ZonedDateTime
99                             .parse(v.invokeMember("withFixedOffsetZone").invokeMember("toString").asString());
100                 }, HostAccess.TargetMappingPrecedence.LOW)
101
102                 // Translate JS-Joda Duration to java.time.Duration
103                 .targetTypeMapping(Value.class, Duration.class,
104                         // picking two members to check as Duration has many common function names
105                         (v) -> v.hasMember("minusDuration") && v.hasMember("toNanos"), v -> {
106                             return Duration.ofNanos(v.invokeMember("toNanos").asLong());
107                         }, HostAccess.TargetMappingPrecedence.LOW)
108                 .build();
109
110         delegate = GraalJSScriptEngine.create(
111                 Engine.newBuilder().allowExperimentalOptions(true).option("engine.WarnInterpreterOnly", "false")
112                         .build(),
113                 Context.newBuilder("js").allowExperimentalOptions(true).allowAllAccess(true).allowHostAccess(hostAccess)
114                         .option("js.commonjs-require-cwd", JSDependencyTracker.LIB_PATH)
115                         .option("js.nashorn-compat", "true") // to ease migration
116                         .option("js.ecmascript-version", "2021") // nashorn compat will enforce es5 compatibility, we
117                                                                  // want ecma2021
118                         .option("js.commonjs-require", "true") // enable CommonJS module support
119                         .hostClassLoader(getClass().getClassLoader())
120                         .fileSystem(new DelegatingFileSystem(FileSystems.getDefault().provider()) {
121                             @Override
122                             public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
123                                     FileAttribute<?>... attrs) throws IOException {
124                                 if (scriptDependencyListener != null) {
125                                     scriptDependencyListener.accept(path.toString());
126                                 }
127
128                                 if (path.toString().endsWith(".js")) {
129                                     SeekableByteChannel sbc = null;
130                                     if (isRootNodePath(path)) {
131                                         InputStream is = getClass().getResourceAsStream(nodeFileToResource(path));
132                                         if (is == null) {
133                                             throw new IOException("Could not read " + path.toString());
134                                         }
135                                         sbc = new ReadOnlySeekableByteArrayChannel(is.readAllBytes());
136                                     } else {
137                                         sbc = super.newByteChannel(path, options, attrs);
138                                     }
139                                     return new PrefixedSeekableByteChannel(
140                                             ("require=" + REQUIRE_WRAPPER_NAME + "(require);").getBytes(), sbc);
141                                 } else {
142                                     return super.newByteChannel(path, options, attrs);
143                                 }
144                             }
145
146                             @Override
147                             public void checkAccess(Path path, Set<? extends AccessMode> modes,
148                                     LinkOption... linkOptions) throws IOException {
149                                 if (isRootNodePath(path)) {
150                                     if (getClass().getResource(nodeFileToResource(path)) == null) {
151                                         throw new NoSuchFileException(path.toString());
152                                     }
153                                 } else {
154                                     super.checkAccess(path, modes, linkOptions);
155                                 }
156                             }
157
158                             @Override
159                             public Map<String, Object> readAttributes(Path path, String attributes,
160                                     LinkOption... options) throws IOException {
161                                 if (isRootNodePath(path)) {
162                                     return Collections.singletonMap("isRegularFile", true);
163                                 }
164                                 return super.readAttributes(path, attributes, options);
165                             }
166
167                             @Override
168                             public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException {
169                                 if (isRootNodePath(path)) {
170                                     return path;
171                                 }
172                                 return super.toRealPath(path, linkOptions);
173                             }
174                         }));
175     }
176
177     @Override
178     protected void beforeInvocation() {
179         if (initialized) {
180             return;
181         }
182
183         ScriptContext ctx = delegate.getContext();
184
185         // these are added post-construction, so we need to fetch them late
186         this.engineIdentifier = (String) ctx.getAttribute(CONTEXT_KEY_ENGINE_IDENTIFIER);
187         if (this.engineIdentifier == null) {
188             throw new IllegalStateException("Failed to retrieve engine identifier from engine bindings");
189         }
190
191         ScriptExtensionAccessor scriptExtensionAccessor = (ScriptExtensionAccessor) ctx
192                 .getAttribute(CONTEXT_KEY_EXTENSION_ACCESSOR);
193         if (scriptExtensionAccessor == null) {
194             throw new IllegalStateException("Failed to retrieve script extension accessor from engine bindings");
195         }
196
197         scriptDependencyListener = (Consumer<String>) ctx
198                 .getAttribute("oh.dependency-listener"/* CONTEXT_KEY_DEPENDENCY_LISTENER */);
199         if (scriptDependencyListener == null) {
200             LOGGER.warn(
201                     "Failed to retrieve script script dependency listener from engine bindings. Script dependency tracking will be disabled.");
202         }
203
204         ScriptExtensionModuleProvider scriptExtensionModuleProvider = new ScriptExtensionModuleProvider(
205                 scriptExtensionAccessor, lock);
206
207         Function<Function<Object[], Object>, Function<String, Object>> wrapRequireFn = originalRequireFn -> moduleName -> scriptExtensionModuleProvider
208                 .locatorFor(delegate.getPolyglotContext(), engineIdentifier).locateModule(moduleName)
209                 .map(m -> (Object) m).orElseGet(() -> originalRequireFn.apply(new Object[] { moduleName }));
210
211         delegate.getBindings(ScriptContext.ENGINE_SCOPE).put(REQUIRE_WRAPPER_NAME, wrapRequireFn);
212         // Injections into the JS runtime
213         delegate.put("require", wrapRequireFn.apply((Function<Object[], Object>) delegate.get("require")));
214         jsRuntimeFeatures.getFeatures().forEach((key, obj) -> {
215             LOGGER.debug("Injecting {} into the JS runtime...", key);
216             delegate.put(key, obj);
217         });
218
219         initialized = true;
220
221         try {
222             eval(globalScript);
223         } catch (ScriptException e) {
224             LOGGER.error("Could not inject global script", e);
225         }
226     }
227
228     @Override
229     public Object invokeFunction(String s, Object... objects) throws ScriptException, NoSuchMethodException {
230         // Synchronize multi-thread access to avoid exceptions when reloading a script file while the script is running
231         synchronized (lock) {
232             return super.invokeFunction(s, objects);
233         }
234     }
235
236     @Override
237     public void close() {
238         jsRuntimeFeatures.close();
239     }
240
241     /**
242      * Tests if this is a root node directory, `/node_modules`, `C:\node_modules`, etc...
243      *
244      * @param path a root path
245      * @return whether the given path is a node root directory
246      */
247     private boolean isRootNodePath(Path path) {
248         return path.startsWith(path.getRoot().resolve(NODE_DIR));
249     }
250
251     /**
252      * Converts a root node path to a class resource path for loading local modules
253      * Ex: C:\node_modules\foo.js -> /node_modules/foo.js
254      *
255      * @param path a root path, e.g. C:\node_modules\foo.js
256      * @return the class resource path for loading local modules
257      */
258     private String nodeFileToResource(Path path) {
259         return "/" + path.subpath(0, path.getNameCount()).toString().replace('\\', '/');
260     }
261 }