-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashboard.js
419 lines (326 loc) · 9.2 KB
/
dashboard.js
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import fs from 'fs';
import path from 'path';
import mri from 'mri';
import glob from 'glob';
import fse from 'fs-extra';
import blessed from 'blessed';
import contrib from 'blessed-contrib';
import colors from 'colors/safe';
import { getTimestamp } from '@ez-trigger/core';
import { i, w } from '@ez-trigger/server';
import {
recordExportPath,
pluginPackagePath,
serverPackagePath,
configFile
} from './modules/config';
import Logger from './modules/Logger';
import hackRequire from './modules/hackRequire';
import welcomeMessage from './modules/welcome';
import TriggerServer from './modules/Server';
// We hacked node's require method here, to ensure that
// each plugin and program can get the '@ezTrigger/server'
// without installing them in their own path.
hackRequire();
const DEBUG_NO_CUI = false;
// Argvs related code
const argvs = mri(process.argv);
// Dashboard related objects
const logger = new Logger();
logger.log(i('Initializing ezTrigger system dashboard.'));
const screen = blessed.screen({
title: 'ezTrigger System'
});
// Server components
let clientTypes, actions;
clientTypes = {};
actions = {};
const server = new TriggerServer({
ip: configFile.ip,
port: configFile.port,
clientTypes,
logger: logger
});
// Scan the plugins dirs.
const pluginPackageManifestPaths = glob.sync(
`${pluginPackagePath}/*/package.json`
);
const plugins = [];
if (pluginPackageManifestPaths.length) {
logger.log(
i(`Will read plugin package information from ${pluginPackagePath}.`)
);
logger.log(i(`Found ${pluginPackageManifestPaths.length} packages.`));
const pluginPackageManifests = pluginPackageManifestPaths.map(filePath => {
const rawData = fs.readFileSync(filePath);
const result = JSON.parse(rawData);
result.path = path.dirname(filePath);
return result;
});
pluginPackageManifests.forEach(manifest => {
logger.log(i(`Loading "${manifest.name}"...`));
const pluginPackageClass = eval('require')(
path.join(manifest.path, manifest.main)
).default;
new pluginPackageClass(server).integrate();
});
}
// Scan the server dirs.
const serverPackageManifestPaths = glob.sync(
`${serverPackagePath}/*/package.json`
);
if (serverPackagePath.length) {
logger.log(
i(`Will read server package information from ${serverPackagePath}.`)
);
logger.log(i(`Found ${serverPackageManifestPaths.length} packages.`));
const serverPackageManifests = serverPackageManifestPaths.map(filePath => {
const rawData = fs.readFileSync(filePath);
const result = JSON.parse(rawData);
result.path = path.dirname(filePath);
return result;
});
serverPackageManifests.forEach(manifest => {
logger.log(i(`Loading "${manifest.functionListName}"...`));
const ServerPackageClass = eval('require')(
path.join(manifest.path, manifest.main)
).default; //__non_webpack_require__
const serverPackageObject = new ServerPackageClass(server, manifest);
if (manifest.clientTypeId && manifest.clientTypeName) {
clientTypes[manifest.clientTypeId] = manifest.clientTypeName;
}
actions[manifest.functionListName] = { children: {} };
serverPackageObject.fns.forEach(fnDescription => {
actions[manifest.functionListName].children[fnDescription.name] = {
fn: fnDescription.fn
};
});
});
} else {
clientTypes = {
EXP: 'experiment client'
};
}
const tools = [
{
label: 'Records',
getBadge: () => server.records.data.length
},
{
label: ' Export Records',
fn: async () => {
fse.ensureDirSync(recordExportPath);
const exportPath = await server.records.export('record');
logger.log(i(`Exported the records to: ${exportPath}`));
}
},
{
label: ' Clear Records',
fn: () => {
server.records.clear();
logger.log(i(`Records cleared.`));
}
},
{
label: 'Logs',
getBadge: () => logWidget.logLines.length
},
{
label: ' Export Logs',
fn: async () => {
const logLines = logWidget.logLines.join('\n');
const exportPath = path.join(
recordExportPath,
`log ${getTimestamp()}.log`
);
await fse.writeFile(exportPath, logLines);
logger.log(i(`Exported the records to: ${exportPath}`));
}
}
];
const getToolItems = () =>
tools.map(
//item => ()
item => (item.getBadge ? `${item.label} [${item.getBadge()}]` : item.label)
);
// Wait for several second before loading the cui.
logger.log(i('The system will start soon...'));
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2000);
// Start drawing the dashboard.
const generateUnselectedWidgetStyle = () => ({
selected: {
bg: '',
fg: 'white',
bold: true
}
});
const grid = new contrib.grid({ rows: 12, cols: 12, screen: screen });
const logWidget = grid.set(0, 0, 8, 9, contrib.log, {
label: 'Server Log'
});
const debugTypeWidget = grid.set(8, 0, 4, 3, blessed.list, {
label: 'Boroadcast Client Types',
keys: true,
style: generateUnselectedWidgetStyle()
});
const debugCommandWidget = grid.set(8, 3, 4, 3, blessed.list, {
label: 'Broadcast Commands',
keys: true,
style: generateUnselectedWidgetStyle()
});
const toolListWidget = grid.set(8, 6, 4, 3, blessed.list, {
label: 'Tools',
keys: true,
style: generateUnselectedWidgetStyle()
});
toolListWidget.on('select', (_, itemIndex) => {
if (tools[itemIndex].fn) {
tools[itemIndex].fn();
}
});
const experimentWidget = grid.set(0, 9, 5, 3, contrib.tree, {
label: 'Experiment Actions',
style: {
selected: {
bg: 'blue',
fg: 'white',
bold: true
}
}
});
const userWidget = grid.set(5, 9, 7, 3, contrib.table, {
interactive: false,
label: 'Connected clients',
columnSpacing: 0,
columnWidth: [10, 15, 5]
});
userWidget.setData({
headers: ['UUID', 'IP', 'Type'],
data: []
});
experimentWidget.setData({
lines: false,
extended: true,
children: actions
});
experimentWidget.on('select', node => {
if (node.fn) {
node.fn();
}
});
debugTypeWidget.on('select', node => {
const item = node.getText().match(/^\[[ X]\] (.*)$/)[1];
const clientType = Object.entries(clientTypes).find(x => x[1] === item)[0];
selectedTypes[clientType] = !selectedTypes[clientType];
updateTypeUI(server.clientTypes);
});
debugCommandWidget.on('select', node => {
const command = node.getText();
if (!Object.values(selectedTypes).filter(x => x).length) {
logger.log(
w(
'No message sent, check some type of clients on the "Broadcast Client Types" box.'
)
);
return false;
}
logger.log(
i(`Broadcasting ${command} as debug information to all selected clients.`)
);
Object.keys(selectedTypes).map(type => {
server.broadcast(command, type);
});
});
screen.key(['C-c'], () => {
return process.exit(0);
});
let currentFocusIndex = 0;
const focusOrder = [
{
widget: experimentWidget,
repaintStyleTarget: experimentWidget.rows.style.selected
},
{
widget: debugTypeWidget,
repaintStyleTarget: debugTypeWidget.style.selected
},
{
widget: debugCommandWidget,
repaintStyleTarget: debugCommandWidget.style.selected
},
{
widget: toolListWidget,
repaintStyleTarget: toolListWidget.style.selected
}
];
const switchFocus = step => {
currentFocusIndex += step;
if (currentFocusIndex > focusOrder.length - 1) {
currentFocusIndex = 0;
} else if (currentFocusIndex < 0) {
currentFocusIndex = focusOrder.length - 1;
}
focusOrder.forEach((item, index) => {
item.repaintStyleTarget.bg = index === currentFocusIndex ? 'blue' : '';
});
focusOrder[currentFocusIndex].widget.focus();
screen.render();
};
screen.key(['tab', 'd'], () => switchFocus(1));
screen.key(['a'], () => switchFocus(-1));
screen.on('resize', () => {
logWidget.emit('attach');
});
const logFn = msg => {
logWidget.log(`${msg}`);
screen.render();
};
const selectedTypes = {};
const updateTypeUI = clientTypes => {
const uiElements = Object.keys(clientTypes).map(
clientType =>
`[${selectedTypes[clientType] ? 'X' : ' '}] ${clientTypes[clientType]}`
);
debugTypeWidget.setItems(uiElements);
screen.render();
};
const updateCommandUI = commands => {
debugCommandWidget.setItems(server.debugCommands);
screen.render();
};
const updateClientUI = clients => {
const result = [];
clients.forEach((set, client) => {
const type = client.props.type ? client.props.type : '???';
const id = client.props.id
? colors.white(client.props.id)
: client.shortUuid;
result.push([id, client.ip, type]);
});
userWidget.setData({
headers: ['ID', 'IP', 'Type'],
data: result
});
screen.render();
return true;
};
const updateToolsUI = () => {
toolListWidget.setItems(getToolItems());
screen.render();
};
server.on('client-updated', updateClientUI);
server.on('type-updated', updateTypeUI);
server.on('debug-command-updated', updateCommandUI);
server.records.on('record-updated', updateToolsUI);
logger.on('log-updated', updateToolsUI);
(async () => {
logger.setTarget(logFn);
welcomeMessage.split('\n').forEach(msg => logger.log(msg));
logger.log('');
await server.start();
updateTypeUI(server.clientTypes);
updateCommandUI(server.debugCommands);
updateToolsUI();
experimentWidget.focus();
screen.render();
})();