forked from ericmandel/js9
-
Notifications
You must be signed in to change notification settings - Fork 1
/
js9Helper.js
executable file
·1213 lines (1162 loc) · 35.5 KB
/
js9Helper.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
/*
*
* js9Helper: Node-based back-end server for JS9 (September 4, 2012)
*
* Principals: Eric Mandel
* Organization: Harvard Smithsonian Center for Astrophysics, Cambridge MA
* Contact: [email protected]
*
* Copyright (c) 2012 - 2017 Smithsonian Astrophysical Observatory
*
* Utilizes: socket.io, node-uuid
*
*/
/*jslint bitwise: true, plusplus: true, vars: true, white: true, continue: true, unparam: true, regexp: true, browser: true, devel: true, node: true, stupid: true */
/*jshint smarttabs:true */
/* global require process module __dirname Buffer */
"use strict";
// load required modules
var http = require('http'),
path = require('path'),
https = require('https'),
Server = require('socket.io'),
url = require('url'),
qs = require('querystring'),
cproc = require("child_process"),
fs = require("fs"),
uuid = require('node-uuid'),
rmdir = require('rimraf');
// internal variables
var app, io, secure, envs;
var cdir = __dirname;
var prefsfile = path.join(cdir, "js9Prefs.json");
var securefile = path.join(cdir, "js9Secure.json");
var fits2png = {};
var fits2fits = {};
var quotacheck = {};
var analysis = {str:[], pkgs:[]};
var plugins = [];
// secure options ... change as necessary in securefile
var secureOpts = {
// key: "path_to_private.key", // openssl genrsa -out file 2014
// cert: "path_to_certificate_file", // from the certificate authority
// ca: "path_to_certificate_authority" // can be a chain file
};
// default options ... change as necessary in prefsfile
var globalOpts = {
helperPort: 2718,
helperHost: "0.0.0.0",
helperOpts: {"maxHttpBufferSize": 10E9},
cmd: "js9helper",
analysisPlugins: "analysis-plugins",
analysisWrappers: "analysis-wrappers",
helperPlugins: "helper-plugins",
maxBinaryBuffer: 150*1024000, // exec buffer: good for 4096^2 64-bit image
maxTextBuffer: 5*1024000, // exec buffer: good for text
textEncoding: "ascii", // encoding for returned stdout from exec
rmWorkDir: true, // remove workdir on disconnect?
remoteMsgs: 1 // 0 => none, 1 => samehost, 2 => all
};
// globalOpts that might need to have paths relative to __dirname
var globalRelatives = ["analysisPlugins",
"analysisWrappers",
"helperPlugins"];
//
// functions that might depend on specific implementations of socket.io
//
// get ip address and port of the current socket or http connection
var getHost = function(io, req){
// socket.io
if( req.handshake ){
return req.client.conn.remoteAddress;
}
// http server
// http:https://stackoverflow.com/questions/19266329/node-js-get-clients-ip
return (req.headers['x-forwarded-for'] || '').split(',')[0] ||
req.connection.remoteAddress;
};
// http:https://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients
var findClientsSocket = function(io, namespace, roomId){
var id, index;
var res = [];
var ns = io.of(namespace ||"/"); // the default namespace is "/"
if(ns){
for(id in ns.connected){
if( ns.connected.hasOwnProperty(id) ){
if(roomId){
index = ns.connected[id].rooms.indexOf(roomId) ;
if(index !== -1){
res.push(ns.connected[id]);
}
} else {
res.push(ns.connected[id]);
}
}
}
}
return res;
};
// get list of all clients currently connected
// eslint-disable-next-line no-unused-vars
var getClients = function(io, socket){
return findClientsSocket(io);
};
// utility functions
// create a nice date/time string for logging
var datestr = function(){
return new Date().toLocaleString(undefined, {hour12: false});
};
// output a log message on the console
var clog = function(){
var args = Array.prototype.slice.call(arguments, 0);
args.push(" [" + datestr() + "]");
// eslint-disable-next-line no-console
console.log.apply(null, args);
};
// output string to log file
// eslint-disable-next-line no-unused-vars
var flog = function(s){
var buffer = new Buffer(s + "\n");
fs.open('tmp/js9node.log', 'a', function(err, fd){
if( fd ){
fs.write(fd, buffer, 0, buffer.length, null,
// eslint-disable-next-line no-unused-vars
function(err, written, bytes){
fs.closeSync(fd);
});
}
});
};
// output an error message on the console
var cerr = function(){
var args = Array.prototype.slice.call(arguments, 0);
args.unshift("ERROR: ");
args.push(" [" + datestr() + "]");
// eslint-disable-next-line no-console
console.log.apply(null, args);
};
// getTargets: identify target(s) for an external msg for a given ip
var getTargets = function(io, socket, msg){
var i, j, c, clip;
var displays;
var browserip = msg.browserip || "*";
var targets = [];
// ip associated with this socket
var myip = getHost(io, socket);
// list of all clients connected on this socket
var clients = getClients(io, socket);
// authentication function
var authenticate = function(myip, clip){
// if I'm localhost, I can send to anyone
if( (myip === "127.0.0.1") || (myip === "::ffff:127.0.0.1") ){
return true;
}
// I can send to myself, if we configured that way
if( (myip === clip) && (globalOpts.remoteMsgs > 0) ){
return true;
}
// security risk: anyone can send to anyone
if( globalOpts.remoteMsgs > 1 ){
return true;
}
// can't send to anyone
return false;
};
// look at all clients
for(i=0; i<clients.length; i++){
// current client
c = clients[i];
// sanity check
if( !c.js9 ){
continue;
}
// client ip
clip = getHost(io, c);
if( !authenticate(myip, clip) ){
continue;
}
// look for matching clients
// pageid is a unique id associated with a specific page
if( msg.pageid ){
if( msg.pageid === c.js9.pageid ){
targets.push(c);
}
} else if( ((browserip === "*") || (browserip === clip)) ){
// look for matches in display id
displays = c.js9.displays;
for(j=0; j<displays.length; j++){
// look for matching displays
if( (msg.id === "*") || (msg.id === displays[j]) ){
targets.push(c);
}
}
}
}
return targets;
};
// connectWorker: identify main socket for this worker
var connectWorker = function(io, socket, pageid){
var i, c, clip;
// ip associated with this socket
var myip = getHost(io, socket);
// list of all clients connected on this socket
var clients = getClients(io, socket);
// sanity check
if( !pageid ){
return null;
}
// look at all clients
for(i=0; i<clients.length; i++){
// current client
c = clients[i];
// check for client with same pageid
if( c.js9 && (c.js9.pageid === pageid) ){
// get client ip
clip = getHost(io, c);
// ip of worker and client must match!
if( myip === clip ){
return c;
}
}
}
return null;
};
// envClean: clean incoming environment variables
// this should match cleaning in js9Helper.cgi
var envClean = function(s) {
if( typeof s === "string" ){
return s.replace(/[`&]/g, "").replace(/\(\)\s*\{.*/g, "");
}
return s;
};
var loadSecurePreferences = function(securefile){
var s, obj, opt;
var secure = false;
if( fs.existsSync(securefile) ){
s = fs.readFileSync(securefile, "utf-8");
if( s ){
try{ obj = JSON.parse(s.toString()); }
catch(e){ cerr("can't parse: ", securefile, e); }
// merge opts into secureOpts
for( opt in obj ){
if( obj.hasOwnProperty(opt) ){
switch(opt){
case "key":
secureOpts.key = fs.readFileSync(obj[opt]);
break;
case "cert":
secureOpts.cert = fs.readFileSync(obj[opt]);
break;
case "ca":
secureOpts.ca = fs.readFileSync(obj[opt]);
break;
default:
cerr("unknown secure option: ", opt);
break;
}
}
}
// if we have a prefs file, we need to have defined required props
if( secureOpts.key && secureOpts.cert ){
secure = true;
} else {
cerr("missing one or more required secure properties");
}
}
}
return secure;
};
// load preference file, if possible
var loadPreferences = function(prefsfile){
var s, obj, opt, otype, jtype;
if( fs.existsSync(prefsfile) ){
s = fs.readFileSync(prefsfile, "utf-8");
if( s ){
try{ obj = JSON.parse(s.toString()); }
catch(e){ cerr("can't parse: ", prefsfile, e); }
// look for globalOpts and merge
if( obj && obj.globalOpts ){
for( opt in obj.globalOpts ){
if( obj.globalOpts.hasOwnProperty(opt) ){
otype = typeof obj.globalOpts[opt];
jtype = typeof globalOpts[opt];
if( (jtype === otype) || (jtype === "undefined") ){
switch(otype){
case "number":
globalOpts[opt] = obj.globalOpts[opt];
break;
case "boolean":
globalOpts[opt] = obj.globalOpts[opt];
break;
case "string":
globalOpts[opt] = obj.globalOpts[opt];
break;
default:
break;
}
}
}
}
}
}
// some directories should be relative to __dirname
globalRelatives.forEach( function(s){
var file = globalOpts[s];
if( file && !path.isAbsolute(file) ){
globalOpts[s] = path.join(cdir, file);
}
});
}
};
// load analysis plugin files, if available
var loadAnalysisTasks = function(dir){
if( fs.existsSync(dir) ){
fs.readdir(dir, function(err, files){
var i, jstr, pathname;
for(i=0; i<files.length; i++){
pathname = dir + "/" + files[i];
if( fs.existsSync(pathname) ){
// only json files, please
if( !pathname.match(/.json$/) ){
continue;
}
analysis.temp = fs.readFileSync(pathname, "utf-8");
if( analysis.temp ){
jstr = analysis.temp.toString().trim();
switch(files[i]){
case "fits2png.json":
try{ fits2png = JSON.parse(jstr); }
catch(e1){cerr("can't parse: ", pathname, e1);}
break;
case "fits2fits.json":
try{ fits2fits = JSON.parse(jstr); }
catch(e1){cerr("can't parse: ", pathname, e1);}
break;
case "quotacheck.json":
try{ quotacheck = JSON.parse(jstr); }
catch(e1){cerr("can't parse: ", pathname, e1);}
break;
default:
try{
analysis.pkgs.push(JSON.parse(jstr));
analysis.str.push(jstr);
}
catch(e2){cerr("can't parse: ", pathname, e2);}
break;
}
}
}
}
});
}
};
// addAnalysisTask: add to the list of analysis tasks sent to browser
var addAnalysisTask = function(obj) {
analysis.pkgs.push(obj);
analysis.str.push("[" + JSON.stringify(obj) + "]");
};
// load user-defined plugins, if possible
var loadHelperPlugins = function(dir){
if( fs.existsSync(dir) ){
fs.readdir(dir, function(err, files){
var i, x, pathname, name;
for(i=0; i<files.length; i++){
pathname = dir + "/" + files[i];
if( fs.existsSync(pathname) ){
// only js files, please
if( !pathname.match(/.js$/) ){
continue;
}
// name of message
name = files[i].replace(/.js$/, "");
try{ x = require(pathname); }
catch(e){ cerr("warning: can't load: ", pathname); }
if( x ){
plugins.push({name: name,
sockio: x.sockio,
http: x.http,
httpList: x.httpList});
}
}
}
});
}
};
// parse an argument string into an array of arguments, where
// spaces and quotes are delimiters
var parseArgs = function(argstr){
var targs, i, j, ci, c1, c2, s;
var args = [];
// temporarily replace spaces inside file extension brackets
// https://stackoverflow.com/questions/16644159/regex-to-remove-spaces-between-and
var nargstr = argstr.replace(/\s+(?=[^[\]]*\])/g, "__sp__");
// split arguments on spaces
targs = nargstr.split(" ");
// now re-combine quoted args into one arg
for(i=0, j=0, ci=-1; i<targs.length; i++){
// remove or rename dangerous characters
s = targs[i].replace(/`/g, "").replace(/&/g, "__ampersand__");
// are we re-combining?
if( ci >= 0 ){
// yes, add to current arg
args[ci] = args[ci] + " " + s;
} else {
// no, add another arg
args[j] = s;
}
if( ci === -1 ){
// new quoted string?
c1 = s.charAt(0);
c2 = s.charAt(s.length-1);
if( c1 === "'" || c1 === '"' ){
// spread across more than one arg, so we need to recombine?
if( c2 === c1 ){
// no just remove the quotes from this one
args[j] = args[j].substr(1,args[j].length-2);
j++;
} else {
// yes
ci = j;
}
} else {
// no
j++;
}
} else {
// end of current quoted string?
c2 = s.charAt(s.length-1);
if( c2 === c1 ){
// yes, remove enclosing quotes
args[ci] = args[ci].substr(1,args[ci].length-2);
ci = -1;
j++;
}
}
}
// now put back the spaces
for(i=0; i<args.length; i++){
args[i] = args[i].replace(/__sp__/g, " ");
}
return args;
};
// get data path
var getDataPath = function(s){
var dpath;
if( s ){
dpath = envClean(s);
} else if( globalOpts.dataPath ){
dpath = envClean(globalOpts.dataPath);
} else {
dpath = "";
}
dpath += ":" + cdir;
return dpath;
};
// see if a file exists in the dataPath
var getFilePath = function(file, dataPath, myenv){
var i, s, froot, fext, parr;
// eslint-disable-next-line no-unused-vars
var repl = function(m, t, o){
if( myenv && myenv[t] ){
return myenv[t];
}
return m;
};
// sanity check
if( !file ){
return;
}
// look for and remove the extension
froot = file.replace(/\[.*]$/,"");
s = file.match(/\[.*]$/,"");
if( s ){
fext = s[0];
} else {
fext = "";
}
if( path.isAbsolute(froot) ){
parr = [""];
} else {
parr = dataPath.split(":");
}
// replace environment variables in path, if possible
for(i=0; i<parr.length; i++){
s = parr[i].replace(/\${?([a-zA-Z][a-zA-Z0-9_()]+)}?/g, repl);
// make up pathname to check
s = path.join(s, froot);
if( fs.existsSync(s) ){
// found the file add extension to full path
s += fext;
return s;
}
}
return;
};
// get size of a file
var getFileSize = function(file){
var stats;
var size = 0;
var froot = file.replace(/\[.*]$/,"");
if( fs.existsSync(froot) ){
stats = fs.statSync(froot);
if( stats ){
size = stats.size;
}
}
return size;
};
//
// message callbacks
//
// execCmd: exec a analysis wrapper function to run a command
// this is the default callback for server-side analysis tasks
var execCmd = function(io, socket, obj, cbfunc) {
var cmd, argstr, args, maxbuf, child, s;
var myworkdir = null;
var myip = getHost(io, socket);
var myid = obj.id;
var myrtype = obj.rtype || "binary";
var myenv = JSON.parse(envs);
var res = {stdout: null, stderr: null, errcode: 0,
encoding: globalOpts.textEncoding};
// sanity check
if( !obj.cmd || !socket.js9 ){
return;
}
// stdin processing
if( obj.stdin && typeof obj.stdin === "object" ){
// first chunk gets sent after process is started (see below),
// otherwise send a new chunk to stdin now and return
socket.js9.child.stdin.write(obj.stdin.data);
// if this was the last chunk, close off stdin and delete child
if( (obj.stdin.cur + obj.stdin.len) >= obj.stdin.total ){
socket.js9.child.stdin.end();
delete socket.js9.child;
}
if( cbfunc ){
res.stdout = "OK";
cbfunc(res);
}
return;
}
// id of js9 display
myenv.JS9_ID = envClean(myid);
// host ip
myenv.JS9_HOST = envClean(myip);
// JS9 base dir
myenv.JS9_DIR = cdir;
// JS9 unique page id
myenv.JS9_PAGEID = socket.js9.pageid;
// js9 cookie in the sending browser
if( obj.cookie ){
myenv.HTTP_COOKIE = envClean(obj.cookie);
}
// datapath (for finding data files)
myenv.JS9_DATAPATH = getDataPath(obj.dataPath);
// set max buffer size
switch(myrtype){
case "text":
case "plot":
case "alert":
maxbuf = globalOpts.maxTextBuffer;
break;
default:
maxbuf = globalOpts.maxBinaryBuffer;
break;
}
// the command string
argstr = obj.cmd || "";
// expand directory macros
argstr = argstr
.replace(/\$\{?JS9_DIR\}?/, cdir)
.replace(/\$\{?JS9_WORKDIR\}?/, (socket.js9.rworkDir || ""));
// split arguments on spaces, respecting quotes
args = parseArgs(argstr);
// handle fitshelper specially
if( args[0] === globalOpts.cmd ){
// if FITS, handle this request internally instead of exec'ing
// (makes external analysis possible without building js9 programs)
if( obj.image && (path.extname(obj.image ) !== ".png") ){
s = getFilePath(obj.image, myenv.JS9_DATAPATH, myenv);
if( s ){
res.stdout = obj.image + " " + s;
}
if( cbfunc ){
cbfunc(res);
}
return;
}
// handle fitshelper specially
cmd = args[0];
} else {
// start in the appropriate work directory, if possible
if( (obj.useWorkDir !== false) && socket.js9 && socket.js9.aworkDir ){
// abdsolute working directory to cd into
myworkdir = socket.js9.aworkDir;
// working directory relative to JS9 dir is for the worker
myenv.JS9_WORKDIR = socket.js9.rworkDir;
myenv.JS9_WORKDIR_QUOTA = globalOpts.workDirQuota;
}
// construct wrapper
cmd = globalOpts.analysisWrappers + "/" + args[0];
// make path absolute in case we change directories
if( cmd.charAt(0) !== "/" ){
cmd = cdir + "/" + cmd;
}
}
// log what we are about to do
clog("exec: %s [%s]", cmd, args.slice(1));
// execute the analysis script with cmd arguments
// NB: can't use exec because the shell breaks, e.g. region command lines
child = cproc.execFile(cmd, args.slice(1),
{ encoding: "utf8",
timeout: 0,
maxBuffer: maxbuf,
killSignal: "SIGTERM",
cwd: myworkdir,
env: myenv
},
// return from exec
function(errcode, stdout, stderr) {
if( errcode ){
res.errcode = errcode.errno || errcode.code;
}
if( stdout ){
switch(myrtype){
case "text":
case "plot":
case "png":
case "alert":
res.stdout = stdout.toString(res.encoding);
break;
default:
res.encoding = "binary";
res.stdout = stdout;
break;
}
}
if( stderr ){
res.stderr = stderr.toString();
}
// send results back to browser
if( cbfunc ){ cbfunc(res); }
});
// first time through: save child for uploading data
if( obj.stdin === true ){
// save child so we can process future chunks of data
socket.js9.child = child;
// set up to send raw data
socket.js9.child.stdin.setEncoding = 'binary';
}
};
// sendAnalysis: send list of analysis routines to browser
var sendAnalysisTasks = function(io, socket, obj, cbfunc) {
var s;
if( analysis && analysis.str.length ){
s = "[" + analysis.str.join(",") + "]";
if( cbfunc ){ cbfunc(s); }
}
};
// pageReady: wait for a Web browser to load a JS9 page and connect
// used by js9Msg.js to start up a Web browser before executing commands
var pageReady = function(io, socket, obj, cbfunc, tries){
var i, targets;
var timeout = obj.timeout || 500;
var maxtries = obj.tries || 10;
// callback function
var myfunc = function(s){
if( cbfunc ){ cbfunc(s); }
};
setTimeout(function(){
// look for targets
targets = getTargets(io, socket, obj);
// if we have at least one ...
if( (targets.length === 1) || obj.multi ){
// send command to JS9 instance(s)
for(i=0; i<targets.length; i++){
targets[i].emit("msg", obj, myfunc);
}
} else {
// no targets: have we tried enough?
if( !targets.length ){
if( tries < maxtries ){
// no, try again
pageReady(io, socket, obj, cbfunc, tries+1);
} else {
// yes, it's an error
if( cbfunc ){
cbfunc("ERROR: timeout waiting for Web page");
}
}
} else {
// it's an error
if( cbfunc ){
cbfunc("ERROR: "+ targets.length +
" JS9 instance(s) found with" +
" id " + obj.id + " (" + obj.cmd+")");
}
}
}
}, timeout);
};
// sendMsg: send a message to the browser
// this is the default callback for external communication with JS9
var sendMsg = function(io, socket, obj, cbfunc) {
var i, targets;
// callback function
var myfunc = function(s){
if( cbfunc ){ cbfunc(s); }
};
// get list of targets to send to
targets = getTargets(io, socket, obj);
// was that all that's wanted?
if( obj.cmd === "targets" ){
myfunc(targets.length);
return;
}
// look for one target (or else that multi is allowed)
if( (targets.length === 1) || obj.multi ){
// send command to JS9 instance(s)
for(i=0; i<targets.length; i++){
targets[i].emit("msg", obj, myfunc);
}
} else {
// no targets: wait for the page to get ready?
if( !targets.length && obj.pageReady ){
pageReady(io, socket, obj, cbfunc, 0);
return;
}
// it's an error
if( cbfunc ){
cbfunc("ERROR: "+targets.length+" JS9 instance(s) found with" +
" id " + obj.id + " (" + obj.cmd+")");
}
}
};
//
// protocol handlers
//
// socketio handler: field socket.io requests
var socketioHandler = function(socket) {
var i, j, m, a;
// function outside loop needed to make jslint happy
var xfunc = function(obj, cbfunc) {
if( !obj ){return;}
// exec the analysis task (via a wrapper function)
execCmd(io, socket, obj, cbfunc);
};
// on disconnect: display a console message
// returns: N/A
// for other implementations, this is needed if you want to:
// show disconnects in the log
socket.on("disconnect", function() {
var myhost = getHost(io, socket);
// only process disconnect for displays (not js9 msgs or workers)
if( socket.js9 && socket.js9.displays && !socket.js9worker ){
clog("disconnect: %s (%s)", myhost, socket.js9.displays);
// clean up working directory
// use sync to prevent Electron.js from exiting too soon
if( socket.js9.aworkDir && globalOpts.rmWorkDir ){
rmdir.sync(socket.js9.aworkDir);
}
}
});
// on displays: set the list of displays for this connection
// returns: unique page id (not currently used)
// for other implementations, this is needed if you want to:
// support sending external messages to JS9 (i.e., via js9 script)
socket.on("initialize", function(obj, cbfunc) {
var myhost = getHost(io, socket);
var basedir, aworkdir, jpath;
if( !obj ){return;}
socket.js9 = {};
socket.js9.displays = obj.displays;
socket.js9.pageid = uuid.v4();
socket.js9.aworkDir = null;
socket.js9.rworkDir = null;
// create top-level workDir, if necessary
// Electron.js might not be in the default location
basedir = globalOpts.workDir;
if( !path.isAbsolute(basedir) ){
basedir = path.join(cdir, basedir);
}
// futz with the case of a link pointing nowhere
try { aworkdir = fs.readlinkSync(basedir); }
catch(e){ aworkdir = basedir; }
if( !fs.existsSync(aworkdir) ){
try{ fs.mkdirSync(aworkdir, parseInt('0755',8)); }
catch(e){}
}
// create workDir for this connection, if possible
if( fs.existsSync(aworkdir) ){
// absolute path of workdir
socket.js9.aworkDir = aworkdir + "/" + socket.js9.pageid;
// relative path of workdir
socket.js9.rworkDir = globalOpts.workDir + "/" + socket.js9.pageid;
try{ fs.mkdirSync(socket.js9.aworkDir, parseInt('0755',8)); }
catch(e){
cerr("can't create page workDir: ", e.message);
socket.js9.aworkDir = null;
socket.js9.rworkDir = null;
}
}
// can we find the helper program?
jpath = !!getFilePath(globalOpts.cmd, process.env.PATH, process.env);
// log results
clog("connect: %s (%s)", myhost, socket.js9.displays);
if( cbfunc ){ cbfunc({pageid: socket.js9.pageid, js9helper: jpath}); }
});
// on display: add a display to the display list
// returns: unique page id (not currently used)
// for other implementations, this is needed if you want to:
// support sending external messages to JS9 (i.e., via js9 script)
socket.on("addDisplay", function(obj, cbfunc) {
if( !obj ){return;}
socket.js9.displays = socket.js9.displays || [];
socket.js9.displays.push(obj.display);
if( cbfunc ){ cbfunc(socket.js9.pageid); }
});
socket.on("worker", function(obj, cbfunc) {
var main;
obj = obj || {};
main = connectWorker(io, socket, obj.pageid);
if( main ){
// connect worker to main
socket.js9 = main.js9;
// signal this is a worker
socket.js9worker = true;
if( cbfunc ){ cbfunc("OK"); }
} else {
if( cbfunc ){ cbfunc("ERROR"); }
}
});
// on alive: return "OK" to signal a valid connection
socket.on("alive", function(obj, cbfunc) {
if( cbfunc ){ cbfunc("OK"); }
});
// on image: signal from JS9 that a new or redisplayed image is active
// returns: [input file path, fits file path, fits + extension]
// for other implementations, this is needed if you want to:
// get FITS filename associated with PNG representation files
// (args 1 and 2 will be identical when imaging FITS files)
socket.on("image", function(obj, cbfunc) {
if( !obj ){return;}
if( globalOpts.cmd ){
// make up js9helper command
obj.cmd = globalOpts.cmd + " -i " + obj.image;
// exec the command
execCmd(io, socket, obj, cbfunc);
}
});
// on getAnalysis: get analysis task definitions
// returns: json string containing analysis task definitions
// for other implementations, this is needed if you want to:
// support default server-side analysis (i.e. exec a wrapper script)
socket.on("getAnalysis", function(obj, cbfunc) {
if( !obj ){return;}
sendAnalysisTasks(io, socket, obj, cbfunc);
});
// on runAnalysis: run an analysis task
// returns: object w/ errcode, stderr (error string), stdout (results)
// for other implementations, this is needed if you want to:
// support default server-side analysis (i.e. exec a wrapper script)
// NB: retained for backward compatibility with old (cached) versions of JS9
socket.on("runAnalysis", function(obj, cbfunc){
if( !obj ){return;}
// exec the analysis task (via a wrapper function)
execCmd(io, socket, obj, cbfunc);
});
// NB: instead of runAnalysis, now we use a handler for each separate task
// returns: object w/ errcode, stderr (error string), stdout (results)
// for other implementations, this is needed if you want to:
// support default server-side analysis (i.e. exec a wrapper script)
for(j=0; j<analysis.pkgs.length; j++){
for(i=0; i<analysis.pkgs[j].length; i++){
a = analysis.pkgs[j][i];
// check for required workDir
if( a.workDir && !globalOpts.workDir ){
continue;
}
// loadproxy must be enabled explicitly
if( a.name === "loadproxy" && !globalOpts.loadProxy ){
continue;
}
m = a.xclass ? (a.xclass + ":" + a.name) : a.name;
socket.on(m, xfunc);
}
}
// on fits2fits: convert raw fits to fits representation file
// returns: object w/ errcode, stderr (error string), stdout (results)
// for other implementations, this is needed if you want to:
// support conversion of fits to fits representation
socket.on("fits2fits", function(obj, cbfunc) {
var myenv, s, size;
var res = {stdout: null, stderr: null, errcode: 0,
encoding: globalOpts.textEncoding};
// sanity checks
if( !fits2fits[0] || !fits2fits[0].action || !obj ){
return;
}
// environment, and datapath (for finding data files)
myenv = JSON.parse(envs);
myenv.JS9_DATAPATH = getDataPath(obj.dataPath);
s = getFilePath(obj.fits, myenv.JS9_DATAPATH, myenv);
if( !s ){
// did not find file, let js9 take care of it
if( cbfunc ){
res.stdout = obj.fits;
cbfunc(res);
}
return;
}
if( obj.maxsize ){
size = getFileSize(s);
if( size < obj.maxsize ){
// file size does not warrant using imsection
if( cbfunc ){
res.stdout = obj.fits;
cbfunc(res);
}
return;
}
}
if( (obj.fits.charAt(0) !== "/") && !obj.fits.match(/^\${JS9_DIR}/) ){
obj.fits = "${JS9_DIR}/" + obj.fits;
}
// make up fits2fits command string from defined fits2fits action
obj.cmd = fits2fits[0].action;
if( obj.parent ){
obj.cmd = obj.cmd + " -parent";
}
obj.cmd = obj.cmd + " " + obj.fits + " " + obj.sect;
// exec the conversion task (via a wrapper function)
execCmd(io, socket, obj, cbfunc);
});
// on fits2png: convert raw fits to png
// returns: object w/ errcode, stderr (error string), stdout (results)
// for other implementations, this is needed if you want to:
// support conversion of fits to png representation
socket.on("fits2png", function(obj, cbfunc) {
if( !obj ){return;}
if( fits2png[0] && fits2png[0].action ){
// make up fits2png command string from defined fits2png action
obj.cmd = fits2png[0].action + " " + obj.fits;
// don't use a workdir
obj.useWorkDir = false;
// exec the conversion task (via a wrapper function)
execCmd(io, socket, obj, cbfunc);
}
});
// on quotacheck: check whether temp directory is set up and under quota
// returns: object w/ errcode, stderr (error string), stdout (results)
// for other implementations, this is needed if you want to:
// allow JS9 to check quota before executing a file-generating task
// (e.g. upload a fits file)
socket.on("quotacheck", function(obj, cbfunc) {
if( !obj ){return;}
if( quotacheck[0] && quotacheck[0].action ){
// make up quotacheck command string from defined quotacheck action
obj.cmd = quotacheck[0].action;
obj.rtype = quotacheck[0].rtype;
// exec the task (via a wrapper function)
execCmd(io, socket, obj, cbfunc);
}
});