]> git.basschouten.com Git - openhab-addons.git/blob
91132e4f401b7fa32a26efe404d27bd7a979261d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.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;
33 import java.util.Map;
34 import java.util.Set;
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;
39
40 import javax.script.ScriptContext;
41 import javax.script.ScriptException;
42
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.openhab.core.items.Item;
56 import org.openhab.core.library.types.QuantityType;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
61
62 /**
63  * GraalJS ScriptEngine implementation
64  *
65  * @author Jonathan Gilbert - Initial contribution
66  * @author Dan Cunningham - Script injections
67  * @author Florian Hotze - Create lock object for multi-thread synchronization; Inject the {@link JSRuntimeFeatures}
68  *         into the JS context; Fix memory leak caused by HostObject by making HostAccess reference static; Switch to
69  *         {@link Lock} for multi-thread synchronization; globals & openhab-js injection code caching
70  */
71 public class OpenhabGraalJSScriptEngine
72         extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<GraalJSScriptEngine> {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(OpenhabGraalJSScriptEngine.class);
75     private static Source GLOBAL_SOURCE;
76     static {
77         try {
78             GLOBAL_SOURCE = Source.newBuilder("js", getFileAsReader("node_modules/@jsscripting-globals.js"),
79                     "@jsscripting-globals.js").cached(true).build();
80         } catch (IOException e) {
81             throw new RuntimeException("Failed to load @jsscripting-globals.js", e);
82         }
83     }
84
85     private static Source OPENHAB_JS_SOURCE;
86     static {
87         try {
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);
93         }
94     }
95     private static final String OPENHAB_JS_INJECTION_CODE = "Object.assign(this, require('openhab'));";
96
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"),
107                     v -> ZonedDateTime.parse(v.invokeMember("withFixedOffsetZone").invokeMember("toString").asString()),
108                     HostAccess.TargetMappingPrecedence.LOW)
109
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"),
114                     v -> Duration.ofNanos(v.invokeMember("toNanos").asLong()), HostAccess.TargetMappingPrecedence.LOW)
115
116             // Translate openhab-js Item to org.openhab.core.items.Item
117             .targetTypeMapping(Value.class, Item.class, v -> v.hasMember("rawItem"),
118                     v -> v.getMember("rawItem").as(Item.class), HostAccess.TargetMappingPrecedence.LOW)
119
120             // Translate openhab-js Quantity to org.openhab.core.library.types.QuantityType
121             .targetTypeMapping(Value.class, QuantityType.class, v -> v.hasMember("raw") && v.hasMember("toUnit"),
122                     v -> v.getMember("raw").as(QuantityType.class), HostAccess.TargetMappingPrecedence.LOW)
123             .build();
124
125     /** {@link Lock} synchronization of multi-thread access */
126     private final Lock lock = new ReentrantLock();
127     private final JSRuntimeFeatures jsRuntimeFeatures;
128
129     // these fields start as null because they are populated on first use
130     private String engineIdentifier;
131     private @Nullable Consumer<String> scriptDependencyListener;
132
133     private boolean initialized = false;
134     private final boolean injectionEnabled;
135     private final boolean useIncludedLibrary;
136
137     /**
138      * Creates an implementation of ScriptEngine (& Invocable), wrapping the contained engine, that tracks the script
139      * lifecycle and provides hooks for scripts to do so too.
140      */
141     public OpenhabGraalJSScriptEngine(boolean injectionEnabled, boolean useIncludedLibrary,
142             JSScriptServiceUtil jsScriptServiceUtil, JSDependencyTracker jsDependencyTracker) {
143         super(null); // delegate depends on fields not yet initialised, so we cannot set it immediately
144         this.injectionEnabled = injectionEnabled;
145         this.useIncludedLibrary = useIncludedLibrary;
146         this.jsRuntimeFeatures = jsScriptServiceUtil.getJSRuntimeFeatures(lock);
147
148         LOGGER.debug("Initializing GraalJS script engine...");
149
150         delegate = GraalJSScriptEngine.create(ENGINE,
151                 Context.newBuilder("js").allowExperimentalOptions(true).allowAllAccess(true)
152                         .allowHostAccess(HOST_ACCESS)
153                         .option("js.commonjs-require-cwd", jsDependencyTracker.getLibraryPath().toString())
154                         .option("js.nashorn-compat", "true") // Enable Nashorn compat mode as openhab-js relies on
155                                                              // accessors, see
156                                                              // https://github.com/oracle/graaljs/blob/master/docs/user/NashornMigrationGuide.md#accessors
157                         .option("js.ecmascript-version", "2022") // If Nashorn compat is enabled, it will enforce ES5
158                                                                  // compatibility, we want ECMA2022
159                         .option("js.commonjs-require", "true") // Enable CommonJS module support
160                         .hostClassLoader(getClass().getClassLoader())
161                         .fileSystem(new DelegatingFileSystem(FileSystems.getDefault().provider()) {
162                             @Override
163                             public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
164                                     FileAttribute<?>... attrs) throws IOException {
165                                 Consumer<String> localScriptDependencyListener = scriptDependencyListener;
166                                 if (localScriptDependencyListener != null) {
167                                     localScriptDependencyListener.accept(path.toString());
168                                 }
169
170                                 if (path.toString().endsWith(".js")) {
171                                     SeekableByteChannel sbc = null;
172                                     if (isRootNodePath(path)) {
173                                         InputStream is = getClass().getResourceAsStream(nodeFileToResource(path));
174                                         if (is == null) {
175                                             throw new IOException("Could not read " + path.toString());
176                                         }
177                                         sbc = new ReadOnlySeekableByteArrayChannel(is.readAllBytes());
178                                     } else {
179                                         sbc = super.newByteChannel(path, options, attrs);
180                                     }
181                                     return new PrefixedSeekableByteChannel(
182                                             ("require=" + REQUIRE_WRAPPER_NAME + "(require);").getBytes(), sbc);
183                                 } else {
184                                     return super.newByteChannel(path, options, attrs);
185                                 }
186                             }
187
188                             @Override
189                             public void checkAccess(Path path, Set<? extends AccessMode> modes,
190                                     LinkOption... linkOptions) throws IOException {
191                                 if (isRootNodePath(path)) {
192                                     if (getClass().getResource(nodeFileToResource(path)) == null) {
193                                         throw new NoSuchFileException(path.toString());
194                                     }
195                                 } else {
196                                     super.checkAccess(path, modes, linkOptions);
197                                 }
198                             }
199
200                             @Override
201                             public Map<String, Object> readAttributes(Path path, String attributes,
202                                     LinkOption... options) throws IOException {
203                                 if (isRootNodePath(path)) {
204                                     return Collections.singletonMap("isRegularFile", true);
205                                 }
206                                 return super.readAttributes(path, attributes, options);
207                             }
208
209                             @Override
210                             public Path toRealPath(Path path, LinkOption... linkOptions) throws IOException {
211                                 if (isRootNodePath(path)) {
212                                     return path;
213                                 }
214                                 return super.toRealPath(path, linkOptions);
215                             }
216                         }));
217     }
218
219     @Override
220     protected void beforeInvocation() {
221         super.beforeInvocation();
222
223         lock.lock();
224
225         if (initialized) {
226             return;
227         }
228
229         ScriptContext ctx = delegate.getContext();
230         if (ctx == null) {
231             throw new IllegalStateException("Failed to retrieve script context");
232         }
233
234         // these are added post-construction, so we need to fetch them late
235         this.engineIdentifier = (String) ctx.getAttribute(CONTEXT_KEY_ENGINE_IDENTIFIER);
236         if (this.engineIdentifier == null) {
237             throw new IllegalStateException("Failed to retrieve engine identifier from engine bindings");
238         }
239
240         ScriptExtensionAccessor scriptExtensionAccessor = (ScriptExtensionAccessor) ctx
241                 .getAttribute(CONTEXT_KEY_EXTENSION_ACCESSOR);
242         if (scriptExtensionAccessor == null) {
243             throw new IllegalStateException("Failed to retrieve script extension accessor from engine bindings");
244         }
245
246         scriptDependencyListener = (Consumer<String>) ctx
247                 .getAttribute("oh.dependency-listener"/* CONTEXT_KEY_DEPENDENCY_LISTENER */);
248         if (scriptDependencyListener == null) {
249             LOGGER.warn(
250                     "Failed to retrieve script script dependency listener from engine bindings. Script dependency tracking will be disabled.");
251         }
252
253         ScriptExtensionModuleProvider scriptExtensionModuleProvider = new ScriptExtensionModuleProvider(
254                 scriptExtensionAccessor, lock);
255
256         // Wrap the "require" function to also allow loading modules from the ScriptExtensionModuleProvider
257         Function<Function<Object[], Object>, Function<String, Object>> wrapRequireFn = originalRequireFn -> moduleName -> scriptExtensionModuleProvider
258                 .locatorFor(delegate.getPolyglotContext(), engineIdentifier).locateModule(moduleName)
259                 .map(m -> (Object) m).orElseGet(() -> originalRequireFn.apply(new Object[] { moduleName }));
260         delegate.getBindings(ScriptContext.ENGINE_SCOPE).put(REQUIRE_WRAPPER_NAME, wrapRequireFn);
261         delegate.put("require", wrapRequireFn.apply((Function<Object[], Object>) delegate.get("require")));
262
263         // Injections into the JS runtime
264         jsRuntimeFeatures.getFeatures().forEach((key, obj) -> {
265             LOGGER.debug("Injecting {} into the JS runtime...", key);
266             delegate.put(key, obj);
267         });
268
269         initialized = true;
270
271         try {
272             LOGGER.debug("Evaluating cached global script...");
273             delegate.getPolyglotContext().eval(GLOBAL_SOURCE);
274             if (this.injectionEnabled) {
275                 if (this.useIncludedLibrary) {
276                     LOGGER.debug("Evaluating cached openhab-js injection...");
277                     delegate.getPolyglotContext().eval(OPENHAB_JS_SOURCE);
278                 } else {
279                     LOGGER.debug("Evaluating openhab-js injection from the file system...");
280                     eval(OPENHAB_JS_INJECTION_CODE);
281                 }
282             }
283             LOGGER.debug("Successfully initialized GraalJS script engine.");
284         } catch (ScriptException e) {
285             LOGGER.error("Could not inject global script", e);
286         }
287     }
288
289     @Override
290     protected Object afterInvocation(Object obj) {
291         lock.unlock();
292         return super.afterInvocation(obj);
293     }
294
295     @Override
296     protected Exception afterThrowsInvocation(Exception e) {
297         lock.unlock();
298         return super.afterThrowsInvocation(e);
299     }
300
301     @Override
302     public void close() {
303         jsRuntimeFeatures.close();
304     }
305
306     /**
307      * Tests if this is a root node directory, `/node_modules`, `C:\node_modules`, etc...
308      *
309      * @param path a root path
310      * @return whether the given path is a node root directory
311      */
312     private boolean isRootNodePath(Path path) {
313         return path.startsWith(path.getRoot().resolve(NODE_DIR));
314     }
315
316     /**
317      * Converts a root node path to a class resource path for loading local modules
318      * Ex: C:\node_modules\foo.js -> /node_modules/foo.js
319      *
320      * @param path a root path, e.g. C:\node_modules\foo.js
321      * @return the class resource path for loading local modules
322      */
323     private String nodeFileToResource(Path path) {
324         return "/" + path.subpath(0, path.getNameCount()).toString().replace('\\', '/');
325     }
326
327     /**
328      * @param fileName filename relative to the resources folder
329      * @return file as {@link InputStreamReader}
330      */
331     private static Reader getFileAsReader(String fileName) throws IOException {
332         InputStream ioStream = OpenhabGraalJSScriptEngine.class.getClassLoader().getResourceAsStream(fileName);
333
334         if (ioStream == null) {
335             throw new IOException(fileName + " not found");
336         }
337
338         return new InputStreamReader(ioStream);
339     }
340 }