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