-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine_merge.js
1412 lines (1138 loc) · 33.6 KB
/
engine_merge.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
// UNCLASSIFIED
/**
* @class ENGINE
* @requires child_process
* @requires fs
* @requires engineIF
* @requires enum
* @requires jslab
* @requires vm
*/
var // NodeJS modules
CP = require("child_process"),
FS = require("fs"),
CLUSTER = require("cluster"),
NET = require("net"),
VM = require("vm");
var // Totem modules
ENUM = require("enum"),
Copy = ENUM.copy,
Each = ENUM.each,
Log = console.log,
ENV = process.env;
var
ENGINE = module.exports = Copy( //< extend the engineIF built by node-gyp
require("./ifs/build/Release/engineIF"), {
/**
@cfg {Object}
@private
@member ENGINE
Paths to various things.
*/
paths: {
jobs: "./jobs/"
},
/**
@cfg {Function}
@private
@member ENGINE
@method thread
Start a sql thread
*/
thread: null,
/**
@cfg {Number}
@member ENGINE
Number of worker cores (aka threads) to provide in the cluster. 0 cores provides only the master.
*/
cores: 0, //< number if cores: 0 master on port 8080; >0 master on 8081, workers on 8080
/**
@cfg {Number}
@private
Next available core
*/
nextcore: 0,
matlab: {
path: {
save: "./public/matlab/",
agent: "http://totem.west.ile.nga.ic.gov:8080/matlab"
},
flush: function (sql,qname) {
var
agent = ENGINE.matlab.path.agent,
func = qname,
path = ENGINE.matlab.path.save + func + ".m",
script = `disp(webread('${agent}?flush=${qname}'));` ;
Trace("FLUSH MATLAB");
sql.query("INSERT INTO openv.matlab SET ?", {
queue: qname,
script: script
}, function (err) {
sql.query("SELECT * FROM openv.matlab WHERE ? ORDER BY ID", {
queue: qname
}, function (err,recs) {
FS.writeFile( path, recs.joinify("\n", function (rec) {
return rec.script;
}), "utf8" );
sql.query("DELETE FROM openv.matlab WHERE ?", {
queue: qname
});
});
});
},
queue: function (qname, script) {
ENGINE.thread( function (sql) {
sql.query("INSERT INTO openv.matlab SET ?", {
queue: qname,
script: script
}, function (err) {
Log("matlab queue", err);
});
sql.release();
});
}
},
/**
@cfg {Object}
@method config
@member ENGINE
Configure are start the engine interface, estblish worker core connections
*/
config: function (opts) { // configure with options
Trace(`CONFIG ENGINES`);
if (opts) Copy(opts,ENGINE);
if (CLUSTER.isMaster) {
/*var ipcsrv = NET.createServer( function (c) {
L("srv got connect");
c.on("data", function (d) {
L("srv got data",d);
});
c.on("end", function () {
L("srv got end");
});
//c.pipe(c);
//c.write("your connected");
});
ipcsrv.listen("/tmp/totem.sock");*/
/*
var sock = ENGINE.ipcsocket = NET.createConnection("/tmp/totem.sock", function () {
console.log("connected?");
});
sock.on("error", function (err) {
console.log("sockerr",err);
});
sock.on("data", function (d) {
console.log("got",d);
}); */
}
if (thread = ENGINE.thread)
thread( function (sql) { // compile engines defined in engines DB
ENGINE.matlab.flush(sql, "init_queue");
ENGINE.matlab.flush(sql, "step_queue");
// Using https generates a TypeError("Listener must be a function") at runtime.
process.on("message", function (req,socket) { // cant use CLUSTER.worker.process.on
if (req.action) { // process only our messages (ignores sockets, etc)
if (CLUSTER.isWorker) {
console.log("CORE"+CLUSTER.worker.id+" GRABBING "+req.action);
//console.log(req);
if ( route = ENGINE[req.action] )
ENGINE.thread( function (sql) {
req.sql = sql;
//delete req.socket;
route( req, function (tau) {
console.log( "sending " + JSON.stringify(tau));
sql.release();
socket.end( JSON.stringify(tau) );
});
});
else
socket.end( ENGINE.errors.badRequest+"" );
}
else {
}
}
});
});
return ENGINE;
},
flex: null,
/**
@cfg {Object}
@member ENGINE
Modules to share accross all js-engines
*/
plugins: { // js-engine plugins
},
/**
@cfg {Object}
@private
@member ENGINE
Error messages
*/
errors: { // error messages
0: null,
101: new Error("engine could not be loaded"),
102: new Error("engine received bad port/query"),
103: new Error("engine port invalid"),
104: new Error("engine failed to compile"),
105: new Error("engine exhausted thread pool"),
106: new Error("engine received bad arguments"),
badType: new Error("engine type not supported"),
badPort: new Error("engine provided invalid port"),
badError: new Error("engine returned invalid code"),
lostContext: new Error("engine context lost"),
badEngine: new Error("engine does not exist, is disabled, has invalid context, or failed to compile"),
badStep: new Error("engine step faulted"),
badContext: new Error("engine context invalid"),
badRequest: new Error("engine worker handoff failed")
},
context: {}, // engine contexts
vm: {}, // js-machines
tau: function (job) { // default event token sent to and produced by engines in workflows
return new Object({
job: job || "", // Current job thread N.N...
work: 0, // Anticipated/delivered data volume (dims, bits, etc)
disem: "", // Disemination channel for this event
classif: "", // Classification of this event
cost: "", // Billing center
policy: "", // Data retention policy (time+place to hold, method to remove, outside disem rules)
status: 0, // Status code (health, purpose, etc)
value: 0 // Flow calculation
});
},
program: function (sql, ctx, cb) { //< callback cb(ctx) with programed engine context or null if error
var runctx = ctx.req.query;
if ( initEngine = ctx.init )
ENGINE.prime(sql, runctx, function (runctx) { // mixin sql vars into engine query
//Log("eng prime", ctx.thread, runctx);
if (runctx)
initEngine(ctx.thread, ctx.code || "", runctx, function (err) {
//Log("eng init", err);
cb( err ? null : ctx );
});
else
cb( null );
});
else
cb( null );
},
run: function (req, cb) { // callback cb(ctx, step) with its engine context and stepper, or with nulls if error.
/*
Request must contain:
req = { group, table, client, query, body, action, state }
If the engine's req.state is not provided, then the engine is programmed; otherwise it is stepped.
Allocate the supplied callback cb(core) with the engine core that is/was allocated to a Client.Engine.Type.Instance
thread as defined by this request (in the req.body and req.log). If a workflow Instance is
provided, then the engine is assumed to be in a workflow (thus the returned core will remain
on the same compile-step thread); otherwise, the engine is assumed to be standalone (thus forcing
the engine to re-compile each time it is stepped).
As used here (and elsewhere) the terms "process", "engine core", "safety core", and "worker" are
equivalent, and should not be confused with a physical "cpu core". Because heavyweight
(spawned) workers run in their own V8 instance, these workers can tollerate all faults (even
core-dump exceptions). The lightweight (cluster) workers used here, however, share the same V8
instance. Heavyweight workers thus provide greater safety for bound executables (like opencv and
python) at the expense of greater cpu overhead.
The goal of hyperthreading is to balance threads across cpu cores. The workerless (master only)
configuration will intrinsically utilize only one of its underlying cpu cores (the OS remains,
however, free to bounce between cpu cores via SMP). A worker cluster, however, tends to
balance threads across all cpu cores, especially when the number of allocated workers exceeds
the number of physical cpu cores.
Only the cluster master can see its workers; thus workers can not send work to other workers, only
the master can send work to workers. Thus hyperthreading to *stateful* engines can be supported
only when master and workers are listening on different ports (workers are all listening on
same ports to provide *stateless* engines). So typically place master on port N+1 (to server
stateful engines) and its workers on port N (to serve stateless engines).
This method will callback cb(core) with the requested engine core; null if the core could not
be located or allocated.
*/
var
sql = req.sql,
query = req.query,
client = req.client.replace(".ic.gov","").replace(/\./g,"").replace("@",""),
thread = `${client}.${req.table}.${query.ID || 0}`;
//Log("def eng thread", thread, req.query);
function CONTEXT (thread) { // engine context constructor for specified thread
this.worker = CLUSTER.isMaster
? ENGINE.cores
? CLUSTER.workers[ Math.floor(Math.random() * ENGINE.cores) ] // assign a worker
: 0 // assign to master
: CLUSTER.worker; // use this worker
this.thread = thread;
this.req = null;
/*
var sock = this.socket = NET.connect("/tmp/totem."+thread+".sock");
sock.on("data", function (d) {
console.log("thread",this.thread,"rx",d);
});
sock.write("hello there");*/
}
function execute(ctx, cb) { //< callback cb(ctx,stepcb) with revised engine ctx and stepper
var
sql = req.sql,
query = ctx.req.query,
body = ctx.req.body,
port = body.port || "",
runctx = body.tau || Copy( req.query, query);
//Log("exe ctx",runctx);
cb( runctx, function (res) { // callback engine using this stepper
if ( stepEngine = ctx.step )
ENGINE.prime(sql, runctx, function (runctx) { // mixin sql vars into engine query
//Log("prime ctx", runctx);
try { // step the engine then return an error if it failed or null if it worked
return ENGINE.errors[ stepEngine(ctx.thread, port, runctx, res) ] || ENGINE.badError;
}
catch (err) {
return err;
}
});
else
return ENGINE.errors.badEngine;
});
}
function handoff(ctx, cb) { //< handoff ctx to worker or cb(null) if handoff fails
var
ipcreq = { // ipc request must not contain sql, socket, state etc
group: req.group,
table: req.table,
client: req.client,
query: req.query,
body: req.body,
action: req.action
};
if ( CLUSTER.isWorker ) // handoff thread to master
process.send(ipcreq, req.resSocket() );
else
if ( worker = ctx.worker ) //handoff thread to worker
worker.send(ipcreq, req.resSocket() );
else // cant handoff
cb( null );
}
function initialize(ctx, cb) { //< initialize engine then callback cb(ctx,stepper) or cb(null) if failed
var
sql = req.sql;
//Log("eng init",req.query);
ENGINE.getEngine(req, ctx, function (ctx) {
//Log("get eng", ctx);
if (ctx)
ENGINE.program(sql, ctx, function (ctx) { // program/initialize the engine
//Log("pgm eng", ctx);
if (ctx) // all went well so execute it
execute( ctx, cb );
else // failed to compile
cb( null );
});
else
cb( null );
});
}
Log("eng thread", thread, CLUSTER.isMaster ? "on master" : "on worker", ENGINE.context[thread] ? "has ctx":"needs ctx");
if ( CLUSTER.isMaster ) { // on master so handoff to worker or execute
if ( ctx = ENGINE.context[thread] ) // get context
if (ENGINE.cores) // handoff to worker
handoff( ctx, cb );
else
if ( ctx.req ) // was sucessfullly initialized so execute it
execute( ctx, cb );
else // never initialized so reject it
cb( null );
else { // assign a worker to new context then handoff or initialize
var ctx = ENGINE.context[thread] = new CONTEXT(thread);
if (ENGINE.cores)
handoff( ctx, cb );
else
initialize( ctx, cb );
}
}
else { // on worker
if ( ctx = ENGINE.context[thread] ) { // run it if worker has an initialized context
Trace( `RUN core-${ctx.worker.id} FOR ${ctx.thread}`, sql );
if ( ctx.req ) // was sucessfullyl initialized so can execute it
execute( ctx, cb );
else // had failed initialization so must reject
cb( null );
}
else { // worker must initialize its context, then run it
var ctx = ENGINE.context[thread] = new CONTEXT(thread);
Trace( `INIT core-${ctx.worker.id} FOR ${ctx.thread}` );
initialize( ctx, cb );
}
}
},
save: function (sql,taus,port,engine,saves) {
/**
* @method save
* @member ENGINE
*
* Save tau job files.
*/
var t = new Date();
Each(taus, function (n,tau) {
if (tau.job) {
var hasjpg = FS.existsSync(tau.job+".jpg");
var log = hasjpg ? {jpg: "jpg".tag("a",{href:tau.job+".jpg"})} : {};
FS.readFile(tau.job+".json", {encoding: "utf8"}, function (err,data) {
if (!err) {
var rtn = data.parse({});
Each(saves.split(","), function (i,save) {
if (save in rtn)
switch (save) {
case "file":
case "jpg":
log[save] = "jpg".tag("a",{href:rtn[save]});
break;
default:
log[save] = rtn[save];
}
});
}
Each( log, function (logn,logv) {
sql.query("INSERT INTO simresults SET ?", {
t: t,
input: tau.job,
output: `${engine}.${port}`,
name: logn,
value: logv,
special: logv
});
});
});
}
});
},
returns: function (context) { //< legacy
/**
* @method returns
* Return tau parameters in matrix format
* */
var tau = context.tau || [];
return tau;
if (tau.constructor == Array) {
for (var n=0,N=tau.length; n<N; n++)
switch ( tau[n].constructor ) {
case Array:
var fix = {};
for (var m=0,M=tau[n].length; m<M; m++)
fix['tau'+m] = tau[n][m];
tau[n] = fix;
break;
case Object:
break;
default:
tau[n] = {tau: JSON.stringify(tau[n])};
}
return tau;
}
else
return [{tau: JSON.stringify(tau)}];
},
/**
@method insert(step)
@method delete(kill)
@method select(read)
@method update(init)
Provides engine CRUD interface: step/insert/POST, compile/update/PUT, run/select/GET, and
free/delete/DELETE.
*/
insert: function (req,res) { // step a stateful engine
ENGINE.run(req, function (ctx,step) {
//Log(">step ",ctx);
if ( ctx )
step( res );
else
res( ENGINE.errors.badThread );
});
},
delete: function (req,res) { // free a stateful engine
ENGINE.run(req, function (ctx,step) {
//Log(">kill ",ctx);
res( ctx ? "" : ENGINE.errors.badThread );
});
},
select: function (req,res) { // run a stateless engine
ENGINE.run( req, function (ctx, step) {
//Log(">run", ctx);
if (ctx)
step( res );
else
res( ENGINE.errors.badEngine );
});
},
update: function (req,res) { // compile a stateful engine
ENGINE.run( req, function (ctx,step) {
//console.log(">init",ctx);
res( ctx ? "" : ENGINE.errors.badThread );
});
},
prime: function (sql, ctx, cb) { //< callback cb(ctx) with ctx primed by sql ctx.entry and ctx.exit queries
/**
@method prime
Callback engine cb(ctx) with its state ctx primed with state from its ctx.entry, then export its
ctx state specified by its ctx.exit.
The ctx.sqls = {var:"query...", ...} || "query..." enumerates the engine's ctx.entry (to import
state into its ctx before the engine is run), and enumerates the engine's ctx.exit (to export
state from its ctx after the engine is run). If an sqls entry/exit exists, this will cause the
ctx.req = [var, ...] list to be built to synchronously import/export the state into/from the
engine's context.
* */
var keys = ctx.keys;
if (keys) { // enumerate over each sql key
if ( keys.length ) { // more keys to import/export
var
key = keys.pop(), // var to import/export
query = ctx.sqls[key]; // sql query to import/export
if (typeof query != "string") {
query = query[0];
args = query.slice(1);
}
//Trace([key,query]);
if (ctx.sqls == ctx.entry) { // importing this var into the ctx
var data = ctx[key] = [];
var args = ctx.query;
}
else { // exporting this var from the ctx
var data = ctx[key] || [];
var args = [key, {result:data}, ctx.query];
}
//Trace(JSON.stringify(args));
sql.query(query, args, function (err, recs) { // import/export this var
//Trace([key,err,q.sql]);
if (err) {
//ctx.err = err;
ctx[key] = null;
}
else
if (ctx.sqls == ctx.entry) // importing matrix
recs.each( function (n,rec) {
var vec = [];
data.push( vec );
for ( var x in rec ) vec.push( rec[x] );
});
else { // exporting matrix
}
ENGINE.prime(sql,ctx,cb);
});
}
else // no more keys to load
if (cb) { // run engine in its ctx
cb(ctx);
if (ctx.exit) { // save selected engine ctx keys
var sqls = ctx.sqls = ctx.exit;
var keys = ctx.keys = []; for (var n in sqls) keys.push(n);
ENGINE.prime(sql,ctx);
}
}
}
else
if (ctx.entry) { // build ctx.keys from the ctx.entry sqls
var sqls = ctx.sqls = ctx.entry;
if (sqls.constructor == String) // load entire ctx
sql.query(sqls)
.on("result", function (rec) {
cb( Copy(rec, ctx) );
});
else { // load specific ctx keys
var keys = ctx.keys = [];
for (var key in sqls) keys.push(key);
}
ENGINE.prime(sql, ctx, cb);
}
else
cb(ctx);
},
getEngine: function (req, ctx, cb) { //< callback cb(ctx) with engine context or null if failed
var
sql = req.sql,
group = req.group,
name = req.table;
sql.query(
"SELECT * FROM ??.engines WHERE least(?) LIMIT 0,1", [ group, {
Name: name,
Enabled: true
}], function (err, engs) {
if (err)
cb( null );
else
if ( isEmpty = engs.each() )
cb( null );
else
try { // return full engine context
var eng = engs[0];
cb( Copy({
req: { // http request
group: req.group,
table: req.table,
client: req.client,
query: JSON.parse(eng.State || "null") || {},
body: req.body,
action: req.action
},
type: eng.Type,
code: eng.Code,
init: ENGINE.init[ eng.Type ],
step: ENGINE.step[ eng.Type ]
}, ctx) );
}
catch (err) {
cb( null );
}
});
},
gen: { // controls code generation during init
debug: false,
trace: false,
dbcon: {
user: ENV.DB_USER,
name: ENV.DB_NAME,
pass: ENV.DB_PASS
},
db: true,
libs: true,
code: true
},
init: { // program engines on given thread with flush-load-save-script logic
py: function pyInit(thread,code,ctx,cb) {
function portsDict(portsHash) {
var ports = Object.keys( portsHash );
ports.each( function (n,port) {
ports[n] = port + ":" + port;
});
return "{" + ports.join(",") + "}";
}
var
Thread = thread.split("."),
Thread = {
case: Thread.pop(),
plugin: Thread.pop(),
client: Thread.pop()
},
script = "",
gen = ENGINE.gen,
ports = portsDict( ctx.ports || {} ),
logic = {
flush: {
all: `
def flush(ctx,rec,recs):
return False`,
none:`
def flush(ctx,rec,recs):
return True`,
byTime: `
def flush(ctx,rec,recs):
if len(recs):
return (rec[ 't' ] -recs[0][ 't' ] ) > ctx.Job.buffer
else:
return False`,
byDepth: `
def flush(ctx,rec,recs):
return len(recs) < ctx.Job.buffer`
},
save: `
def save(ctx): #save jpg/json/event results
if ctx:
if 'Dump' in ctx:
Query = ctx['Dump']
if 'Save' in ctx:
Data = ctx['Save']
if Query.endswith(".jpg"):
Data.save(Query, "jpg")
elif Query.endswith(".json"):
fid = open(Query, "w")
fid.write( JSON.dumps( Data ) )
fid.close()
elif Query:
SQL0.execute(Query,Data)
`,
load: `
def load(ctx, os, cb): #load jpg/json/event dataset
SQL = os['SQL']
os['SQL0'] = SQL.cursor(buffered=True)
os['SQL1'] = SQL.cursor(buffered=True)
if 'Load' in ctx:
Query = ctx['Load']
if Query.endswith(".jpg"):
cb( LWIP.open(Query), os )
elif Query.endswith(".json"):
cb( JSON.loads(Query), os )
elif Query.startswith("/"):
recs = []
for (rec) in FETCH(query):
if flush(ctx,rec,recs):
print "FLUSH", len(recs)
cb( recs, os )
recs = []
recs.append(rec)
print "FLUSH", len(recs)
cb( recs, os )
elif Query:
recs = []
SQL0.execute(Query)
for (rec) in SQL0:
if flush(ctx,rec,recs):
print "FLUSH", len(recs)
cb( recs, os )
recs = []
recs.append(rec)
print "FLUSH", len(recs)
cb( recs, os )
else:
cb( 0, os )
else:
cb( 0, os )
` },
Job = ctx.Job || {},
flush = logic.flush[Job.flush |= ""] || logic.flush.all,
script = "";
Job.buffer |= 0;
if (gen.libs) { script += `
if INIT:
#import modules
#import caffe as CAFFE #caffe interface
import mysql.connector as SQLC #db connector interface
from PIL import Image as LWIP #jpeg image interface
import json as JSON #json interface
import sys as SYS #system info
` }
if (gen.db) { script += `
if INIT:
#connect to db
SQL = SQLC.connect(user='${gen.dbcon.user}', password='${gen.dbcon.pass}', database='${gen.dbcon.name}')
` }
if (gen.debug) { script += `
#trace engine context
print 'py>locals', locals()
print 'py>sys', SYS.path, SYS.version
#print 'py>caffe',CAFFE
#print 'py>sql', SQL
print 'py>ctx',CTX
print 'py>port',PORT
` }
if (gen.code) { script += `
# record buffering logic
${flush}
# data saving logic
${logic.save}
# data loading logic
${logic.load}
# engine and port logic
${code}
PORTS = ${ports}
def loadcb(req, os):
#print "loadcb", os['SQL']
port = os['PORT']
ports = os['PORTS']
ctx = os['CTX']
plugin = os['${Thread.plugin}']
os['REQ'] = req
if port:
if port in ports:
return ports[port](req,ctx['ports'][port])
else:
return 103
else:
plugin(ctx,os)
save(ctx)
return 0
if INIT:
INIT = 0;
else:
os = locals()
print "os", os # why is this dump required to make sql connector visibile to plugin ?
load(CTX, os, loadcb)
` }
if (false) { script += `
#exit code
SQL.commit()
SQL0.close()
SQL1.close()
` }
/*
mysql connection notes:
install the python2.7 connector (rpm -Uvh mysql-conector-python-2.x.rpm)
into /usr/local/lib/python2.7/site-packages/mysql, then copy
this mysql folder to the anaconda/lib/python2.7/site-packages.
import will fail with mysql-connector-python-X installed (rum or rpm installed as root using either
python 2.2 or python 2.7). Will however import under python 2.6. To fix, we must:
cp -R /usr/lib/python2.6/site-packages/mysql $CONDA/lib/python2.7/site-packages
after "rpm -i mysql-connector-python-2.X".
For some reaon, only two sql cursors are allowed.
*/
if (gen.trace) Log(script);
cb( ENGINE.python(thread,script,ctx), ctx );
},
cv: function cvInit(thread,code,ctx,cb) {
var
Thread = thread.split("."),
Thread = {
case: Thread.pop(),
plugin: Thread.pop(),
client: Thread.pop()
},
gen = ENGINE.gen,
script = "",
logic = {
flush: "",
save: "",
load: "",
code: code,
startup: ""
};
if ( ctx.frame && ctx.detector )
if ( err = ENGINE.opencv(thread,code,ctx) )
cb( null, ctx );
else
cb( null, ctx );
else
cb( ENGINE.errors.badContext, ctx );
},
js: function jsInit(thread,code,ctx,cb) {
var
Thread = thread.split("."),
Thread = {
case: Thread.pop(),
plugin: Thread.pop(),
client: Thread.pop()
},
gen = ENGINE.gen,
script = "",
logic = {
flush: {
all: function flush(ctx,rec,recs) {
return false;
},
none: function flush(ctx,rec,recs) {
return true;
},
byTime: function flush(ctx,rec,recs) {
return recs.length ? (rec.t - recs[0].t) > ctx.Job.buffer : false;
},
byDepth: function flush(ctx,rec,recs) {
return recs.length < ctx.Job.buffer;
}
},
save: function save(ctx, cb) {
var Data = ctx.Save;
if ( Query = ctx.Dump ) { // the RES was already issued so save results to db w/o RES
if ( Query.endsWith(".json") )
FS.writeFile( Query, JSON.stringify(Data) );
else