forked from typedb/typedb-console
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsoleSession.java
321 lines (268 loc) · 11.5 KB
/
ConsoleSession.java
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
* GRAKN.AI - THE KNOWLEDGE GRAPH
* Copyright (C) 2019 Grakn Labs Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package grakn.console;
import grakn.client.GraknClient;
import grakn.client.exception.GraknClientException;
import grakn.console.exception.GraknConsoleException;
import grakn.console.printer.Printer;
import graql.lang.Graql;
import graql.lang.query.GraqlQuery;
import io.grpc.StatusRuntimeException;
import jline.console.ConsoleReader;
import jline.console.history.FileHistory;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import static org.apache.commons.lang.StringEscapeUtils.unescapeJava;
/**
* A Grakn Console Session that allows a user to interact with the Grakn Server
*/
public class ConsoleSession implements AutoCloseable {
private static final String COPYRIGHT = "\n" +
"Welcome to Grakn Console. You are now in Grakn Wonderland!\n" +
"Copyright (C) 2019 Grakn Labs Limited\n\n";
private static final String EDITOR = "editor";
private static final String COMMIT = "commit";
private static final String ROLLBACK = "rollback";
private static final String LOAD = "load";
private static final String CLEAR = "clear";
private static final String EXIT = "exit";
private static final String CLEAN = "clean";
private static final String ANSI_PURPLE = "\u001B[35m";
private static final String ANSI_RESET = "\u001B[0m";
private static final String HISTORY_FILE = System.getProperty("user.home") + "/.grakn-console-history";
private static final String UNIX_EDITOR_DEFAULT = "vim";
private static final String WINDOWS_EDITOR_DEFAULT = "notepad";
private static final String EDITOR_FILE = "/grakn-console-editor.gql";
private final boolean infer;
private final String keyspace;
private final PrintStream printErr;
private final ConsoleReader consoleReader;
private final Printer<?> printer = Printer.stringPrinter(true);
private final FileHistory historyFile;
private final GraknClient client;
private final GraknClient.Session session;
private GraknClient.Transaction tx;
private final AtomicBoolean terminated = new AtomicBoolean(false);
ConsoleSession(String serverAddress, String keyspace, boolean infer, PrintStream printOut, PrintStream printErr) throws IOException, GraknConsoleException {
this.keyspace = keyspace;
this.infer = infer;
try {
this.client = new GraknClient(serverAddress);
this.session = client.session(keyspace);
} catch (StatusRuntimeException grpcException) {
throw GraknConsoleException.unreachableServer(serverAddress, grpcException);
}
this.consoleReader = new ConsoleReader(System.in, printOut);
this.consoleReader.setPrompt(ANSI_PURPLE + session.keyspace().name() + ANSI_RESET + "> ");
this.printErr = printErr;
File file = new File(HISTORY_FILE);
file.createNewFile();
this.historyFile = new FileHistory(file);
this.consoleReader.setHistory(this.historyFile);
}
void load(Path filePath) throws IOException {
consoleReader.println("Loading: " + filePath.toString());
consoleReader.println("...");
consoleReader.flush();
tx = session.transaction().write();
try {
String queries = readFile(filePath);
executeQuery(queries, false);
tx.commit();
consoleReader.println("Successful commit: " + filePath.getFileName().toString());
} catch (GraknClientException e) {
printErr.println("Failed to load file:");
printErr.println(e.getMessage());
} finally {
consoleReader.flush();
}
}
void run() throws IOException, InterruptedException {
consoleReader.setExpandEvents(false); // Disable JLine feature when seeing a '!'
consoleReader.print(COPYRIGHT);
tx = session.transaction().write();
String input;
while ((input = consoleReader.readLine()) != null && !terminated.get()) {
if (input.equals(EDITOR)) {
executeQuery(openTextEditor());
} else if (input.startsWith(LOAD + ' ')) {
try {
input = readFile(Paths.get(unescapeJava(input.substring(LOAD.length() + 1))));
executeQuery(input);
} catch (NoSuchFileException e) {
System.err.println("File not found: " + e.getMessage());
}
} else if (input.equals(COMMIT)) {
commit();
} else if (input.equals(ROLLBACK)) {
rollback();
} else if (input.equals(CLEAN)) {
boolean cleaned = clean();
if (cleaned) {
consoleReader.flush();
return;
}
} else if (input.equals(CLEAR)) {
consoleReader.clearScreen();
} else if (input.equals(EXIT)) {
consoleReader.flush();
return;
} else if (!input.isEmpty()) {
executeQuery(input);
} // We ignore empty commands
}
}
private static String readFile(Path filePath) throws IOException {
List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
return String.join("\n", lines);
}
private void executeQuery(String queryString) throws IOException {
executeQuery(queryString, true);
}
private void executeQuery(String queryString, boolean catchRuntimeException) throws IOException {
// We'll use streams so we can print the answer out much faster and smoother
try {
// Parse the string to get a stream of Graql Queries
Stream<GraqlQuery> queries = Graql.parseList(queryString);
// Get the stream of answers for each query (query.stream())
// Get the stream of printed answers (printer.toStream(..))
// Combine the stream of printed answers into one stream (queries.flatMap(..))
Stream<String> answers = queries.flatMap(query -> printer.toStream(tx.stream(query, infer)));
// For each printed answer, print them on one line
answers.forEach(answer -> {
try {
consoleReader.println(answer);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (RuntimeException e) {
// Flush out all answers from previous iterators in the stream
consoleReader.flush();
if (catchRuntimeException) {
if (!e.getMessage().isEmpty()) {
printErr.println("Error: " + e.getMessage());
} else {
printErr.println("Error: " + e.getClass().getName());
}
printErr.println("All uncommitted data is cleared");
//If console session was terminated by shutdown hook thread, do not try to reopen transaction
if (terminated.get()) return;
reopenTransaction();
} else {
throw e;
}
}
consoleReader.flush(); // Flush the ConsoleReader before the next command
// It is important that we DO NOT close the transaction at the end of a query
// The user may want to do consecutive operations onto the database
// The transaction will only close once the user decides to COMMIT or ROLLBACK
}
private void commit() {
try {
tx.commit();
} catch (RuntimeException e) {
printErr.println(e.getMessage());
printErr.println("All uncommitted data is cleared");
} finally {
reopenTransaction();
}
}
private void rollback() {
try {
tx.close();
} catch (RuntimeException e) {
printErr.println(e.getMessage());
} finally {
reopenTransaction();
}
}
/**
*
* @return true if a clean took place, false otherwise
* @throws IOException
*/
private boolean clean() throws IOException {
// Get user confirmation to clean graph
consoleReader.println("Are you sure? CLEAN command will delete the current keyspace and its content.");
consoleReader.println("Type 'confirm' to continue: ");
String line = consoleReader.readLine();
if (line != null && line.equals("confirm")) {
consoleReader.println("Cleaning keyspace: " + keyspace);
consoleReader.println("...");
consoleReader.flush();
client.keyspaces().delete(keyspace);
consoleReader.println("Keyspace deleted: " + keyspace);
return true;
} else {
consoleReader.println("Clean command cancelled");
return false;
}
}
private void reopenTransaction() {
if (!tx.isClosed()) tx.close();
tx = session.transaction().write();
}
@Override
public final void close() {
terminated.set(true);
tx.close();
session.close();
client.close();
try {
historyFile.flush();
} catch (IOException e) {
// Print stacktrace to any available stream
// nothing more to do here
e.printStackTrace();
}
}
/**
* Open the user's preferred editor to write a query
*
* @return the string written in the editor
*/
private String openTextEditor() throws IOException, InterruptedException {
File tempFile = new File(System.getProperty("java.io.tmpdir") + EDITOR_FILE);
tempFile.createNewFile();
ProcessBuilder builder;
if (isWindows()) {
String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(WINDOWS_EDITOR_DEFAULT);
builder = new ProcessBuilder("cmd", "/c", editor + " " + tempFile.getAbsolutePath());
} else {
String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(UNIX_EDITOR_DEFAULT);
// Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
builder = new ProcessBuilder("/bin/bash", "-c", editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath());
}
builder.start().waitFor();
return String.join("\n", Files.readAllLines(tempFile.toPath()));
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}
}