diff --git a/code/common/merge.q b/code/common/merge.q index df7fef9d3..e10a9a844 100644 --- a/code/common/merge.q +++ b/code/common/merge.q @@ -20,13 +20,19 @@ getextrapartitiontype:{[tablename] tabparts }; -/- function to check each partiton type specified in sort.csv is actually present in specified table +/- function to check each partition type specified in sort.csv is actually present in specified table checkpartitiontype:{[tablename;extrapartitiontype] $[count colsnotintab:extrapartitiontype where not extrapartitiontype in cols get tablename; .lg.e[`checkpart;"parted columns ",(", " sv string colsnotintab)," are defined in sort.csv but not present in ",(string tablename)," table"]; .lg.o[`checkpart;"all parted columns defined in sort.csv are present in ",(string tablename)," table"]]; }; +/- function to check if the extra partition column has a symbol type +checksymboltype:{[tablename;extrapartitiontype] + $[all extrapartitiontype in exec c from meta[tablename] where t="s"; + .lg.o[`checksymbol;"all columns do have a symbol type in ",(string tablename)," table"]; + .lg.e[`checksymbol;"not all columns ",string[extrapartitiontype]," do have a symbol type in ",(string tablename)," table"]]; + }; /- function to get list of distinct combiniations for partition directories @@ -66,7 +72,7 @@ mergebypart:{[tablename;dest;partchunks] .lg.o[`merge;"upserting ",(string count chunks)," rows to ",string dest]; /-merge columns to permanent storage .[upsert;(dest;chunks); - {.lg.e[`merge;"failed to merge to ", sting[dest], " from segments ", (", " sv string chunks)];}]; + {.lg.e[`merge;"failed to merge to ", string[dest], " from segments ", (", " sv string chunks)];}]; }; /-merge data from partition in temporary storage to permanent storage, column by column rather than by entire partition diff --git a/code/common/os.q b/code/common/os.q index 9853115e1..db6ff4f20 100644 --- a/code/common/os.q +++ b/code/common/os.q @@ -21,4 +21,4 @@ df:{(`$("/";"\\")[NT]sv -1_v;`$-1#v:("/";"\\")[NT]vs pth(string x;x)[10h=type x] run:{system"q ",x} kill:{[p]@[(`::p);"\\\\";1];} sleep:{x:string x; system("sleep ",x;"timeout /t ",x," >nul")[NT]} -pthq:{[x] $[10h=type x;ssr [x;"\\";"/"];`$ -1 _ ssr [string (` sv x,`);"\\";"/"]]} +pthq:{[x] $[10h=type x;ssr [x;"\\";"/"];`$ -1 _ ssr [string (` sv x,`);"\\";"/"]]} \ No newline at end of file diff --git a/code/processes/idb.q b/code/processes/idb.q new file mode 100644 index 000000000..a663b7747 --- /dev/null +++ b/code/processes/idb.q @@ -0,0 +1,95 @@ +/-default parameters +\d .idb + +wdbtypes:@[value;wdbtypes;`wdb]; + +/-these parameters are only used once their value has been set with values retrieved from the WBD. +writedownmode:idbdir:savedir:currentpartition:symfilepath:`; +symsize:partitionsize:0; + +/-force loads sym file +loadsym:{[] + .lg.o[`load;"loading the sym file"]; + @[load;symfilepath; {.lg.e[`load;"failed to load sym file: ",string[symfilepath]," error: ",x]}]; + symsize::hcount symfilepath; + }; + +/-force loads IDB +loadidb:{[] + .lg.o[`load;"loading the db"]; + @[system; "l ", 1_string idbdir; {.lg.e[`load;"failed to load IDB: ",string[idbdir]," error: ",x]}]; + partitionsize::count key idbdir; + }; + +/- force loads the idb and the sym file +loaddb:{[] + starttime:.proc.ct[]; + loadsym[]; + loadidb[]; + .lg.o[`load;"IDB load has been finished for partition: ",string[currentpartition],". Time taken(ms): ",string .proc.ct[]-starttime]; + }; + +/- sets current partition and force loads the idb and the sym file. Called by the WDB after EOD. +rollover:{[pt] + currentpartition::pt; + idbdir::.Q.dd[savedir; currentpartition]; + loaddb[]; + }; + +/- reloads the db. Called by wdb process midday/eod. +intradayreload:{[] + starttime:.proc.ct[]; + if[symfilehaschanged[];loadsym[]]; + if[partitioncounthaschanged[];loadidb[]]; + .lg.o[`intradayreload;"IDB reload has been finished for partition: ",string[savedir],". Time taken(ms): ",string .proc.ct[]-starttime]; + }; + +/- checks if sym file has changed since last reload of the IDB. Records new sym size if changed. +symfilehaschanged:{[] + $[symsize<>c:hcount symfilepath;[symsize::c; 1b];0b] + }; + +/- checks if count of partitions has changed since last reload of the IDB. Records new partition count if changed. +/- the default writedown method doesn't need db reloading as no new directory is being created there. +partitioncounthaschanged:{[] + if[writedownmode~`default;:0b]; + $[partitionsize<>c:count key idbdir;[partitionsize::c; 1b];0b] + }; + +setparametersfromwdb:{[wdbHandle] + .lg.o[`init;"querying WDB, HDB locations, current partition and writedown mode from WDB"]; + params:@[wdbHandle; (each;value;`.wdb.savedir`.wdb.hdbdir`.wdb.currentpartition`.wdb.writedownmode); {.lg.e[`connection; "Failed to retrieve values from WDB."]; 'x}]; + savedir::hsym params[0]; + currentpartition::params[2]; + symfilepath::.Q.dd[hsym params[1]; `sym]; + writedownmode::params[3]; + idbdir::.Q.dd[savedir; $[writedownmode~`default;`;currentpartition]]; + .lg.o[`init;"Current settings: db folder: ",string[idbdir],", sym file: ",string[symfilepath],", writedownmode: ", string writedownmode]; + }; + +init:{[] + .lg.o[`init; "searching for servers"]; + .servers.startup[]; + .lg.o[`init;"getting connection handle to the WDB"]; + w:.servers.gethandlebytype[wdbtypes;`any]; + /-exit if no valid handle + if[0=count w; .lg.e[`connection;"no connection to the WDB could be established... failed to initialise."];:()]; + .lg.o[`init;"found a WDB process"]; + /-setting parameters in .idb namespace from WDB + setparametersfromwdb[w]; + .lg.o[`init;"loading the db and the sym file first time"]; + loaddb[]; + .lg.o[`init;"registering IDBs on WDB process..."]; + /-send sync message to WDB to register the existing IDBs. + @[w;(`.servers.registerfromdiscovery;`idb;0b);{.lg.e[`connection;"Failed to register IDB with WDB."];'x}]; + .lg.o[`init; "Initialisation of the IDB is done."]; + } + +\d . + +.idb.init[]; + +/- helper function to support queries against the sym column +maptoint:{[symbol] + sym?symbol + }; diff --git a/code/processes/wdb.q b/code/processes/wdb.q index 1f52cda67..b4a84d841 100644 --- a/code/processes/wdb.q +++ b/code/processes/wdb.q @@ -1,4 +1,4 @@ -/-TorQ wdb process - based upon w.q +/-TorQ wdb process - based upon w.q /http://code.kx.com/wsvn/code/contrib/simon/tick/w.q /-subscribes to tickerplant and appends data to disk after the in-memory table exceeds a specified number of rows /-the row check is set on a timer - the interval may be specified by the user @@ -11,7 +11,7 @@ /- define default parameters mode:@[value;`mode;`saveandsort]; /-the wdb process can operate in three modes /- 1. saveandsort - the process will subscribe for data, - /- periodically write data to disk and at EOD it will flush + /- periodically write data to disk and at EOD it will flush /- remaining data to disk before sorting it and informing /- GWs, RDBs and HDBs etc... /- 2. save - the process will subscribe for data, @@ -28,11 +28,14 @@ writedownmode:@[value;`writedownmode;`default]; /-the /- at EOD the data will be sorted and given attributes according to sort.csv before being moved to hdb /- 2. partbyattr - the data is partitioned by [ partitiontype ] and the column(s) assigned the parted attributed in sort.csv /- at EOD the data will be merged from each partiton before being moved to hdb + /- 3. partbyenum - the data is partitioned by [ partitiontype ] and a symbol column with parted attribution assigned in sort.csv + /- at EOD the data will be merged from each partiton before being moved to hdb +enumcol:@[value;`enumcol;`sym]; /-symbol column to enumerate by. Only used with writedownmode: partbyenum. -mergemode:@[value;`mergemode;`part]; /-the partbyattr writdown mode can merge data from tenmporary storage to the hdb in three ways: - /- 1. part - the entire partition is merged to the hdb - /- 2. col - each column in the temporary partitions are merged individually - /- 3. hybrid - partitions merged by column or entire partittion based on byte limit +mergemode:@[value;`mergemode;`part]; /-the partbyattr writdown mode can merge data from tenmporary storage to the hdb in three ways: + /- 1. part - the entire partition is merged to the hdb + /- 2. col - each column in the temporary partitions are merged individually + /- 3. hybrid - partitions merged by column or entire partittion based on byte limit mergenumbytes:@[value;`mergenumbytes;500000000]; /-default number of bytes for merge process @@ -41,12 +44,13 @@ mergenumtab:@[value;`mergenumtab;`quote`trade!10000 50000]; /-spe hdbtypes:@[value;`hdbtypes;`hdb]; /-list of hdb types to look for and call in hdb reload rdbtypes:@[value;`rdbtypes;`rdb]; /-list of rdb types to look for and call in rdb reload +idbtypes:@[value;`idbtypes;`idb]; /-list of idb types to look for and call in idb reload gatewaytypes:@[value;`gatewaytypes;`gateway]; /-list of gateway types to inform at reload tickerplanttypes:@[value;`tickerplanttypes;`tickerplant]; /-list of tickerplant types to try and make a connection to tpconnsleepintv:@[value;`tpconnsleepintv;10]; /-number of seconds between attempts to connect to the tp -tpcheckcycles:@[value;`tpcheckcycles;0W]; /-number of attempts to connect to tp before process is killed +tpcheckcycles:@[value;`tpcheckcycles;0W]; /-number of attempts to connect to tp before process is killed -sorttypes:@[value;`sorttypes;`sort]; /-list of sort types to look for upon a sort +sorttypes:@[value;`sorttypes;`sort]; /-list of sort types to look for upon a sort sortworkertypes:@[value;`sortworkertypes;`sortworker]; /-list of sort types to look for upon a sort being called with worker process subtabs:@[value;`subtabs;`]; /-list of tables to subscribe for @@ -58,7 +62,7 @@ replay:@[value;`replay;1b]; /-rep schema:@[value;`schema;1b]; /-retrieve schema from tickerplant settimer:@[value;`settimer;0D00:00:10]; /-set timer interval for row check -reloadorder:@[value;`reloadorder;`hdb`rdb]; /-order to reload hdbs and rdbs +reloadorder:@[value;`reloadorder;`hdb`rdb]; /-order to reload hdbs, rdbs sortcsv:@[value;`sortcsv;`:config/sort.csv]; /-location of csv file permitreload:@[value;`permitreload;1b]; /-enable reload of hdbs/rdbs @@ -74,8 +78,8 @@ eodwaittime:@[value;`eodwaittime;0D00:00:10.000]; /-len / - define .z.pd in order to connect to any worker processes .dotz.set[`.z.pd;{$[.z.K<3.3; - `u#`int$(); - `u#exec w from .servers.getservers[`proctype;sortworkertypes;()!();1b;0b]]}] + `u#`int$(); + `u#exec w from .servers.getservers[`proctype;sortworkertypes;()!();1b;0b]]}] /- fix any backslashes on windows savedir:.os.pthq savedir; @@ -85,6 +89,9 @@ hdbdir:.os.pthq hdbdir; saveenabled: any `save`saveandsort in mode; sortenabled: any `sort`saveandsort in mode; +/- parted writedown modes have special behaviour during merging or WDB initialisation +partwritemodes:`partbyattr`partbyenum; + / - log which modes are enabled switch: string `off`on; .lg.o[`savemode;"save mode is ",switch[saveenabled]]; @@ -101,150 +108,175 @@ mergemaxrows:{[tabname] mergenumrows^mergenumtab[tabname]} /- function to return a list of tables that the wdb process has been configured to deal within -tablelist:{[] sortedlist:exec tablename from `bytes xdesc .wdb.tabsizes; - (sortedlist union tables[`.]) except ignorelist} +tablelist:{[] sortedlist:exec tablename from `bytes xdesc tabsizes; + (sortedlist union tables[`.]) except ignorelist} /- function to upsert to specified directory -upserttopartition:{[dir;tablename;tabdata;pt;expttype;expt] - .lg.o[`save;"saving ",(string tablename)," data to partition ", - /- create directory location for selected partiton - string directory:` sv .Q.par[dir;pt;tablename], - /- replace random chracters in symbols with _ - (`$"_"^.Q.an .Q.an?"_" sv string - /- convert to symbols and replace any null values with `NONE - `NONE^ -1 _ `${@[x; where not ((type each x) in (10 -10h));string]} expt,(::)),`]; - /- upsert selected data matched on partition to specific directory - .[ - upsert; - (directory;r:?[tabdata;{(x;y;(),z)}[in;;]'[expttype;expt];0b;()]); - {[e] .lg.e[`savetablesbypart;"Failed to save table to disk : ",e];'e} - ]; - .lg.o[`track;"appending details to partsizes"]; - /-key in partsizes are directory to partition, need to drop training slash in directory key - .merge.partsizes[first ` vs directory]+:(count r;-22!r); - }; - -savetablesbypart:{[dir;pt;forcesave;tablename] - /- check row count and save if maxrows exceeded - /- forcesave will write flush the data to disk irrespective of counts - if[forcesave or maxrows[tablename] < arows: count value tablename; - .lg.o[`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; - /- get additional partition(s) defined by parted attribute in sort.csv - extrapartitiontype:.merge.getextrapartitiontype[tablename]; - /- check each partition type actually is a column in the selected table - .merge.checkpartitiontype[tablename;extrapartitiontype]; - /- get list of distinct combiniations for partition directories - extrapartitions:.merge.getextrapartitions[tablename;extrapartitiontype]; - /- enumerate data to be upserted - enumdata:.Q.en[hdbsettings[`hdbdir];0!.save.manipulate[tablename;`. tablename]]; - .lg.o[`save;"enumerated ",(string tablename)," table"]; - /- upsert data to specific partition directory - upserttopartition[dir;tablename;enumdata;pt;extrapartitiontype] each extrapartitions; - /- empty the table - .lg.o[`delete;"deleting ",(string tablename)," data from in-memory table"]; - @[`.;tablename;0#]; - /- run a garbage collection (if enabled) - if[gc;.gc.run[]]; - ]; - }; - +upserttopartition:{[dir;tablename;tabdata;pt;expttype;expt;writedownmode] + /- enumerate current extra partition against the hdb sym file + if[writedownmode~`partbyenum;i:`long$(` sv hdbsettings[`hdbdir],`sym)?first expt;]; + /- create directory location for selected partiton + /- replace non-alphanumeric characters in symbols with _ + /- convert to symbols and replace any null values with `NONE + directory:$[writedownmode~`partbyenum; + ` sv .Q.par[dir;pt;`$string i],tablename,`; + ` sv .Q.par[dir;pt;tablename],(`$"_"^.Q.an .Q.an?"_" sv string `NONE^ -1 _ `${@[x; where not ((type each x) in (10 -10h));string]} expt,(::)),`]; + .lg.o[`save;"saving ",(string tablename)," data to partition ",string directory]; + /- selecting rows of table with matching partition + r:?[tabdata;$[writedownmode~`partbyenum;enlist(in;first expttype;expt);{(x;y;(),z)}[in;;]'[expttype;expt]];0b;()]; + /- upsert selected data matched on partition to specific directory + .[upsert;(directory;r);{[e] .lg.e[`savetablesbypart;"Failed to save table to disk : ",e];'e}]; + .lg.o[`track;"appending details to partsizes"]; + /-key in partsizes are directory to partition, need to drop training slash in directory key + .merge.partsizes[first ` vs directory]+:(count r;-22!r); + }; + +savetablesbypart:{[dir;pt;forcesave;tablename;writedownmode] + /- check row count and save if maxrows exceeded + /- forcesave will write flush the data to disk irrespective of counts + if[forcesave or maxrows[tablename] < arows: count value tablename; + .lg.o[`rowcheck;"the ",(string tablename)," table consists of ", (string arows), " rows"]; + /- get additional partition(s) defined by parted attribute in sort.csv + extrapartitiontype:.merge.getextrapartitiontype[tablename]; + if[(writedownmode~`partbyenum) and 1.wdb.timeouttime) or (count[.wdb.reloadsummary]=.wdb.countreload); + /-insert process reload outcome into reloadsummary + reloadsummary[.z.w]:x; + /-log result of reload in wdb out log + .lg.o[`reloadproc;"the ", string[reloadsummary[.z.w]`process]," process ", string[reloadsummary[.z.w]`result]]; + if[(.proc.cp[]>timeouttime) or (count[reloadsummary]=countreload); .lg.o[`handler;"releasing processes"]; - .lg.o[`reload;string[count select from .wdb.reloadsummary where status=1]," out of ", string[count .wdb.reloadsummary]," processes successfully reloaded"]; - .wdb.flushend[]; - /-delete contents from .wdb.reloadsummary when reloads completed + .lg.o[`reload;string[count select from reloadsummary where status=1]," out of ", string[count reloadsummary]," processes successfully reloaded"]; + flushend[]; + /-delete contents from reloadsummary when reloads completed delete from `.wdb.reloadsummary]; - }; + }; /- evaluate contents of d dictionary asynchronously /- notify the gateway that we are done flushend:{ - if[not @[value;`.wdb.reloadcomplete;0b]; - @[{neg[x]"";neg[x][]};;()] each key reloadsummary; - informgateway(`reloadend;`); - .lg.o[`sort;"end of day sort is now complete"]; - .wdb.reloadcomplete:1b]; - /- run a garbage collection (if enabled) - if[gc;.gc.run[]]; - }; - -/- initialise reloadsummary, keyed tale to track status of local reloads + if[not @[value;`.wdb.reloadcomplete;0b]; + @[{neg[x]"";neg[x][]};;()] each key reloadsummary; + informgateway(`reloadend;`); + .lg.o[`sort;"end of day sort is now complete"]; + reloadcomplete::1b]; + /- run a garbage collection (if enabled) + if[gc;.gc.run[]]; + }; + +/- initialise reloadsummary, keyed table to track status of local reloads reloadsummary:([handle:`int$()]process:`symbol$();status:`boolean$();result:`symbol$()); doreload:{[pt] - .wdb.reloadcomplete:0b; - /-inform gateway of reload start - informgateway(`reloadstart;`); - getprocs[;pt] each reloadorder; - if[eodwaittime>0; - .timer.one[.wdb.timeouttime:.proc.cp[]+.wdb.eodwaittime;(value;".wdb.flushend[]");"release all hdbs and rdbs as timer has expired";0b]; - ]; - }; + reloadcomplete::0b; + /-inform gateway of reload start + informgateway(`reloadstart;`); + getprocs[;pt] each reloadorder; + if[eodwaittime>0; + .timer.one[timeouttime::.proc.cp[]+eodwaittime;(value;".wdb.flushend[]");"release all hdbs and rdbs as timer has expired";0b]; + ]; + }; // set .z.zd to control how data gets compressed setcompression:{[compression] if[3=count compression; - .lg.o[`compression;$[compression~16 0 0;"resetting";"setting"]," compression level to (",(";" sv string compression),")"]; - .dotz.set[`.z.zd;compression] - ]} + .lg.o[`compression;$[compression~16 0 0;"resetting";"setting"]," compression level to (",(";" sv string compression),")"]; + .dotz.set[`.z.zd;compression] + ]} resetcompression:{setcompression 16 0 0 } //check if the hdb directory contains current partition //if yes check if patition is empty and if it is not see if any of the tables exist in both the //temporary parition and the hdb partition. If there is a clash abort operation otherwise copy //each table to the hdb partition -movetohdb:{[dw;hw;pt] +movetohdb:{[dw;hw;pt] $[not(`$string pt)in key hsym`$-10 _ hw; .[.os.ren;(dw;hw);{.lg.e[`mvtohdb;"Failed to move data from wdb ",x," to hdb directory ",y," : ",z]}[dw;hw]]; not any a[dw]in(a:{key hsym`$x}) hw; - [{[y;x] + [{[y;x] $[not(b:`$last"/"vs x)in key y; [.[.os.ren;(x;y);{[x;y;e].lg.e[`mvtohdb;"Table ",string[x]," has failed to copy to ",string[y]," with error: ",e]}[b;y;]]; .lg.o[`mvtohdb;"Table ",string[b]," has been successfully moved to ",string[y]]]; @@ -273,7 +305,7 @@ endofdaysortdate:{[dir;pt;tablist;hdbsettings] reloadsymfile[.Q.dd[hdbsettings `hdbdir;`sym]]; {[x] .sort.sorttab[x];if[gc;.gc.run[]]} each tablist,'.Q.par[dir;pt;] each tablist]]; .lg.o[`sort;"finished sorting data"]; - + /-move data into hdb .lg.o[`mvtohdb;"Moving partition from the temp wdb ",(dw:.os.pth -1 _ string .Q.par[dir;pt;`])," directory to the hdb directory ",hw:.os.pth -1 _ string .Q.par[hdbsettings[`hdbdir];pt;`]]; .lg.o[`mvtohdb;"Attempting to move ",(", "sv string key hsym`$dw)," from ",dw," to ",hw]; @@ -281,17 +313,21 @@ endofdaysortdate:{[dir;pt;tablist;hdbsettings] /-call the posteod function .save.postreplay[hdbsettings[`hdbdir];pt]; - if[permitreload; + if[permitreload; doreload[pt]; ]; }; -merge:{[dir;pt;tableinfo;mergelimits;hdbsettings;mergemethod] +merge:{[dir;pt;tableinfo;mergelimits;hdbsettings;mergemethod;writedownmode] setcompression[hdbsettings[`compression]]; /- get tablename tabname:tableinfo[0]; - /- get list of partition directories for specified table - partdirs:` sv' tabledir,/:k:key tabledir:.Q.par[hsym dir;pt;tabname]; + /- get list of partition directories for specified table - partbyenum uses different folder structure vs partbyattr/default + partdirs:$[writedownmode in `partbyenum; + p where 0// +/- this function deletes
folder or the whole if it only has one element +removetablefromenumdir:{[partdir] + enumdir:` sv -1_` vs partdir; + .os.deldir .os.pth string $[1=count key enumdir;enumdir;partdir]; + }; + +endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode] /- merge data from partitons /- .z.pd funciton in finspace will cause an error. Add in this check to skip over the use of .z.pd. This should be temporary and will be removed when issue resolved by AWS. tempfix2:$[.finspace.enabled;0b;(0 < count .z.pd[])]; $[tempfix2 and ((system "s")<0); [.lg.o[`merge;"merging on worker"]; {(neg x)(`.wdb.reloadsymfile;y);(neg x)(::)}[;.Q.dd[hdbsettings `hdbdir;`sym]] each .z.pd[]; - /-upsert .merge.partsize data to sort workers, only needed for part and hybrid method + /-upsert .merge.partsize data to sort workers, only needed for part and hybrid method if[(mergemode~`hybrid)or(mergemode~`part); {(neg x)(upsert;`.merge.partsizes;y);(neg x)(::)}[;.merge.partsizes] each .z.pd[]; ]; - merge[dir;pt;;mergelimits;hdbsettings;mergemethod] peach flip (key tablist;value tablist); + merge[dir;pt;;mergelimits;hdbsettings;mergemethod;writedownmode] peach flip (key tablist;value tablist); /-clear out in memory table, .merge.partsizes, and call sort worker processes to do the same .lg.o[`eod;"Delete from partsizes"]; delete from `.merge.partsizes; @@ -344,182 +391,202 @@ endofdaymerge:{[dir;pt;tablist;mergelimits;hdbsettings;mergemethod] delete from `.merge.partsizes; /- run a garbage collection if enabled if[gc;.gc.run[]]};`);(neg x)(::)} each .z.pd[]; - ]; + ]; [.lg.o[`merge;"merging on main"]; reloadsymfile[.Q.dd[hdbsettings `hdbdir;`sym]]; - merge[dir;pt;;mergelimits;hdbsettings;mergemethod] each flip (key tablist;value tablist); + merge[dir;pt;;mergelimits;hdbsettings;mergemethod;writedownmode] each flip (key tablist;value tablist); .lg.o[`eod;"Delete from partsizes"]; delete from `.merge.partsizes; ] ]; /- if path exists, delete it - if[not () ~ key savedir; + if[not () ~ key savedir; .lg.o[`merge;"deleting temp storage directory"]; .os.deldir .os.pth[string[` sv savedir,`$string[pt]]]; ]; /-call the posteod function .save.postreplay[hdbsettings[`hdbdir];pt]; - $[permitreload; + $[permitreload; doreload[pt]; if[gc;.gc.run[]]; ]; }; - + /- end of day sort [depends on writedown mode] endofdaysort:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] - /- set compression level (.z.zd) - setcompression[hdbsettings[`compression]]; - $[writedownmode~`partbyattr; - endofdaymerge[dir;pt;tablist;mergelimits;hdbsettings;mergemethod]; - endofdaysortdate[dir;pt;key tablist;hdbsettings] - ]; - /- reset compression level (.z.zd) - resetcompression[16 0 0] - }; + /- set compression level (.z.zd) + setcompression[hdbsettings[`compression]]; + $[writedownmode in partwritemodes; + endofdaymerge[dir;pt;tablist;mergelimits;hdbsettings;mergemethod;writedownmode]; + endofdaysortdate[dir;pt;key tablist;hdbsettings] + ]; + /- reset compression level (.z.zd) + resetcompression[16 0 0] + }; /-function to send reload message to rdbs/hdbs reloadproc:{[h;d;ptype] - /-count of processes to be reloaded - .wdb.countreload:count[raze .servers.getservers[`proctype;;()!();1b;0b]each reloadorder]; - /-defining lambdas to be in asynchronously calling processes to reload + /-count of processes to be reloaded + countreload::count[raze .servers.getservers[`proctype;;()!();1b;0b]each reloadorder]; + /-defining lambdas to be in asynchronously calling processes to reload /-async call back function executed when eodwaittime>0 sendfunc:{[x;y;ptype].[{neg[y]@x};(x;y);{[ptype;x].lg.e[`reloadproc;"failed to reload the ",string[ptype]];'x}[ptype]]}; - /-reload function sent to processes by sendfunc in order to call process to reload. If process fail to reload log error + /-reload function sent to processes by sendfunc in order to call process to reload. If process fail to reload log error /-and call .wdb.handler with failed reload message. If reload is successful call .wdb.handler with successful reload message. reloadfunc:{[d;ptype] r:@[{(1b;`. `reload x)};d;{.lg.e[`reloadproc;"failed to reload from .wdb.reloadproc call. The error was : ",x];(0b;x)}]; (neg .z.w)(`.wdb.handler;(ptype;first r;$[first r;`$"reloaded successfully";`$"reload failed with error ",last r]));(neg .z.w)[]}; /-reload function to be executed if eodwaitime = 0 - sync message processes to reload and log if reload was successful or failed syncreloadfunc:{[h;d;ptype] r:@[h;({(1b;`reload x)};d);{[ptype;e] .lg.e[`reloadproc;"failed to reload the ",string[ptype],". The error was : ",e];(0b;e)}[ptype]]; - .lg.o[`reloadproc;"the ", string[ptype]," ", $[first r; "successfully reloaded"; "failed to reload with error ",last r]]}; + .lg.o[`reloadproc;"the ", string[ptype]," ", $[first r; "successfully reloaded"; "failed to reload with error ",last r]]}; .lg.o[`reloadproc;"sending reload call to ", string[ptype]]; $[eodwaittime>0; - sendfunc[(reloadfunc;d;ptype);h;ptype]; - syncreloadfunc[h;d;ptype] + sendfunc[(reloadfunc;d;ptype);h;ptype]; + syncreloadfunc[h;d;ptype] ]; } /-function to discover rdbs/hdbs and attempt to reconnect getprocs:{[x;y] - a:exec (w!x) from .servers.getservers[`proctype;x;()!();1b;0b]; - /-exit if no valid handle - if[0=count a; .lg.e[`connection;"no connection to the ",(string x)," could be established... failed to reload ",string x];:()]; - .lg.o[`connection;"connection to the ", (string x)," has been located"]; - /-send message along each handle a - reloadproc[;y;value a] each key a; - } + a:exec (w!x) from .servers.getservers[`proctype;x;()!();1b;0b]; + /-exit if no valid handle + if[0=count a; .lg.e[`connection;"no connection to the ",(string x)," could be established... failed to reload ",string x];:()]; + .lg.o[`connection;"connection to the ", (string x)," has been located"]; + /-send message along each handle a + reloadproc[;y;value a] each key a; + } /-function to send messages to gateway informgateway:{[message] - .lg.o[`informgateway;"sending message to gateway(s)"]; - $[count gateways:.servers.getservers[`proctype;gatewaytypes;()!();1b;0b]; - [ - {.[@;(y;x);{.lg.e[`informgateway;"unable to run command on gateway"];'x}]}[message;] each exec w from gateways; - .lg.o[`informgateway;"the message - ",(.Q.s message), " was sent to the gateways"] - ]; - .lg.e[`informgateway;"can't connect to the gateway - no gateway detected"]] - } - + .lg.o[`informgateway;"sending message to gateway(s)"]; + $[count gateways:.servers.getservers[`proctype;gatewaytypes;()!();1b;0b]; + [ + {.[@;(y;x);{.lg.e[`informgateway;"unable to run command on gateway"];'x}]}[message;] each exec w from gateways; + .lg.o[`informgateway;"the message - ",(.Q.s message), " was sent to the gateways"] + ]; + .lg.e[`informgateway;"can't connect to the gateway - no gateway detected"]] + } + /- function to call that will cause sort & reload process to sort data and reload rdb and hdbs informsortandreload:{[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod] .lg.o[`informsortandreload;"attempting to contact sort process to initiate data ",$[writedownmode~`default;"sort";"merge"]]; - $[count sortprocs:.servers.getservers[`proctype;sorttypes;()!();1b;0b]; - [if[(mergemode~`hybrid)or(mergemode~`part); - // for part and hybrid method sort procs need access to partsizes table data - upsert data tp sort procs - {(neg x)(upsert;`.merge.partsizes;y);(neg x)(::)}[;.merge.partsizes] each exec w from sortprocs; - ]; - {.[{neg[y]@x;neg[y][]};(x;y);{.lg.e[`informsortandreload;"unable to run command on sort and reload process"];'x}]}[(`.wdb.endofdaysort;dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod);] each exec w from sortprocs; - ]; - [.lg.e[`informsortandreload;"can't connect to the sortandreload - no sortandreload process detected"]; - // try to run the sort locally - endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]]]; - }; + $[count sortprocs:.servers.getservers[`proctype;sorttypes;()!();1b;0b]; + [if[(mergemode~`hybrid)or(mergemode~`part); + // for part and hybrid method sort procs need access to partsizes table data - upsert data tp sort procs + {(neg x)(upsert;`.merge.partsizes;y);(neg x)(::)}[;.merge.partsizes] each exec w from sortprocs; + ]; + {.[{neg[y]@x;neg[y][]};(x;y);{.lg.e[`informsortandreload;"unable to run command on sort and reload process"];'x}]}[(`.wdb.endofdaysort;dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod);] each exec w from sortprocs; + ]; + [.lg.e[`informsortandreload;"can't connect to the sortandreload - no sortandreload process detected"]; + // try to run the sort locally + endofdaysort[dir;pt;tablist;writedownmode;mergelimits;hdbsettings;mergemethod]]]; + }; /-function to set the timer for the save to disk function starttimer:{[] - $[@[value;`.timer.enabled;0b]; - [.lg.o[`init;"adding the wdb save to disk function to the timer"]; - /-add .wdb.savetodisk function to TorQ timer - .timer.repeat[.proc.cp[];0Wp;settimer;(`.wdb.savetodisk;`);"save wdb data to disk"]; - .lg.o[`init;"the timer has been set to ", string settimer]]; - /-if timer not enabled, prompt user to enable it - .lg.e[`init;"the timer has not been enabled - please enable the timer to run the wdb"]]; - } - -/-function to subscribe to tickerplant + $[@[value;`.timer.enabled;0b]; + [.lg.o[`init;"adding the wdb save to disk function to the timer"]; + /-add .wdb.savetodisk function to TorQ timer + .timer.repeat[.proc.cp[];0Wp;settimer;(`.wdb.savetodisk;`);"save wdb data to disk"]; + .lg.o[`init;"the timer has been set to ", string settimer]]; + /-if timer not enabled, prompt user to enable it + .lg.e[`init;"the timer has not been enabled - please enable the timer to run the wdb"]]; + } + +/-function to subscribe to tickerplant subscribe:{[] - s:.sub.getsubscriptionhandles[tickerplanttypes;();()!()]; - if[count s; - .lg.o[`subscribe;"tickerplant found - subscribing to ", string (subproc: first s)`procname]; - /- return the tables subscribed to and the tickerplant log date - subto:.sub.subscribe[subtabs;subsyms;schema;replay;subproc]; - /- check the tp logdate against the current date and correct if necessary - fixpartition[subto];];} - + s:.sub.getsubscriptionhandles[tickerplanttypes;();()!()]; + if[count s; + .lg.o[`subscribe;"tickerplant found - subscribing to ", string (subproc: first s)`procname]; + /- return the tables subscribed to and the tickerplant log date + subto:.sub.subscribe[subtabs;subsyms;schema;replay;subproc]; + /- check the tp logdate against the current date and correct if necessary + fixpartition[subto];]; + } + /- function to rectify data written to wrong partition -fixpartition:{[subto] - /- check if the tp logdate matches current date - if[not (tplogdate:subto[`tplogdate])~orig:.wdb.currentpartition; - .lg.o[`fixpartition;"Current partiton date does not match the ticker plant log date"]; - /- set the current partiton date to the log date - .wdb.currentpartition:tplogdate; - /- move the data that has been written to correct partition - pth1:.os.pth[-1 _ string .Q.par[savedir;orig;`]]; - pth2:.os.pth[-1 _ string .Q.par[savedir;tplogdate;`]]; - if[not ()~key hsym `$.os.pthq pth1; - /- delete any data in the current partiton directory - clearwdbdata[]; - .lg.o[`fixpartition;"Moving data from partition ",(.os.pthq pth1) ," to partition ",.os.pthq pth2]; - .[.os.ren;(pth1;pth2);{.lg.e[`fixpartition;"Failed to move data from wdb partition ",x," to wdb partition ",y," : ",z]}[pth1;pth2]]]; - ]; - } +fixpartition:{[subto] + /- check if the tp logdate matches current date + if[not (tplogdate:subto[`tplogdate])~orig:currentpartition; + .lg.o[`fixpartition;"Current partiton date does not match the ticker plant log date"]; + /- set the current partiton date to the log date + currentpartition::tplogdate; + /- move the data that has been written to correct partition + pth1:.os.pth[-1 _ string .Q.par[savedir;orig;`]]; + pth2:.os.pth[-1 _ string .Q.par[savedir;tplogdate;`]]; + if[not ()~key hsym `$.os.pthq pth1; + /- delete any data in the current partiton directory + clearwdbdata[]; + .lg.o[`fixpartition;"Moving data from partition ",(.os.pthq pth1) ," to partition ",.os.pthq pth2]; + .[.os.ren;(pth1;pth2);{.lg.e[`fixpartition;"Failed to move data from wdb partition ",x," to wdb partition ",y," : ",z]}[pth1;pth2]]]; + ]; + } + +/- for writedown modes partbyenum/default we make sure that partition 0/currentpartition has all the tables. +/- In that case we can use .Q.chk later to fill the db making it useable for intraday processes +initmissingtables:{[] + .lg.o[`fixpartition;"Adding missing tables(empty) to partition ",string currentpartition]; + inittable each tablelist[]; + filldb[]; + } + +filldb:{[] + /- for all enumerated partitions we want to make sure that all tables are present + .Q.chk[.Q.par[hsym savedir; currentpartition; `]]; + } + +/- initialises table t in db with its schema in part +inittable:{[t] + tabledir:` sv $[writedownmode~`partbyenum; .Q.par[.Q.dd[hsym savedir;currentpartition];0;t]; .Q.par[hsym savedir;currentpartition;t]],`; + if[() ~ key tabledir;tabledir set .Q.en[hsym hdbdir;0#value t]]; + } /- will check on each upd to determine where data should be flushed to disk (if max row limit has been exceeded) replayupd:{[f;t;d] - /- execute the supplied function + /- execute the supplied function f . (t;d); - /- if the data count is greater than the threshold, then flush data to disk - if[(rpc:count[value t]) > lmt:maxrows[t]; - .lg.o[`replayupd;"row limit (",string[lmt],") exceeded for ",string[t],". Table count is : ",string[rpc],". Flushing table to disk..."]; - savetables[savedir;getpartition[];0b;t]] - }[upd]; + /- if the data count is greater than the threshold, then flush data to disk + if[(rpc:count[value t]) > lmt:maxrows[t]; + .lg.o[`replayupd;"row limit (",string[lmt],") exceeded for ",string[t],". Table count is : ",string[rpc],". Flushing table to disk..."]; + savetables[savedir;getpartition[];0b;t]] + }[upd]; / - if there is data in the wdb directory for the partition, if there is remove it before replay / - is only for wdb processes that are saving data to disk -clearwdbdata:{[] - $[saveenabled and not () ~ key wdbpart:.Q.par[savedir;getpartition[];`]; - [.lg.o[`deletewdbdata;"removing wdb data (",(delstrg:1_string wdbpart),") prior to log replay"]; - @[.os.deldir;delstrg;{[e] .lg.e[`deletewdbdata;"Failed to delete existing wdb data. Error was : ",e];'e }]; - .lg.o[`deletewdbdata;"finished removing wdb data prior to log replay"]; - ]; - .lg.o[`deletewdbdata;"no directory found at ",1_string wdbpart] - ]; - }; - +clearwdbdata:{[] + $[saveenabled and not () ~ key wdbpart:.Q.par[savedir;getpartition[];`]; + [.lg.o[`deletewdbdata;"removing wdb data (",(delstrg:1_string wdbpart),") prior to log replay"]; + @[.os.deldir;delstrg;{[e] .lg.e[`deletewdbdata;"Failed to delete existing wdb data. Error was : ",e];'e }]; + .lg.o[`deletewdbdata;"finished removing wdb data prior to log replay"]; + ]; + .lg.o[`deletewdbdata;"no directory found at ",1_string wdbpart] + ]; + }; + / - function to check that the tickerplant is connected and subscription has been setup notpconnected:{[] - 0 = count select from .sub.SUBSCRIPTIONS where proctype in .wdb.tickerplanttypes, active} + 0 = count select from .sub.SUBSCRIPTIONS where proctype in tickerplanttypes, active} getsortparams:{[] - /- get the attributes csv file - /-even if running with a sort process should read this file to cope with backups - .sort.getsortcsv[.wdb.sortcsv]; - /- check the sort.csv for parted attributes `p if the writedownmode `partbyattr is selected - /- if each table does not have at least one `p attribute the process will exit - if[writedownmode~`partbyattr; - - /- check that default table is defined - if[not count exec distinct tabname from .sort.params where tabname=`default,att=`p,sort=1b; - .lg.e[`init;"default table not defined in sort.csv with at least one `p attribute and sort=1b"]; - ]; - .lg.o[`init;"default table defined in sort.csv and with at least one `p attribute and sort=1b"]; - - /- check for `p attributes - if[count notparted:distinct .sort.params[`tabname] except distinct exec tabname from .sort.params where att in `p; - .lg.e[`init;"parted attribute p not set at least once in sort.csv for table(s): ", ", " sv string notparted]; - ]; - .lg.o[`init;"parted attribute p set at least once for each table in sort.csv"]; - ]; - }; + /- get the attributes csv file + /-even if running with a sort process should read this file to cope with backups + .sort.getsortcsv[sortcsv]; + /- check the sort.csv for parted attributes `p if the writedownmode `partbyattr or `partbyenum is selected + /- if each table does not have at least one `p attribute the process will exit + if[writedownmode in partwritemodes; + + /- check that default table is defined + if[not count exec distinct tabname from .sort.params where tabname=`default,att=`p,sort=1b; + .lg.e[`init;"default table not defined in sort.csv with at least one `p attribute and sort=1b"]; + ]; + .lg.o[`init;"default table defined in sort.csv and with at least one `p attribute and sort=1b"]; + + /- check for `p attributes + if[count notparted:distinct .sort.params[`tabname] except distinct exec tabname from .sort.params where att in `p; + .lg.e[`init;"parted attribute p not set at least once in sort.csv for table(s): ", ", " sv string notparted]; + ]; + .lg.o[`init;"parted attribute p set at least once for each table in sort.csv"]; + ]; + }; \d . @@ -528,15 +595,15 @@ getsortparams:{[] /- make sure to request connections for all the correct types -.servers.CONNECTIONS:(distinct .servers.CONNECTIONS,.wdb.hdbtypes,.wdb.rdbtypes,.wdb.gatewaytypes,.wdb.tickerplanttypes,.wdb.sorttypes,.wdb.sortworkertypes) except ` +.servers.CONNECTIONS:(distinct .servers.CONNECTIONS,.wdb.hdbtypes,.wdb.rdbtypes,.wdb.gatewaytypes,.wdb.tickerplanttypes,.wdb.sorttypes,.wdb.sortworkertypes,.wdb.idbtypes) except `; /- adds endofday function to top level namespace endofday: .wdb.endofday; /- setting the upd and .u.end functions as the .wdb versions .u.end:{[pt] - .wdb.endofday[.wdb.getpartition[];()!()]; + .wdb.endofday[.wdb.getpartition[];()!()]; } - + /- set the replay upd .lg.o[`init;"setting the log replay upd function"]; upd:.wdb.replayupd; diff --git a/code/wdb/origstartup.q b/code/wdb/origstartup.q index 3f7cd4d50..db884fa29 100644 --- a/code/wdb/origstartup.q +++ b/code/wdb/origstartup.q @@ -1,17 +1,21 @@ \d .wdb startup:{[] - .lg.o[`init;"searching for servers"]; - .servers.startup[]; - if[writedownmode~`partbyattr; - .lg.o[`init;"writedown mode set to ",(string .wdb.writedownmode)] - ]; - .lg.o[`init;"partition has been set to [savedir]/[", (string partitiontype),"]/[tablename]/", $[writedownmode~`partbyattr;"[parted column(s)]/";""]]; - if[saveenabled; - //check if tickerplant is available and if not exit with error - if[not .finspace.enabled; /-TODO Remove when tickerplant fixed in finspace - .servers.startupdepcycles[.wdb.tickerplanttypes;.wdb.tpconnsleepintv;.wdb.tpcheckcycles]; - ]; - subscribe[]; - ]; - @[`.;`upd;:;.wdb.upd]; - } + .lg.o[`init; "searching for servers"]; + .servers.startup[]; + .lg.o[`init; "writedown mode set to ",(string .wdb.writedownmode)]; + $[writedownmode~`partbyattr; + .lg.o[`init; "partition has been set to [savedir]/[",(string partitiontype),"]/[tablename]/[parted column(s)]/"]; + writedownmode~`partbyenum; + .lg.o[`init; "partition has been set to [savedir]/[",(string partitiontype),"]/[parted symbol column enumerated]/[tablename]/"]; + .lg.o[`init; "partition has been set to [savedir]/[",(string partitiontype),"]/[tablename]/"]]; + if[saveenabled; + //check if tickerplant is available and if not exit with error + if[not .finspace.enabled; /-TODO Remove when tickerplant fixed in finspace + .servers.startupdepcycles[.wdb.tickerplanttypes; .wdb.tpconnsleepintv; .wdb.tpcheckcycles]; + ]; + subscribe[]; + /- add missing tables to partitions in case an IDB process wants to connect. Only applicable for partbyenum writedown mode + if[.wdb.writedownmode in `default`partbyenum;initmissingtables[]]; + ]; + @[`.; `upd; :; .wdb.upd]; + } \ No newline at end of file diff --git a/code/wdb/writedown.q b/code/wdb/writedown.q index c27bd6868..d0ee2566d 100644 --- a/code/wdb/writedown.q +++ b/code/wdb/writedown.q @@ -2,13 +2,12 @@ /-Required variables for savetables function compression:@[value;`compression;()]; /-specify the compress level, empty list if no required -savedir:@[value;`savedir;`:temphdb]; /-location to save wdb data -hdbdir:@[value;`hdbdir;`:hdb]; /-move wdb database to different location +savedir:hsym @[value;`savedir;`:temphdb]; /-location to save wdb data +hdbdir:hsym @[value;`hdbdir;`:hdb]; /-move wdb database to different location -hdbsettings:(`compression`hdbdir)!(compression;hdbdir); +hdbsettings:(`compression`hdbdir)!(compression;hsym hdbdir); numrows:@[value;`numrows;100000]; /-default number of rows numtab:@[value;`numtab;`quote`trade!10000 50000]; /-specify number of rows per table -gmttime:@[value;`gmttime;1b]; /-define whether the process is on gmttime or not maxrows:{[tabname] numrows^numtab[tabname]}; /- extract user defined row counts @@ -18,7 +17,7 @@ partitiontype:@[value;`partitiontype;`date]; /-set getpartition:@[value;`getpartition; /-function to determine the partition value {{@[value;`.wdb.currentpartition; - (`date^partitiontype)$(.z.D,.z.d)gmttime]}}]; + (`date^partitiontype)$.proc.cd[]]}}]; currentpartition:.wdb.getpartition[]; /- Initialise current partiton @@ -38,13 +37,14 @@ savetables:{[dir;pt;forcesave;tabname] ]; /- make addition to tabsizes .lg.o[`track;"appending table details to tabsizes"]; - .wdb.tabsizes+:([tablename:enlist tabname]rowcount:enlist arows;bytes:enlist -22!r); + .wdb.tabsizes+:([tablename:enlist tabname]rowcount:enlist arows;bytes:enlist -22!r); /- empty the table .lg.o[`delete;"deleting ",(string tabname)," data from in-memory table"]; @[`.;tabname;0#]; /- run a garbage collection (if enabled) if[gc;.gc.run[]]; - ]}; + :1b; + ]; 0b}; \d . /-endofperiod function diff --git a/config/passwords/idb.txt b/config/passwords/idb.txt new file mode 100644 index 000000000..272ed7758 --- /dev/null +++ b/config/passwords/idb.txt @@ -0,0 +1 @@ +idb:pass diff --git a/config/settings/gateway.q b/config/settings/gateway.q index 820c6c9bc..8787e7e4c 100644 --- a/config/settings/gateway.q +++ b/config/settings/gateway.q @@ -4,21 +4,21 @@ // if error & sync message, throws an error. Else passes result as normal // status - 1b=success, 0b=error. sync - 1b=sync, 0b=async formatresponse:{[status;sync;result]$[not[status]and sync;'result;result]}; -synccallsallowed:0b // whether synchronous calls are allowed -querykeeptime:0D00:30 // the time to keep queries in the -errorprefix:"error: " // the prefix for clients to look for in error strings -clearinactivetime:0D01:00 // the time to keep inactive handle data +synccallsallowed:0b // whether synchronous calls are allowed +querykeeptime:0D00:30 // the time to keep queries in the +errorprefix:"error: " // the prefix for clients to look for in error strings +clearinactivetime:0D01:00 // the time to keep inactive handle data \d .kxdash -enabled:0b // Functionality for parsing and handling kx dashboard queries - disabled by default +enabled:0b // Functionality for parsing and handling kx dashboard queries - disabled by default \d .proc loadprocesscode:1b // whether to load the process specific code defined at ${KDBCODE}/{process type} // Server connection details \d .servers -CONNECTIONS:`rdb`hdb // list of connections to make at start up +CONNECTIONS:`rdb`hdb`idb // list of connections to make at start up RETRY:0D00:01 // period on which to retry dead connections. If 0, no reconnection attempts \d .aqrest -loadexecute:0b // Whether to reset .aqrest.execute +loadexecute:0b // Whether to reset .aqrest.execute diff --git a/config/settings/idb.q b/config/settings/idb.q new file mode 100644 index 000000000..f37d53b62 --- /dev/null +++ b/config/settings/idb.q @@ -0,0 +1,11 @@ +// Bespoke IDB config +\d .idb +wdbtypes:`wdb; + +// Server connection details +\d .servers +CONNECTIONS:`wdb // list of connections to make at start up +STARTUP:1b // create connections + +\d .proc +loadprocesscode:0b // whether to load the process specific code defined at ${KDBCODE}/{process type} diff --git a/config/settings/sort.q b/config/settings/sort.q index b32c3d7f7..8f3233700 100644 --- a/config/settings/sort.q +++ b/config/settings/sort.q @@ -23,9 +23,9 @@ mode:`sort // the wdb process can operate in three // save mode process. When this is triggered it will sort the // data on disk, apply attributes and the trigger a reload on the // rdb and hdb processes - -mergenumrows:100000 // default number of rows for merge process -mergenumtab:`quote`trade!10000 50000 // specify number of rows per table + +mergenumrows:100000 // default number of rows for merge process +mergenumtab:`quote`trade!10000 50000 // specify number of rows per table tpconnsleepintv:10 // number of seconds between attempts to connect to the tp upd:insert // value of the upd function @@ -33,19 +33,18 @@ replay:1b // replay the tickerplant log file schema:1b // retrieve schema from tickerplant settimer:0D00:00:10 // timer to check if data needs written to disk partitiontype:`date // set type of partition (defaults to `date, can be `date, `month or `year) -gmttime:1b // define whether the process is on gmttime or not getpartition:{@[value; - `.wdb.currentpartition; - (`date^partitiontype)$(.z.D,.z.d)gmttime]} //function to determine the partition value + `.wdb.currentpartition; + (`date^partitiontype)$.proc.cd[]]} //function to determine the partition value reloadorder:`hdb`rdb // order to reload hdbs and rdbs hdbdir:`:hdb // move wdb database to different location sortcsv:hsym first .proc.getconfigfile["sort.csv"] // location of csv file permitreload:1b // enable reload of hdbs/rdbs compression:() // specify the compress level, empty list if no required gc:1b // garbage collect at appropriate points (after each table save and after sorting data) -eodwaittime:0D00:00:10.000 // time to wait for async calls to complete at eod +eodwaittime:0D00:00:10.000 // time to wait for async calls to complete at eod // Server connection details \d .servers -CONNECTIONS:`hdb`tickerplant`rdb`gateway // list of connections to make at start up -STARTUP:1b // create connections +CONNECTIONS:`hdb`tickerplant`rdb`gateway // list of connections to make at start up +STARTUP:1b // create connections diff --git a/config/settings/wdb.q b/config/settings/wdb.q index 1c9d12390..16250689d 100644 --- a/config/settings/wdb.q +++ b/config/settings/wdb.q @@ -5,6 +5,7 @@ ignorelist:`heartbeat`logmsg // list of tables to ignore hdbtypes:`hdb // list of hdb types to look for and call in hdb reload rdbtypes:`rdb // list of rdb types to look for and call in rdb reload +idbtypes:`idb // list of idb types to look for and call in rdb reload gatewaytypes:`gateway // list of gateway types to inform at reload tickerplanttypes:`segmentedtickerplant // list of tickerplant types to try and make a connection to subtabs:` // list of tables to subscribe for (` for all) @@ -30,6 +31,10 @@ writedownmode:`default // at EOD the data will be sorted and given attributes according to sort.csv before being moved to hdb // 2. partbyattr - the data is partitioned by [ partitiontype ] and the column(s)assigned the parted attributed in sort.csv // at EOD the data will be merged from each partiton before being moved to hdb + // 3. partbyenum - the data is partitioned by [ partitiontype ] and a symbol column with parted attrobution assigned in sort.csv + // at EOD the data will be merged from each partiton before being moved to hdb +enumcol:`sym; // default column for partitioning. Only used with writedownmode: partbyenum. + mergemode:`part // the partbyattr writdown mode can merge data from tenmporary storage to the hdb in three ways: // 1. part - the entire partition is merged to the hdb // 2. col - each column in the temporary partitions are merged individually @@ -45,8 +50,7 @@ replay:1b schema:1b // retrieve schema from tickerplant settimer:0D00:00:10 // timer to check if data needs written to disk partitiontype:`date // set type of partition (defaults to `date, can be `date, `month or `year) -gmttime:1b // define whether the process is on gmttime or not -getpartition:{@[value;`.wdb.currentpartition;(`date^partitiontype)$(.z.D,.z.d)gmttime]} // function to determine the partition value +getpartition:{@[value;`.wdb.currentpartition;(`date^partitiontype)$.proc.cd[]]} // function to determine the partition value reloadorder:`hdb`rdb // order to reload hdbs and rdbs hdbdir:`:hdb // move wdb database to different location sortcsv:hsym first .proc.getconfigfile"sort.csv" // location of csv file @@ -58,9 +62,9 @@ tpcheckcycles:0W // Server connection details \d .servers -CONNECTIONS:`hdb`tickerplant`rdb`gateway`sort // list of connections to make at start up STARTUP:1b // create connections +CONNECTIONS:`hdb`tickerplant`rdb`gateway`sort // list of connections to make at start up \d .proc -loadprocesscode:1b // Whether to load the process specific code defined at ${KDBCODE}/{process type} +loadprocesscode:1b // Whether to load the process specific code defined at ${KDBCODE}/{process type} diff --git a/docs/Processes.md b/docs/Processes.md index 4abdb1725..4ebf3f335 100755 --- a/docs/Processes.md +++ b/docs/Processes.md @@ -988,7 +988,7 @@ process should be configured in the processes.csv file with a proctype of sort. The save process will check for processes with a proctype of sort when it attempts to trigger the end of day sort of the data. -The wdb process provides two methods for persisting data to disk and +The wdb process provides three methods for persisting data to disk and sorting at the end of the day. - default - Data is persisted into a partition defined by the @@ -1019,14 +1019,53 @@ sorting at the end of the day. need for sorting. The number of rows that are joined at once is limited by the mergenumrows and mergenumtab parameters. -The optional partbyattr method may provide a significant saving in time -at the end of day, allowing the hdb to be accessed sooner. For large +- partbyenum - Data is persisted to a partition scheme where the partition + is derived from parameters in the sort.csv file. In this mode partition + only can be done by one column which has parted attribute applied on it + and it also has to be of a symbol type. The partitioning on disk will + be the enumerated symbol entries of the parted symbol column. The + enumeration is done against the HDB sym file. + The general partition scheme is of the form + \[wdbdir\]/\[partitiontype\]/\[parted enumerated symbol column\]/\[table(s)\]/. + A typical partition directory would be similar to(for ex sym: MSFT_N) + wdb/database/2015.11.26/456/trade/ + In the above example, the data is parted by sym, and number 456 is + the order of MSFT_N symbol entry in the HDB sym file. + + The advantage of partbyenum over partbyattr could be that the + directory structure it uses represents a HDB that is ready to be loaded + intraday. At the end of the day the data gets upserted to the HDB the + same way it would be when using partbyattr. + +The optional partbyattr/partbyenum methods may provide a significant saving in +time at the end of day, allowing the hdb to be accessed sooner. For large data sets with a low cardinality (ie. small number of distinct elements) the optional method may provide a significant time saving, upwards of 50%. The optional method should also reduce the memory usage at the end of day event, as joining data is generally less memory intensive than sorting. + + +Intraday Database (IDB) +-------------------- + +The Intraday Database or IDB is a simple process that allows access to +data written down intraday. This assumes that there is an existing WDB +process creating a DB on disk that can be loaded with a simple load command. +As of now default and partbyenum WDB writedown modes are supported. +The responsibility of an IDB is therefore: + +1. Serving queries. Since partbyenum writedown mode is done by enumerated + symbol columns a helper function maptoint is implemented to support + symbol lookup in sym file: + select from trade where int=maptoint[`MSFT_N] + +2. Can be triggered for a reload. This is usually done by the WDB process + periodically. + +![IDB diagram](graphics/idb.png) + Tickerplant Log Replay diff --git a/docs/graphics/idb.png b/docs/graphics/idb.png new file mode 100644 index 000000000..14ff0b409 Binary files /dev/null and b/docs/graphics/idb.png differ diff --git a/tests/stp/idbdefault/config/sort.csv b/tests/stp/idbdefault/config/sort.csv new file mode 100644 index 000000000..1113f6251 --- /dev/null +++ b/tests/stp/idbdefault/config/sort.csv @@ -0,0 +1,4 @@ +tabname,att,column,sort +quote,p,sym,1 +trade,p,sym,1 +default,p,sym,1 \ No newline at end of file diff --git a/tests/stp/idbdefault/idbdefault.csv b/tests/stp/idbdefault/idbdefault.csv new file mode 100644 index 000000000..0899fac3c --- /dev/null +++ b/tests/stp/idbdefault/idbdefault.csv @@ -0,0 +1,35 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,.servers.startup[],1,,"Start TorQ connection management" +before,0,0,q,startproc["stp1"],1,,"Start STP" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for proc to start" +before,0,0,q,stpHandle:gethandle[`stp1],1,,"Open STP handle" +before,0,0,q,logdir:1_string stpHandle(`.stplg.dldir),1,,"Get location of log directory" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for connections to get set up" +before,0,0,q,.os.md hdbdir,1,,"Creating HDB directory" +before,0,0,q,startproc each ("wdbdefault";"hdb1";"gateway1";"idbdefault"),1,,"Start WDB, HDB, GW and IDB" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for procs to start" +before,0,0,q,wdbHandle:gethandle[`wdbdefault],1,,"Open WDB handle" +before,0,0,q,idbHandle:gethandle[`idbdefault],1,,"Open IDB handle" +before,0,0,q,gwHandle:gethandle[`gateway1],1,,"Open GW handle" +before,0,0,q,wdbHandle(set;`.wdb.numtab;`quote`trade!7 8),1,,"Set low treshold numbers for merging" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade";`idb);0~count gwHandle[],1,,"Check if trade table initialised correctly with 0 rows" +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 get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where sym=`GOOG";`idb);5~count gwHandle[],1,,"Check trade update was correctly published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from quote_iex";`idb);0~count gwHandle[],1,,"Check if table that not have been published has 0 rows" +run,0,0,q,wdbHandle(`.u.end;`.wdb.currentpartition),1,,"Trigger EOD on WDB" +run,0,0,q,.proc.sys "sleep 2",1,,"Wait for merge to HDB to happen" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where sym in `GOOG";`hdb);5~count gwHandle[],1,,"Check if HDB has the merged data" +true,0,0,q,0=sum idbHandle@/: {raze ("count select from ";x)} each string wdbHandle(`.wdb.tablelist;()),1,,"Check if all tables have been correctly initilised with 0 rows after eod trigger" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade";`idb);0~count gwHandle[],1,,"Check if IDB has been emptied." +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 get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where sym=`GOOG";`idb);5~count gwHandle[],1,,"Check trade update was correctly published" +run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;enlist[(count[testtrade[0]]#`round2)],1_testtrade);(`quote;testquote))",1,,"Publish some new data to the tickplant with new symbol" +run,0,0,q,.proc.sys "sleep 2",1,,"Wait for updates to get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where sym=`round2";`idb);10~count gwHandle[],1,,"Check if IDB was realoaded and is aware if the new symbol" +after,0,0,q,hclose each (wdbHandle;gwHandle;idbHandle);,1,,"Close handles" +after,0,0,q,stopproc each ("idbdefault";"wdbdefault";"hdb1";"gateway1";"stp1"),1,,"Stop all procs" +after,0,0,q,.os.deldir logdir,1,,"Delete test segmented tickerplant logs" +after,0,0,q,.os.deldir 1_string hdbdir,1,,"Delete temp HDB" +after,0,0,q,.os.deldir 1_string wdbdir,1,,"Delete temp WDB" \ No newline at end of file diff --git a/tests/stp/idbdefault/process.csv b/tests/stp/idbdefault/process.csv new file mode 100644 index 000000000..7116909db --- /dev/null +++ b/tests/stp/idbdefault/process.csv @@ -0,0 +1,8 @@ +host,port,proctype,procname,U,localtime,g,T,w,load,startwithall,extras,qcmd +localhost,{KDBBASEPORT}+100,discovery,discovery1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/discovery.q,1,,q +localhost,{KDBBASEPORT}+101,segmentedtickerplant,stp1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/segmentedtickerplant.q,1,-schemafile ${TORQHOME}/database.q,q +localhost,{KDBBASEPORT}+110,idb,idbdefault,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/idb.q,1,,q +localhost,{KDBBASEPORT}+111,wdb,wdbdefault,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q -.wdb.mode saveandsort -.wdb.sortcsv ${KDBTESTS}/stp/idbdefault/config/sort.csv -.wdb.savedir ${KDBTESTS}/stp/idbdefault/tempwdb/ -.wdb.hdbdir ${KDBTESTS}/stp/idbdefault/temphdb/ -.wdb.mergemode hybrid -.wdb.mergenumbytes 50000000 -.merge.mergebybytelimit 1 -.wdb.settimer 0D00:00:02,1,,q +localhost,{KDBBASEPORT}+104,hdb,hdb1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBTESTS}/stp/idbdefault/temphdb/,1,,q +localhost,{KDBBASEPORT}+106,gateway,gateway1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/gateway.q,1,,q +localhost,{KDBBASEPORT}+107,sort,sort1,${TORQAPPHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q ${KDBTESTS}/merge/wdb/config/wdbsettings.q,1,-s -2, diff --git a/tests/stp/idbdefault/run.sh b/tests/stp/idbdefault/run.sh new file mode 100644 index 000000000..e2c7d2995 --- /dev/null +++ b/tests/stp/idbdefault/run.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Handle command-line arguments +source $KDBTESTS/flagparse.sh + +# Path to test directory +testpath=${KDBTESTS}/stp/idbdefault + +# Start procs +${TORQHOME}/torq.sh start discovery1 -csv ${testpath}/process.csv + +# Start test proc +/usr/bin/rlwrap q ${TORQHOME}/torq.q \ + -proctype test -procname test1 \ + -test ${testpath} \ + -load ${KDBTESTS}/helperfunctions.q ${testpath}/settings.q \ + -testresults ${KDBTESTS}/stp/results/ \ + -runtime $run \ + -procfile ${testpath}/process.csv \ + $debug $stop $write $quiet + +# Shut down procs +${TORQHOME}/torq.sh stop discovery1 -csv ${testpath}/process.csv \ No newline at end of file diff --git a/tests/stp/idbdefault/settings.q b/tests/stp/idbdefault/settings.q new file mode 100644 index 000000000..8d4bc3d00 --- /dev/null +++ b/tests/stp/idbdefault/settings.q @@ -0,0 +1,17 @@ +// IPC connection parameters +.servers.CONNECTIONS:`segmentedtickerplant`wdb`hdb`idb`gateway`sort; +.servers.USERPASS:`admin:admin; + +// Paths to process CSV and test STP log directory +processcsv:getenv[`KDBTESTS],"/stp/idbdefault/process.csv"; +wdbdir:hsym `$getenv[`KDBTESTS],"/stp/idbdefault/tempwdb/"; +hdbdir:hsym `$getenv[`KDBTESTS],"/stp/idbdefault/temphdb/"; +testlogdb:"testlog"; + +// Test updates +testtrade:((5#`GOOG),5?`4;10?100.0;10?100i;10#0b;10?.Q.A;10?.Q.A;10#`buy); +testquote:(10?`4;(5?50.0),50+5?50.0;10?100.0;10?100i;10?100i;10?.Q.A;10?.Q.A;10#`3); + +// Function projections (using functions from helperfunctions.q) +startproc:startorstopproc["start";;processcsv]; +stopproc:startorstopproc["stop";;processcsv]; diff --git a/tests/stp/idbpartbyenum/config/sort.csv b/tests/stp/idbpartbyenum/config/sort.csv new file mode 100644 index 000000000..1113f6251 --- /dev/null +++ b/tests/stp/idbpartbyenum/config/sort.csv @@ -0,0 +1,4 @@ +tabname,att,column,sort +quote,p,sym,1 +trade,p,sym,1 +default,p,sym,1 \ No newline at end of file diff --git a/tests/stp/idbpartbyenum/idbenum.csv b/tests/stp/idbpartbyenum/idbenum.csv new file mode 100644 index 000000000..fafee05a8 --- /dev/null +++ b/tests/stp/idbpartbyenum/idbenum.csv @@ -0,0 +1,40 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,.servers.startup[],1,,"Start TorQ connection management" +before,0,0,q,startproc["stp1"],1,,"Start STP" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for proc to start" +before,0,0,q,stpHandle:gethandle[`stp1],1,,"Open STP handle" +before,0,0,q,logdir:1_string stpHandle(`.stplg.dldir),1,,"Get location of log directory" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for connections to get set up" +before,0,0,q,.os.md hdbdir,1,,"Creating HDB directory" +before,0,0,q,startproc each ("wdbenum";"hdb1";"gateway1";"idbenum";"idbenum2"),1,,"Start WDB, HDB, GW, IDB and IDB2" +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,idbHandle:gethandle[`idbenum],1,,"Open IDB handle" +before,0,0,q,gwHandle:gethandle[`gateway1],1,,"Open GW handle" +before,0,0,q,wdbHandle(set;`.wdb.numtab;`quote`trade!7 8),1,,"Set low treshold numbers for merging" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade";`idb);0~count gwHandle[],1,,"Check if trade table initialised correctly with 0 rows" +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 get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where int=maptoint[`GOOG]";`idb);5~count gwHandle[],1,,"Check trade update was correctly published and maptoint works" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from quote_iex";`idb);0~count gwHandle[],1,,"Check if table that not have been published has 0 rows" +run,0,0,q,wdbHandle(`.u.end;`.wdb.currentpartition),1,,"Trigger EOD on WDB" +run,0,0,q,.proc.sys "sleep 2",1,,"Wait for merge to HDB to happen" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where sym=`GOOG";`hdb);5~count gwHandle[],1,,"Check if HDB has the merged data" +true,0,0,q,0=sum idbHandle@/: {raze ("count select from ";x)} each string wdbHandle(`.wdb.tablelist;()),1,,"Check if all tables have been correctly initilised with 0 rows after eod trigger" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade";`idb);0~count gwHandle[],1,,"Check if IDB has been emptied." +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 get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where int=maptoint[`GOOG]";`idb);5~count gwHandle[],1,,"Check trade update was correctly published and maptoint works, meaning IDB has a new partition GOOG and is reloaded" +run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;enlist[(count[testtrade[0]]#`round2)],1_testtrade);(`quote;testquote))",1,,"Publish some new data to the tickplant with new symbol" +run,0,0,q,.proc.sys "sleep 2",1,,"Wait for updates to get published" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where int=maptoint[`round2]";`idb);10~count gwHandle[],1,,"Check if IDB was realoaded and is aware if the new symbol" +run,0,0,q,neg[gwHandle](`.gw.asyncexec;(.proc.sys;"sleep 2");`idb),1,,"Make one IDB busy on GW" +run,0,0,q,starttime:.proc.ct[],1,,"Start recording execution time of next query so we see that GW could execute it while IDB1 was busy" +true,0,0,q,neg[gwHandle](`.gw.asyncexec;"select from trade where int=maptoint[`round2]";`idb);10~count gwHandle[],1,,"Check if GW is still available to serve our query since we have 2 backends" +true,0,0,q,(.proc.ct[]-starttime)<100000,1,,"Check if GW executed previous query in time - so NOT after IDB1 finished sleeping" +true,0,0,q,2~count exec distinct inuse from gwHandle(`.gw.servers) where servertype in `idb,1,,"Check if all 2 IDBs could come back alive on GW." +after,0,0,q,hclose each (wdbHandle;gwHandle;idbHandle);,1,,"Close handles" +after,0,0,q,kill9proc each ("wdbenum";"hdb1";"gateway1";"idbenum";"idbenum2";"stp1"),1,,"Stop all procs" +after,0,0,q,.os.deldir logdir,1,,"Delete test segmented tickerplant logs" +after,0,0,q,.os.deldir 1_string hdbdir,1,,"Delete temp HDB" +after,0,0,q,.os.deldir 1_string wdbdir,1,,"Delete temp WDB" \ No newline at end of file diff --git a/tests/stp/idbpartbyenum/process.csv b/tests/stp/idbpartbyenum/process.csv new file mode 100644 index 000000000..e481dd814 --- /dev/null +++ b/tests/stp/idbpartbyenum/process.csv @@ -0,0 +1,9 @@ +host,port,proctype,procname,U,localtime,g,T,w,load,startwithall,extras,qcmd +localhost,{KDBBASEPORT}+100,discovery,discovery1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/discovery.q,1,,q +localhost,{KDBBASEPORT}+101,segmentedtickerplant,stp1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/segmentedtickerplant.q,1,-schemafile ${TORQHOME}/database.q,q +localhost,{KDBBASEPORT}+102,idb,idbenum,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/idb.q,1,,q +localhost,{KDBBASEPORT}+109,idb,idbenum2,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/idb.q,1,,q +localhost,{KDBBASEPORT}+103,wdb,wdbenum,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q -.wdb.writedownmode partbyenum -.wdb.mode saveandsort -.wdb.sortcsv ${KDBTESTS}/stp/idbpartbyenum/config/sort.csv -.wdb.savedir ${KDBTESTS}/stp/idbpartbyenum/tempwdb/ -.wdb.hdbdir ${KDBTESTS}/stp/idbpartbyenum/temphdb/ -.wdb.mergemode hybrid -.wdb.mergenumbytes 50000000 -.merge.mergebybytelimit 1 -.wdb.settimer 0D00:00:02,1,,q +localhost,{KDBBASEPORT}+104,hdb,hdb1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBTESTS}/stp/idbpartbyenum/temphdb/,1,,q +localhost,{KDBBASEPORT}+106,gateway,gateway1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/gateway.q,1,,q +localhost,{KDBBASEPORT}+107,sort,sort1,${TORQAPPHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q ${KDBTESTS}/merge/wdb/config/wdbsettings.q,1,-s -2, diff --git a/tests/stp/idbpartbyenum/run.sh b/tests/stp/idbpartbyenum/run.sh new file mode 100644 index 000000000..b362946ab --- /dev/null +++ b/tests/stp/idbpartbyenum/run.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Handle command-line arguments +source $KDBTESTS/flagparse.sh + +# Path to test directory +testpath=${KDBTESTS}/stp/idbpartbyenum + +# Start procs +${TORQHOME}/torq.sh start discovery1 -csv ${testpath}/process.csv + +# Start test proc +/usr/bin/rlwrap q ${TORQHOME}/torq.q \ + -proctype test -procname test1 \ + -test ${testpath} \ + -load ${KDBTESTS}/helperfunctions.q ${testpath}/settings.q \ + -testresults ${KDBTESTS}/stp/results/ \ + -runtime $run \ + -procfile ${testpath}/process.csv \ + $debug $stop $write $quiet + +# Shut down procs +${TORQHOME}/torq.sh stop discovery1 -csv ${testpath}/process.csv \ No newline at end of file diff --git a/tests/stp/idbpartbyenum/settings.q b/tests/stp/idbpartbyenum/settings.q new file mode 100644 index 000000000..dc4a21bbb --- /dev/null +++ b/tests/stp/idbpartbyenum/settings.q @@ -0,0 +1,17 @@ +// IPC connection parameters +.servers.CONNECTIONS:`segmentedtickerplant`wdb`hdb`idb`gateway`sort; +.servers.USERPASS:`admin:admin; + +// Paths to process CSV and test STP log directory +processcsv:getenv[`KDBTESTS],"/stp/idbpartbyenum/process.csv"; +wdbdir:hsym `$getenv[`KDBTESTS],"/stp/idbpartbyenum/tempwdb/"; +hdbdir:hsym `$getenv[`KDBTESTS],"/stp/idbpartbyenum/temphdb/"; +testlogdb:"testlog"; + +// Test updates +testtrade:((5#`GOOG),5?`4;10?100.0;10?100i;10#0b;10?.Q.A;10?.Q.A;10#`buy); +testquote:(10?`4;(5?50.0),50+5?50.0;10?100.0;10?100i;10?100i;10?.Q.A;10?.Q.A;10#`3); + +// Function projections (using functions from helperfunctions.q) +startproc:startorstopproc["start";;processcsv]; +stopproc:startorstopproc["stop";;processcsv]; diff --git a/tests/stp/wdb/config/sort.csv b/tests/stp/wdb/config/sort.csv new file mode 100644 index 000000000..1113f6251 --- /dev/null +++ b/tests/stp/wdb/config/sort.csv @@ -0,0 +1,4 @@ +tabname,att,column,sort +quote,p,sym,1 +trade,p,sym,1 +default,p,sym,1 \ No newline at end of file diff --git a/tests/stp/wdb/partbyenum.csv b/tests/stp/wdb/partbyenum.csv new file mode 100644 index 000000000..2fae50992 --- /dev/null +++ b/tests/stp/wdb/partbyenum.csv @@ -0,0 +1,32 @@ +action,ms,bytes,lang,code,repeat,minver,comment +before,0,0,q,.servers.startup[],1,,"Start TorQ connection management" +before,0,0,q,startproc["stpnone"],1,,"Start STP" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for proc to start" +before,0,0,q,stpHandle:gethandle[`stpnone],1,,"Open STP handle" +before,0,0,q,stpHandle(`.stplg.init;testlogdb),1,,"Create test stplog test directory" +before,0,0,q,logdir:1_string stpHandle(`.stplg.dldir),1,,"Get location of log directory" +before,0,0,q,.proc.sys "sleep 3",1,,"Wait for connections to get set up" +before,0,0,q,.os.md temphdbdir,1,,"Creating HDB directory" +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,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" +true,0,0,q,count[first testtrade]~wdbHandle "count trade",1,,"Check trade update was correctly published" +true,0,0,q,count[first testquote]~wdbHandle "count quote",1,,"Check quote update was correctly published" +run,0,0,q,"stpHandle @/: `.u.upd ,/: ((`trade;testtrade);(`quote;testquote))",1,,"Send trade and quote updates to STP to force a writedown" +run,0,0,q,.proc.sys "sleep 3",1,,"Wait for updates to publish and writedown to happen" +true,0,0,q,"all (distinct (testtrade[0]),(testquote[0])) in get hdbsym",1,,"Check if all symbols are enumerated against hdb sym" +true,0,0,q,all {any x like/: y}[;folder_patterns] exec ptdir from wdbHandle `.merge.partsizes,1,,"Check if all partitions are placed in the correct enumerated tables" +true,0,0,q,0=wdbHandle"count trade",1,,"Check final WDB has no trade table" +run,0,0,q,wdbHandle(`.u.end;`.wdb.currentpartition),1,,"Trigger EOD on WDB" +run,0,0,q,.proc.sys "sleep 3",1,,"Wait for merge to HDB to happen" +true,0,0,q,(2*count[first testtrade])~hdbHandle "count select from trade",1,,"Check trade in hdb" +true,0,0,q,(2*count[first testquote])~hdbHandle "count select from quote",1,,"Check quote in hdb" +after,0,0,q,kill9proc each ("stpnone";"wdbenum";"hdb1"),1,,"Stop all procs" +after,0,0,q,.os.deldir logdir,1,,"Delete test segmented tickerplant logs" +after,0,0,q,.os.deldir 1_string temphdbdir,1,,"Delete temp HDB" +after,0,0,q,.os.deldir 1_string wdbdir,1,,"Delete temp WDB" diff --git a/tests/stp/wdb/process.csv b/tests/stp/wdb/process.csv index 5e3624d3d..aae3e0f4d 100644 --- a/tests/stp/wdb/process.csv +++ b/tests/stp/wdb/process.csv @@ -3,6 +3,8 @@ localhost,{KDBBASEPORT}+100,discovery,discovery1,${TORQHOME}/appconfig/passwords localhost,{KDBBASEPORT}+101,wdb,wdball,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q,1,,q localhost,{KDBBASEPORT}+102,wdb,wdbsymfilt,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,180,,${KDBCODE}/processes/wdb.q,1,-.wdb.subsyms GOOG,q localhost,{KDBBASEPORT}+103,wdb,wdbtabfilt,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,180,,${KDBCODE}/processes/wdb.q,1,-.wdb.subtabs quote,q +localhost,{KDBBASEPORT}+107,wdb,wdbenum,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBCODE}/processes/wdb.q -.wdb.writedownmode partbyenum -.wdb.mode saveandsort -.wdb.sortcsv ${KDBTESTS}/stp/wdb/config/sort.csv -.wdb.savedir ${KDBTESTS}/stp/wdb/tempwdb/ -.wdb.hdbdir ${KDBTESTS}/stp/wdb/temphdb/ -.wdb.settimer 0D00:00:02,1,,q +localhost,{KDBBASEPORT}+108,hdb,hdb1,${TORQHOME}/appconfig/passwords/accesslist.txt,1,1,,,${KDBTESTS}/stp/wdb/temphdb/,1,,q localhost,{KDBBASEPORT}+104,segmentedtickerplant,stpnone,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/segmentedtickerplant.q,1,-schemafile ${TORQHOME}/database.q -.stplg.multilog singular,q localhost,{KDBBASEPORT}+105,segmentedtickerplant,stptabular,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/segmentedtickerplant.q,1,-schemafile ${TORQHOME}/database.q -.stplg.multilog tabular,q localhost,{KDBBASEPORT}+106,segmentedtickerplant,stptabperiod,${TORQHOME}/appconfig/passwords/accesslist.txt,1,0,,,${KDBCODE}/processes/segmentedtickerplant.q,1,-schemafile ${TORQHOME}/database.q -.stplg.multilog tabperiod,q diff --git a/tests/stp/wdb/settings.q b/tests/stp/wdb/settings.q index c9b9c6f82..bf98412a9 100644 --- a/tests/stp/wdb/settings.q +++ b/tests/stp/wdb/settings.q @@ -1,16 +1,21 @@ // IPC connection parameters -.servers.CONNECTIONS:`wdb`segmentedtickerplant`tickerplant; +.servers.CONNECTIONS:`wdb`segmentedtickerplant`tickerplant`hdb; .servers.USERPASS:`admin:admin; // Paths to process CSV and test STP log directory processcsv:getenv[`KDBTESTS],"/stp/wdb/process.csv"; -temphdbdir:hsym `$getenv[`KDBTESTS],"/stp/wdb/tmphdb/"; +wdbdir:hsym `$getenv[`KDBTESTS],"/stp/wdb/tempwdb/"; +temphdbdir:hsym `$getenv[`KDBTESTS],"/stp/wdb/temphdb/"; testlogdb:"testlog"; // Test updates testtrade:((5#`GOOG),5?`4;10?100.0;10?100i;10#0b;10?.Q.A;10?.Q.A;10#`buy); testquote:(10?`4;(5?50.0),50+5?50.0;10?100.0;10?100i;10?100i;10?.Q.A;10?.Q.A;10#`3); +// expected WDB folder structure +folder_patterns:{"*",x,"*"}each 1_/:string ` sv/: cross[hsym each `$string til count distinct testtrade[0],testquote[0];`trade`quote]; + + // Function projections (using functions from helperfunctions.q) startproc:startorstopproc["start";;processcsv]; -stopproc:startorstopproc["stop";;processcsv]; \ No newline at end of file +stopproc:startorstopproc["stop";;processcsv];