forked from mjeries/mineos-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
2060 lines (1818 loc) · 74.6 KB
/
server.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var mineos = require('./mineos');
var async = require('async');
var path = require('path');
var events = require('events');
var os = require('os');
var logging = require('winston');
var fs = require('fs-extra');
var server = exports;
logging.add(logging.transports.File, {
filename: '/var/log/mineos.log',
handleExceptions: true
});
server.backend = function(base_dir, socket_emitter) {
var self = this;
self.servers = {};
self.profiles = [];
self.front_end = socket_emitter;
self.commit_msg = '';
process.umask(0002);
fs.ensureDirSync(base_dir);
fs.ensureDirSync(path.join(base_dir, mineos.DIRS['servers']));
fs.ensureDirSync(path.join(base_dir, mineos.DIRS['backup']));
fs.ensureDirSync(path.join(base_dir, mineos.DIRS['archive']));
fs.ensureDirSync(path.join(base_dir, mineos.DIRS['import']));
fs.ensureDirSync(path.join(base_dir, mineos.DIRS['profiles']));
fs.chmod(path.join(base_dir, mineos.DIRS['import']), 0777);
(function() {
var which = require('which');
async.waterfall([
async.apply(which, 'git'),
function(path, cb) {
var child = require('child_process');
var opts = {cwd: __dirname};
child.execFile(path, [ 'show', '--oneline', '-s' ], opts, cb);
},
function(stdout, stderr, cb) {
self.commit_msg = (stdout ? stdout : '');
logging.info('Starting up server, using commit:', self.commit_msg);
cb();
}
])
})();
(function() {
//thanks to https://github.com/flareofghast/node-advertiser/blob/master/advert.js
var dgram = require('dgram');
var udp_broadcaster = {};
var UDP_DEST = '255.255.255.255';
var UDP_PORT = 4445;
var BROADCAST_DELAY_MS = 4000;
async.forever(
function(next) {
for (var s in self.servers) {
self.servers[s].broadcast_to_lan(function(msg, server_ip) {
if (msg) {
if (udp_broadcaster[server_ip]) {
udp_broadcaster[server_ip].send(msg, 0, msg.length, UDP_PORT, UDP_DEST);
} else {
udp_broadcaster[server_ip] = dgram.createSocket('udp4');
udp_broadcaster[server_ip].bind(UDP_PORT, server_ip);
udp_broadcaster[server_ip].on("listening", function () {
udp_broadcaster[server_ip].setBroadcast(true);
udp_broadcaster[server_ip].send(msg, 0, msg.length, UDP_PORT, UDP_DEST);
});
udp_broadcaster[server_ip].on("error", function (err) {
logging.error("Cannot bind broadcaster to ip " + server_ip);
});
}
}
})
}
setTimeout(next, BROADCAST_DELAY_MS);
}
)
})();
(function() {
var HOST_HEARTBEAT_DELAY_MS = 1000;
function host_heartbeat() {
self.front_end.emit('host_heartbeat', {
'uptime': os.uptime(),
'freemem': os.freemem(),
'loadavg': os.loadavg()
})
}
setInterval(host_heartbeat, HOST_HEARTBEAT_DELAY_MS);
})();
(function() {
var server_path = path.join(base_dir, mineos.DIRS['servers']);
function discover() {
//http://stackoverflow.com/a/24594123/1191579
return fs.readdirSync(server_path).filter(function(p) {
return fs.statSync(path.join(server_path, p)).isDirectory();
});
}
function track(sn) {
self.servers[sn] = null;
//if new server_container() isn't instant, double broadcast might trigger this if/then twice
//setting to null is immediate and prevents double execution
self.servers[sn] = new server_container(sn, base_dir, self.front_end);
self.front_end.emit('track_server', sn);
}
function untrack(sn) {
try {
self.servers[sn].cleanup();
delete self.servers[sn];
} catch (e) {
//if server has already been deleted and this is running for reasons unknown, catch and ignore
} finally {
self.front_end.emit('untrack_server', sn);
}
}
var discovered_servers = discover();
for (var i in discovered_servers)
track(discovered_servers[i]);
fs.watch(server_path, function() {
var current_servers = discover();
for (var i in current_servers)
if (!(current_servers[i] in self.servers)) //if detected directory not a discovered server, track
track(current_servers[i]);
for (var s in self.servers)
if (current_servers.indexOf(s) < 0)
untrack(s);
})
})();
(function() {
var fireworm = require('fireworm');
var importable_archives = path.join(base_dir, mineos.DIRS['import']);
var fw = fireworm(importable_archives);
fw.add('**/*.zip');
fw.add('**/*.tar');
fw.add('**/*.tgz');
fw.add('**/*.tar.gz');
fw
.on('add', function(fp) {
logging.info('[WEBUI] New file found in import directory', fp);
self.send_importable_list();
})
.on('remove', function(fp) {
logging.info('[WEBUI] File removed from import directory', fp);
self.send_importable_list();
})
})();
self.start_servers = function() {
var MS_TO_PAUSE = 10000;
async.eachLimit(
Object.keys(self.servers),
1,
function(server_name, callback) {
self.servers[server_name].onreboot_start(function(err) {
if (err)
logging.error('[{0}] Aborted server startup; condition not met:'.format(server_name), err);
else
logging.info('[{0}] Server started. Waiting {1} ms...'.format(server_name, MS_TO_PAUSE));
setTimeout(callback, (err ? 1 : MS_TO_PAUSE));
});
},
function(err) {}
)
}
setTimeout(self.start_servers, 5000);
self.shutdown = function() {
for (var server_name in self.servers)
self.servers[server_name].cleanup();
}
self.send_profile_list = function(send_existing) {
if (send_existing && self.profiles.length) //if requesting to just send what you already have AND they are already present
self.front_end.emit('profile_list', self.profiles);
else
check_profiles(base_dir, function(err, all_profiles) {
if (!err)
self.profiles = all_profiles;
self.front_end.emit('profile_list', self.profiles);
})
}
self.send_spigot_list = function() {
var profiles_dir = path.join(base_dir, mineos.DIRS['profiles']);
var spigot_profiles = {};
async.waterfall([
async.apply(fs.readdir, profiles_dir),
function(listing, cb) {
for (var i in listing) {
var match = listing[i].match(/(paper)?spigot_([\d\.]+)/);
if (match)
spigot_profiles[match[0]] = {
'directory': match[0],
'jarfiles': fs.readdirSync(path.join(profiles_dir, match[0])).filter(function(a) { return a.match(/.+\.jar/i) })
}
}
cb();
}
], function(err) {
self.front_end.emit('spigot_list', spigot_profiles);
})
}
self.front_end.on('connection', function(socket) {
var userid = require('userid');
var fs = require('fs-extra');
var ip_address = socket.request.connection.remoteAddress;
var username = socket.request.user.username;
var OWNER_CREDS = {
uid: userid.uid(username),
gid: userid.gid(username)
}
function webui_dispatcher (args) {
logging.info('[WEBUI] Received emit command from {0}:{1}'.format(ip_address, username), args);
switch (args.command) {
case 'create':
var instance = new mineos.mc(args.server_name, base_dir);
async.series([
async.apply(instance.verify, '!exists'),
async.apply(instance.create, OWNER_CREDS),
async.apply(instance.overlay_sp, args.properties),
], function(err, results) {
if (!err)
logging.info('[{0}] Server created in filesystem.'.format(args.server_name));
else
logging.error(err);
})
break;
case 'create_unconventional_server':
var instance = new mineos.mc(args.server_name, base_dir);
async.series([
async.apply(instance.verify, '!exists'),
async.apply(instance.create_unconventional_server, OWNER_CREDS),
], function(err, results) {
if (!err)
logging.info('[{0}] Server (unconventional) created in filesystem.'.format(args.server_name));
else
logging.error(err);
})
break;
case 'download':
function progress_emitter(args) {
self.front_end.emit('file_progress', args);
}
for (var idx in self.profiles)
if (self.profiles[idx].id == args.profile.id) {
download_profiles(base_dir, self.profiles[idx], progress_emitter, function(retval){
self.front_end.emit('host_notice', retval);
self.send_profile_list();
});
break;
}
break;
case 'build_jar':
var which = require('which');
var child_process = require('child_process');
try {
var profile_path = path.join(base_dir, mineos.DIRS['profiles']);
var working_dir = path.join(profile_path, '{0}_{1}'.format(args.builder.group, args.version));
var bt_path = path.join(profile_path, args.builder.id, args.builder.filename);
var dest_path = path.join(working_dir, args.builder.filename);
var params = { cwd: working_dir };
} catch (e) {
logging.error('[WEBUI] Could not build jar; insufficient/incorrect arguments provided:', args);
logging.error(e);
return;
}
async.series([
async.apply(fs.mkdir, working_dir),
async.apply(fs.copy, bt_path, dest_path),
function(cb) {
var binary = which.sync('java');
var proc = child_process.spawn(binary, ['-jar', dest_path, '--rev', args.version], params);
proc.stdout.on('data', function (data) {
self.front_end.emit('build_jar_output', data.toString());
//logging.log('stdout: ' + data);
});
logging.info('[WEBUI] BuildTools starting with arguments:', args)
proc.stderr.on('data', function (data) {
self.front_end.emit('build_jar_output', data.toString());
logging.error('stderr: ' + data);
});
proc.on('close', function (code) {
cb(code);
});
}
], function(err, results) {
logging.info('[WEBUI] BuildTools jar compilation finished {0} in {1}'.format( (err ? 'unsuccessfully' : 'successfully'), working_dir));
logging.info('[WEBUI] Buildtools used: {0}'.format(dest_path));
var retval = {
'command': 'BuildTools jar compilation',
'success': true,
'help_text': ''
}
if (err) {
retval['success'] = false;
retval['help_text'] = "Error {0} ({1}): {2}".format(err.errno, err.code, err.path);
}
self.front_end.emit('host_notice', retval);
self.send_spigot_list();
})
break;
case 'delete_build':
if (args.type == 'spigot')
var spigot_path = path.join(base_dir, mineos.DIRS['profiles'], 'spigot_' + args.version);
else if (args.type == 'paperspigot')
var spigot_path = path.join(base_dir, mineos.DIRS['profiles'], 'paperspigot_' + args.version);
else {
logging.error('[WEBUI] Unknown type of craftbukkit server -- potential modified webui request?');
return;
}
fs.remove(spigot_path, function(err) {
var retval = {
'command': 'Delete BuildTools jar',
'success': true,
'help_text': ''
}
if (err) {
retval['success'] = false;
retval['help_text'] = "Error {0}".format(err);
}
self.front_end.emit('host_notice', retval);
self.send_spigot_list();
})
break;
case 'copy_to_server':
var rsync = require('rsync');
if (args.type == 'spigot')
var spigot_path = path.join(base_dir, mineos.DIRS['profiles'], 'spigot_' + args.version) + '/';
else if (args.type == 'paperspigot')
var spigot_path = path.join(base_dir, mineos.DIRS['profiles'], 'paperspigot_' + args.version) + '/';
else {
logging.error('[WEBUI] Unknown type of craftbukkit server -- potential modified webui request?');
return;
}
var dest_path = path.join(base_dir, mineos.DIRS['servers'], args.server_name) + '/';
var obj = rsync.build({
source: spigot_path,
destination: dest_path,
flags: 'au',
shell:'ssh'
});
obj.set('--include', '*.jar');
obj.set('--exclude', '*');
obj.set('--prune-empty-dirs');
obj.set('--chown', '{0}:{1}'.format(OWNER_CREDS.uid, OWNER_CREDS.gid));
obj.execute(function(error, code, cmd) {
var retval = {
'command': 'BuildTools jar copy',
'success': true,
'help_text': ''
}
if (error) {
retval['success'] = false;
retval['help_text'] = "Error {0} ({1})".format(error, code);
}
self.front_end.emit('host_notice', retval);
for (var s in self.servers)
self.front_end.emit('track_server', s);
});
break;
case 'refresh_server_list':
for (var s in self.servers)
self.front_end.emit('track_server', s);
break;
case 'refresh_profile_list':
self.send_profile_list();
self.send_spigot_list();
break;
case 'create_from_archive':
var instance = new mineos.mc(args.new_server_name, base_dir);
if (args.awd_dir)
var filepath = path.join(instance.env.base_dir, mineos.DIRS['archive'], args.awd_dir, args.filename);
else
var filepath = path.join(instance.env.base_dir, mineos.DIRS['import'], args.filename);
async.series([
async.apply(instance.verify, '!exists'),
async.apply(instance.create_from_archive, OWNER_CREDS, filepath)
], function(err, results) {
if (!err) {
logging.info('[{0}] Server created in filesystem.'.format(args.new_server_name));
setTimeout(function(){ self.front_end.emit('track_server', args.new_server_name) }, 1000);
} else
logging.error(err);
})
break;
default:
logging.warn('Command ignored: no such command {0}'.format(args.command));
break;
}
}
self.send_user_list = function() {
var passwd = require('etc-passwd');
var users = [];
var groups = [];
var gu = passwd.getUsers()
.on('user', function(user_data) {
if (user_data.username == username)
users.push({
username: user_data.username,
uid: user_data.uid,
gid: user_data.gid,
home: user_data.home
})
})
.on('end', function() {
socket.emit('user_list', users);
})
var gg = passwd.getGroups()
.on('group', function(group_data) {
if (group_data.users.indexOf(username) >= 0 || group_data.gid == userid.gid(username)) {
if (group_data.gid > 0) {
groups.push({
groupname: group_data.groupname,
gid: group_data.gid
})
}
}
})
.on('end', function() {
socket.emit('group_list', groups);
})
}
logging.info('[WEBUI] {0} connected from {1}'.format(username, ip_address));
socket.emit('whoami', username);
socket.emit('commit_msg', self.commit_msg);
for (var server_name in self.servers)
socket.emit('track_server', server_name);
socket.on('command', webui_dispatcher);
self.send_user_list();
self.send_profile_list(true);
self.send_spigot_list();
self.send_importable_list();
})
self.send_importable_list = function() {
var importable_archives = path.join(base_dir, mineos.DIRS['import']);
var all_info = [];
fs.readdir(importable_archives, function(err, files) {
if (!err) {
var fullpath = files.map(function(value, index) {
return path.join(importable_archives, value);
});
var stat = fs.stat;
async.map(fullpath, stat, function(inner_err, results){
results.forEach(function(value, index) {
all_info.push({
time: value.mtime,
size: value.size,
filename: files[index]
})
})
all_info.sort(function(a, b) {
return a.time.getTime() - b.time.getTime();
});
self.front_end.emit('archive_list', all_info);
});
}
})
}
return self;
}
function server_container(server_name, base_dir, socket_io) {
// when evoked, creates a permanent 'mc' instance, namespace, and place for file tails.
var self = this;
var instance = new mineos.mc(server_name, base_dir),
nsp = socket_io.of('/{0}'.format(server_name)),
tails = {},
notices = [],
cron = {},
intervals = {},
HEARTBEAT_INTERVAL_MS = 5000,
COMMIT_INTERVAL_MIN = null;
logging.info('[{0}] Discovered server'.format(server_name));
//async.series([ async.apply(instance.sync_chown) ]);
//uncomment sync_chown to correct perms on server discovery
//commenting out for high cpu usage on startup
make_tail('logs/latest.log');
make_tail('server.log');
make_tail('proxy.log.0');
(function() {
var fireworm = require('fireworm');
var fw = fireworm(instance.env.cwd, {skipDirEntryPatterns: ['world', 'dynmap', 'plugins', 'web', 'logs']});
fw.add('**/server.properties');
fw.add('**/server.config');
fw.add('**/cron.config');
fw.add('**/eula.txt');
fw.add('**/server-icon.png');
fw.add('**/config.yml');
function handle_event(fp) {
var FS_DELAY = 250;
// because it is unknown when fw triggers on add/change and
// further because if it catches DURING the write, it will find
// the file has 0 size, adding arbitrary delay.
// process.nexttick didnt work.
var file_name = path.basename(fp);
switch (file_name) {
case 'server.properties':
setTimeout(broadcast_sp, FS_DELAY);
break;
case 'server.config':
setTimeout(broadcast_sc, FS_DELAY);
break;
case 'cron.config':
setTimeout(broadcast_cc, FS_DELAY);
break;
case 'eula.txt':
setTimeout(emit_eula, FS_DELAY);
break;
case 'server-icon.png':
setTimeout(broadcast_icon, FS_DELAY);
break;
case 'config.yml':
setTimeout(broadcast_cy, FS_DELAY);
break;
}
}
fw.on('add', handle_event);
fw.on('change', handle_event);
})();
intervals['heartbeat'] = setInterval(heartbeat, HEARTBEAT_INTERVAL_MS);
function heartbeat() {
async.series({
'up': function(cb) { instance.property('up', function(err, is_up) { cb(null, is_up) }) },
'memory': function(cb) { instance.property('memory', function(err, mem) { cb(null, err ? {} : mem) }) },
'ping': function(cb) {
instance.property('unconventional', function(err, is_unconventional) {
if (is_unconventional)
cb(null, {}); //ignore ping--wouldn't respond in any meaningful way
else
instance.property('ping', function(err, ping) { cb(null, err ? {} : ping) })
})
},
'query': function(cb) {
instance.property('server.properties', function(err, dict) {
if ((dict || {})['enable-query'])
instance.property('query', cb);
else
cb(null, {}); //ignore query--wouldn't respond in any meaningful way
})
}
}, function(err, retval) {
nsp.emit('heartbeat', {
'server_name': server_name,
'timestamp': Date.now(),
'payload': retval
})
})
}
intervals['world_commit'] = setInterval(world_committer, 1 * 60 * 1000);
function world_committer() {
async.waterfall([
async.apply(instance.property, 'commit_interval'),
function(minutes, cb) {
if (minutes != COMMIT_INTERVAL_MIN) { //upon change or init
COMMIT_INTERVAL_MIN = minutes;
if (minutes > 0) {
logging.info('[{0}] committing world to disk every {1} minutes.'.format(server_name, minutes));
intervals['commit'] = setInterval(instance.saveall, minutes * 60 * 1000);
} else {
logging.info('[{0}] not committing world to disk automatically (interval set to {1})'.format(server_name, minutes));
clearInterval(intervals['commit']);
}
}
}
])
}
(function() {
var CronJob = require('cron').CronJob;
function cron_dispatcher(args) {
var introspect = require('introspect');
var fn, required_args;
var arg_array = [];
fn = instance[args.command];
required_args = introspect(fn);
for (var i in required_args) {
// all callbacks expected to follow the pattern (success, payload).
if (required_args[i] == 'callback')
arg_array.push(function(err, payload) {
args.success = !err;
args.err = err;
args.time_resolved = Date.now();
if (err)
logging.error('[{0}] command "{1}" errored out:'.format(server_name, args.command), args);
})
else if (required_args[i] in args) {
arg_array.push(args[required_args[i]])
}
}
fn.apply(instance, arg_array);
}
instance.crons(function(err, cron_dict) {
for (var cronhash in cron_dict) {
if (cron_dict[cronhash].enabled) {
try {
cron[cronhash] = new CronJob({
cronTime: cron_dict[cronhash].source,
onTick: function() {
cron_dispatcher(this);
},
start: true,
context: cron_dict[cronhash]
});
} catch (e) {
// catches invalid cron expressions
logging.warn('[{0}] invalid cron expression:'.format(server_name), cronhash, cron_dict[cronhash]);
instance.set_cron(cronhash, false, function(){});
}
}
}
})
})();
self.broadcast_to_lan = function(callback) {
async.waterfall([
async.apply(instance.verify, 'exists'),
async.apply(instance.verify, 'up'),
async.apply(instance.sc),
function(sc_data, cb) {
var broadcast_value = (sc_data.minecraft || {}).broadcast;
cb(!broadcast_value) //logically notted to make broadcast:true pass err cb
},
async.apply(instance.sp)
], function(err, sp_data) {
if (err)
callback(null);
else {
var msg = new Buffer("[MOTD]" + sp_data.motd + "[/MOTD][AD]" + sp_data['server-port'] + "[/AD]");
var server_ip = sp_data['server-ip'];
callback(msg, server_ip);
}
})
}
self.onreboot_start = function(callback) {
async.waterfall([
async.apply(instance.property, 'onreboot_start'),
function(autostart, cb) {
logging.info('[{0}] autostart = {1}'.format(server_name, autostart));
cb(!autostart); //logically NOT'ing so that autostart = true continues to next func
},
async.apply(instance.start)
], function(err) {
callback(err);
})
}
self.cleanup = function () {
for (var t in tails)
tails[t].unwatch();
for (var i in intervals)
clearInterval(intervals[i]);
nsp.removeAllListeners();
}
function emit_eula() {
var fs = require('fs-extra');
var eula_path = path.join(instance.env.cwd, 'eula.txt');
async.waterfall([
async.apply(instance.property, 'eula'),
function(accepted, cb) {
logging.info('[{0}] eula.txt detected: {1} (eula={2})'.format(server_name,
(accepted ? 'ACCEPTED' : 'NOT YET ACCEPTED'),
accepted));
nsp.emit('eula', accepted);
cb();
},
])
}
function broadcast_icon() {
// function to encode file data to base64 encoded string
//http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html
var fs = require('fs');
var filepath = path.join(instance.env.cwd, 'server-icon.png');
fs.readFile(filepath, function(err, data) {
if (!err && data.toString('hex',0,4) == '89504e47') //magic number for png first 4B
nsp.emit('server-icon.png', new Buffer(data).toString('base64'));
});
}
function broadcast_cy() {
// function to broadcast raw config.yml from bungeecord
var fs = require('fs');
var filepath = path.join(instance.env.cwd, 'config.yml');
fs.readFile(filepath, function(err, data) {
if (!err)
nsp.emit('config.yml', new Buffer(data).toString());
});
}
function broadcast_notices() {
nsp.emit('notices', notices);
}
function broadcast_sp() {
instance.sp(function(err, sp_data) {
logging.debug('[{0}] broadcasting server.properties'.format(server_name));
nsp.emit('server.properties', sp_data);
})
}
function broadcast_sc() {
instance.sc(function(err, sc_data) {
logging.debug('[{0}] broadcasting server.config'.format(server_name));
if (!err)
nsp.emit('server.config', sc_data);
})
}
function broadcast_cc() {
instance.crons(function(err, cc_data) {
logging.debug('[{0}] broadcasting cron.config'.format(server_name));
if (!err)
nsp.emit('cron.config', cc_data);
})
}
function make_tail(rel_filepath) {
/* makes a file tail relative to the CWD, e.g., /var/games/minecraft/servers/myserver.
tails are used to get live-event reads on files.
if the server does not exist, a watch is made in the interim, waiting for its creation.
once the watch is satisfied, the watch is closed and a tail is finally created.
*/
var tail = require('tail').Tail;
var abs_filepath = path.join(instance.env.cwd, rel_filepath);
if (rel_filepath in tails) {
logging.warn('[{0}] Tail already exists for {1}'.format(server_name, rel_filepath));
return;
}
try {
var new_tail = new tail(abs_filepath);
logging.info('[{0}] Created tail on {1}'.format(server_name, rel_filepath));
new_tail.on('line', function(data) {
//logging.info('[{0}] {1}: transmitting new tail data'.format(server_name, rel_filepath));
nsp.emit('tail_data', {'filepath': rel_filepath, 'payload': data});
})
tails[rel_filepath] = new_tail;
} catch (e) {
logging.error('[{0}] Create tail on {1} failed'.format(server_name, rel_filepath));
logging.info('[{0}] Watching for file generation: {1}'.format(server_name, rel_filepath));
var fireworm = require('fireworm');
var fw = fireworm(instance.env.cwd, {skipDirEntryPatterns: ['world', 'dynmap', 'web', 'plugins']});
fw.add('**/{0}'.format(rel_filepath));
fw.on('add', function(fp) {
fw.clear();
logging.info('[{0}] {1} created! Watchfile {2} closed'.format(server_name, path.basename(fp), rel_filepath));
make_tail(rel_filepath);
})
}
}
self.direct_dispatch = function(user, args) {
var introspect = require('introspect');
var fn, required_args;
var arg_array = [];
async.waterfall([
async.apply(instance.property, 'owner'),
function(ownership_data, cb) {
var auth = require('./auth');
auth.test_membership(user, ownership_data.groupname, function(is_valid) {
cb(null, is_valid);
});
},
function(is_valid, cb) {
cb(!is_valid); //logical NOT'ted: is_valid ? falsy error, !is_valid ? truthy error
}
], function(err) {
if (err) {
logging.error('User "{0}" does not have permissions on [{1}]:'.format(user, args.server_name), args);
} else {
try {
fn = instance[args.command];
required_args = introspect(fn);
// receives an array of all expected arguments, using introspection.
// they are in order as listed by the function definition, which makes iteration possible.
} catch (e) {
args.success = false;
args.error = e;
args.time_resolved = Date.now();
nsp.emit('server_fin', args);
logging.error('server_fin', args);
return;
}
for (var i in required_args) {
// all callbacks expected to follow the pattern (success, payload).
if (required_args[i] == 'callback')
arg_array.push(function(err, payload) {
args.success = !err;
args.err = err;
args.time_resolved = Date.now();
nsp.emit('server_fin', args);
if (err)
logging.error('[{0}] command "{1}" errored out:'.format(server_name, args.command), args);
logging.log('server_fin', args)
})
else if (required_args[i] in args) {
arg_array.push(args[required_args[i]])
} else {
args.success = false;
logging.error('Provided values missing required argument', required_args[i]);
args.error = 'Provided values missing required argument: {0}'.format(required_args[i]);
nsp.emit('server_fin', args);
return;
}
}
if (args.command == 'delete')
self.cleanup();
logging.info('[{0}] received request "{1}"'.format(server_name, args.command))
fn.apply(instance, arg_array);
}
})
}
nsp.on('connection', function(socket) {
var ip_address = socket.request.connection.remoteAddress;
var username = socket.request.user.username;
var NOTICES_QUEUE_LENGTH = 10; // 0 < q <= 10
function server_dispatcher(args) {
var introspect = require('introspect');
var fn, required_args;
var arg_array = [];
try {
fn = instance[args.command];
required_args = introspect(fn);
// receives an array of all expected arguments, using introspection.
// they are in order as listed by the function definition, which makes iteration possible.
} catch (e) {
args.success = false;
args.error = e;
args.time_resolved = Date.now();
nsp.emit('server_fin', args);
logging.error('server_fin', args);
while (notices.length > NOTICES_QUEUE_LENGTH)
notices.shift();
notices.push(args);
return;
}
for (var i in required_args) {
// all callbacks expected to follow the pattern (success, payload).
if (required_args[i] == 'callback')
arg_array.push(function(err, payload) {
args.success = !err;
args.err = err;
args.time_resolved = Date.now();
nsp.emit('server_fin', args);
if (err)
logging.error('[{0}] command "{1}" errored out:'.format(server_name, args.command), args);
logging.log('server_fin', args)
while (notices.length > NOTICES_QUEUE_LENGTH)
notices.shift();
if (args.command != 'delete')
notices.push(args);
})
else if (required_args[i] in args) {
arg_array.push(args[required_args[i]])
} else {
args.success = false;
logging.error('Provided values missing required argument', required_args[i]);
args.error = 'Provided values missing required argument: {0}'.format(required_args[i]);
nsp.emit('server_fin', args);
return;
}
}
if (args.command == 'delete')
self.cleanup();
logging.info('[{0}] received request "{1}"'.format(server_name, args.command))
fn.apply(instance, arg_array);
}
function produce_receipt(args) {
/* when a command is received, immediately respond to client it has been received */
var uuid = require('node-uuid');
logging.info('[{0}] {1} issued command : "{2}"'.format(server_name, ip_address, args.command))
args.uuid = uuid.v1();
args.time_initiated = Date.now();
nsp.emit('server_ack', args);
switch (args.command) {
case 'chown':
async.waterfall([
async.apply(instance.property, 'owner'),
function(owner_data, cb) {
if (owner_data.username != username)
cb('Only the current user owner may reassign server ownership.');
else if (owner_data.uid != args.uid)
cb('You may not change the user owner of the server.');
else
cb();
}
], function(err) {
if (err) {
args.success = false;
args.err = err;
args.time_resolved = Date.now();
logging.error('[{0}] command "{1}" errored out:'.format(server_name, args.command), args);
nsp.emit('server_fin', args);
} else {