Skip to content
2 changes: 1 addition & 1 deletion code/common/dbwriteutils.q
Original file line number Diff line number Diff line change
Expand Up @@ -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:{
Expand Down
191 changes: 191 additions & 0 deletions code/common/engine.q
Original file line number Diff line number Diff line change
@@ -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<count .z.l};::;1b];.z.o in `l32`m32`w32);
`kdb;
`unknown];
}

// -25!(handles;::) - bc no handles, it only errors if -25! is missing
probebroadcast:{[found] -25!(0#0i;::); 1b}

// -30!(handle;0b;msg) answers a deferred sync request; fails with 'domain when handle is not in .z.W.
// As 0Wi never is. An engine without -30! fails with something else
probedeferred:{[found] @[{-30!(0Wi;0b;1); 1b};::;{x~"domain"}]}

// a unix socket which does not exist: an engine with unix sockets reports the failed connection (the operating system's
// "connection refused" or "no such file"; Korze a bare 'hop), one without them reports something else (PeachQ: 'nyi)
// by default on port 5 as unused by convention (below 1024: no q process can listen there unless run as root)
probeunixsockets:{[found]
// for windows (w32, w64), 0b
if[.z.o like "w*";
:0b];
// try socket, if it opens 1b. Else, see error message
@[{hclose hopen `:unix://5; 1b};::;{any x like/: ("*refused*";"*[Nn]o such file*";"hop")}]
};

probereval:{[found] 2~reval(value;"1+1")}

// .Q.w[], the memory statistics (Korze has no .Q.w)
probememstats:{[found] 99h=type .Q.w[]}

// does .z.ph evaluate "?expr" requests through .h.val? (PeachQ has .h.val but .z.ph never calls it, so existence is not enough)
// the second argument is the HTTP header dictionary q passes to .z.ph; it must hold Accept-Encoding. .h.val is put back afterwards
probehval:{[found]
hadval:`val in key `.h;
oldval:$[hadval;.h.val;::];
.proc.hvalcalled:0b;
.h.val:{[x] .proc.hvalcalled:1b; value x};
@[.z.ph;("?1+1";(`Host,`$"Accept-Encoding")!("localhost";""));::];
$[hadval;.h.val:oldval;![`.h;();0b;enlist`val]];
.proc.hvalcalled}

// replay a log through a named pipe, as TorQ does for zipped logs (see replayinner in tickerlogreplay.q)
probeupd:{[x] .proc.probecount:.proc.probecount+1}
probecount:0
probepipereplay:{[found]
if[not .z.o like "l*"; :0b];
withscratch {[dir]
logfile:hsym`$dir,"/log";
pipe:dir,"/pipe";
logfile set ();
// a log with two messages
handle:hopen logfile;
handle enlist (`.proc.probeupd;1);
handle enlist (`.proc.probeupd;2);
hclose handle;
system "mkfifo '",pipe,"'";
// feeds the pipe once something reads it
system "(cat '",(1_string logfile),"' > '",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<count each candidates;"\\";"/"];
dir:$["/"=last tmp;-1_tmp;tmp],"/torqprobe_",string[.z.i],"_",string first 1?1000000000;
result:@[f;dir;0b];
@[{hdel each (` sv/: x,/:key x),x};hsym`$dir;::];
result
}

// kdb+/KDB-X: by the version K and release date k (an argument so the rules can be tested for any version)
versioncapabilities:{[K;k]
exec feature!((K>=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];
4 changes: 3 additions & 1 deletion code/common/grafana.q
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 2 additions & 0 deletions code/common/monitoringchecks.q
Original file line number Diff line number Diff line change
Expand Up @@ -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[],"<br/>";
Expand All @@ -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[],"<br />";
Expand Down
15 changes: 15 additions & 0 deletions code/common/pubsub.q
Original file line number Diff line number Diff line change
Expand Up @@ -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,:()];
Expand Down
2 changes: 1 addition & 1 deletion code/common/u.q
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
3 changes: 2 additions & 1 deletion code/dqc/advanceddtd.q
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions code/dqc/memoryusage.q
Original file line number Diff line number Diff line change
Expand Up @@ -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")];
Expand Down
3 changes: 2 additions & 1 deletion code/filealerter/pcapdecoder.q
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion code/handlers/permissions.q
Original file line number Diff line number Diff line change
Expand Up @@ -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]];
Expand Down
8 changes: 1 addition & 7 deletions code/handlers/trackservers.q
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions code/handlers/writeaccess.q
Original file line number Diff line number Diff line change
Expand Up @@ -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]];
Expand Down
6 changes: 4 additions & 2 deletions code/processes/dqe.q
Original file line number Diff line number Diff line change
Expand Up @@ -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"];
Expand Down
6 changes: 3 additions & 3 deletions code/processes/gateway.q
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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]]]
Expand All @@ -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];
Expand Down
11 changes: 10 additions & 1 deletion code/processes/tickerlogreplay.q
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 2 additions & 1 deletion code/processes/wdb.q
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading