diff --git a/code/common/dbwriteutils.q b/code/common/dbwriteutils.q index 97a997fb5..35e122971 100644 --- a/code/common/dbwriteutils.q +++ b/code/common/dbwriteutils.q @@ -85,7 +85,7 @@ postreplay:@[value;`postreplay;{[d;p] }]; \d .gc / - format the process memory stat's into a string for logging -memstats:{"mem stats: ",{"; "sv "=" sv'flip (string key x;(string value x),\:" MB")}`long$.Q.w[]%1048576} +memstats:{"mem stats: ",$[.proc.capabilities`memstats;{"; "sv "=" sv'flip (string key x;(string value x),\:" MB")}`long$.Q.w[]%1048576;"not available on this engine"]} / - run garbage collection and log out memory stats run:{ diff --git a/code/common/engine.q b/code/common/engine.q new file mode 100644 index 000000000..7bfd2c5a5 --- /dev/null +++ b/code/common/engine.q @@ -0,0 +1,191 @@ +\d .proc +// engine.q - which q engine TorQ is running on, and what that engine can do +// TorQ runs on kdb+, L, PeachQ and Korze. torq.q loads this file first, so the engine is known before anything else; +// it is loaded again with the rest of code/common, where init finds the capabilities already set and does nothing. +// The engine can be given on start-up with -engine (kdb, l, peachq or korze) or the KDBENGINE environment variable; +// otherwise it is detected only once. + +// set everything up, in order: the engine, its name and version, then the capabilities dict. +// Runs once: when this file is loaded again (with the rest of code/common), the capabilities are already set +init:{[] + if[`capabilities in key `.proc; + :() + ]; + .proc.engine:getengine[]; + .proc.enginename:$[engine=`kdb; + $[5<=.z.K;"KDB-X";"kdb+"]; + engine=`l;enlist "L"; + engine=`peachq;"PeachQ"; + engine=`korze;"Korze";"unknown q engine"]; + + .proc.engineversion:$[engine=`peachq; + @[{$[10h=type v:value x;v;string v]};`.pq.version;(string .z.K)," ",string .z.k]; + (string .z.K)," ",string .z.k]; + + // compute capabilities dict once + .proc.capabilities:$[engine=`kdb; + versioncapabilities[.z.K;.z.k]; + probecapabilities[] + ]; + } + +//gets engine used (kdb, l or peachq) +getengine:{[] + //get engine given on start-up or KDBENGINE environment variable if given + cmdlineopts:.Q.opt .z.x; + + requested:$[`engine in key cmdlineopts; + first cmdlineopts`engine; + $[count e:getenv`KDBENGINE;e;""] + ]; + if[count requested; + :`$lower trim requested + ]; + + //detect engine (kdb, l, peachq or korze) + //.z.KK names the engine where it is defined (Korze has it; on kdb+ it is an error, hence the trap) + if[-11h=type e:@[value;".z.KK";0b]; + :e + ]; + //l: .z.L is a number + if[(type @[value;".z.L";`]) in -9 -8 -7 -6 -5h; + :`l + ]; + if[`version in key `.pq; + :`peachq + ]; + //kdb+: a licence in .z.l (trapped: older kdb+ has no .z.l), or a free 32-bit edition, where .z.l is empty + :$[any(@[{0 '",pipe,"') >/dev/null 2>&1 &"; + .proc.probecount:0; + result:@[{-11!hsym`$x; 1b};pipe;0b]; + // stop the feeder if nothing read the pipe ("[t]": pkill must not match itself) + system "pkill -f '",ssr[dir;"torqprobe";"[t]orqprobe"],"' ; true"; + result and 2=.proc.probecount + } + } + + + +// --------------------------------------------------------------------------------------------------------------------- +// Features. TorQ checks these instead of .z.K, so a new engine, or a new release of one, is picked up without changes. +// For kdb+ we check the release which introduced the feature (versioncapabilities) +// any other engine each feature is tried in a trap: if it runs the engine has it, any error means it does not +// (the table comes after the probes: q builds it when the file is loaded, so the probes must already exist) + +// feature - what TorQ checks +// kdbK - the kdb+ release which introduced it, with the date it first worked where the release was not enough (0Nd: no date) +// atstart - 1b: checked when TorQ starts; 0b: checked by supports the first time it is asked for +// probe - the name of the function in .proc which checks it on any other engine, 1b if it works +features:flip `feature`kdbK`kdbdate`atstart`probe!flip ( + / feature kdbK kdbdate atstart probe used in + (`broadcast; 3.4; 0Nd; 1b; `probebroadcast); / -25! broadcast publish u.q, pubsub.q + (`deferred; 3.6; 0Nd; 1b; `probedeferred); / -30! deferred sync responses gateway.q + (`unixsockets; 3.4; 0Nd; 1b; `probeunixsockets); / unix domain sockets trackservers.q + (`reval; 3.3; 0Nd; 1b; `probereval); / reval, to block writes writeaccess.q + (`hval; 3.5; 2019.11.13; 1b; `probehval); / .z.ph evaluates requests with .h.val permissions.q + (`pipereplay; 4.0; 0Nd; 0b; `probepipereplay); / -11! replay from a named pipe tickerlogreplay.q + (`memstats; 2.0; 0Nd; 1b; `probememstats)) / .Q.w[] memory statistics dbwriteutils.q, monitoringchecks.q, memoryusage.q + +// run f with a scratch directory, which is removed afterwards (q creates it when the first file is written) +withscratch:{[f] + candidates:(getenv each `TMPDIR`TEMP`TMP),enlist "/tmp"; / macOS and Linux set TMPDIR, Windows TEMP + tmp:ssr[first candidates where 0=kdbK) and k>=kdbdate) from features + } + +// for any other engine than kdb, try each feature checked at start-up +probecapabilities:{[] + {[found;f;p] found,(enlist f)!enlist 1b~@[p;found;0b]}/[(`symbol$())!`boolean$(); + exec feature from features where atstart; + .proc exec probe from features where atstart] + } + +// feature -> 1b/0b: from the capabilities, or checked the first time it is asked for (pipereplay) and remembered; +// 0b for a name which is not a feature +supports:{[name] + if[11h=type name; + :.proc.supports each name]; + if[not name in key capabilities; + // a name that is not in the features table is not supported + if[not count probes:.proc exec probe from features where feature=name; + :0b]; + .proc.capabilities:capabilities,(enlist name)!enlist 1b~@[first probes;capabilities;0b] + ]; + capabilities name + } + + +// show engine, version and capabilities +logengine:{[] + .lg.o[`init;"q engine ",enginename," ",engineversion,", capabilities: ",", " sv {string[x],"=",string y}'[key capabilities;value capabilities]] + } + +init[]; + +\d . + +// kdb+'s alphabet constants, on an engine which does not define them (Korze has .Q.n and .Q.an but no .Q.A or .Q.a) +if[not `A in key `.Q; .Q.A:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; .Q.a:lower .Q.A]; diff --git a/code/common/grafana.q b/code/common/grafana.q index 7a66378e8..08d2bb021 100644 --- a/code/common/grafana.q +++ b/code/common/grafana.q @@ -12,7 +12,9 @@ ticks:@[value;`.grafana.ticks;1000]; del:@[value;`.grafana.del;"."]; // json types of kdb datatypes -types:.Q.t!`array`boolean,(3#`null),(5#`number),11#`string; +// (.Q.t!`array`boolean,(3#`null),(5#`number),11#`string)~.Q.t!(count .Q.t)#`array`boolean,(3#`null),(5#`number),11#`string on kdb,peachQ +// .Q.t!`array`boolean,(3#`null),(5#`number),11#`string throws 'length on L version 1 2026.11.01 +types:.Q.t!(count .Q.t)#`array`boolean,(3#`null),(5#`number),11#`string; // milliseconds between 1970 and 2000 epoch:946684800000; diff --git a/code/common/monitoringchecks.q b/code/common/monitoringchecks.q index 609693a7d..4c8731577 100644 --- a/code/common/monitoringchecks.q +++ b/code/common/monitoringchecks.q @@ -27,6 +27,7 @@ hdbdatecheck:{[date; tablelist] memorycheck:{[size] .checks.errs::(); + if[not .proc.capabilities`memstats; :([]messages:enlist "memory check not available on this engine: it has no .Q.w")]; if [size < (.Q.w[]`heap) + .Q.w[]`symw; .checks.errs,:"This process exceeded the warning level of ",numformat[size]," bytes of allocated memory at ",timeformat[],"
"; @@ -37,6 +38,7 @@ memorycheck:{[size] symwcheck:{[size] .checks.errs::(); + if[not .proc.capabilities`memstats; :([]messages:enlist "symbol memory check not available on this engine: it has no .Q.w")]; if [(h:.Q.w[]`symw) > size; .checks.errs,:"This process exceeded the warning for symbol size of ",numformat[size]," bytes at ",timeformat[],"
"; diff --git a/code/common/pubsub.q b/code/common/pubsub.q index 5878728b0..f351382ea 100644 --- a/code/common/pubsub.q +++ b/code/common/pubsub.q @@ -82,6 +82,21 @@ pub:{[t;x] ]; }; +// Publish table data on an engine without -25! (broadcast): the same, with one message per subscriber +pubeach:{[t;x] + if[not count x;:()]; + if[count h:subrequestall[t];neg[h]@\:(`upd;t;x)]; + if[t in .stpps.subrequestfiltered`tbl; + {[t;x;sels] data:eval(?;x;sels`filts;0b;sels`columns); + if[count data;neg[sels`handle](`upd;t;data)]}[t;x;] + each select handle,filts,columns from .stpps.subrequestfiltered where tbl=t + ]; + }; + +// Chosen once, at load, so no publish pays for the check: kdb+ (and any engine with -25!) keeps pub, any other uses +// pubeach. It must stay above .u.pub:.stpps.pub and .ps.publish:.stpps.pub, which copy pub when this file loads +if[not @[{.proc.capabilities`broadcast};::;1b]; pub:pubeach]; + // publish and clear tables pubclear:{ .stpps.pub'[x;value each x,:()]; diff --git a/code/common/u.q b/code/common/u.q index a49347b87..e18c8fdc7 100644 --- a/code/common/u.q +++ b/code/common/u.q @@ -21,7 +21,7 @@ sub:{if[x~`;:sub[;y]each t];if[not x in t;'x];del[x].z.w;add[x;y]} end:{(neg union/[w[;;0]])@\:(`.u.end;x)} // broadcasting. will override .u.pub with -25! -if[broadcast and .z.K>=3.4; +if[broadcast and .proc.capabilities`broadcast; // group subscribers by their sym subscription pub_broadcast:{[t;x] subgroups:flip (w[t;;0]@/:value g;key g:group w[t;;1]); diff --git a/code/dqc/advanceddtd.q b/code/dqc/advanceddtd.q index a3e124db2..c6c58825e 100644 --- a/code/dqc/advanceddtd.q +++ b/code/dqc/advanceddtd.q @@ -11,9 +11,10 @@ advancedsymdtd:{[tab;func;vars] /- a utility function for the conditional f:{" "sv({x,'".",'y}/){$[10h=type x;x;string x]}each x` vs y}; /- if everything matches, then proceed to 1b on the result. if not, check what is missing from today/missing from yesterday + /- (missy, not mfy: L has a built-in called mfy, which cannot be assigned) $[(all b in a)and all(a:keyst 0)in b:keyst 1; (1b;"All keys from day ",(string last .Q.PV)," matched keys from ",string first -2#.Q.PV); - (0b;"Error: ",$[count mfy:a where not a in b;" ",f[mfy;vars]," missing from T-1.";""],$[count mft:b where not b in a;" ",f[mft;vars]," missing from T-2.";""])] + (0b;"Error: ",$[count missy:a where not a in b;" ",f[missy;vars]," missing from T-1.";""],$[count mft:b where not b in a;" ",f[mft;vars]," missing from T-2.";""])] } // This function checks if count from tables of resultdata has changed diff --git a/code/dqc/memoryusage.q b/code/dqc/memoryusage.q index 6ce6c1043..f0e1f6cb7 100644 --- a/code/dqc/memoryusage.q +++ b/code/dqc/memoryusage.q @@ -3,6 +3,7 @@ / - Check percentage of memory usage compared to max memory memoryusage:{[perc] .lg.o[`dqc;"checking whether the percetnage of memory usage exceeds ",(string 100*perc),"%"]; + if[not .proc.capabilities`memstats; :(0b;"error: memory usage is not available on this engine: it has no .Q.w")]; used:.Q.w[]`used; maxm:.Q.w[]`mphy; if[perc>=1; :(0b;"error: percentage is greater than or equal to 1")]; diff --git a/code/filealerter/pcapdecoder.q b/code/filealerter/pcapdecoder.q index e67d2ff10..c24f5d3da 100644 --- a/code/filealerter/pcapdecoder.q +++ b/code/filealerter/pcapdecoder.q @@ -69,7 +69,8 @@ datafromfile:{[filebinary;x;start;numofbytes] getflags:{[filebinary;x] // flag data stored at 49th byte - bools: 2 vs filebinary[globheader+packetheader+x[0]+49]; + // as longs: on L, 2 vs a byte gives ints, which do not join the long padding below + bools: "j"$2 vs filebinary[globheader+packetheader+x[0]+49]; `CWR`ECE`URG`ACK`PSH`RST`SYN`FIN where ((8 - count bools)#0), bools } diff --git a/code/handlers/permissions.q b/code/handlers/permissions.q index 761dbfc30..649458a99 100644 --- a/code/handlers/permissions.q +++ b/code/handlers/permissions.q @@ -256,7 +256,7 @@ init:{ .dotz.set[`.z.pi;{$[x in (1#"\n";"");.Q.s value x;.Q.s $[.z.w=0;value;req]@x]}]; .dotz.set[`.z.pp;{'"pm: HTTP POST requests not permitted"}]; // from V3.5 2019.11.23, .h.val is used in .z.ph to evaluate request; below that disallow .z.ph - $[(.z.K>=3.5)&.z.k>=2019.11.13;.h.val:req;.dotz.set[`.z.ph;{'"pm: HTTP GET requests not permitted"}]]; + $[.proc.capabilities`hval;.h.val:req;.dotz.set[`.z.ph;{'"pm: HTTP GET requests not permitted"}]]; .dotz.set[`.z.ws;{'"pm: websocket access not permitted"}]; .dotz.set[`.z.pw;login]; .dotz.set[`.z.pc;{droppublic[y];@[x;y]}value .dotz.getcommand[`.z.pc]]; diff --git a/code/handlers/trackservers.q b/code/handlers/trackservers.q index fda2115d3..1a7f114de 100644 --- a/code/handlers/trackservers.q +++ b/code/handlers/trackservers.q @@ -258,13 +258,7 @@ refreshattributes:{ } // return true if unix domain sockets can be used -domainsocketsenabled:{[] - // unix domain sockets only works on unix and not windows - notwin:not .z.o like "w*"; - // v3.4 brought in the first version of unix domain sockets ipc - iskdbv:3.4<=.z.K; - :notwin and iskdbv; - } +domainsocketsenabled:{[] :.proc.capabilities`unixsockets} // format hpup from procs table, take into account ipc type // IPCTYPE [-11h] (`tcp;`tcps;`unix); diff --git a/code/handlers/writeaccess.q b/code/handlers/writeaccess.q index 4596a4708..1daa0cd0f 100644 --- a/code/handlers/writeaccess.q +++ b/code/handlers/writeaccess.q @@ -14,9 +14,9 @@ enabled:@[value;`enabled;0b] // whether read only is enabled .lg.o[`readonly;"read only mode is ",("disabled";"enabled").readonly.enabled]; if[.readonly.enabled; // Check if the current KDB version supports blocking write access to clients - if[3.3>.z.K; - .lg.e[`readonly;"current KDB+ version ",(string .z.K), - " does not support blocking write access,a minimum of KDB+ version 3.3 is required"] + if[not .proc.capabilities`reval; + .lg.e[`readonly;"current engine ",.proc.enginename," ",.proc.engineversion, + " does not support blocking write access, a minimum of KDB+ version 3.3 is required"] ]; // Modify the sync message handler .dotz.set[`.z.pg;{[x;y] $[10h=type y;reval(x;y); x y]}value .dotz.getcommand[`.z.pg]]; diff --git a/code/processes/dqe.q b/code/processes/dqe.q index e66bd19e9..05a1459aa 100644 --- a/code/processes/dqe.q +++ b/code/processes/dqe.q @@ -27,9 +27,11 @@ init:{ /- store i numbers of rows to be saved down to DB .dqe.tosavedown:()!(); .dqe.configtimer[]; - st:.dqe.writedownperiodengine+min .timer.timer[;`periodstart]; + /- (exec, not .timer.timer[;`periodstart]: indexing a keyed table that way differs between engines, and PeachQ has none) + st:.dqe.writedownperiodengine+min exec periodstart from .timer.timer; et:.eodtime.nextroll-.dqe.writedownperiodengine; - if[((.z.Z,.z.z).dqe.utctime)>st;st:((.z.Z,.z.z).dqe.utctime)+.dqe.writedownperiodengine]; + /- (timestamps: PeachQ cannot add a timespan to a datetime) + if[((.z.P,.z.p).dqe.utctime)>st;st:((.z.P,.z.p).dqe.utctime)+.dqe.writedownperiodengine]; .lg.o[`init;"start time of periodic writedown is: ",string st]; .lg.o[`init;"end time of periodic writedown is: ",string et]; .timer.repeat[st;et;.dqe.writedownperiodengine;(`.dqe.writedownengine;`);"Running periodic writedown on resultstab"]; diff --git a/code/processes/gateway.q b/code/processes/gateway.q index 32d076bc7..3db5359c8 100644 --- a/code/processes/gateway.q +++ b/code/processes/gateway.q @@ -386,7 +386,7 @@ asyncexecjpts:{[query;servertype;joinfunction;postback;timeout;sync] ]; query:({[u;q]$[`.pm.execas ~ key `.pm.execas;value (`.pm.execas; q; u);`.pm.valp ~ key `.pm.valp; .pm.valp q; value q]}; .z.u; query); /- if sync calls are allowed disable async calls to avoid query conflicts - $[.gw.synccallsallowed and .z.K<3.6; + $[.gw.synccallsallowed and not .proc.capabilities`deferred; errstr:.gw.errorprefix,"only synchronous calls are allowed"; [errstr:""; if[99h<>type servertype; @@ -453,7 +453,7 @@ syncexecjpre36:{[query;servertype;joinfunction] // check if there are any errors in the returned results :$[all res[;0]; // no errors - join the results - [s:@[{(1b;x y)}joinfunction;res[;2];{(0b;"failed to apply supplied join function to results: ",x)}]; + [s:@[{(1b;$[10h=type x;value(x;y);x y])}joinfunction;res[;2];{(0b;"failed to apply supplied join function to results: ",x)}]; .gw.formatresponse[s 0;1b;s 1]]; [failed:where not res[;0]; .gw.formatresponse[0b;1b;"queries failed on server(s) ",(", " sv string exec servertype from servers where handle in handles failed),". Error(s) were ","; " sv res[failed][;2]]] @@ -473,7 +473,7 @@ syncexecjt:{[query;servertype;joinfunction;timeout] .[asyncexecjpts;(query;servertype;joinfunction;();timeout;1b);{-30!(x;1b;y)}[.z.w;]]; }; -$[.z.K < 3.6; +$[not .proc.capabilities`deferred; [syncexecj:syncexecjpre36; syncexec:syncexecjpre36[;;raze]]; [syncexecj:syncexecjt[;;;0Wn]; diff --git a/code/processes/tickerlogreplay.q b/code/processes/tickerlogreplay.q index fe2658680..d13210d8d 100644 --- a/code/processes/tickerlogreplay.q +++ b/code/processes/tickerlogreplay.q @@ -230,7 +230,16 @@ cleanhdb:{[dt] replayinner:{[msgnum;logfile] if[not .replay.zipped;-11!(msgnum;logfile);:()]; if[not .z.o like "l*";.lg.e[`replaylog;m:"Zipped log files can only be directly replayed on Linux systems"];'m]; - if[.z.K<4.0;.lg.e[`replaylog;m:"Zipped log files can only be directly replayed on kdb+ 4.0 or higher"];'m]; + // an engine which cannot replay from a named pipe (kdb+ before 4.0, L, PeachQ, Korze): unzip to a temporary file and replay that + if[not .proc.supports`pipereplay; + .lg.o[`replay;"Replaying logfile ",(f:1_string logfile)," from a temporary unzipped copy"]; + tmp:"/tmp/logunzip",string .z.i; + // "&& true": q adds its own redirect to the end of a system command, which would otherwise take gunzip's output + r:@[{system "gunzip -cd ",x," > ",y," && true";-11!(z;hsym `$y);`ok}[f;tmp];msgnum;{x}]; + system "rm -f ",tmp; + .replay.zipped:0b; + if[not `ok~r;.lg.e[`replaylog;m:"Failed to replay the unzipped copy of ",f," : ",r];'m]; + :()]; .lg.o[`replay;"Replaying logfile ",(f:1_string logfile)," over named pipe"]; -11!(msgnum;hsym `$fifo:.replay.readintofifo f); diff --git a/code/processes/wdb.q b/code/processes/wdb.q index f67a1a77b..37ab4c1bf 100644 --- a/code/processes/wdb.q +++ b/code/processes/wdb.q @@ -124,7 +124,8 @@ maptoint:{[val] /- if using an integer column, clamp value between 0 and max int (null maps to 0) 0| 2147483647& `long$ val; /- if using a symbol column, enumerate against the hdb sym file - `long$ (` sv hdbsettings[`hdbdir],`sym)?`TORQNULLSYMBOL^val] + /- (enumerated as a list, and the first item taken back for a single value: L cannot enumerate a symbol atom) + $[0>type val;first;::] `long$ (` sv hdbsettings[`hdbdir],`sym)?(),`TORQNULLSYMBOL^val] }; mapfctoint:{[val] diff --git a/setenv.sh b/setenv.sh index 63cf8f3e1..b8c7afdf9 100644 --- a/setenv.sh +++ b/setenv.sh @@ -35,4 +35,4 @@ export TORQMONIT=${TORQHOME}/logs/monit export RLWRAP="rlwrap" # set rlwrap path export QCON="qcon" # set qcon path -export QCMD="q" # set qcmd path +export QCMD=${QCMD:-q} # set qcmd path diff --git a/tests/engine/engine.csv b/tests/engine/engine.csv new file mode 100644 index 000000000..7fe1ab359 --- /dev/null +++ b/tests/engine/engine.csv @@ -0,0 +1,58 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,.et.connect[],1,,"Connect to the engine test server" +true,0,0,q,.et.engineknown[],1,,"torq.q: .proc.engine is kdb l peachq or unknown" +true,0,0,q,.et.engineexpected[],1,,"torq.q: .proc.engine is the engine named in TORQTEST_ENGINE (when set)" +true,0,0,q,.et.detectstable[],1,,"torq.q: .proc.getengine[] gives the same answer again" +true,0,0,q,.et.names[],1,,"torq.q: .proc.enginename and .proc.engineversion are non-empty strings" +true,0,0,q,.et.nameformengine[],1,,"torq.q: .proc.enginename matches .proc.engine" +true,0,0,q,.et.capsshape[],1,,"torq.q: .proc.capabilities is a boolean dictionary of the nine features" +true,0,0,q,.et.capssource[],1,,"torq.q: capabilities come from the version on kdb+ and from the probes elsewhere" +true,0,0,q,.et.probesmatchversion[],1,,"torq.q: on kdb+ every probe agrees with the version-based answer" +true,0,0,q,.et.matches[`broadcast;.et.broadcastworks[]],1,,"capability broadcast matches whether -25! delivers to the test server" +true,0,0,q,.et.matches[`deferred;.et.deferredworks[]],1,,"capability deferred matches whether a -30! deferred reply arrives" +true,0,0,q,.et.matches[`unixsockets;.et.unixworks[]],1,,"capability unixsockets matches whether a unix:// connection works" +true,0,0,q,.et.matches[`reval;.et.revalworks[]],1,,"capability reval matches whether reval evaluates" +true,0,0,q,.et.matches[`hval;.et.hvalworks[]],1,,"capability hval matches whether .z.ph evaluates through .h.val" +true,0,0,q,.et.matches[`memstats;.et.memstatsworks[]],1,,"engine.q: the memstats capability matches whether .Q.w[] works" +true,0,0,q,.et.alphabets[],1,,"engine.q: .Q.A and .Q.a exist and hold the alphabets on every engine" +true,0,0,q,.et.supportsunknown[],1,,"engine.q: supports gives 0b for a name that is not a feature, and stores nothing" +true,0,0,q,.et.supportslist[],1,,"engine.q: supports with several names gives an answer for each" +true,0,0,q,$[.z.o like "l*";(.et.pipeworks[])~.proc.supports`pipereplay;1b],1,,"capability pipereplay (checked when first asked for) matches whether -11! replays from a named pipe (Linux)" +true,0,0,q,.et.upub[],1,,"u.q: the -25! publish is defined only when broadcast is on and supported" +true,0,0,q,.et.upubbroadcast[],1,,"u.q: the -25! publish delivers to a subscriber where it is defined" +true,0,0,q,.et.domainsockets[],1,,"trackservers.q: domainsocketsenabled follows the unixsockets capability" +true,0,0,q,.et.replayinner[],1,,"tickerlogreplay.q: a zipped log is no longer refused on an engine without pipereplay" +true,0,0,q,.et.grafana[],1,,"grafana.q: types maps every character of .Q.t" +true,0,0,q,.et.loadonce[],1,,"torq.q: loading the same file twice through .proc.loadf runs it once" +true,0,0,q,.et.depdefined[],1,,"torq.q: .proc.a holds the TorQ and kdb versions after start-up" +true,0,0,q,.et.depappends[],1,,"torq.q: checkdependency appends to .proc.a rather than replacing it" +true,0,0,q,.et.permissions[],1,,"permissions.q: .h.val is used only where .z.ph evaluates through it" +true,0,0,q,.et.readonly[],1,,"writeaccess.q: an error is logged when reval is not available" +true,0,0,q,.et.paramwins[],1,,"engine.q: -engine on the command line wins over KDBENGINE" +true,0,0,q,.et.envused[],1,,"engine.q: KDBENGINE chooses the engine when -engine is not given" +true,0,0,q,.et.envtrimmed[],1,,"engine.q: KDBENGINE with spaces and capitals is still that engine" +true,0,0,q,.et.detected[],1,,"engine.q: with neither the engine is detected the same way in a new process" +true,0,0,q,.et.chosenkdb[],1,,"engine.q: -engine kdb takes capabilities from the version" +true,0,0,q,.et.reloadkeeps[],1,,"engine.q: loading it again keeps the capabilities" +true,0,0,q,.et.initonce[],1,,"engine.q: init runs once - called again it keeps the engine and the capabilities" +true,0,0,q,.et.featuretable[],1,,"engine.q: one row per feature, and the version rules and capabilities list the same features in the same order" +true,0,0,q,.et.hvalrestored[],1,,"engine.q: the .h.val check puts .h.val back" +true,0,0,q,.et.pipegate[],1,,"engine.q: off Linux the named-pipe replay is not reported on other engines" +true,0,0,q,.et.unknownengine[],1,,"engine.q: -engine with a name TorQ does not know is taken as given and probed" +true,0,0,q,.et.viasymlink[],1,,"engine.q: started by a bare name on the PATH (q, or l for L) the engine is recognised" +true,0,0,q,.et.noshell[],1,,"engine.q: starting TorQ runs no shell commands (same answers with no PATH)" +true,0,0,q,.et.lazy[],1,,"engine.q: pipereplay is checked when first asked for, not at start-up, on other engines" +true,0,0,q,.et.logengine[],1,,"torq.q: the engine and its capabilities are logged as one line" +true,0,0,q,.et.int3[],1,,"internal -3! (replaced by .Q.s1) gives the same text" +true,0,0,q,.et.int4[],1,,"internal -4! tokenises as the kx docs show (L leaves out the blank tokens)" +true,0,0,q,.et.int89[],1,,"internal -8! and -9! round trip a dictionary and a table" +true,0,0,q,.et.int22[],1,,"internal -22! equals count -8! (the kx docs definition)" +true,0,0,q,.et.int11[],1,,"internal -11! replays a log: all, n chunks, and the (-2;log) check" +true,0,0,q,.et.int0N[],1,,"internal 0N! returns what it shows" +true,0,0,q,.et.usedkeys[],1,,"every capabilities or supports key the code reads is a feature in the table" +true,0,0,q,.et.probecleanup[],1,,"engine.q: the probes leave no temporary files or processes" +true,0,0,q,.et.nofiles[],1,,"engine.q: starting TorQ on any engine writes no file" +true,0,0,q,.et.tmpdirforms[],1,,"engine.q: the named-pipe check gives the same answer with a temp directory with a trailing slash or spaces" +true,0,0,q,.et.kdbversions[],1,,"engine.q: for every kdb+ version the capabilities equal the original .z.K tests" +true,0,0,q,.et.gzreplay[],1,,"tickerlogreplay.q: a zipped log replays on Linux, through a named pipe or from a temporary unzipped copy" +after,0,0,q,.et.cleanup[],1,,"Remove the scratch directories the tests made" diff --git a/tests/engine/process.csv b/tests/engine/process.csv new file mode 100644 index 000000000..273a9bfb0 --- /dev/null +++ b/tests/engine/process.csv @@ -0,0 +1,2 @@ +host,port,proctype,procname,U,localtime,g,T,w,load,startwithall,extras,qcmd +localhost,{KDBBASEPORT}+120,engsrv,engsrv1,,1,0,,,${KDBTESTS}/engine/server.q,0,,q diff --git a/tests/engine/run.sh b/tests/engine/run.sh new file mode 100755 index 000000000..d4ac3c1e6 --- /dev/null +++ b/tests/engine/run.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# Engine compatibility tests: engine detection, .proc.capabilities and every place TorQ reads it. +# Runs on whichever engine "q" on the PATH is. Set TORQTEST_ENGINE (kdb, l or peachq) to also check the detection. + +source $KDBTESTS/flagparse.sh + +testpath=${KDBTESTS}/engine +port=$((KDBBASEPORT+120)) + +# plain q server (not TorQ) on the same engine, for the IPC checks +q ${testpath}/server.q -p $port -q /dev/null 2>&1 & +serverpid=$! +sleep 2 + +q ${TORQHOME}/torq.q \ + -proctype test -procname test1 \ + -test ${testpath} \ + -load ${KDBTESTS}/helperfunctions.q ${testpath}/settings.q \ + -testresults ${KDBTESTS}/engine/results/ \ + -procfile ${testpath}/process.csv \ + -runtime $run \ + $debug $stop $write $quiet + +kill $serverpid 2>/dev/null diff --git a/tests/engine/server.q b/tests/engine/server.q new file mode 100644 index 000000000..12e8a8d2c --- /dev/null +++ b/tests/engine/server.q @@ -0,0 +1,8 @@ +// server for the engine tests: started by run.sh with the same engine as the test process +// .z.pg answers "defer" through -30! (deferred response); upd counts rows; .srv.set is called by -25! broadcasts +.srv.cnt:0; .srv.b:0b; .srv.w:0Ni; +.srv.set:{[x] .srv.b:x}; +upd:{[t;x] .srv.cnt:.srv.cnt+count x}; +.z.pg:{[x] $[x~"defer";[.srv.w:.z.w;-30!(::)];value x]}; +.z.ts:{[x] if[not null .srv.w; -30!(.srv.w;0b;`deferredok); .srv.w:0Ni]}; +system "t 10"; diff --git a/tests/engine/settings.q b/tests/engine/settings.q new file mode 100644 index 000000000..7b23787ef --- /dev/null +++ b/tests/engine/settings.q @@ -0,0 +1,210 @@ +// Engine compatibility tests - helper functions (each returns 1b when the check passes) + +.et.port:120+"J"$getenv`KDBBASEPORT; +.et.h:0Ni; +.et.connect:{[] .et.h:hopen .et.port; 1b}; +.et.dirs:(); / every scratch directory made, removed by .et.cleanup at the end +.et.tmp:{[] d:$[count t:getenv`TMPDIR;t;"/tmp"],"/torqengtest_",string[.z.i],"_",string first 1?1000000000; system "mkdir -p ",d; .et.dirs:.et.dirs,enlist d; d}; +.et.cleanup:{[] {system "rm -rf '",x,"'"} each .et.dirs; .et.dirs:(); 1b}; + +// ---------------------------------------------------------------- engine detection +.et.engineknown:{[] .proc.engine in `kdb`l`peachq`korze`unknown}; +.et.engineexpected:{[] $[count e:getenv`TORQTEST_ENGINE; .proc.engine~`$e; 1b]}; +.et.detectstable:{[] .proc.engine~.proc.getengine[]}; +.et.names:{[] (10h=type .proc.enginename) and (10h=type .proc.engineversion) and (0 ",p,") >/dev/null 2>&1 &"; + .et.pc:0; -11!hsym`$p; system "rm -rf ",d; 3=.et.pc};::;0b]}; +.et.memstatsworks:{[] @[{99h=type .Q.w[]};::;0b]}; / .Q.w[] gives the memory statistics (Korze has no .Q.w) +// a name that is not a feature: 0b, nothing added to the capabilities; several names: an answer for each +.et.supportsunknown:{[] k:key .proc.capabilities; (0b~.proc.supports`zznosuch) and (0b~.proc.supports`) and k~key .proc.capabilities}; +.et.supportslist:{[] (.proc.supports`broadcast`zznosuch`deferred)~(.proc.supports`broadcast;0b;.proc.supports`deferred)}; +// kdb+'s alphabet constants exist on every engine (engine.q defines them where the engine does not: Korze) +.et.alphabets:{[] (.Q.A~"ABCDEFGHIJKLMNOPQRSTUVWXYZ") and .Q.a~"abcdefghijklmnopqrstuvwxyz"}; +.et.matches:{[f;works] works~.proc.capabilities f}; + +// ---------------------------------------------------------------- u.q: .u.pub uses -25! only when it can +// (pubsub.q later points .u.pub at .stpps.pub, so check what u.q itself defined) +.et.upub:{[] $[.u.broadcast and .proc.capabilities`broadcast; all `pub_broadcast`pub_default in key `.u; not any `pub_broadcast`pub_default in key `.u]}; +// where u.q defined the -25! version, it delivers to a .u.w subscriber +.et.upubbroadcast:{[] if[not `pub_broadcast in key `.u; :1b]; + had:`w in key `.u; oldw:$[had;.u.w;::]; .et.h".srv.cnt:0"; + .u.w:(enlist`trade)!enlist enlist (.et.h;`); + r:@[{.u.pub_broadcast[`trade;([]sym:`a`b;price:1 2f)]; .et.h".srv.cnt"};::;{x}]; + $[had;.u.w:oldw;![`.u;();0b;enlist`w]]; .et.upubresult:r; 2~r}; + +// ---------------------------------------------------------------- trackservers.q: unix domain sockets +.et.domainsockets:{[] .servers.domainsocketsenabled[]~(not .z.o like "w*") and .proc.capabilities`unixsockets}; + +// ---------------------------------------------------------------- tickerlogreplay.q: zipped logs need pipereplay +// replayinner is process code, so take its definition from the file and run it with a zipped log name +.et.replayinner:{[] + f:read0 hsym`$getenv[`KDBCODE],"/processes/tickerlogreplay.q"; + i:first where f like "replayinner:{*"; j:i+first where (i _ f) like " };*"; + value "\n" sv f i+til 1+j-i; + .replay.zipped:1b; m:"Zipped log files can only be directly replayed on kdb+ 4.0 or higher"; + r:@[replayinner[0];`:/tmp/torqengtest_none.log.gz;{x}]; + .replay.zipped:0b; + not r~m}; + +// ---------------------------------------------------------------- helpers +.et.lgcapture:{[f;x] olde:.lg.e; .et.errs:(); .lg.e:{[x;y] .et.errs,:enlist (x;y)}; r:@[f;x;{x}]; .lg.e:olde; (r;.et.errs)}; +// ---------------------------------------------------------------- grafana.q: type map sized to .Q.t +.et.grafana:{[] (key[.grafana.types]~.Q.t) and (count .grafana.types)=count .Q.t}; + +// ---------------------------------------------------------------- torq.q: a file is loaded once (Korze's in never matched the loaded-files list) +.et.loadonce:{[] f:.et.tmp[],"/once.q"; (hsym`$f) 0: enlist ".et.loadcount+:1"; .et.loadcount:0; .proc.loadf f; .proc.loadf f; 1=.et.loadcount}; + +// ---------------------------------------------------------------- torq.q: checkdependency appends to .proc.a +.et.depdefined:{[] (98h=type .proc.a) and all `TorQ`kdb in .proc.a`app}; +.et.depappends:{[] n:count .proc.a; .et.lgcapture[.proc.checkdependency;.proc.getconfig["dependency.csv";1]]; (count .proc.a)>n}; + +// ---------------------------------------------------------------- permissions.q: .h.val only where .z.ph uses it +.et.permissions:{[] saved:`ph`val!(.z.ph;@[value;`.h.val;::]); / the test turns permissions on, which replaces .z.ph and .h.val: put them back afterwards + .pm.init[]; + r:$[.proc.capabilities`hval;.pm.req~@[value;`.h.val;::];not .pm.req~@[value;`.h.val;::]]; + .z.ph:saved`ph; $[(::)~saved`val;![`.h;();0b;enlist`val];.h.val:saved`val]; + r}; + +// ---------------------------------------------------------------- writeaccess.q: no reval -> an error is logged +.et.readonly:{[] .readonly.enabled:1b; + e:last .et.lgcapture[system;"l ",getenv[`KDBCODE],"/handlers/writeaccess.q"]; + logged:any (e[;1]) like "*does not support blocking write access*"; + $[.proc.capabilities`reval;not logged;logged]}; + +// ---------------------------------------------------------------- engine.q: start-up choice, operating systems, reload +.et.enginefile:getenv[`KDBCODE],"/common/engine.q"; +// this process's binary, to start a child of the same engine: /proc//exe resolved to a real file, when it is one. +// L runs from memory: readlink then gives "/memfd: (deleted)", or on some systems just the /proc path back - neither can +// be started, so .z.X is used instead (looked up on the PATH when it has no directory) +.et.exepick:{[e] $[(0=count e) or (e like "*(deleted)*") or (e like "/proc/*") or (e like "/memfd*") or ()~key hsym`$e; + $["/" in x:first .z.X;x;first system "command -v ",x];e]}; +.et.exe:{[] .et.exepick @[{first system "readlink -f /proc/",string[.z.i],"/exe 2>/dev/null"};::;""]}; +// start this engine's binary with engine.q and the given environment/arguments; return the engine it settled on +.et.child:{[envs;args] f:.et.tmp[],"/show.q"; + (hsym`$f) 0: ("system \"l ",.et.enginefile,"\";";"-1 \"ENGINE=\",string .proc.engine;";"exit 0"); + r:@[system;$[count envs;envs," ";""],.et.exe[]," ",f," ",args," -q /dev/null";enlist ""]; / no leading space: system " ..." is not a shell command + `$7_first r where r like "ENGINE=*"}; +.et.paramwins:{[] `l~.et.child["KDBENGINE=peachq";"-engine l"]}; +.et.envused:{[] `peachq~.et.child["KDBENGINE=peachq";""]}; +.et.envtrimmed:{[] `peachq~.et.child["KDBENGINE=' PeachQ '";""]}; / spaces and case in KDBENGINE are ignored +.et.detected:{[] $[count getenv`KDBENGINE;1b;.proc.engine~.et.child["";""]]}; +// a chosen engine decides where capabilities come from: kdb -> version, anything else -> probes +.et.chosenkdb:{[] f:.et.tmp[],"/caps.q"; + (hsym`$f) 0: ("system \"l ",.et.enginefile,"\";";"-1 \"OK=\",string .proc.capabilities~.proc.versioncapabilities[.z.K;.z.k];";"exit 0"); + r:@[system;.et.exe[]," ",f," -engine kdb -q /dev/null";enlist ""]; "OK=1"~first r where r like "OK=*"}; +// ---------------------------------------------------------------- engine.q: the feature table and how it is probed +.et.bits:{raze string value x}; +// run code in a new process of this engine: envs is "NAME=value ..." (or ""), exe the program, args extra arguments; returns its output lines +.et.childout:{[envs;exe;args;code] + f:.et.tmp[],"/child.q"; + (hsym`$f) 0: ("system \"l ",.et.enginefile,"\";";code;"exit 0"); + @[system;$[count envs;envs," ";""],exe," ",f," ",args," -q /dev/null";enlist ""]}; +.et.probebits:"-1 \"BITS=\",raze string value .proc.probecapabilities[]"; +.et.childbits:{[envs;exe] 5_first r where (r:.et.childout[envs;exe;"";.et.probebits]) like "BITS=*"}; + +// one row per feature, each naming a probe function that exists; the version rules list every feature; capabilities hold the features checked at start-up (all of them on kdb+), in the same order +.et.featuretable:{[] f:.proc.features; + ((count f`feature)=count distinct f`feature) and (all 100h=type each .proc f`probe) and ((key .proc.versioncapabilities[.z.K;.z.k])~f`feature) and (.et.atstart[])~(count .et.atstart[])#key .proc.capabilities}; +// the .h.val check puts .h.val back as it found it +.et.hvalrestored:{[] had:`val in key `.h; old:$[had;.h.val;::]; .proc.probecapabilities[]; (had~`val in key `.h) and $[had;old~.h.val;1b]}; +// off Linux the pipe is not probed (TorQ replays zipped logs through a pipe on Linux only) +.et.pipegate:{[] $[.proc.engine=`kdb;1b;$[.z.o like "l*";1b;not .proc.supports`pipereplay]]}; +.et.cleanbits:{[] .et.childbits["";.et.exe[]]}; / the answers in a clean new process (the test process has had handlers installed by earlier tests) +// an engine name TorQ does not know is taken as given, shown as unknown, and probed +.et.unknownengine:{[] r:.et.childout["";.et.exe[];"-engine foo";"-1 \"ENGINE=\",string .proc.engine; -1 \"NAME=\",.proc.enginename; -1 \"BITS=\",raze string value .proc.capabilities"]; + (`foo~`$7_first r where r like "ENGINE=*") and ("unknown q engine"~5_first r where r like "NAME=*") and (.et.cleanbits[]~5_first r where r like "BITS=*")}; +// started by a bare name found on the PATH (q, and l for L) the engine is still recognised +.et.viasymlink:{[] + d:.et.tmp[]; names:$[.proc.engine~`l;`q`l;enlist `q]; + one:{[d;n] system "ln -s '",.et.exe[],"' '",d,"/",string[n],"'"; + r:.et.childout["PATH=\"",d,":$PATH\"";string n;"";"-1 \"ENGINE=\",string .proc.engine"]; (`$7_first r where r like "ENGINE=*")~.proc.engine}[d]; + r:all one each names; system "rm -rf '",d,"'"; r}; + +// loading engine.q again (as code/common does) keeps the capabilities instead of probing again +.et.reloadkeeps:{[] c:.proc.capabilities; .proc.capabilities[`zzmarker]:1b; system "l ",.et.enginefile; + r:(1b~.proc.capabilities`zzmarker) and .proc.engine~.proc.getengine[]; .proc.capabilities:c; r}; + +// init runs once: called again (as a second load of engine.q does) it keeps the engine, its name and version, and the capabilities +.et.initonce:{[] c:.proc.capabilities; e:(.proc.engine;.proc.enginename;.proc.engineversion); .proc.capabilities[`zzinit]:1b; .proc.init[]; + r:(.proc.capabilities`zzinit) and e~(.proc.engine;.proc.enginename;.proc.engineversion); .proc.capabilities:c; r}; + +// starting TorQ runs no shell commands: the answers are the same when there is no PATH to find any command on +.et.noshell:{[] (.et.childbits["PATH=/nonexistent";.et.exe[]])~.et.cleanbits[]}; +// pipereplay is not checked at start-up on other engines (it runs shell commands): it is checked when first asked for, then remembered +.et.lazy:{[] + if[.proc.engine=`kdb; :1b]; + r:.et.childout["";.et.exe[];"";"-1 \"BEFORE=\",string `pipereplay in key .proc.capabilities; x:.proc.supports`pipereplay; -1 \"AFTER=\",string `pipereplay in key .proc.capabilities"]; + ((enlist "0")~7_first r where r like "BEFORE=*") and (enlist "1")~6_first r where r like "AFTER=*"}; + +// the engine and capabilities go in the log, once, as one line (torq.q calls logengine for every process) +.et.logengine:{[] old:.lg.o; .et.logged:(); .lg.o:{[category;message] .et.logged:.et.logged,enlist message}; .proc.logengine[]; .lg.o:old; + (1=count .et.logged) and ((first .et.logged) like "q engine *") and 0/dev/null";()]) and 0=count @[system;"pgrep -f '",ssr[prefix;"torqprobe";"[t]orqprobe"],"'";()]}; +// starting TorQ writes nothing: with a scratch directory to hand, the start-up probes leave it empty +.et.nofiles:{[] + d:.et.tmp[]; + r:.et.childout["TMPDIR='",d,"'";.et.exe[];"";"-1 \"BEFORE=\",string count key hsym`$getenv`TMPDIR; .proc.probecapabilities[]; -1 \"AFTER=\",string count key hsym`$getenv`TMPDIR"]; + ((enlist "0")~7_first r where r like "BEFORE=*") and (enlist "0")~6_first r where r like "AFTER=*"}; +// the temporary directory comes in forms (macOS has a trailing slash, users have spaces): the named-pipe check, the one probe which uses it, must not change +.et.pipechild:{[envs] r:.et.childout[envs;.et.exe[];"";"-1 \"PIPE=\",string .proc.probepipereplay[::]"]; 5_first r where r like "PIPE=*"}; +.et.tmpdirforms:{[] d:.et.tmp[]; clean:.et.pipechild[""]; + r:(clean~.et.pipechild["TMPDIR='",d,"/a dir with spaces/'"]) and clean~.et.pipechild["TMPDIR='",d,"/'"]; + system "rm -rf '",d,"'"; r}; + +// ---------------------------------------------------------------- kdb+ is decided by version, exactly as TorQ did before engine.q +// the .z.K and .z.k tests as they were in the code engine.q replaced (u.q, gateway.q, writeaccess.q, permissions.q, trackservers.q, tickerlogreplay.q) +.et.originalrules:{[K;k] `broadcast`deferred`unixsockets`reval`hval`pipereplay!(K>=3.4;not K<3.6;3.4<=K;not 3.3>K;(K>=3.5)&k>=2019.11.13;not K<4.0)}; +.et.kdbversions:{[] + grid:((3.3;2016.01.01);(3.4;2016.06.01);(3.5;2017.06.01);(3.5;2019.11.12);(3.5;2019.11.13);(3.6;2018.05.18);(3.6;2020.05.04);(4.0;2020.03.04);(4.0;2023.08.11);(4.1;2024.04.29);(5.0;2026.10.15)); + all {[p] want:.et.originalrules[p 0;p 1]; want~(key want)#.proc.versioncapabilities[p 0;p 1]} each grid}; + +// ---------------------------------------------------------------- tickerlogreplay.q: a zipped log really replays on Linux: through a named pipe where the engine can, from a temporary unzipped copy where it cannot +.et.gzreplay:{[] + f:read0 hsym`$getenv[`KDBCODE],"/processes/tickerlogreplay.q"; + grab:{[f;head] i:first where f like head; j:i+first where (i _ f) like " };*"; "\n" sv f i+til 1+j-i}; + d:.et.tmp[]; tplog:hsym`$d,"/tp.log"; tplog set (); h:hopen tplog; do[3;h enlist (`upd;`gzt;1)]; hclose h; + system "gzip -c '",d,"/tp.log' > '",d,"/tp.log.gz'; true"; / "; true": q's system returns when stdout closes, which for a lone redirected command is before it finishes + (hsym`$d,"/fns.q") 0: "\n" vs ".replay.",grab[f;"readintofifo:{*"],"\n.replay.",grab[f;"replayinner:{*"]; / TorQ's own two functions, from the file + / a clean new process of this engine replays it (the test process has had permissions switched on by earlier tests) + code:".lg.o:{[c;m] ::}; .lg.e:{[c;m] -1 \"LGE \",m}; system \"l ",d,"/fns.q\"; n:0; `upd set {[t;x] n::n+1}; .replay.zipped:1b; ", + "r:@[.replay.replayinner[-1];`$\":",d,"/tp.log.gz\";{\"ERR \",x}]; -1 \"COUNT=\",string n"; + r:.et.childout["";.et.exe[];"";code]; + got:first 6_first r where r like "COUNT=*"; + system "rm -rf '",d,"'"; + $[.z.o like "l*";"3"~got;"0"~got]}; diff --git a/tests/helperfunctions.q b/tests/helperfunctions.q index b8ad95f21..dca671918 100644 --- a/tests/helperfunctions.q +++ b/tests/helperfunctions.q @@ -2,17 +2,20 @@ startorstopproc:{[startorstop;procname;processcsv] .proc.sys getenv[`TORQHOME],"/torq.sh ",startorstop," ",procname," -csv ",processcsv }; +// The pids of this user's processes whose command line matches the pattern. The process is found by TorQ's own +// arguments, not by the name of its executable: that is q for kdb+, but not for every engine (Korze's is z, and L +// can show as memfd:). The first character goes in brackets so that the pattern cannot match this pgrep command itself +procpids:{[pattern] @[system;"pgrep -u $USER -f \"[",(1#pattern),"]",(1_pattern),"\"";()]}; + deadproccheck:{[proctype;procname] - / pairs are of the form " ssh" for 'PID TTY...' part of pgrep, and " q" if process is running - pidnamepairs:.proc.sys "pgrep -lf \"stackid ",getenv[`KDBBASEPORT]," -proctype ",proctype," -procname ",procname,"\""; - not "q" in last each pidnamepairs + 0=count procpids "stackid ",getenv[`KDBBASEPORT]," -proctype ",proctype," -procname ",procname }; // Kill process dead with -9 -kill9proc:{[proc] a:"q" in' b:@[system;"pgrep -lf ",proc," -u $USER";" "];system "kill -9 ",first " " vs first b where a}; +kill9proc:{[proc] system "kill -9 "," " sv procpids "procname ",proc}; // Returns boolean true if process is alive -isalive:{[proc] any "q" in' @[system;"pgrep -lf ",proc," -u $USER";" "]}; +isalive:{[proc] 0`se true,0,0,q,currlog[`trade;`logname]~exec first logname from met,1,,"Check lognames the same in log and meta" true,0,0,q,(0#trade)~(first exec schema from met)[`trade],1,,"Check trade schema saved to meta table" true,0,0,q,(0#quote)~(first exec schema from met)[`quote],1,,"Check quote schema saved to meta table" -true,0,0,q,`error~.tst.err,1,,"Check errors were logged to disk" +true,0,0,q,`error~first .tst.err,1,,"Check errors were logged to disk" after,0,0,q,"system ""rm -rf "",1_string stpHandle(`.stplg.dldir)",1,,"Delete logs folder" after,0,0,q,"system ""rm -rf "",1_string sctpHandle(`.stplg.dldir)",1,,"Delete logs folder" \ No newline at end of file diff --git a/tests/stp/pubsub/pubsub.csv b/tests/stp/pubsub/pubsub.csv index 7edf841be..0ad9b2882 100644 --- a/tests/stp/pubsub/pubsub.csv +++ b/tests/stp/pubsub/pubsub.csv @@ -19,6 +19,11 @@ true,0,0,q,1~count psHandle(`trade),1,,"Check there is one row in trade table" run,0,0,q,neg[psHandle](`.stpps.pubclear;`trade),1,,"Call pubclear funtion" true,0,0,q,0~count psHandle(`trade),1,,"Check that trade table has been cleared" true,0,0,q,0~.tst.upd,1,,"Check that local UPD function has been called" +true,0,0,q,"psHandle""((.stpps.pub~.stpps.pubeach)~not @[{.proc.capabilities`broadcast};::;1b]) and (.u.pub~.stpps.pub) and .ps.publish~.stpps.pub""",1,,"pubsub.q: .stpps.pub is pubeach exactly where the engine has no -25! (chosen once, at load), and .u.pub and .ps.publish follow it" +run,0,0,q,psHandle(upsert;`trade;testtrade),1,,"Update trade table on pubsub" +run,0,0,q,"psHandle"".stpps.pubeach[`trade;trade]; delete from `trade""",1,,"Publish it through pubeach, then clear it" +true,0,0,q,1~.tst.upd,1,,"pubeach delivered it to this subscriber, on every engine" +run,0,0,q,.tst.upd:0,1,,"Put the upd count back for the tests below" run,0,0,q,psHandle(`.stpps.closesub;localw),1,,"Unsubscribe" true,0,0,q,all 0=count each value psHandle(`.stpps.subrequestall),1,,"Check all subs empty" run,0,0,q,sub2:psHandle(`.u.sub;`trade;`GOOG`AMZN),1,,"Subscribe for filtered trade table" diff --git a/tests/stp/subscription/sub.csv b/tests/stp/subscription/sub.csv index 0351a071d..642b235af 100644 --- a/tests/stp/subscription/sub.csv +++ b/tests/stp/subscription/sub.csv @@ -12,7 +12,7 @@ before,0,0,q,![-11;] each exec logname from currlog where tbl in `trade`quote,1, before,0,0,q,t2:count trade,1,,"Get local trade table count" before,0,0,q,q2:count quote,1,,"Get local quote table count" before,0,0,q,{delete from x} each `trade`quote,1,,"Clear local tables" -run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote);(`heartbeat;`error))",1,,"Publish table updates" +run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote);(`heartbeat;enlist`error))",1,,"Publish table updates" run,0,0,q,system "sleep 10",1,,"Wait for update to publish" run,0,0,q,![-11;] each exec logname from currlog where tbl in `trade`quote`segmentederrorlogfile,1,,"Replay logs locally" true,0,0,q,"all not raze value exec null logname,null handle from currlog",1,,"Check lognames and handles generated" @@ -30,7 +30,7 @@ true,0,0,q,`time`sym ~ (rdbHandles`complex)"cols trade",1,,"check published cols true,0,0,q,"(10+q2,t2)~count each (trade;quote)",1,,"Check updates were correctly saved to disk" true,0,0,q,all `GOOG=rdbHandles[`sym]"exec distinct sym from trade",1,,"Check sym update" true,0,0,q,0=count rdbHandles[`complex]"select from quote where bid<50",1,,"Check complex update" -true,0,0,q,`error~.tst.err,1,,"Check errors were logged to disk" +true,0,0,q,`error~first .tst.err,1,,"Check errors were logged to disk" run,0,0,q,"stpHandle @/: `.z.pc ,/: ah,fh",1,,"Disconnect handles" true,0,0,q,all 0=count each stpHandle".stpps.subrequestall .stpps.t",1,,"Check all subs table is cleared" true,0,0,q,0=count stpHandle".stpps.subrequestfiltered",1,,"Check filtered subs table is cleared" diff --git a/tests/stp/subscription/subperiodic.csv b/tests/stp/subscription/subperiodic.csv index 356032d4b..aba68acc0 100644 --- a/tests/stp/subscription/subperiodic.csv +++ b/tests/stp/subscription/subperiodic.csv @@ -4,7 +4,7 @@ before,0,0,q,stpHandle(`.stplg.init;testlogdb),1,,"Create test stplog test direc before,0,0,q,stpHandle"init[`defaultbatch]",1,,"Init STP main script" before,0,0,q,currlog:stpHandle"currlog",1,,"Get STP log table" before,0,0,q,met:stpHandle".stpm.metatable",1,,"Get STP meta table" -run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote);(`heartbeat;`error))",1,,"Publish table updates" +run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote);(`heartbeat;enlist`error))",1,,"Publish table updates" run,0,0,q,system "sleep 10",1,,"Wait for update to publish" run,0,0,q,![-11;] each exec logname from currlog where tbl in `trade`quote`segmentederrorlogfile,1,,"Replay logs locally" true,0,0,q,"all not raze value exec null logname,null handle from currlog",1,,"Check lognames and handles generated" @@ -12,5 +12,5 @@ true,0,0,q,all currlog[`trade;`logname]=exec logname from currlog where tbl<>`se true,0,0,q,currlog[`trade;`logname]~exec last logname from met,1,,"Check lognames the same in log and meta" true,0,0,q,(0#trade)~(last exec schema from met)[`trade],1,,"Check trade schema saved to meta table" true,0,0,q,(0#quote)~(last exec schema from met)[`quote],1,,"Check quote schema saved to meta table" -true,0,0,q,`error~.tst.err,1,,"Check errors were logged to disk" +true,0,0,q,`error~first .tst.err,1,,"Check errors were logged to disk" after,0,0,q,"system ""rm -rf "",1_string stpHandle(`.stplg.dldir)",1,,"Delete logs folder" diff --git a/tests/stp/tpvalidation/oldtp.csv b/tests/stp/tpvalidation/oldtp.csv index f4e184e0c..0a6004902 100644 --- a/tests/stp/tpvalidation/oldtp.csv +++ b/tests/stp/tpvalidation/oldtp.csv @@ -23,6 +23,7 @@ true,0,0,q,q2~raze[value each (rdbHandles;wdbHandles)] @\: "count quote",1,,"Che true,0,0,q,all `GOOG=raze ((rdbHandles;wdbHandles) @\: `sym) @\: "exec distinct sym from trade",1,,"Check sym subscription" run,0,0,q,"wdbHandles[`all`sym] @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`trade)",1,,"Force save trade table to disk" run,0,0,q,"(value wdbHandles) @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`quote)",1,,"Force save quote table to disk" +run,0,0,q,"sym:get ` sv (wdbHandles[`all]"".wdb.hdbsettings`hdbdir""),`sym",1,,"Load the sym list the WDBs enumerated against (Korze cannot read an enumerated column without it)" run,0,0,q,"system ""l "",1_string temphdbdir",1,,"Load in temp HDB" true,0,0,q,(sum each 2_'(t2;q2))~count each (trade;quote),1,,"Check WDB data was saved correctly to disk (drop RDB data)" true,0,0,q,all 0=wdbHandles[`all`sym] @\: "count trade",1,,"Check trade table is flushed from WDBs" diff --git a/tests/stp/upds/errorupds.csv b/tests/stp/upds/errorupds.csv index 33b24022c..23afabd23 100644 --- a/tests/stp/upds/errorupds.csv +++ b/tests/stp/upds/errorupds.csv @@ -10,15 +10,15 @@ before,0,0,q,rdbHandle:gethandle[`rdb1],1,,"Get RDB handle" before,0,0,q,stpHandle".stplg.errmode:1b",1,,"Ensure error mode is on in stp" run,0,0,q,"stpHandle""init[`defaultbatch]"" ",1,,"Define timer and update functions" run,0,0,q,stpHandle(`.u.upd;`undefinedtable;testtrade),1,,"Run update to an undefined table" -run,0,0,q,stplogdata: get stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" -true,0,0,q,"1 ~ count stplogdata",1,,"one row in error log +run,0,0,q,stplogdata: readlog[`upderr] stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" +true,0,0,q,"1 ~ count stplogdata",1,,"one row in error log" run,0,0,q,"stpHandle""init[`memorybatch]"" ",1,,"Define timer and update functions" run,0,0,q,"stpHandle(`.u.upd;`trade;testtrade,(enlist 10#`b),(enlist 10#`a))",1,,"Run trade update with data that is too wide" -run,0,0,q,stplogdata: get stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" -true,0,0,q,"2 ~ count stplogdata",1,,"two rows in error log +run,0,0,q,stplogdata: readlog[`upderr] stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" +true,0,0,q,"2 ~ count stplogdata",1,,"two rows in error log" run,0,0,q,"stpHandle""init[`immediate]"" ",1,,"Define timer and update functions" run,0,0,q,stpHandle(`.u.upd;`undefinedtable;testtrade),1,,"Run update to an undefined table" -run,0,0,q,stplogdata: get stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" +run,0,0,q,stplogdata: readlog[`upderr] stpHandle"currlog[`segmentederrorlogfile][`logname]",1,,"access latest error log file" true,0,0,q,"3 ~ count stplogdata",1,,"three rows in error log" true,0,0,q,"all (count each stplogdata[;2]) <> rdbHandle""count cols trade"" ",1,,"length of data is different to schema, time and seqnum are not being added" true,0,0,q,all stplogdata[;1] in `trade`undefinedtable,1,,"Check only errors for trade and undefinedtable tables" diff --git a/tests/stp/upds/settings.q b/tests/stp/upds/settings.q index 669c89fc7..00440f642 100644 --- a/tests/stp/upds/settings.q +++ b/tests/stp/upds/settings.q @@ -18,3 +18,7 @@ stopproc:startorstopproc["stop";;processcsv]; // Flag to save tests to disk .k4.savetodisk:0b; + +// Read the messages of a tickerplant log which call fn (upd, or upderr in the error log), by replaying it. +// get on a log file returns the messages on kdb+, but nothing on Korze +readlog:{[fn;f] `.tst.msgs set (); orig:@[value;fn;{{[t;x]}}]; fn set {[fn;t;x] .tst.msgs,:enlist(fn;t;x)}[fn]; r:@[{-11!x;1b};f;{x}]; fn set orig; if[not 1b~r;'r]; .tst.msgs}; diff --git a/tests/stp/upds/upds.csv b/tests/stp/upds/upds.csv index b6cf9b80d..f6eb96400 100644 --- a/tests/stp/upds/upds.csv +++ b/tests/stp/upds/upds.csv @@ -38,5 +38,5 @@ true,0,0,q,rdbHandle"7h ~ type quote`seqnum",1,,"Check sequence numbers are of t true,0,0,q,rdbHandle"not any null quote`seqnum",1,,"Check column is being filled with valid sequence numbers" true,0,0,q,rdbHandle"not any 0 > deltas quote`seqnum",1,,"Check seq numbers are always ascending" true,0,0,q,rdbHandle"10 ~ count quote",1,,"Check count of quote table" -after,0,0,q,rdbHandle"delete from `quote",1,,"Clear quote table +after,0,0,q,rdbHandle"delete from `quote",1,,"Clear quote table" after,0,0,q,".os.deldir getenv[`KDBTPLOG],""/"", testlogdb,""_"",string .z.d",1,,"Delete test segmented tickerplant logs" \ No newline at end of file diff --git a/tests/stp/wdb/partbyenum.csv b/tests/stp/wdb/partbyenum.csv index 2fae50992..50c81de76 100644 --- a/tests/stp/wdb/partbyenum.csv +++ b/tests/stp/wdb/partbyenum.csv @@ -11,7 +11,7 @@ before,0,0,q,startproc each ("wdbenum";"hdb1"),1,,"Start WDB and HDB" before,0,0,q,.proc.sys "sleep 3",1,,"Wait for procs to start" before,0,0,q,wdbHandle:gethandle[`wdbenum],1,,"Open WDB handle" before,0,0,q,hdbHandle:gethandle[`hdb1],1,,"Open HDB handle" -before,0,0,q,"hdbsym:` sv (wdbHandle(`.wdb.hdbsettings;`hdbdir)),`sym",1,,"Get location of hdb sym file" +before,0,0,q,"hdbsym:` sv (wdbHandle"".wdb.hdbsettings`hdbdir""),`sym",1,,"Get location of hdb sym file" before,0,0,q,wdbHandle(set;`.wdb.numtab;`quote`trade!12 15),1,,"Set low treshold numbers for merging" run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote))",1,,"Send trade and quote updates to STP" run,0,0,q,.proc.sys "sleep 2",1,,"Wait for updates to publish" diff --git a/tests/stp/wdb/singlelog.csv b/tests/stp/wdb/singlelog.csv index 7817506fa..9cc999477 100644 --- a/tests/stp/wdb/singlelog.csv +++ b/tests/stp/wdb/singlelog.csv @@ -29,6 +29,7 @@ true,0,0,q,all raze `GOOG=wdbHandles[`sym]"exec distinct sym from trade",1,,"Che fail,0,0,q,wdbHandles[`tab]"count trade",1,,"Check final WDB still has no trade table" run,0,0,q,"wdbHandles[`all`sym] @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`trade)",1,,"Force save trade table to disk" run,0,0,q,"(value wdbHandles) @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`quote)",1,,"Force save quote table to disk" +run,0,0,q,"sym:get ` sv (wdbHandles[`all]"".wdb.hdbsettings`hdbdir""),`sym",1,,"Load the sym list the WDBs enumerated against (Korze cannot read an enumerated column without it)" run,0,0,q,"system ""l "",1_string temphdbdir",1,,"Load in temp HDB" true,0,0,q,(sum each (t2;q2))~count each (trade;quote),1,,"Check data was saved correctly to disk" true,0,0,q,all 0=wdbHandles[`all`sym] @\: "count trade",1,,"Check trade table is flushed from WDBs" diff --git a/tests/stp/wdb/tabperiod.csv b/tests/stp/wdb/tabperiod.csv index 9c0ac756c..af0c96a4f 100644 --- a/tests/stp/wdb/tabperiod.csv +++ b/tests/stp/wdb/tabperiod.csv @@ -32,6 +32,7 @@ true,0,0,q,all raze `GOOG=wdbHandles[`sym]"exec distinct sym from trade",1,,"Che fail,0,0,q,wdbHandles[`tab]"count trade",1,,"Check final WDB still has no trade table" run,0,0,q,"wdbHandles[`all`sym] @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`trade)",1,,"Force save trade table to disk" run,0,0,q,"(value wdbHandles) @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`quote)",1,,"Force save quote table to disk" +run,0,0,q,"sym:get ` sv (wdbHandles[`all]"".wdb.hdbsettings`hdbdir""),`sym",1,,"Load the sym list the WDBs enumerated against (Korze cannot read an enumerated column without it)" run,0,0,q,"system ""l "",1_string temphdbdir",1,,"Load in temp HDB" true,0,0,q,(sum each (t1;q1))~count each (trade;quote),1,,"Check data was saved correctly to disk" true,0,0,q,all 0=wdbHandles[`all`sym] @\: "count trade",1,,"Check trade table is flushed from WDBs" diff --git a/tests/stp/wdb/tabular.csv b/tests/stp/wdb/tabular.csv index 968eab001..d9ee0b0c2 100644 --- a/tests/stp/wdb/tabular.csv +++ b/tests/stp/wdb/tabular.csv @@ -32,6 +32,7 @@ true,0,0,q,all raze `GOOG=wdbHandles[`sym]"exec distinct sym from trade",1,,"Che fail,0,0,q,wdbHandles[`tab]"count trade",1,,"Check final WDB still has no trade table" run,0,0,q,"wdbHandles[`all`sym] @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`trade)",1,,"Force save trade table to disk" run,0,0,q,"(value wdbHandles) @\: (`.wdb.savetables;temphdbdir;.z.d;1b;`quote)",1,,"Force save quote table to disk" +run,0,0,q,"sym:get ` sv (wdbHandles[`all]"".wdb.hdbsettings`hdbdir""),`sym",1,,"Load the sym list the WDBs enumerated against (Korze cannot read an enumerated column without it)" run,0,0,q,"system ""l "",1_string temphdbdir",1,,"Load in temp HDB" true,0,0,q,(sum each (t1;q1))~count each (trade;quote),1,,"Check data was saved correctly to disk" true,0,0,q,all 0=wdbHandles[`all`sym] @\: "count trade",1,,"Check trade table is flushed from WDBs" diff --git a/torq.q b/torq.q index dfab9433d..cdf949ac6 100644 --- a/torq.q +++ b/torq.q @@ -6,6 +6,9 @@ loaded:1b // Initialised flag - used to check if the process is still initialisation initialised:0b +// q engine (kdb+/KDB-X, L, PeachQ or Korze) and what it can do: .proc.engine, .proc.enginename, .proc.capabilities +system"l ",$[count getenv`KDBCODE;getenv`KDBCODE;(-6_string .z.f),"code"],"/common/engine.q" + // function to add functions to initialisation list initlist:() initexecuted:() @@ -136,6 +139,7 @@ checkdependency:{[path] /- check TorQ config file is supplied if[()~key hsym last path;[.lg.e[`config;"TorQ config file not supplied ",string last path]]]; /-load config csv files + if[not `a in key `.proc; .proc.a:()]; a,:raze {("SSS";enlist ",") 0: hsym[x]} each path; /- check for kdb verion if[not `kdb in a[`app];a,:(`kdb;`$(string .z.K),".",string .z.k;`)]; @@ -143,6 +147,9 @@ checkdependency:{[path] dict:exec version by app from a; /- update table to contain string dependencies t:update vs[";";]each string dependency from (select from a where dependency<>`); + /- a "kdb x.y" requirement can only be judged on kdb+: on another engine .z.K is that engine's own version + /- number (Korze's is 1.07), and what the engine can do is in .proc.capabilities + if[not .proc.engine=`kdb;t:update {x where not x like "kdb *"}each dependency from t]; /-check each dependency within t {[t;dict] runchk[dict;t;]'[t[`dependency]]}[;dict]'[t]]} @@ -262,7 +269,7 @@ banner:{ -1 format"w : www.dataintellect.com"; -1 format"e : torqsupport@dataintellect.com"; -1 blank; - -1 format"Running on ","kdb+ ",(string .z.K)," ",string .z.k; + -1 format"Running on ",.proc.enginename," ",.proc.engineversion; if[count customtext:.proc.getapplication[];-1 format each customtext;-1 blank]; // prints custom text from file -1 full;} @@ -499,15 +506,18 @@ rolllogauto:{[] // Create log files as long as they haven't been switched off if[not any `debug`noredirect in key params; rolllogauto[]]; +// the engine and what it can do, in the log (after the redirect above, so it goes in the out log) +.proc.logengine[] + // utilities to load individual files / paths, and also a complete directory // this should then be enough to bootstrap -loadedf:enlist enlist"" +loadedf:0#` loadf0:{[reload;x] - if[not[reload]&x in loadedf;.lg.o[`fileload;"already loaded ",x];:()]; + if[not[reload]&(`$x) in loadedf;.lg.o[`fileload;"already loaded ",x];:()]; .lg.o[`fileload;"loading ",x]; $[`debug in key params;system"l ",x;@[system;"l ",x;{.lg.e[`fileload;"failed to load ",x," : ",y]}[x]]]; // if we got this far, file is loaded - loadedf,:enlist x; + .proc.loadedf,:`$x; .lg.o[`fileload;"successfully loaded ",x] } loadf:loadf0[0b] /load a file if it hasn't been loaded diff --git a/torq.sh b/torq.sh index 6a5530b5c..9d9df2cc6 100755 --- a/torq.sh +++ b/torq.sh @@ -160,7 +160,9 @@ stop() { if [[ ! $port =~ ^[0-9]+$ ]]; then port=$(($(eval echo \$$port))) fi - eval "$cmd `lsof -i :$port -sTCP:LISTEN | awk '{if(NR>1)print $2}'`" + # the pid comes from the process's own arguments (findproc), not from lsof on its port: lsof cannot see the + # listening socket of a process it is not allowed to inspect, which is every L process unless you are root + $cmd $(findproc "$1") fi }