forked from iotaledger-archive/iri
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIXI.java
More file actions
287 lines (257 loc) · 10.2 KB
/
IXI.java
File metadata and controls
287 lines (257 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package com.iota.iri;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.iota.iri.service.CallableRequest;
import com.iota.iri.service.dto.AbstractResponse;
import com.sun.nio.file.SensitivityWatchEventModifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.sun.jmx.mbeanserver.Util.cast;
import static java.nio.file.StandardWatchEventKinds.*;
public class IXI {
private static final Logger log = LoggerFactory.getLogger(IXI.class);
private static final int MAX_TREE_DEPTH = 2;
private final Gson gson = new GsonBuilder().create();
private final ScriptEngine scriptEngine = (new ScriptEngineManager()).getEngineByName("JavaScript");
private final Map<String, Map<String, CallableRequest<AbstractResponse>>> ixiAPI = new HashMap<>();
private final Map<String, Map<String, Runnable>> ixiLifetime = new HashMap<>();
private final Map<WatchKey, Path> watchKeys = new HashMap<>();
private final Map<Path, Long> loadedLastTime = new HashMap<>();
private WatchService watcher;
private Thread dirWatchThread;
private Path rootPath;
private boolean shutdown = false;
private final Iota iota;
public IXI() {
iota = null;
}
public IXI(Iota iota) {
this.iota = iota;
}
public void init(String rootDir) throws IOException {
if(rootDir.length() > 0) {
watcher = FileSystems.getDefault().newWatchService();
this.rootPath = Paths.get(rootDir);
if(this.rootPath.toFile().exists() || this.rootPath.toFile().mkdir()) {
registerRecursive(this.rootPath);
dirWatchThread = (new Thread(this::processWatchEvents));
dirWatchThread.start();
}
}
}
private void registerRecursive(final Path root) throws IOException {
Files.walkFileTree(root, EnumSet.allOf(FileVisitOption.class), MAX_TREE_DEPTH, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path modulePath, BasicFileAttributes attrs) {
watch(modulePath);
if (!modulePath.equals(rootPath)) {
loadModule(modulePath);
}
return FileVisitResult.CONTINUE;
}
});
}
private void processWatchEvents() {
while(!shutdown) {
WatchKey key = null;
try {
key = watcher.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
log.error("Watcher interrupted: ", e);
}
if (key == null) {
continue;
}
WatchKey finalKey = key;
key.pollEvents().forEach(watchEvent -> {
WatchEvent<Path> pathEvent = cast(watchEvent);
IxiEvent ixiEvent = IxiEvent.fromName(watchEvent.kind().name());
Path watchedPath = watchKeys.get(finalKey);
if (watchedPath != null) {
handleModulePathEvent(watchedPath, ixiEvent, watchedPath.resolve(pathEvent.context()));
}
});
key.reset();
}
}
private String getModuleName(Path modulePath, boolean checkIfIsDir) {
return rootPath.relativize(!checkIfIsDir || Files.isDirectory(modulePath) ? modulePath : modulePath.getParent()).toString();
}
private Path getRealPath(Path currentPath) {
if (Files.isDirectory(currentPath.getParent()) && !currentPath.getParent().equals(rootPath)) {
return currentPath.getParent();
} else {
return currentPath;
}
}
private void handleModulePathEvent(Path watchedPath, IxiEvent ixiEvent, Path changedPath) {
if (!watchedPath.equals(rootPath) && Files.isDirectory(changedPath)) { // we are only interested in dir changes in tree depth level 2
return;
}
handlePathEvent(ixiEvent, changedPath);
}
private void handlePathEvent(IxiEvent ixiEvent, Path changedPath) {
switch(ixiEvent) {
case CREATE_MODULE:
if (checkOs() == OsVariants.Unix) {
watch(changedPath);
loadModule(changedPath);
}
break;
case MODIFY_MODULE:
Long lastModification = loadedLastTime.get(getRealPath(changedPath));
if (lastModification == null || Instant.now().toEpochMilli() - lastModification > 50L) {
if (ixiLifetime.containsKey(getModuleName(changedPath, true))) {
unloadModule(changedPath);
}
loadedLastTime.put(getRealPath(changedPath), Instant.now().toEpochMilli());
loadModule(getRealPath(changedPath));
}
break;
case DELETE_MODULE:
Path realPath = getRealPath(changedPath);
unwatch(realPath);
if (ixiLifetime.containsKey(getModuleName(realPath, false))) {
unloadModule(changedPath);
}
break;
default:
}
}
private static OsVariants checkOs() {
String os = System.getProperty("os.name");
if (os.startsWith("Windows")) {
return OsVariants.Windows;
} else {
return OsVariants.Unix;
}
}
private void watch(Path dir) {
try {
WatchKey watchKey = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}, SensitivityWatchEventModifier.HIGH);
watchKeys.put(watchKey, dir);
} catch (IOException e) {
log.error("Could not create watcher for path '{}'.", dir);
}
}
private void unwatch(Path dir) {
// TODO: Get watchkey for 'dir' in an optimized way
Optional<WatchKey> dirKey = watchKeys.keySet().stream().filter(watchKey -> watchKeys.get(watchKey).equals(dir)).findFirst();
if (dirKey.isPresent()) {
watchKeys.remove(dirKey.get());
dirKey.get().cancel();
}
}
private Path getPackagePath(Path modulePath) {
return modulePath.resolve("package.json");
}
public AbstractResponse processCommand(final String command, Map<String, Object> request) {
Pattern pattern = Pattern.compile("^(.*)\\.(.*)$");
Matcher matcher = pattern.matcher(command);
if (matcher.find()) {
Map<String, CallableRequest<AbstractResponse>> ixiMap = ixiAPI.get(matcher.group(1));
if (ixiMap != null) {
return ixiMap.get(matcher.group(2)).call(request);
}
}
return null;
}
private void loadModule(Path modulePath) {
log.info("Searching: {}", modulePath);
Path packageJsonPath = getPackagePath(modulePath);
if (!Files.exists(packageJsonPath)) {
log.info("No package.json found in {}", modulePath);
return;
}
final Map packageJson;
Reader packageJsonReader;
try {
packageJsonReader = new FileReader(packageJsonPath.toFile());
packageJson = gson.fromJson(packageJsonReader, Map.class);
} catch (FileNotFoundException e) {
log.error("Could not load {}", packageJsonPath);
return;
}
try {
packageJsonReader.close();
} catch (IOException e) {
log.error("Could not close file {}", packageJsonPath);
}
if(packageJson != null && packageJson.get("main") != null) {
log.info("Loading module: {}", getModuleName(modulePath, true));
Path pathToMain = Paths.get(modulePath.toString(), (String) packageJson.get("main"));
attach(pathToMain, getModuleName(modulePath, true));
} else {
log.info("No start script found");
}
}
private void unloadModule(Path moduleNamePath) {
log.debug("Unloading module: {}", moduleNamePath);
Path realPath = getRealPath(moduleNamePath);
String moduleName = getModuleName(realPath, false);
detach(moduleName);
ixiAPI.remove(moduleName);
}
private void attach(Path pathToMain, String moduleName) {
Reader ixiModuleReader;
try {
ixiModuleReader = new FileReader(pathToMain.toFile());
} catch (FileNotFoundException e) {
log.error("Could not load {}", pathToMain);
return;
}
log.info("Starting script: {}", pathToMain);
Map<String, CallableRequest<AbstractResponse>> ixiMap = new HashMap<>();
Map<String, Runnable> startStop = new HashMap<>();
Bindings bindings = scriptEngine.createBindings();
bindings.put("API", ixiMap);
bindings.put("IXICycle", startStop);
bindings.put("IOTA", iota);
ixiAPI.put(moduleName, ixiMap);
ixiLifetime.put(moduleName, startStop);
try {
scriptEngine.eval(ixiModuleReader, bindings);
} catch (ScriptException e) {
log.error("Script error", e);
}
try {
ixiModuleReader.close();
} catch (IOException e) {
log.error("Could not close {}", pathToMain);
}
}
private void detach(String moduleName) {
Map<String, Runnable> ixiMap = ixiLifetime.get(moduleName);
if(ixiMap != null) {
Runnable stop = ixiMap.get("shutdown");
if (stop != null) {
stop.run();
}
}
ixiLifetime.remove(moduleName);
}
public void shutdown() throws InterruptedException {
if(dirWatchThread != null) {
shutdown = true;
dirWatchThread.join();
ixiAPI.keySet().forEach(this::detach);
ixiAPI.clear();
ixiLifetime.clear();
}
}
}