-
Notifications
You must be signed in to change notification settings - Fork 0
/
launcher.js
557 lines (468 loc) · 15.5 KB
/
launcher.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/**
* # Launcher file for nodeGame Server
* Copyright(c) 2016 Stefano Balietti
* MIT Licensed
*
* Load configuration options and start the server
*
* http://www.nodegame.org
*/
"use strict";
// Modules.
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var J = require('JSUS').JSUS;
var NDDB;
// Load commander.
var program = require('commander');
// Load the ServerNode class.
var ServerNode = require('nodegame-server').ServerNode;
// nodeGame version.
var version = require('./package.json').version;
// ServerNode object.
var sn;
// ServerNode options.
var options;
// Conf file for all variables.
var confFile;
// Other local options.
var confDir, logDir, gamesDir, debug, infoQuery, runTests;
var nClients, clientType, killServer, auth, wait;
var codesDb;
var cert, key;
// Warn message.
var ignoredOptions;
// Helper variables.
// Split input parameters.
function list(val) {
return val.split(',');
}
// Go!
ignoredOptions = [];
// Defaults.
confFile = null;
confDir = './conf';
logDir = './log';
gamesDir = './games';
debug = false;
infoQuery = false;
nClients = 4;
clientType = 'autoplay';
runTests = false;
killServer = false;
// Commander.
program
.version(version)
// Specify a configuration file (other inline-options will be ignored).
.option('-C, --config [confFile]',
'Specifies a configuration file to load')
// Specify inline options (more limited than a conf file, but practical).
.option('-c, --confDir <confDir>',
'Sets the configuration directory')
.option('-l, --logDir <logDir>',
'Sets the log directory')
.option('-g, --gamesDir <gamesDir>',
'Sets the games directory')
.option('-d, --debug',
'Enables the debug mode')
.option('-i, --infoQuery',
'Enables getting information via query-string ?q=')
.option('-b, --build [components]',
'Rebuilds the specified components', list)
.option('-s, --ssl [path-to-ssl-dir]',
'Starts the server with SSL encryption')
// Connect phantoms.
.option('-p, --phantoms <channel>',
'Connect phantoms to the specified channel')
.option('-n, --nClients <n>',
'Sets the number of clients phantoms to connect (default: 4)')
.option('-t, --clientType <t>',
'Sets the client type of connecting phantoms (default: autoplay)')
.option('-T, --runTests',
'Run tests after all phantoms have reached game over ' +
'(overwrites settings.js in test/ folder')
.option('-k, --killServer',
'Kill server after all phantoms have reached game over')
.option('-a --auth [option]',
'Phantoms pass through /auth/. Options: createNew|new|' +
'nextAvailable|next|code|id:code&pwd:password|file:path/to/file. ' +
'Default: "new".')
.option('-w --wait [milliseconds]',
'Waits before connecting the next phantom. Default: 1000')
.parse(process.argv);
if (program.confFile) {
if (!fs.existsSync(program.ConfFile)) {
return printErr('--confFile ' + program.confFile + ' not found.');
}
options = require(program.confFile);
if ('object' !== typeof options) {
return printErr('--confFile ' + program.confFile + ' did not return ' +
'a configuration object.');
}
if (program.confDir) ignoredOptions.push('--confDir');
if (program.logDir) ignoredOptions.push('--logDir');
if (program.gamesDir) ignoredOptions.push('--gamesDir');
if (program.debug) ignoredOptions.push('--debug');
if (program.infoQuery) ignoredOptions.push('--infoQuery');
}
else {
options = {
// Additional conf directory.
confDir: confDir,
// Log Dir
logDir: logDir,
servernode: function(servernode) {
// Special configuration for the ServerNode object.
// Adds a new game directory (Default is nodegame-server/games).
servernode.gamesDirs.push(gamesDir);
// Sets the debug mode, exceptions will be thrown.
servernode.debug = debug;
// Can get information from /?q=
servernode.enableInfoQuery = infoQuery;
// Basepath (without trailing slash).
// servernode.basepath = '/mybasepath';
return true;
},
http: function(http) {
// Special configuration for Express goes here.
return true;
},
sio: function(sio) {
// Special configuration for Socket.Io goes here here.
// Might not work in Socket.IO 1.x (check).
// sio.set('transports', ['xhr-polling']);
// sio.set('transports', ['jsonp-polling']);
// sio.set('transports', [
// 'websocket'
// , 'flashsocket'
// , 'htmlfile'
// , 'xhr-polling'
// , 'jsonp-polling'
// ]);
return true;
}
};
// Validate other options.
if (program.confDir) {
if (!fs.existsSync(program.confDir)) {
return printErr('--confDir ' + program.confDir + ' not found.');
}
confDir = program.confDir;
}
if (program.logDir) {
if (!fs.existsSync(program.logDir)) {
return printErr('--logDir ' + program.logDir + ' not found.');
}
logDir = program.logDir;
}
if (program.gamesDir) {
if (!fs.existsSync(program.gamesDir)) {
return printErr('--gamesDir ' + program.gamesDir + ' not found.');
}
gamesDir = program.gamesDir;
}
if (program.debug) debug = true;
if (program.infoQuery) infoQuery = true;
}
// Rebuild server files as needed.
if (program.build) {
(function() {
var i, len, opts, modules;
var info, module, out;
out = 'nodegame-full.js';
modules = {
window: 'window',
client: 'client',
widgets: 'widgets',
JSUS: 'JSUS',
NDDB: 'NDDB'
};
info = require(J.resolveModuleDir('nodegame-server', __dirname) +
'bin/info.js');
len = program.build.length;
if (!len) {
program.build = [ 'client' ];
}
else if (len === 1 && program.build[0] === 'all') {
// Client will be done anyway.
program.build = [ 'window', 'widgets', 'JSUS', 'NDDB' ];
}
// Starting build.
i = -1, len = program.build.length;
for ( ; ++i < len ; ) {
module = program.build[i];
if (!modules[module]) {
throw new Error('unknown build component: ' + module);
}
// Will be done last anyway.
if (module === 'client') continue;
else if (module === 'NDDB') {
console.log('NDDB does not require build.');
continue;
}
opts = { all: true, clean: true };
info.build[module](opts);
console.log('');
}
// Do client last.
info.build.client({
clean: true,
all: true,
output: out
});
J.copyFile(info.modulesDir.client + 'build/' + out,
info.serverDir.build + out);
console.log(info.serverDir.build + out + ' rebuilt.');
console.log('');
})(program.build);
}
// Validate general options.
if ('boolean' === typeof program.ssl) {
options.ssl = true;
}
else if ('string' === typeof program.ssl) {
options.ssl = (function(dir) {
var ssl;
dir = path.resolve(dir) + '/';
if (!fs.existsSync(dir)) {
printErr('ssl directory not found: ' + dir);
return;
}
key = dir + 'private.key';
if (!fs.existsSync(key)) {
printErr('ssl private key not found: ' + key);
return;
}
cert = dir + 'certificate.pem';
if (!fs.existsSync(cert)) {
printErr('ssl certificate not found: ' + cert);
return;
}
ssl = {};
ssl.key = fs.readFileSync(key, 'utf8');
ssl.cert = fs.readFileSync(cert, 'utf8');
return ssl;
})(program.ssl);
if (!options.ssl) return;
}
if (program.nClients) {
if (!program.phantoms) ignoredOptions.push('--nClients');
else {
nClients = parseInt(program.nClients, 10);
if (isNaN(nClients)) {
return printErr('--nClients ' + program.nClients +
' is invalid.');
}
}
}
if (program.clientType) {
if (!program.phantoms) ignoredOptions.push('--clientType');
else clientType = program.clientType;
}
if (program.runTests) {
if (!program.runTests) ignoredOptions.push('--runTests');
else runTests = program.runTests;
}
if (program.killServer) {
if (!program.phantoms) ignoredOptions.push('--killServer');
else killServer = true;
}
if (program.wait) {
if (!program.phantoms) {
ignoredOptions.push('--wait');
}
else {
if (true === program.wait) {
wait = 1000;
}
else {
wait = J.isInt(program.wait, 0);
if (false === wait) {
printErr('--wait must be a positive number or undefined. ' +
'Found:' + program.wait);
process.exit();
}
}
}
}
if (program.auth) {
if (!program.phantoms) {
ignoredOptions.push('--auth');
}
else if ('string' === typeof program.auth) {
auth = (function(idIdx, pwdIdx) {
var auth;
idIdx = program.auth.indexOf('id:');
if (idIdx === 0) {
pwdIdx = program.auth.indexOf('&pwd:');
if (pwdIdx !== -1) {
auth = {
id: program.auth.substr(3, (pwdIdx-3)),
pwd: program.auth.substr(pwdIdx+5)
};
}
else {
printErr('--auth must be a client id or id and ' +
'pwd in the form "id:123&pwd:456"');
process.exit();
}
}
else if (program.auth === 'new') {
auth = 'createNew';
}
else if (program.auth === 'next') {
auth = 'nextAvailable';
}
else if (program.auth.indexOf('file:') === 0) {
NDDB = require('NDDB').NDDB;
codesDb = new NDDB();
codesDb.loadSync(program.auth.substr(5));
if (!codesDb.size()) {
printErr('--auth no auth codes found: program.auth');
process.exit();
}
codesDb = codesDb.db;
}
else {
auth = program.auth;
}
return auth;
})();
}
else if ('boolean' === typeof program.auth) {
auth = 'createNew';
}
else if ('number' === typeof program.auth ||
'object' === typeof program.auth) {
auth = program.auth;
}
}
// Print warnings, if any.
printIgnoredOptions();
console.log('nodeGame v.' + require('./package.json').version);
// Start server, options parameter is optional.
sn = new ServerNode(options);
sn.ready(function() {
var channel;
var i, phantoms;
var startPhantom, handleGameover;
var gameName, gameDir, queryString;
var numFinished;
// If there are not bots to add returns.
if (!program.phantoms) return;
gameName = program.phantoms;
channel = sn.channels[gameName];
if (!channel) {
printErr('channel ' + gameName + ' was not found.');
if (killServer) process.exit();
return;
}
if (auth && !channel.gameInfo.auth.enabled) {
printErr('auth option enabled, but channel does not support it.');
process.exit();
}
gameDir = sn.channels[gameName].getGameDir();
if (clientType) queryString = '?clientType=' + clientType;
if (killServer || runTests) {
handleGameover = function() {
var command, testProcess;
console.log();
console.log(gameName + ' game has run successfully.');
console.log();
if (runTests) {
command = gameDir + 'node_modules/.bin/mocha';
if (fs.existsSync(command)) {
// Write and backup settings file.
writeSettingsFile(gameDir);
command += ' ' + gameDir + 'test/ --colors';
testProcess = exec(command, function(err, stdout, stderr) {
if (stdout) console.log(stdout);
if (stderr) console.log(stderr);
testProcess.kill();
if (killServer) process.exit();
});
}
else {
printErr('Cannot run tests, mocha executable not found: ',
command);
}
}
else if (killServer) process.exit();
};
}
startPhantom = function(i) {
var str, config;
str = 'Connecting phantom #' + (i+1) + '/' + nClients;
if (codesDb) {
config = { queryString: queryString, auth: codesDb[i] };
}
else {
config = { queryString: queryString, auth: auth };
}
if (config.auth) {
if (config.auth.id) {
str += ' id: ' + config.auth.id;
if (config.auth.pwd) str += ' pwd: ' + config.auth.pwd;
}
else {
str += ' ' + config.auth;
}
}
console.log(str);
phantoms[i] = channel.connectPhantom(config);
if ('undefined' !== typeof handleGameover) {
// Wait for all PhantomJS processes to exit, then stop the server.
phantoms[i].on('exit', function(code) {
numFinished ++;
if (numFinished === nClients) {
handleGameover();
}
});
}
};
phantoms = [], numFinished = 0;
for (i = 0; i < nClients; ++i) {
if (i > 0 && wait) {
(function(i) {
setTimeout(function() { startPhantom(i); }, wait * i);
})(i);
}
else {
startPhantom(i);
}
}
// TODO: Listen for room creation instead of timeout.
//setTimeout(function() {
// var node;
// node = sn.channels.ultimatum.gameRooms["ultimatum1"].node;
// node.events.ee.ng.on(
// 'GAME_OVER', function() {console.log('The game is over now.');});
//}, 5000);
});
// ## Helper functions.
function printIgnoredOptions() {
if (ignoredOptions.length) {
console.log(' ignored options:', ignoredOptions.join(', '));
console.log();
console.log();
}
}
function printErr(err) {
console.log(' Check the input parameters.');
console.log(' Error: ' + err);
}
function writeSettingsFile(gameDir) {
var settings, settingsFile, bak;
settings = 'module.exports = { numPlayers: ' + nClients + ' };';
settingsFile = gameDir + 'test/settings.js';
// Make a backup of existing settings file, if found.
if (fs.existsSync(settingsFile)) {
bak = fs.readFileSync(settingsFile).toString();
fs.writeFileSync(settingsFile + '.bak', bak);
}
// Write updated settings file.
fs.writeFileSync(gameDir + 'test/settings.js', settings);
}
// Exports the ServerNode instance.
module.exports = sn;