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