ccdactivities.cpp 201 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "jlib.hpp"
  15. #include "ccd.hpp"
  16. #include "ccdquery.hpp"
  17. #include "ccdstate.hpp"
  18. #include "ccdactivities.hpp"
  19. #include "ccdqueue.ipp"
  20. #include "ccdsnmp.hpp"
  21. #include "ccdfile.hpp"
  22. #include "ccdkey.hpp"
  23. #include "rtlkey.hpp"
  24. #include "eclrtl_imp.hpp"
  25. #include "rtlread_imp.hpp"
  26. #include "jhtree.hpp"
  27. #include "jlog.hpp"
  28. #include "jmisc.hpp"
  29. #include "udplib.hpp"
  30. #include "csvsplitter.hpp"
  31. #include "thorxmlread.hpp"
  32. #include "thorcommon.ipp"
  33. #include "jstats.h"
  34. size32_t diskReadBufferSize = 0x10000;
  35. using roxiemem::OwnedRoxieRow;
  36. using roxiemem::OwnedConstRoxieRow;
  37. using roxiemem::IRowManager;
  38. #define maxContinuationSize 48000 // note - must fit in the 2-byte length field... but also needs to be possible to send back from Roxie server->slave in one packet
  39. size32_t serializeRow(IOutputRowSerializer * serializer, IMessagePacker *output, const void *unserialized)
  40. {
  41. CSizingSerializer sizer;
  42. serializer->serialize(sizer, (const byte *) unserialized);
  43. unsigned serializedLength = sizer.size();
  44. void *udpBuffer = output->getBuffer(serializedLength, true);
  45. CRawRowSerializer memSerializer(serializedLength, (byte *) udpBuffer);
  46. serializer->serialize(memSerializer, (const byte *) unserialized);
  47. assertex(memSerializer.size() == serializedLength);
  48. output->putBuffer(udpBuffer, serializedLength, true);
  49. return serializedLength;
  50. }
  51. inline void appendBuffer(IMessagePacker * output, size32_t size, const void * data, bool isVariable)
  52. {
  53. void *recBuffer = output->getBuffer(size, isVariable);
  54. memcpy(recBuffer, data, size);
  55. output->putBuffer(recBuffer, size, isVariable);
  56. }
  57. extern void putStatsValue(IPropertyTree *node, const char *statName, const char *statType, unsigned __int64 val)
  58. {
  59. if (val)
  60. {
  61. StringBuffer xpath;
  62. xpath.appendf("att[@name='%s']", statName);
  63. IPropertyTree *att = node->queryPropTree(xpath.str());
  64. if (!att)
  65. {
  66. att = node->addPropTree("att", createPTree());
  67. att->setProp("@name", statName);
  68. }
  69. att->setProp("@type", statType);
  70. att->setPropInt64("@value", val);
  71. }
  72. }
  73. extern void putStatsValue(StringBuffer &reply, const char *statName, const char *statType, unsigned __int64 val)
  74. {
  75. if (val)
  76. {
  77. reply.appendf(" <att name='%s' type='%s' value='%"I64F"d'/>\n", statName, statType, val);
  78. }
  79. }
  80. CActivityFactory::CActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  81. : id(_id),
  82. subgraphId(_subgraphId),
  83. queryFactory(_queryFactory),
  84. helperFactory(_helperFactory),
  85. kind(_kind)
  86. {
  87. if (helperFactory)
  88. {
  89. Owned<IHThorArg> helper = helperFactory();
  90. meta.set(helper->queryOutputMeta());
  91. }
  92. }
  93. void CActivityFactory::addChildQuery(unsigned id, ActivityArray *childQuery)
  94. {
  95. childQueries.append(*childQuery);
  96. childQueryIndexes.append(id);
  97. }
  98. ActivityArray *CActivityFactory::queryChildQuery(unsigned idx, unsigned &id)
  99. {
  100. if (childQueries.isItem(idx))
  101. {
  102. id = childQueryIndexes.item(idx);
  103. return &childQueries.item(idx);
  104. }
  105. id = 0;
  106. return NULL;
  107. }
  108. class CSlaveActivityFactory : public CActivityFactory, implements ISlaveActivityFactory
  109. {
  110. public:
  111. CSlaveActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  112. : CActivityFactory(_graphNode.getPropInt("@id", 0), _subgraphId, _queryFactory, _helperFactory, getActivityKind(_graphNode))
  113. {
  114. }
  115. virtual IQueryFactory &queryQueryFactory() const
  116. {
  117. return CActivityFactory::queryQueryFactory();
  118. }
  119. void addChildQuery(unsigned id, ActivityArray *childQuery)
  120. {
  121. CActivityFactory::addChildQuery(id, childQuery);
  122. }
  123. StringBuffer &toString(StringBuffer &ret) const
  124. {
  125. return ret.appendf("%p", this);
  126. }
  127. bool getEnableFieldTranslation() const
  128. {
  129. return queryFactory.getEnableFieldTranslation();
  130. }
  131. const char *queryQueryName() const
  132. {
  133. return queryFactory.queryQueryName();
  134. }
  135. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  136. {
  137. return CActivityFactory::queryChildQuery(idx, id);
  138. }
  139. virtual unsigned queryId() const
  140. {
  141. return CActivityFactory::queryId();
  142. }
  143. virtual ThorActivityKind getKind() const
  144. {
  145. return CActivityFactory::getKind();
  146. }
  147. virtual void noteStatistics(const StatsCollector &fromStats)
  148. {
  149. CActivityFactory::noteStatistics(fromStats);
  150. }
  151. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  152. {
  153. CActivityFactory::getEdgeProgressInfo(idx, edge);
  154. }
  155. virtual void getNodeProgressInfo(IPropertyTree &node) const
  156. {
  157. CActivityFactory::getNodeProgressInfo(node);
  158. }
  159. virtual void resetNodeProgressInfo()
  160. {
  161. CActivityFactory::resetNodeProgressInfo();
  162. }
  163. virtual void getActivityMetrics(StringBuffer &reply) const
  164. {
  165. CActivityFactory::getActivityMetrics(reply);
  166. }
  167. IRoxieSlaveContext *createSlaveContext(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  168. {
  169. return queryFactory.createSlaveContext(logctx, packet);
  170. }
  171. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  172. {
  173. if (datafile)
  174. addXrefFileInfo(reply, datafile);
  175. }
  176. IRoxieSlaveContext *createChildQueries(IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IProbeManager *_probeManager, SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  177. {
  178. if (!childQueries.length())
  179. logctx.setDebuggerActive(false);
  180. if (meta.needsDestruct() || meta.needsSerialize() || childQueries.length())
  181. {
  182. Owned<IRoxieSlaveContext> queryContext = queryFactory.createSlaveContext(logctx, packet);
  183. ForEachItemIn(idx, childQueries)
  184. {
  185. if (!_probeManager) // MORE - the probeAllRows is a hack!
  186. _probeManager = queryContext->queryProbeManager();
  187. IActivityGraph *childGraph = createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), NULL, _probeManager, logctx); // MORE - the parent is wrong!
  188. childGraphs.append(*childGraph);
  189. queryContext->noteChildGraph(childQueryIndexes.item(idx), childGraph);
  190. childGraph->onCreate(queryContext, colocalArg); //NB: onCreate() on helper for activities in child graph are delayed, otherwise this would go wrong.
  191. }
  192. return queryContext.getClear();
  193. }
  194. return NULL;
  195. }
  196. Owned<const IResolvedFile> datafile;
  197. protected:
  198. static IPropertyTree *queryStatsNode(IPropertyTree *parent, const char *xpath)
  199. {
  200. StringBuffer levelx;
  201. const char *sep = strchr(xpath, '/');
  202. if (sep)
  203. levelx.append(sep-xpath, xpath);
  204. else
  205. levelx.append(xpath);
  206. IPropertyTree *child = parent->queryPropTree(levelx);
  207. if (!child)
  208. {
  209. const char *id = strchr(levelx, '[');
  210. if (!id)
  211. {
  212. child = createPTree(levelx);
  213. parent->addPropTree(levelx, child);
  214. }
  215. else
  216. {
  217. StringBuffer elem;
  218. elem.append(id-levelx, levelx);
  219. child = createPTree(elem);
  220. parent->addPropTree(elem, child);
  221. loop
  222. {
  223. StringBuffer attr, val;
  224. id++;
  225. while (*id != '=')
  226. attr.append(*id++);
  227. id++;
  228. char qu = *id++;
  229. while (*id != qu)
  230. val.append(*id++);
  231. child->setProp(attr, val);
  232. id++;
  233. if (*id == ']')
  234. {
  235. if (id[1]!='[')
  236. break;
  237. id++;
  238. }
  239. else
  240. throwUnexpected();
  241. }
  242. }
  243. }
  244. if (sep)
  245. return queryStatsNode(child, sep+1);
  246. else
  247. return child;
  248. }
  249. };
  250. //================================================================================================
  251. class CRoxieSlaveActivity : public CInterface, implements IRoxieSlaveActivity, implements ICodeContext
  252. {
  253. protected:
  254. SlaveContextLogger &logctx;
  255. Linked<IRoxieQueryPacket> packet;
  256. mutable Owned<IRoxieSlaveContext> queryContext; // bit of a hack but easier than changing the ICodeContext callback interface to remove const
  257. const CSlaveActivityFactory *basefactory;
  258. IArrayOf<IActivityGraph> childGraphs;
  259. IHThorArg *basehelper;
  260. PartNoType lastPartNo;
  261. MemoryBuffer serializedCreate;
  262. MemoryBuffer resentInfo;
  263. CachedOutputMetaData meta;
  264. Owned<IOutputRowSerializer> serializer;
  265. Owned<IEngineRowAllocator> rowAllocator;
  266. #ifdef _DEBUG
  267. Owned<IProbeManager> probeManager;
  268. #endif
  269. bool aborted;
  270. bool resent;
  271. bool isOpt;
  272. bool variableFileName;
  273. bool allowFieldTranslation;
  274. Owned<const IResolvedFile> varFileInfo;
  275. virtual void setPartNo(bool filechanged) = 0;
  276. inline void checkPartChanged(PartNoType &newPart)
  277. {
  278. if (newPart.partNo!=lastPartNo.partNo || newPart.fileNo!=lastPartNo.fileNo)
  279. {
  280. lastPartNo.partNo = newPart.partNo;
  281. bool filechanged = lastPartNo.fileNo != newPart.fileNo;
  282. lastPartNo.fileNo = newPart.fileNo;
  283. setPartNo(filechanged);
  284. }
  285. }
  286. virtual bool needsRowAllocator()
  287. {
  288. return meta.needsSerialize() || meta.isVariableSize();
  289. }
  290. virtual void onCreate()
  291. {
  292. #ifdef _DEBUG
  293. // MORE - need to consider debugging....
  294. if (probeAllRows)
  295. {
  296. probeManager.setown(createProbeManager());
  297. queryContext.setown(basefactory->createChildQueries(basehelper, childGraphs, probeManager, logctx, packet));
  298. }
  299. else
  300. #endif
  301. queryContext.setown(basefactory->createChildQueries(basehelper, childGraphs, NULL, logctx, packet));
  302. if (!queryContext)
  303. queryContext.setown(basefactory->createSlaveContext(logctx, packet));
  304. if (meta.needsSerialize())
  305. serializer.setown(meta.createRowSerializer(queryContext->queryCodeContext(), basefactory->queryId()));
  306. if (needsRowAllocator())
  307. rowAllocator.setown(getRowAllocator(meta.queryOriginal(), basefactory->queryId()));
  308. unsigned parentExtractSize;
  309. serializedCreate.read(parentExtractSize);
  310. const byte * parentExtract = serializedCreate.readDirect(parentExtractSize);
  311. basehelper->onCreate(this, NULL, &serializedCreate);
  312. basehelper->onStart(parentExtract, &serializedCreate);
  313. deserializeExtra(serializedCreate);
  314. if (variableFileName) // note - in keyed join with dependent index case, kj itself won't have variableFileName but indexread might
  315. {
  316. CDateTime cacheDate(serializedCreate);
  317. unsigned checksum;
  318. serializedCreate.read(checksum);
  319. varFileInfo.setown(querySlaveDynamicFileCache()->lookupDynamicFile(logctx, queryDynamicFileName(), cacheDate, checksum, &packet->queryHeader(), isOpt, true));
  320. setVariableFileInfo();
  321. }
  322. }
  323. virtual void deserializeExtra(MemoryBuffer &out)
  324. {
  325. }
  326. CRoxieSlaveActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_factory)
  327. : logctx(_logctx), packet(_packet), basefactory(_factory)
  328. {
  329. allowFieldTranslation = _factory->getEnableFieldTranslation();
  330. resent = packet->getContinuationLength() != 0;
  331. serializedCreate.setBuffer(packet->getContextLength(), (void *) packet->queryContextData(), false);
  332. if (resent)
  333. resentInfo.setBuffer(packet->getContinuationLength(), (void *) packet->queryContinuationData(), false);
  334. basehelper = _hFactory();
  335. aborted = false;
  336. lastPartNo.partNo = 0xffff;
  337. lastPartNo.fileNo = 0xffff;
  338. isOpt = false;
  339. variableFileName = false;
  340. meta.set(basehelper->queryOutputMeta());
  341. }
  342. ~CRoxieSlaveActivity()
  343. {
  344. ::Release(basehelper);
  345. }
  346. public:
  347. IMPLEMENT_IINTERFACE;
  348. virtual const char *queryDynamicFileName() const = 0;
  349. virtual void setVariableFileInfo() = 0;
  350. virtual IIndexReadActivityInfo *queryIndexReadActivity() { throwUnexpected(); } // should only be called for index activity
  351. virtual unsigned queryId()
  352. {
  353. return basefactory->queryId();
  354. }
  355. virtual bool check()
  356. {
  357. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  358. doCheck(output);
  359. output->flush(true);
  360. return true;
  361. }
  362. virtual void doCheck(IMessagePacker *output)
  363. {
  364. // MORE - unsophisticated default - if this approach seems fruitful then we can add something more thorough
  365. void *recBuffer = output->getBuffer(sizeof(bool), false);
  366. bool ret = false;
  367. memcpy(recBuffer, &ret, sizeof(bool));
  368. }
  369. virtual void abort()
  370. {
  371. if (logctx.queryTraceLevel() > 2)
  372. {
  373. StringBuffer s;
  374. logctx.CTXLOG("Aborting running activity: %s", packet->queryHeader().toString(s).str());
  375. }
  376. logctx.requestAbort();
  377. aborted = true;
  378. if (queryContext)
  379. {
  380. Owned<IException> E = MakeStringException(ROXIE_ABORT_ERROR, "Roxie server requested abort for running activity");
  381. queryContext->notifyAbort(E);
  382. }
  383. }
  384. virtual IRoxieQueryPacket *queryPacket() const
  385. {
  386. return packet;
  387. }
  388. void limitExceeded(bool keyed = false)
  389. {
  390. RoxiePacketHeader &header = packet->queryHeader();
  391. StringBuffer s;
  392. logctx.CTXLOG("%sLIMIT EXCEEDED: %s", keyed ? "KEYED " : "", header.toString(s).str());
  393. header.activityId = keyed ? ROXIE_KEYEDLIMIT_EXCEEDED : ROXIE_LIMIT_EXCEEDED;
  394. Owned<IMessagePacker> output = ROQ->createOutputStream(header, false, logctx);
  395. output->flush(true);
  396. aborted = true;
  397. }
  398. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  399. {
  400. assertex(colocal == basehelper);
  401. return queryContext->queryCodeContext()->resolveChildQuery(activityId, colocal);
  402. }
  403. size32_t serializeRow(IMessagePacker *output, const void *unserialized) const
  404. {
  405. return ::serializeRow(serializer, output, unserialized);
  406. }
  407. virtual const char *loadResource(unsigned id)
  408. {
  409. return queryContext->queryCodeContext()->loadResource(id);
  410. }
  411. // Gets and sets should not happen - they can only happen in the main Roxie server context
  412. virtual void setResultBool(const char *name, unsigned sequence, bool value) { throwUnexpected(); }
  413. virtual void setResultData(const char *name, unsigned sequence, int len, const void * data) { throwUnexpected(); }
  414. virtual void setResultDecimal(const char * stepname, unsigned sequence, int len, int precision, bool isSigned, const void *val) { throwUnexpected(); }
  415. virtual void setResultInt(const char *name, unsigned sequence, __int64 value) { throwUnexpected(); }
  416. virtual void setResultRaw(const char *name, unsigned sequence, int len, const void * data) { throwUnexpected(); }
  417. virtual void setResultReal(const char * stepname, unsigned sequence, double value) { throwUnexpected(); }
  418. virtual void setResultSet(const char *name, unsigned sequence, bool isAll, size32_t len, const void * data, ISetToXmlTransformer * transformer) { throwUnexpected(); }
  419. virtual void setResultString(const char *name, unsigned sequence, int len, const char * str) { throwUnexpected(); }
  420. virtual void setResultUInt(const char *name, unsigned sequence, unsigned __int64 value) { throwUnexpected(); }
  421. virtual void setResultUnicode(const char *name, unsigned sequence, int len, UChar const * str) { throwUnexpected(); }
  422. virtual void setResultVarString(const char * name, unsigned sequence, const char * value) { throwUnexpected(); }
  423. virtual void setResultVarUnicode(const char * name, unsigned sequence, UChar const * value) { throwUnexpected(); }
  424. virtual bool getResultBool(const char * name, unsigned sequence) { throwUnexpected(); }
  425. virtual void getResultData(unsigned & tlen, void * & tgt, const char * name, unsigned sequence) { throwUnexpected(); }
  426. virtual void getResultDecimal(unsigned tlen, int precision, bool isSigned, void * tgt, const char * stepname, unsigned sequence) { throwUnexpected(); }
  427. virtual void getResultRaw(unsigned & tlen, void * & tgt, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { throwUnexpected(); }
  428. virtual void getResultSet(bool & isAll, size32_t & tlen, void * & tgt, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { throwUnexpected(); }
  429. virtual __int64 getResultInt(const char * name, unsigned sequence) { throwUnexpected(); }
  430. virtual double getResultReal(const char * name, unsigned sequence) { throwUnexpected(); }
  431. virtual void getResultString(unsigned & tlen, char * & tgt, const char * name, unsigned sequence) { throwUnexpected(); }
  432. virtual void getResultStringF(unsigned tlen, char * tgt, const char * name, unsigned sequence) { throwUnexpected(); }
  433. virtual void getResultUnicode(unsigned & tlen, UChar * & tgt, const char * name, unsigned sequence) { throwUnexpected(); }
  434. virtual char *getResultVarString(const char * name, unsigned sequence) { throwUnexpected(); }
  435. virtual UChar *getResultVarUnicode(const char * name, unsigned sequence) { throwUnexpected(); }
  436. virtual unsigned getResultHash(const char * name, unsigned sequence) { throwUnexpected(); }
  437. virtual void getResultRowset(size32_t & tcount, byte * * & tgt, const char * name, unsigned sequence, IEngineRowAllocator * _rowAllocator, IOutputRowDeserializer * deserializer, bool isGrouped, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { throwUnexpected(); }
  438. virtual void getResultDictionary(size32_t & tcount, byte * * & tgt, IEngineRowAllocator * _rowAllocator, const char * name, unsigned sequence, IOutputRowDeserializer * deserializer, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer, IHThorHashLookupInfo * hasher) { throwUnexpected(); }
  439. // Not yet thought about these....
  440. virtual char *getWuid() { throwUnexpected(); } // caller frees return string.
  441. virtual void getExternalResultRaw(unsigned & tlen, void * & tgt, const char * wuid, const char * stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { throwUnexpected(); } // shouldn't really be here, but it broke thor.
  442. virtual char *getDaliServers() { throwUnexpected(); } // caller frees return string.
  443. virtual void executeGraph(const char * graphName, bool realThor, size32_t parentExtractSize, const void * parentExtract) { throwUnexpected(); }
  444. virtual unsigned __int64 getDatasetHash(const char * name, unsigned __int64 hash) { throwUnexpected(); return 0; }
  445. virtual unsigned getRecoveringCount() { throwUnexpected(); }
  446. virtual __int64 countDiskFile(const char * lfn, unsigned recordSize) { throwUnexpected(); }
  447. virtual __int64 countIndex(__int64 activityId, IHThorCountIndexArg & arg) { throwUnexpected(); }
  448. virtual __int64 countDiskFile(__int64 activityId, IHThorCountFileArg & arg) { throwUnexpected(); } // only used for roxie...
  449. virtual char * getExpandLogicalName(const char * logicalName) { throwUnexpected(); }
  450. virtual void addWuException(const char * text, unsigned code, unsigned severity) { throwUnexpected(); }
  451. virtual void addWuAssertFailure(unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, bool isAbort) { throwUnexpected(); }
  452. virtual IUserDescriptor *queryUserDescriptor() { throwUnexpected(); }
  453. virtual unsigned getNodes() { throwUnexpected(); }
  454. virtual unsigned getNodeNum() { throwUnexpected(); }
  455. virtual char *getFilePart(const char *logicalPart, bool create=false) { throwUnexpected(); } // caller frees return string.
  456. virtual unsigned __int64 getFileOffset(const char *logicalPart) { throwUnexpected(); }
  457. virtual IDistributedFileTransaction *querySuperFileTransaction() { throwUnexpected(); }
  458. virtual char *getJobName() { throwUnexpected(); } // caller frees return string.
  459. virtual char *getJobOwner() { throwUnexpected(); } // caller frees return string.
  460. virtual char *getClusterName() { throwUnexpected(); } // caller frees return str.
  461. virtual char *getGroupName() { throwUnexpected(); } // caller frees return string.
  462. virtual char * queryIndexMetaData(char const * lfn, char const * xpath) { throwUnexpected(); }
  463. // The below are called on Roxie server and passed in context
  464. virtual unsigned getPriority() const { throwUnexpected(); }
  465. virtual char *getPlatform() { throwUnexpected(); }
  466. virtual char *getEnv(const char *name, const char *defaultValue) const { throwUnexpected(); }
  467. virtual char *getOS() { throwUnexpected(); }
  468. virtual unsigned logString(const char *text) const
  469. {
  470. if (text && *text)
  471. {
  472. logctx.CTXLOG("USER: %s", text);
  473. return strlen(text);
  474. }
  475. else
  476. return 0;
  477. }
  478. virtual const IContextLogger &queryContextLogger() const
  479. {
  480. return logctx;
  481. }
  482. virtual IEngineRowAllocator * getRowAllocator(IOutputMetaData * meta, unsigned activityId) const
  483. {
  484. return queryContext->queryCodeContext()->getRowAllocator(meta, activityId);
  485. }
  486. virtual void getRowXML(size32_t & lenResult, char * & result, IOutputMetaData & info, const void * row, unsigned flags)
  487. {
  488. convertRowToXML(lenResult, result, info, row, flags);
  489. }
  490. const void * fromXml(IEngineRowAllocator * rowAllocator, size32_t len, const char * utf8, IXmlToRowTransformer * xmlTransformer, bool stripWhitespace)
  491. {
  492. return createRowFromXml(rowAllocator, len, utf8, xmlTransformer, stripWhitespace);
  493. }
  494. };
  495. //================================================================================================
  496. class OptimizedRowBuilder : public ARowBuilder, public CInterface
  497. {
  498. public:
  499. OptimizedRowBuilder(IEngineRowAllocator * _rowAllocator, const CachedOutputMetaData & _meta, IMessagePacker * _output, IOutputRowSerializer * _serializer)
  500. : dynamicBuilder(_rowAllocator, false), meta(_meta), serializer(_serializer), output(_output)
  501. {
  502. useDynamic = serializer != NULL || meta.isVariableSize();
  503. }
  504. IMPLEMENT_IINTERFACE
  505. virtual byte * createSelf()
  506. {
  507. if (useDynamic)
  508. {
  509. dynamicBuilder.ensureRow();
  510. self = dynamicBuilder.getSelf();
  511. }
  512. else
  513. self = static_cast<byte *>(output->getBuffer(meta.getFixedSize(), false));
  514. return self;
  515. }
  516. virtual byte * ensureCapacity(size32_t required, const char * fieldName)
  517. {
  518. if (useDynamic)
  519. {
  520. self = dynamicBuilder.ensureCapacity(required, fieldName);
  521. return static_cast<byte *>(self);
  522. }
  523. else
  524. {
  525. size32_t fixedLength = meta.getFixedSize();
  526. if (required <= fixedLength)
  527. return static_cast<byte *>(self);
  528. // This should never happen!
  529. rtlReportFieldOverflow(required, fixedLength, fieldName);
  530. return NULL;
  531. }
  532. }
  533. virtual void reportMissingRow() const
  534. {
  535. throw MakeStringException(MSGAUD_user, 1000, "OptimizedRowBuilder::row() is NULL");
  536. }
  537. inline void ensureRow()
  538. {
  539. if (!self)
  540. createSelf();
  541. }
  542. inline void clear()
  543. {
  544. if (useDynamic)
  545. dynamicBuilder.clear();
  546. self = NULL;
  547. }
  548. size_t writeToOutput(size32_t transformedSize, bool outputIfEmpty)
  549. {
  550. size32_t outputSize = transformedSize;
  551. if (transformedSize || outputIfEmpty)
  552. {
  553. if (useDynamic)
  554. {
  555. OwnedConstRoxieRow result = dynamicBuilder.finalizeRowClear(transformedSize);
  556. if (serializer)
  557. outputSize = serializeRow(serializer, output, result);
  558. else
  559. {
  560. self = static_cast<byte *>(output->getBuffer(transformedSize, true));
  561. memcpy(self, result, transformedSize);
  562. output->putBuffer(self, transformedSize, true);
  563. }
  564. }
  565. else
  566. {
  567. output->putBuffer(self, transformedSize, false);
  568. }
  569. }
  570. clear();
  571. return outputSize;
  572. }
  573. private:
  574. RtlDynamicRowBuilder dynamicBuilder;
  575. const CachedOutputMetaData & meta;
  576. IMessagePacker * output;
  577. IOutputRowSerializer * serializer;
  578. bool useDynamic;
  579. };
  580. class OptimizedKJRowBuilder : public ARowBuilder, public CInterface
  581. {
  582. // Rules are different enough that we can't easily derive from OptimizedRowBuilder
  583. public:
  584. IMPLEMENT_IINTERFACE;
  585. OptimizedKJRowBuilder(IEngineRowAllocator * _rowAllocator, const CachedOutputMetaData & _meta, IMessagePacker * _output)
  586. : dynamicBuilder(_rowAllocator, false), meta(_meta), output(_output)
  587. {
  588. useDynamic = meta.isVariableSize();
  589. }
  590. virtual byte * createSelf()
  591. {
  592. if (useDynamic)
  593. {
  594. dynamicBuilder.ensureRow();
  595. self = dynamicBuilder.getSelf();
  596. return self;
  597. }
  598. else
  599. {
  600. self = static_cast<byte *>(output->getBuffer(KEYEDJOIN_RECORD_SIZE(meta.getFixedSize()), true)) + KEYEDJOIN_RECORD_SIZE(0);
  601. return self ;
  602. }
  603. }
  604. virtual byte * ensureCapacity(size32_t required, const char * fieldName)
  605. {
  606. if (useDynamic)
  607. {
  608. self = dynamicBuilder.ensureCapacity(required, fieldName);
  609. return self;
  610. }
  611. else
  612. {
  613. size32_t fixedLength = meta.getFixedSize();
  614. if (required <= fixedLength)
  615. return self;
  616. rtlReportFieldOverflow(required, fixedLength, fieldName);
  617. return NULL;
  618. }
  619. }
  620. virtual void reportMissingRow() const
  621. {
  622. throw MakeStringException(MSGAUD_user, 1000, "OptimizedKJRowBuilder::row() is NULL");
  623. }
  624. inline void ensureRow()
  625. {
  626. if (!self)
  627. createSelf();
  628. }
  629. void writeToOutput(size32_t transformedSize, offset_t recptr, CJoinGroup *jg, unsigned short partNo)
  630. {
  631. KeyedJoinHeader *rec;
  632. if (useDynamic)
  633. {
  634. OwnedConstRoxieRow result = dynamicBuilder.finalizeRowClear(transformedSize);
  635. rec = (KeyedJoinHeader *) (output->getBuffer(KEYEDJOIN_RECORD_SIZE(transformedSize), true));
  636. memcpy(&rec->rhsdata, result, transformedSize);
  637. }
  638. else
  639. {
  640. rec = (KeyedJoinHeader *)(self - KEYEDJOIN_RECORD_SIZE(0));
  641. }
  642. rec->fpos = recptr;
  643. rec->thisGroup = jg;
  644. rec->partNo = partNo;
  645. output->putBuffer(rec, KEYEDJOIN_RECORD_SIZE(transformedSize), true);
  646. self = NULL;
  647. }
  648. private:
  649. RtlDynamicRowBuilder dynamicBuilder;
  650. const CachedOutputMetaData & meta;
  651. IMessagePacker * output;
  652. bool useDynamic;
  653. };
  654. //================================================================================================
  655. class CRoxieDiskReadBaseActivity : public CRoxieSlaveActivity, implements IIndexReadContext//, implements IDiskReadActivity
  656. {
  657. friend class RecordProcessor;
  658. friend class KeyedRecordProcessor;
  659. friend class UnkeyedRecordProcessor;
  660. friend class UnkeyedVariableRecordProcessor;
  661. friend class KeyedNormalizeRecordProcessor;
  662. friend class UnkeyedNormalizeRecordProcessor;
  663. friend class KeyedCountRecordProcessor;
  664. friend class UnkeyedCountRecordProcessor;
  665. friend class UnkeyedVariableCountRecordProcessor;
  666. friend class KeyedAggregateRecordProcessor;
  667. friend class UnkeyedAggregateRecordProcessor;
  668. friend class UnkeyedVariableAggregateRecordProcessor;
  669. friend class KeyedGroupAggregateRecordProcessor;
  670. friend class UnkeyedGroupAggregateRecordProcessor;
  671. friend class UnkeyedVariableGroupAggregateRecordProcessor;
  672. protected:
  673. IHThorDiskReadBaseArg *helper;
  674. unsigned processed;
  675. unsigned parallelPartNo;
  676. unsigned numParallel;
  677. bool isKeyed;
  678. bool forceUnkeyed;
  679. offset_t readPos;
  680. CachedOutputMetaData diskSize;
  681. Owned<IInMemoryIndexCursor> cursor;
  682. Linked<IInMemoryIndexManager> manager;
  683. Owned<IInMemoryFileProcessor> processor;
  684. Owned<IFileIOArray> varFiles;
  685. CriticalSection pcrit;
  686. public:
  687. IMPLEMENT_IINTERFACE;
  688. CRoxieDiskReadBaseActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  689. IInMemoryIndexManager *_manager,
  690. unsigned _parallelPartNo, unsigned _numParallel, bool _forceUnkeyed)
  691. : CRoxieSlaveActivity(_logctx, _packet, _hFactory, _aFactory),
  692. manager(_manager),
  693. parallelPartNo(_parallelPartNo),
  694. numParallel(_numParallel),
  695. forceUnkeyed(_forceUnkeyed)
  696. {
  697. helper = (IHThorDiskReadBaseArg *) basehelper;
  698. variableFileName = (helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0;
  699. isOpt = (helper->getFlags() & TDRoptional) != 0;
  700. diskSize.set(helper->queryDiskRecordSize());
  701. processed = 0;
  702. readPos = 0;
  703. isKeyed = false;
  704. if (resent)
  705. {
  706. bool usedKey;
  707. resentInfo.read(processed);
  708. resentInfo.read(usedKey);
  709. if (usedKey)
  710. {
  711. cursor.setown(manager->createCursor());
  712. cursor->deserializeCursorPos(resentInfo);
  713. isKeyed = true;
  714. }
  715. else
  716. resentInfo.read(readPos);
  717. assertex(resentInfo.remaining() == 0);
  718. }
  719. }
  720. virtual void onCreate()
  721. {
  722. CRoxieSlaveActivity::onCreate();
  723. helper->createSegmentMonitors(this);
  724. if (!resent)
  725. isKeyed = (cursor && !forceUnkeyed) ? cursor->selectKey() : false;
  726. }
  727. virtual const char *queryDynamicFileName() const
  728. {
  729. return helper->getFileName();
  730. }
  731. virtual void setVariableFileInfo()
  732. {
  733. unsigned channel = packet->queryHeader().channel;
  734. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel)); // MORE could combine
  735. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  736. }
  737. inline bool queryKeyed() const
  738. {
  739. return isKeyed;
  740. }
  741. void setParallel(unsigned _partno, unsigned _numParallel)
  742. {
  743. assertex(!processor);
  744. parallelPartNo = _partno;
  745. numParallel = _numParallel;
  746. }
  747. virtual StringBuffer &toString(StringBuffer &ret) const
  748. {
  749. return ret.appendf("DiskRead %u", packet->queryHeader().activityId);
  750. }
  751. virtual void append(IKeySegmentMonitor *segment)
  752. {
  753. if (!segment->isWild())
  754. {
  755. if (!cursor)
  756. cursor.setown(manager->createCursor());
  757. cursor->append(segment);
  758. }
  759. }
  760. virtual unsigned ordinality() const
  761. {
  762. return cursor ? cursor->ordinality() : 0;
  763. }
  764. virtual IKeySegmentMonitor *item(unsigned idx) const
  765. {
  766. return cursor ? cursor->item(idx) : 0;
  767. }
  768. virtual void setMergeBarrier(unsigned barrierOffset)
  769. {
  770. // no merging so no issue...
  771. }
  772. virtual void abort()
  773. {
  774. aborted = true;
  775. CriticalBlock p(pcrit);
  776. if (processor)
  777. processor->abort();
  778. }
  779. virtual bool process()
  780. {
  781. MTIME_SECTION(timer, "CRoxieDiskReadBaseActivity::process");
  782. atomic_inc(&diskReadStarted);
  783. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  784. doProcess(output);
  785. helper->setCallback(NULL);
  786. logctx.flush(true, aborted);
  787. if (aborted)
  788. {
  789. output->abort();
  790. return false;
  791. }
  792. else
  793. {
  794. output->flush(true);
  795. atomic_inc(&diskReadCompleted);
  796. return true;
  797. }
  798. }
  799. virtual void doCheck(IMessagePacker *output)
  800. {
  801. // for in-memory diskread activities, not a lot to check. If it got this far the answer is 'true'...
  802. void *recBuffer = output->getBuffer(sizeof(bool), false);
  803. bool ret = true;
  804. memcpy(recBuffer, &ret, sizeof(bool));
  805. }
  806. virtual void doProcess(IMessagePacker * output) = 0;
  807. virtual void setPartNo(bool filechanged)
  808. {
  809. throwUnexpected();
  810. }
  811. };
  812. class CRoxieDiskBaseActivityFactory : public CSlaveActivityFactory
  813. {
  814. protected:
  815. Owned<IFileIOArray> fileArray;
  816. Owned<IInMemoryIndexManager> manager;
  817. public:
  818. CRoxieDiskBaseActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  819. : CSlaveActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  820. {
  821. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  822. bool variableFileName = (helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0;
  823. if (!variableFileName)
  824. {
  825. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  826. const char *fileName = helper->getFileName();
  827. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, _queryFactory.queryWorkUnit()));
  828. if (datafile)
  829. {
  830. unsigned channel = queryFactory.queryChannel();
  831. fileArray.setown(datafile->getIFileIOArray(isOpt, channel));
  832. manager.setown(datafile->getIndexManager(isOpt, channel, fileArray, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  833. Owned<IPropertyTreeIterator> memKeyInfo = queryFactory.queryPackage().getInMemoryIndexInfo(_graphNode);
  834. if (memKeyInfo)
  835. {
  836. ForEach(*memKeyInfo)
  837. {
  838. IPropertyTree &info = memKeyInfo->query();
  839. manager->setKeyInfo(info);
  840. }
  841. }
  842. }
  843. else
  844. manager.setown(getEmptyIndexManager());
  845. }
  846. }
  847. ~CRoxieDiskBaseActivityFactory()
  848. {
  849. }
  850. };
  851. //================================================================================================
  852. class CRoxieDiskReadActivity;
  853. class CRoxieCsvReadActivity;
  854. class CRoxieXmlReadActivity;
  855. IInMemoryFileProcessor *createKeyedRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskReadActivity &owner, bool resent);
  856. IInMemoryFileProcessor *createUnkeyedRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskReadActivity &owner, bool variableDisk, IDirectReader *reader);
  857. IInMemoryFileProcessor *createCsvRecordProcessor(CRoxieCsvReadActivity &owner, IDirectReader *reader, bool _skipHeader, const IResolvedFile *datafile);
  858. IInMemoryFileProcessor *createXmlRecordProcessor(CRoxieXmlReadActivity &owner, IDirectReader *reader);
  859. class CRoxieDiskReadActivity : public CRoxieDiskReadBaseActivity
  860. {
  861. friend class ReadRecordProcessor;
  862. protected:
  863. IHThorDiskReadArg *helper;
  864. public:
  865. IMPLEMENT_IINTERFACE;
  866. CRoxieDiskReadActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  867. IInMemoryIndexManager *_manager)
  868. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, 1, false)
  869. {
  870. onCreate();
  871. helper = (IHThorDiskReadArg *) basehelper;
  872. }
  873. virtual StringBuffer &toString(StringBuffer &ret) const
  874. {
  875. return ret.appendf("DiskRead %u", packet->queryHeader().activityId);
  876. }
  877. virtual void doProcess(IMessagePacker * output)
  878. {
  879. {
  880. CriticalBlock p(pcrit);
  881. processor.setown(isKeyed ? createKeyedRecordProcessor(cursor, *this, resent) :
  882. createUnkeyedRecordProcessor(cursor, *this, diskSize.isVariableSize(), manager->createReader(readPos, parallelPartNo, numParallel)));
  883. }
  884. unsigned __int64 rowLimit = helper->getRowLimit();
  885. unsigned __int64 stopAfter = helper->getChooseNLimit();
  886. processor->doQuery(output, processed, rowLimit, stopAfter);
  887. }
  888. size32_t doTransform(IMessagePacker * output, const void *src) const
  889. {
  890. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  891. unsigned transformedSize = helper->transform(rowBuilder, src);
  892. return rowBuilder.writeToOutput(transformedSize, false);
  893. }
  894. };
  895. class CRoxieCsvReadActivity : public CRoxieDiskReadBaseActivity
  896. {
  897. public:
  898. friend class CsvRecordProcessor;
  899. protected:
  900. IHThorCsvReadArg *helper;
  901. const IResolvedFile *datafile;
  902. public:
  903. IMPLEMENT_IINTERFACE;
  904. CRoxieCsvReadActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory,
  905. const CSlaveActivityFactory *_aFactory, IInMemoryIndexManager *_manager, const IResolvedFile *_datafile)
  906. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, 1, true), datafile(_datafile)
  907. {
  908. onCreate();
  909. helper = (IHThorCsvReadArg *) basehelper;
  910. }
  911. virtual StringBuffer &toString(StringBuffer &ret) const
  912. {
  913. return ret.appendf("CsvRead %u", packet->queryHeader().activityId);
  914. }
  915. virtual void doProcess(IMessagePacker * output)
  916. {
  917. {
  918. CriticalBlock p(pcrit);
  919. processor.setown(
  920. createCsvRecordProcessor(*this,
  921. manager->createReader(readPos, parallelPartNo, numParallel),
  922. packet->queryHeader().channel==1 && !resent,
  923. varFileInfo ? varFileInfo.get() : datafile));
  924. }
  925. unsigned __int64 rowLimit = helper->getRowLimit();
  926. unsigned __int64 stopAfter = helper->getChooseNLimit();
  927. processor->doQuery(output, processed, rowLimit, stopAfter);
  928. }
  929. size32_t doTransform(IMessagePacker * output, unsigned *srcLen, const char **src) const
  930. {
  931. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  932. unsigned transformedSize = helper->transform(rowBuilder, srcLen, src);
  933. return rowBuilder.writeToOutput(transformedSize, false);
  934. }
  935. };
  936. class CRoxieXmlReadActivity : public CRoxieDiskReadBaseActivity
  937. {
  938. public:
  939. friend class XmlRecordProcessor;
  940. protected:
  941. IHThorXmlReadArg *helper;
  942. public:
  943. IMPLEMENT_IINTERFACE;
  944. CRoxieXmlReadActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  945. IInMemoryIndexManager *_manager)
  946. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, 1, true)
  947. {
  948. onCreate();
  949. helper = (IHThorXmlReadArg *) basehelper;
  950. }
  951. virtual StringBuffer &toString(StringBuffer &ret) const
  952. {
  953. return ret.appendf("XmlRead %u", packet->queryHeader().activityId);
  954. }
  955. virtual void doProcess(IMessagePacker * output)
  956. {
  957. {
  958. CriticalBlock p(pcrit);
  959. processor.setown(createXmlRecordProcessor(*this, manager->createReader(readPos, parallelPartNo, numParallel)));
  960. }
  961. unsigned __int64 rowLimit = helper->getRowLimit();
  962. unsigned __int64 stopAfter = helper->getChooseNLimit();
  963. processor->doQuery(output, processed, rowLimit, stopAfter);
  964. }
  965. size32_t doTransform(IMessagePacker * output, IXmlToRowTransformer *rowTransformer, IColumnProvider *lastMatch, IThorDiskCallback *callback) const
  966. {
  967. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  968. unsigned transformedSize = rowTransformer->transform(rowBuilder, lastMatch, callback);
  969. return rowBuilder.writeToOutput(transformedSize, false);
  970. }
  971. };
  972. class CRoxieDiskReadActivityFactory : public CRoxieDiskBaseActivityFactory
  973. {
  974. public:
  975. IMPLEMENT_IINTERFACE;
  976. CRoxieDiskReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  977. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  978. {
  979. }
  980. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  981. {
  982. return new CRoxieDiskReadActivity(logctx, packet, helperFactory, this, manager);
  983. }
  984. virtual StringBuffer &toString(StringBuffer &s) const
  985. {
  986. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  987. }
  988. };
  989. class CRoxieCsvReadActivityFactory : public CRoxieDiskBaseActivityFactory
  990. {
  991. public:
  992. IMPLEMENT_IINTERFACE;
  993. CRoxieCsvReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  994. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  995. {
  996. }
  997. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  998. {
  999. return new CRoxieCsvReadActivity(logctx, packet, helperFactory, this, manager, datafile);
  1000. }
  1001. virtual StringBuffer &toString(StringBuffer &s) const
  1002. {
  1003. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  1004. }
  1005. };
  1006. class CRoxieXmlReadActivityFactory : public CRoxieDiskBaseActivityFactory
  1007. {
  1008. public:
  1009. IMPLEMENT_IINTERFACE;
  1010. CRoxieXmlReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1011. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  1012. {
  1013. }
  1014. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  1015. {
  1016. return new CRoxieXmlReadActivity(logctx, packet, helperFactory, this, manager);
  1017. }
  1018. virtual StringBuffer &toString(StringBuffer &s) const
  1019. {
  1020. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  1021. }
  1022. };
  1023. //================================================================================================
  1024. // Note - the classes below could be commoned up to make the code smaller, but they have been deliberately unrolled to
  1025. // keep to a bare minimum the number of virtual calls/variable tests per record scanned. This is very speed critical.
  1026. class RecordProcessor : public CInterface, implements IInMemoryFileProcessor
  1027. {
  1028. protected:
  1029. IInMemoryIndexCursor *cursor; // Unkeyed variants still may need to check segmonitors in here
  1030. bool aborted;
  1031. const char *endRec;
  1032. static inline size32_t roundDown(size32_t got, size32_t fixedSize)
  1033. {
  1034. // Make sure that the buffer size we process is a multiple of the fixed record size
  1035. return (got / fixedSize) * fixedSize;
  1036. }
  1037. static size32_t getBufferSize(size32_t fixedSize)
  1038. {
  1039. // Calculate appropriate buffer size for fixed size record processors
  1040. assert(fixedSize);
  1041. unsigned recordsPerBuffer = diskReadBufferSize / fixedSize;
  1042. if (!recordsPerBuffer)
  1043. recordsPerBuffer = 1;
  1044. return fixedSize * recordsPerBuffer;
  1045. }
  1046. public:
  1047. IMPLEMENT_IINTERFACE;
  1048. RecordProcessor(IInMemoryIndexCursor *_cursor) : cursor(_cursor)
  1049. {
  1050. aborted = false;
  1051. endRec = NULL;
  1052. }
  1053. virtual void abort()
  1054. {
  1055. aborted = true;
  1056. endRec = NULL; // speeds up the abort in some of the derived classes
  1057. }
  1058. };
  1059. //================================================================================================
  1060. // Base class for all varieties of RecordProcessor used by disk read activity
  1061. class ReadRecordProcessor : public RecordProcessor
  1062. {
  1063. protected:
  1064. CRoxieDiskReadActivity &owner;
  1065. IHThorDiskReadArg *helper;
  1066. public:
  1067. ReadRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskReadActivity &_owner)
  1068. : RecordProcessor(_cursor), owner(_owner)
  1069. {
  1070. helper = _owner.helper;
  1071. }
  1072. };
  1073. // Used by disk read when an in-memory index is available
  1074. class KeyedRecordProcessor : public ReadRecordProcessor
  1075. {
  1076. bool resent;
  1077. public:
  1078. KeyedRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskReadActivity &_owner, bool _resent) : ReadRecordProcessor(_cursor, _owner)
  1079. {
  1080. resent = _resent;
  1081. helper->setCallback(cursor);
  1082. }
  1083. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1084. {
  1085. // doQuery needs to be as fast as possible - we are making a virtual call to it per query in order to avoid tests of loop-invariants within it
  1086. unsigned totalSizeSent = 0;
  1087. IInMemoryIndexCursor *lc = cursor;
  1088. if (!resent)
  1089. lc->reset();
  1090. bool continuationFailed = false;
  1091. while (!aborted)
  1092. {
  1093. const void *nextCandidate = lc->nextMatch();
  1094. if (!nextCandidate)
  1095. break;
  1096. unsigned transformedSize = owner.doTransform(output, nextCandidate);
  1097. if (transformedSize)
  1098. {
  1099. processed++;
  1100. if (processed > rowLimit)
  1101. {
  1102. owner.limitExceeded();
  1103. break;
  1104. }
  1105. if (processed == stopAfter)
  1106. break;
  1107. totalSizeSent += transformedSize;
  1108. if (totalSizeSent > indexReadChunkSize && !continuationFailed)
  1109. {
  1110. MemoryBuffer si;
  1111. unsigned short siLen = 0;
  1112. si.append(siLen);
  1113. si.append(processed);
  1114. si.append(true); // using a key
  1115. lc->serializeCursorPos(si);
  1116. if (si.length() <= maxContinuationSize)
  1117. {
  1118. siLen = si.length() - sizeof(siLen);
  1119. si.writeDirect(0, sizeof(siLen), &siLen);
  1120. output->sendMetaInfo(si.toByteArray(), si.length());
  1121. return;
  1122. }
  1123. else
  1124. continuationFailed = true;
  1125. }
  1126. }
  1127. }
  1128. }
  1129. };
  1130. IInMemoryFileProcessor *createKeyedRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskReadActivity &owner, bool resent)
  1131. {
  1132. return new KeyedRecordProcessor(cursor, owner, resent);
  1133. }
  1134. // Used by disk read when an in-memory index is NOT available
  1135. // We use different variants for fixed versus variable sized records, in order to make the fixed version as fast as possible
  1136. class UnkeyedRecordProcessor : public ReadRecordProcessor
  1137. {
  1138. protected:
  1139. Owned<IDirectReader> reader;
  1140. public:
  1141. IMPLEMENT_IINTERFACE;
  1142. UnkeyedRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskReadActivity &_owner, IDirectReader *_reader)
  1143. : ReadRecordProcessor(_cursor, _owner), reader(_reader)
  1144. {
  1145. }
  1146. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1147. {
  1148. unsigned totalSizeSent = 0;
  1149. helper->setCallback(reader->queryThorDiskCallback());
  1150. size32_t recordSize = owner.diskSize.getFixedSize();
  1151. size32_t bufferSize = getBufferSize(recordSize);
  1152. while (!aborted && !reader->eos())
  1153. {
  1154. size32_t gotSize;
  1155. const char *firstRec = (const char *) reader->peek(bufferSize, gotSize);
  1156. if (!gotSize)
  1157. break;
  1158. gotSize = roundDown(gotSize, recordSize);
  1159. const char *nextRec = firstRec;
  1160. endRec = firstRec + gotSize;
  1161. while (nextRec < endRec)
  1162. {
  1163. size32_t transformedSize;
  1164. if (cursor && cursor->isFiltered(nextRec))
  1165. transformedSize = 0;
  1166. else
  1167. transformedSize = owner.doTransform(output, nextRec);
  1168. nextRec += recordSize;
  1169. if (transformedSize)
  1170. {
  1171. processed++;
  1172. if (processed > rowLimit)
  1173. {
  1174. owner.limitExceeded();
  1175. return;
  1176. }
  1177. if (processed == stopAfter)
  1178. return;
  1179. totalSizeSent += transformedSize;
  1180. if (totalSizeSent > indexReadChunkSize)
  1181. {
  1182. MemoryBuffer si;
  1183. unsigned short siLen = 0;
  1184. si.append(siLen);
  1185. si.append(processed);
  1186. si.append(false); // not using a key
  1187. offset_t readPos = reader->tell() + (nextRec - firstRec);
  1188. si.append(readPos);
  1189. siLen = si.length() - sizeof(siLen);
  1190. si.writeDirect(0, sizeof(siLen), &siLen);
  1191. output->sendMetaInfo(si.toByteArray(), si.length());
  1192. return;
  1193. }
  1194. }
  1195. }
  1196. reader->skip(gotSize);
  1197. }
  1198. }
  1199. };
  1200. class UnkeyedVariableRecordProcessor : public UnkeyedRecordProcessor
  1201. {
  1202. public:
  1203. UnkeyedVariableRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskReadActivity &_owner, IDirectReader *_reader)
  1204. : UnkeyedRecordProcessor(_cursor, _owner, _reader), deserializeSource(_reader)
  1205. {
  1206. prefetcher.setown(owner.diskSize.queryOriginal()->createRowPrefetcher(owner.queryContext->queryCodeContext(), owner.basefactory->queryId()));
  1207. }
  1208. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1209. {
  1210. unsigned totalSizeSent = 0;
  1211. helper->setCallback(reader->queryThorDiskCallback());
  1212. while (!aborted && !deserializeSource.eos())
  1213. {
  1214. // This loop is the inner loop for memory diskreads - so keep it efficient!
  1215. prefetcher->readAhead(deserializeSource);
  1216. const byte *nextRec = deserializeSource.queryRow();
  1217. size32_t transformedSize;
  1218. if (cursor && cursor->isFiltered(nextRec))
  1219. transformedSize = 0;
  1220. else
  1221. transformedSize = owner.doTransform(output, nextRec);
  1222. deserializeSource.finishedRow();
  1223. if (transformedSize)
  1224. {
  1225. processed++;
  1226. if (processed > rowLimit)
  1227. {
  1228. owner.limitExceeded();
  1229. return;
  1230. }
  1231. if (processed == stopAfter)
  1232. return;
  1233. totalSizeSent += transformedSize;
  1234. if (totalSizeSent > indexReadChunkSize)
  1235. {
  1236. MemoryBuffer si;
  1237. unsigned short siLen = 0;
  1238. si.append(siLen);
  1239. si.append(processed);
  1240. si.append(false); // not using a key
  1241. offset_t readPos = deserializeSource.tell();
  1242. si.append(readPos);
  1243. siLen = si.length() - sizeof(siLen);
  1244. si.writeDirect(0, sizeof(siLen), &siLen);
  1245. output->sendMetaInfo(si.toByteArray(), si.length());
  1246. return;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. protected:
  1252. CThorContiguousRowBuffer deserializeSource;
  1253. Owned<ISourceRowPrefetcher> prefetcher;
  1254. };
  1255. IInMemoryFileProcessor *createUnkeyedRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskReadActivity &owner, bool variableDisk, IDirectReader *_reader)
  1256. {
  1257. if (variableDisk)
  1258. return new UnkeyedVariableRecordProcessor(cursor, owner, _reader);
  1259. else
  1260. return new UnkeyedRecordProcessor(cursor, owner, _reader);
  1261. }
  1262. //================================================================================================
  1263. // RecordProcessor used by CSV read activity. We don't try to index these or optimize fixed size cases...
  1264. class CsvRecordProcessor : public RecordProcessor
  1265. {
  1266. protected:
  1267. CRoxieCsvReadActivity &owner;
  1268. IHThorCsvReadArg *helper;
  1269. Owned<IDirectReader> reader;
  1270. bool skipHeader;
  1271. const IResolvedFile *datafile;
  1272. public:
  1273. IMPLEMENT_IINTERFACE;
  1274. CsvRecordProcessor(CRoxieCsvReadActivity &_owner, IDirectReader *_reader, bool _skipHeader, const IResolvedFile *_datafile)
  1275. : RecordProcessor(NULL), owner(_owner), reader(_reader), datafile(_datafile)
  1276. {
  1277. helper = _owner.helper;
  1278. skipHeader = _skipHeader;
  1279. helper->setCallback(reader->queryThorDiskCallback());
  1280. }
  1281. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1282. {
  1283. unsigned totalSizeSent = 0;
  1284. ICsvParameters * csvInfo = helper->queryCsvParameters();
  1285. unsigned headerLines = skipHeader ? csvInfo->queryHeaderLen() : 0;
  1286. const char *quotes = NULL;
  1287. const char *separators = NULL;
  1288. const char *terminators = NULL;
  1289. const char *escapes = NULL;
  1290. CSVSplitter csvSplitter;
  1291. if (datafile)
  1292. {
  1293. const IPropertyTree *options = datafile->queryProperties();
  1294. if (options)
  1295. {
  1296. quotes = options->queryProp("@csvQuote");
  1297. separators = options->queryProp("@csvSeparate");
  1298. terminators = options->queryProp("@csvTerminate");
  1299. escapes = options->queryProp("@csvEscape");
  1300. }
  1301. }
  1302. csvSplitter.init(helper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  1303. while (!aborted)
  1304. {
  1305. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  1306. if (reader->eos())
  1307. {
  1308. break;
  1309. }
  1310. size32_t rowSize = 4096; // MORE - make configurable
  1311. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  1312. size32_t thisLineLength;
  1313. loop
  1314. {
  1315. size32_t avail;
  1316. const void *peek = reader->peek(rowSize, avail);
  1317. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  1318. if (thisLineLength < rowSize || avail < rowSize)
  1319. break;
  1320. if (rowSize == maxRowSize)
  1321. throw MakeStringException(0, "Row too big");
  1322. if (rowSize >= maxRowSize/2)
  1323. rowSize = maxRowSize;
  1324. else
  1325. rowSize += rowSize;
  1326. }
  1327. if (!thisLineLength)
  1328. break;
  1329. if (headerLines)
  1330. {
  1331. headerLines--;
  1332. reader->skip(thisLineLength);
  1333. }
  1334. else
  1335. {
  1336. unsigned transformedSize = owner.doTransform(output, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  1337. reader->skip(thisLineLength);
  1338. if (transformedSize)
  1339. {
  1340. processed++;
  1341. if (processed > rowLimit)
  1342. {
  1343. owner.limitExceeded();
  1344. return;
  1345. }
  1346. if (processed == stopAfter)
  1347. return;
  1348. totalSizeSent += transformedSize;
  1349. if (totalSizeSent > indexReadChunkSize)
  1350. {
  1351. MemoryBuffer si;
  1352. unsigned short siLen = 0;
  1353. si.append(siLen);
  1354. si.append(processed);
  1355. si.append(false); // not using a key
  1356. offset_t readPos = reader->tell();
  1357. si.append(readPos);
  1358. siLen = si.length() - sizeof(siLen);
  1359. si.writeDirect(0, sizeof(siLen), &siLen);
  1360. output->sendMetaInfo(si.toByteArray(), si.length());
  1361. return;
  1362. }
  1363. }
  1364. }
  1365. }
  1366. }
  1367. };
  1368. //================================================================================================
  1369. // RecordProcessor used by XML read activity. We don't try to index these or optimize fixed size cases...
  1370. class XmlRecordProcessor : public RecordProcessor, implements IXMLSelect
  1371. {
  1372. public:
  1373. IMPLEMENT_IINTERFACE;
  1374. XmlRecordProcessor(CRoxieXmlReadActivity &_owner, IDirectReader *_reader)
  1375. : RecordProcessor(NULL), owner(_owner), reader(_reader)
  1376. {
  1377. helper = _owner.helper;
  1378. helper->setCallback(reader->queryThorDiskCallback());
  1379. }
  1380. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  1381. {
  1382. lastMatch.set(&entry);
  1383. }
  1384. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1385. {
  1386. #if 0
  1387. // xml read does not support continuation record stuff as too hard to serialize state of xml parser
  1388. unsigned totalSizeSent = 0;
  1389. #endif
  1390. Linked<IXmlToRowTransformer> rowTransformer = helper->queryTransformer();
  1391. Owned<IXMLParse> xmlParser = createXMLParse(*reader->querySimpleStream(), helper->queryIteratorPath(), *this, (0 != (TDRxmlnoroot & helper->getFlags()))?xr_noRoot:xr_none, (helper->getFlags() & TDRusexmlcontents) != 0);
  1392. while (!aborted)
  1393. {
  1394. //call to next() will callback on the IXmlSelect interface
  1395. bool gotNext = false;
  1396. gotNext = xmlParser->next();
  1397. if(!gotNext)
  1398. break;
  1399. else if (lastMatch)
  1400. {
  1401. unsigned transformedSize = owner.doTransform(output, rowTransformer, lastMatch, reader->queryThorDiskCallback());
  1402. lastMatch.clear();
  1403. if (transformedSize)
  1404. {
  1405. processed++;
  1406. if (processed > rowLimit)
  1407. {
  1408. owner.limitExceeded();
  1409. return;
  1410. }
  1411. if (processed == stopAfter)
  1412. return;
  1413. #if 0
  1414. // xml read does not support continuation record stuff as too hard to serialize state of xml parser
  1415. totalSizeSent += transformedSize;
  1416. if (totalSizeSent > indexReadChunkSize)
  1417. {
  1418. MemoryBuffer si;
  1419. unsigned short siLen = 0;
  1420. si.append(siLen);
  1421. si.append(processed);
  1422. si.append(false); // not using a key
  1423. readPos = inputFileIOStream->tell();
  1424. si.append(readPos);
  1425. siLen = si.length() - sizeof(siLen);
  1426. si.writeDirect(0, sizeof(siLen), &siLen);
  1427. output->sendMetaInfo(si.toByteArray(), si.length());
  1428. return;
  1429. }
  1430. #endif
  1431. }
  1432. }
  1433. }
  1434. }
  1435. protected:
  1436. CRoxieXmlReadActivity &owner;
  1437. IHThorXmlReadArg *helper;
  1438. Owned<IColumnProvider> lastMatch;
  1439. Owned<IDirectReader> reader;
  1440. };
  1441. IInMemoryFileProcessor *createCsvRecordProcessor(CRoxieCsvReadActivity &owner, IDirectReader *_reader, bool _skipHeader, const IResolvedFile *datafile)
  1442. {
  1443. return new CsvRecordProcessor(owner, _reader, _skipHeader, datafile);
  1444. }
  1445. IInMemoryFileProcessor *createXmlRecordProcessor(CRoxieXmlReadActivity &owner, IDirectReader *_reader)
  1446. {
  1447. return new XmlRecordProcessor(owner, _reader);
  1448. }
  1449. ISlaveActivityFactory *createRoxieCsvReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1450. {
  1451. return new CRoxieCsvReadActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  1452. }
  1453. ISlaveActivityFactory *createRoxieXmlReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1454. {
  1455. return new CRoxieXmlReadActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  1456. }
  1457. ISlaveActivityFactory *createRoxieDiskReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1458. {
  1459. return new CRoxieDiskReadActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  1460. }
  1461. //================================================================================================
  1462. class CRoxieDiskNormalizeActivity;
  1463. IInMemoryFileProcessor *createKeyedNormalizeRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskNormalizeActivity &owner, bool resent);
  1464. IInMemoryFileProcessor *createUnkeyedNormalizeRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskNormalizeActivity &owner, IDirectReader *reader);
  1465. class CRoxieDiskNormalizeActivity : public CRoxieDiskReadBaseActivity
  1466. {
  1467. friend class NormalizeRecordProcessor;
  1468. protected:
  1469. IHThorDiskNormalizeArg *helper;
  1470. public:
  1471. IMPLEMENT_IINTERFACE;
  1472. CRoxieDiskNormalizeActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  1473. IInMemoryIndexManager *_manager)
  1474. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, 1, false)
  1475. {
  1476. onCreate();
  1477. helper = (IHThorDiskNormalizeArg *) basehelper;
  1478. }
  1479. virtual StringBuffer &toString(StringBuffer &ret) const
  1480. {
  1481. return ret.appendf("DiskNormalize %u", packet->queryHeader().activityId);
  1482. }
  1483. virtual void doProcess(IMessagePacker * output)
  1484. {
  1485. {
  1486. CriticalBlock p(pcrit);
  1487. processor.setown(isKeyed ?
  1488. createKeyedNormalizeRecordProcessor(cursor, *this, resent) :
  1489. createUnkeyedNormalizeRecordProcessor(cursor, *this, manager->createReader(readPos, parallelPartNo, numParallel)));
  1490. }
  1491. unsigned __int64 rowLimit = helper->getRowLimit();
  1492. unsigned __int64 stopAfter = helper->getChooseNLimit();
  1493. processor->doQuery(output, processed, rowLimit, stopAfter);
  1494. }
  1495. size32_t doNormalizeTransform(IMessagePacker * output) const
  1496. {
  1497. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  1498. unsigned transformedSize = helper->transform(rowBuilder);
  1499. return rowBuilder.writeToOutput(transformedSize, false);
  1500. }
  1501. };
  1502. class CRoxieDiskNormalizeActivityFactory : public CRoxieDiskBaseActivityFactory
  1503. {
  1504. public:
  1505. IMPLEMENT_IINTERFACE;
  1506. CRoxieDiskNormalizeActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1507. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  1508. {
  1509. }
  1510. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  1511. {
  1512. return new CRoxieDiskNormalizeActivity(logctx, packet, helperFactory, this, manager);
  1513. }
  1514. virtual StringBuffer &toString(StringBuffer &s) const
  1515. {
  1516. return CSlaveActivityFactory::toString(s.append("DiskNormalize "));
  1517. }
  1518. };
  1519. ISlaveActivityFactory *createRoxieDiskNormalizeActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1520. {
  1521. return new CRoxieDiskNormalizeActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  1522. }
  1523. //================================================================================================
  1524. // RecordProcessors used by Disk Normalize activity.
  1525. class NormalizeRecordProcessor : public RecordProcessor
  1526. {
  1527. public:
  1528. NormalizeRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskNormalizeActivity &_owner)
  1529. : RecordProcessor(_cursor), owner(_owner)
  1530. {
  1531. helper = _owner.helper;
  1532. }
  1533. protected:
  1534. CRoxieDiskNormalizeActivity &owner;
  1535. IHThorDiskNormalizeArg *helper;
  1536. };
  1537. // Used when we have an in-memory key that matches at least some of the filter conditions
  1538. class KeyedNormalizeRecordProcessor : public NormalizeRecordProcessor
  1539. {
  1540. public:
  1541. KeyedNormalizeRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskNormalizeActivity &_owner, bool _resent)
  1542. : NormalizeRecordProcessor(_cursor, _owner)
  1543. {
  1544. resent = _resent;
  1545. helper->setCallback(cursor);
  1546. }
  1547. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1548. {
  1549. // doQuery needs to be as fast as possible - we are making a virtual call to it per query in order to avoid tests of loop-invariants within it
  1550. unsigned totalSizeSent = 0;
  1551. IInMemoryIndexCursor *lc = cursor;
  1552. if (!resent)
  1553. lc->reset();
  1554. bool continuationFailed = false;
  1555. while (!aborted)
  1556. {
  1557. const void *nextCandidate = lc->nextMatch();
  1558. if (!nextCandidate)
  1559. break;
  1560. if (helper->first(nextCandidate))
  1561. {
  1562. do
  1563. {
  1564. size32_t transformedSize = owner.doNormalizeTransform(output);
  1565. if (transformedSize)
  1566. {
  1567. processed++;
  1568. if (processed > rowLimit)
  1569. {
  1570. owner.limitExceeded();
  1571. return;
  1572. }
  1573. totalSizeSent += transformedSize;
  1574. if (processed == stopAfter)
  1575. return;
  1576. }
  1577. } while (helper->next());
  1578. if (totalSizeSent > indexReadChunkSize && !continuationFailed)
  1579. {
  1580. MemoryBuffer si;
  1581. unsigned short siLen = 0;
  1582. si.append(siLen);
  1583. si.append(processed);
  1584. si.append(true); // using a key
  1585. lc->serializeCursorPos(si);
  1586. if (si.length() <= maxContinuationSize)
  1587. {
  1588. siLen = si.length() - sizeof(siLen);
  1589. si.writeDirect(0, sizeof(siLen), &siLen);
  1590. output->sendMetaInfo(si.toByteArray(), si.length());
  1591. return;
  1592. }
  1593. else
  1594. continuationFailed = true;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. private:
  1600. bool resent;
  1601. };
  1602. // Used when we have no key
  1603. // Not split into variable vs fixed varieties (unlike others). We could if there was a demand
  1604. class UnkeyedNormalizeRecordProcessor : public NormalizeRecordProcessor
  1605. {
  1606. public:
  1607. IMPLEMENT_IINTERFACE;
  1608. UnkeyedNormalizeRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskNormalizeActivity &_owner, IDirectReader *_reader)
  1609. : NormalizeRecordProcessor(_cursor, _owner), reader(_reader), deserializeSource(_reader)
  1610. {
  1611. prefetcher.setown(owner.diskSize.queryOriginal()->createRowPrefetcher(owner.queryContext->queryCodeContext(), owner.basefactory->queryId()));
  1612. }
  1613. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1614. {
  1615. unsigned totalSizeSent = 0;
  1616. helper->setCallback(reader->queryThorDiskCallback());
  1617. while (!aborted && !deserializeSource.eos())
  1618. {
  1619. prefetcher->readAhead(deserializeSource);
  1620. const byte *nextRec = deserializeSource.queryRow();
  1621. if (!cursor || !cursor->isFiltered(nextRec))
  1622. {
  1623. if (helper->first(nextRec))
  1624. {
  1625. do
  1626. {
  1627. size32_t transformedSize = owner.doNormalizeTransform(output);
  1628. if (transformedSize)
  1629. {
  1630. processed++;
  1631. if (processed > rowLimit)
  1632. {
  1633. owner.limitExceeded();
  1634. return;
  1635. }
  1636. totalSizeSent += transformedSize;
  1637. if (processed == stopAfter)
  1638. return;
  1639. }
  1640. } while (helper->next());
  1641. }
  1642. }
  1643. deserializeSource.finishedRow();
  1644. if (totalSizeSent > indexReadChunkSize)
  1645. {
  1646. MemoryBuffer si;
  1647. unsigned short siLen = 0;
  1648. si.append(siLen);
  1649. si.append(processed);
  1650. si.append(false); // not using a key
  1651. offset_t readPos = deserializeSource.tell();
  1652. si.append(readPos);
  1653. siLen = si.length() - sizeof(siLen);
  1654. si.writeDirect(0, sizeof(siLen), &siLen);
  1655. output->sendMetaInfo(si.toByteArray(), si.length());
  1656. return;
  1657. }
  1658. }
  1659. }
  1660. protected:
  1661. Owned<IDirectReader> reader;
  1662. CThorContiguousRowBuffer deserializeSource;
  1663. Owned<ISourceRowPrefetcher> prefetcher;
  1664. };
  1665. IInMemoryFileProcessor *createKeyedNormalizeRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskNormalizeActivity &owner, bool resent)
  1666. {
  1667. return new KeyedNormalizeRecordProcessor(cursor, owner, resent);
  1668. }
  1669. IInMemoryFileProcessor *createUnkeyedNormalizeRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskNormalizeActivity &owner, IDirectReader *_reader)
  1670. {
  1671. return new UnkeyedNormalizeRecordProcessor(cursor, owner, _reader);
  1672. }
  1673. //================================================================================================
  1674. class CRoxieDiskCountActivity;
  1675. IInMemoryFileProcessor *createKeyedCountRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskCountActivity &owner);
  1676. IInMemoryFileProcessor *createUnkeyedCountRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskCountActivity &owner, bool variableDisk, IDirectReader *reader);
  1677. class CRoxieDiskCountActivity : public CRoxieDiskReadBaseActivity
  1678. {
  1679. friend class CountRecordProcessor;
  1680. protected:
  1681. IHThorDiskCountArg *helper;
  1682. public:
  1683. IMPLEMENT_IINTERFACE;
  1684. CRoxieDiskCountActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  1685. IInMemoryIndexManager *_manager)
  1686. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, 1, false)
  1687. {
  1688. onCreate();
  1689. helper = (IHThorDiskCountArg *) basehelper;
  1690. }
  1691. virtual StringBuffer &toString(StringBuffer &ret) const
  1692. {
  1693. return ret.appendf("DiskCount %u", packet->queryHeader().activityId);
  1694. }
  1695. virtual void doProcess(IMessagePacker * output)
  1696. {
  1697. {
  1698. CriticalBlock p(pcrit);
  1699. processor.setown(isKeyed ?
  1700. createKeyedCountRecordProcessor(cursor, *this) :
  1701. createUnkeyedCountRecordProcessor(cursor, *this, diskSize.isVariableSize(), manager->createReader(readPos, parallelPartNo, numParallel)));
  1702. }
  1703. unsigned __int64 stopAfter = helper->getChooseNLimit();
  1704. processor->doQuery(output, processed, (unsigned __int64) -1, stopAfter);
  1705. }
  1706. };
  1707. class CRoxieDiskCountActivityFactory : public CRoxieDiskBaseActivityFactory
  1708. {
  1709. public:
  1710. IMPLEMENT_IINTERFACE;
  1711. CRoxieDiskCountActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1712. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  1713. {
  1714. }
  1715. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  1716. {
  1717. return new CRoxieDiskCountActivity(logctx, packet, helperFactory, this, manager);
  1718. }
  1719. virtual StringBuffer &toString(StringBuffer &s) const
  1720. {
  1721. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  1722. }
  1723. };
  1724. //================================================================================================
  1725. // RecordProcessors used by Disk Normalize activity.
  1726. // Note - the classes below could be commoned up to make the code smaller, but they have been deliberately unrolled to
  1727. // keep to a bare minimum the number of virtual calls/variable tests per record scanned. This is very speed critical.
  1728. class CountRecordProcessor : public RecordProcessor
  1729. {
  1730. public:
  1731. CountRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskCountActivity &_owner)
  1732. : RecordProcessor(_cursor), owner(_owner)
  1733. {
  1734. helper = _owner.helper;
  1735. }
  1736. protected:
  1737. CRoxieDiskCountActivity &owner;
  1738. IHThorDiskCountArg *helper;
  1739. };
  1740. // Used when we have an in-memory key that matches at least some of the filter conditions
  1741. class KeyedCountRecordProcessor : public CountRecordProcessor
  1742. {
  1743. public:
  1744. KeyedCountRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskCountActivity &_owner) : CountRecordProcessor(_cursor, _owner)
  1745. {
  1746. helper->setCallback(cursor);
  1747. }
  1748. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1749. {
  1750. // doQuery needs to be as fast as possible - we are making a virtual call to it per query in order to avoid tests of loop-invariants within it
  1751. unsigned recordSize = owner.meta.getFixedSize();
  1752. void *recBuffer = output->getBuffer(recordSize, false);
  1753. IInMemoryIndexCursor *lc = cursor;
  1754. lc->reset();
  1755. unsigned __int64 totalCount = 0;
  1756. while (!aborted)
  1757. {
  1758. const void *nextCandidate = lc->nextMatch();
  1759. if (!nextCandidate)
  1760. break;
  1761. totalCount += helper->numValid(nextCandidate);
  1762. if (totalCount >= stopAfter)
  1763. {
  1764. totalCount = stopAfter;
  1765. break;
  1766. }
  1767. }
  1768. if (!aborted)
  1769. {
  1770. assert(!owner.serializer); // A count can never need serializing, surely!
  1771. if (recordSize == 1)
  1772. *(byte *)recBuffer = (byte)totalCount;
  1773. else
  1774. {
  1775. assertex(recordSize == sizeof(unsigned __int64));
  1776. *(unsigned __int64 *)recBuffer = totalCount;
  1777. }
  1778. output->putBuffer(recBuffer, recordSize, false);
  1779. }
  1780. }
  1781. };
  1782. IInMemoryFileProcessor *createKeyedCountRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskCountActivity &owner)
  1783. {
  1784. return new KeyedCountRecordProcessor(cursor, owner);
  1785. }
  1786. // Used when there is no key, fixed records
  1787. class UnkeyedCountRecordProcessor : public CountRecordProcessor
  1788. {
  1789. protected:
  1790. Owned<IDirectReader> reader;
  1791. public:
  1792. UnkeyedCountRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskCountActivity &_owner, IDirectReader *_reader)
  1793. : CountRecordProcessor(_cursor, _owner), reader(_reader)
  1794. {
  1795. }
  1796. // This version is used for fixed size rows only - variable size rows use more derived class which overrides
  1797. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1798. {
  1799. unsigned outputRecordSize = owner.meta.getFixedSize();
  1800. void *recBuffer = output->getBuffer(outputRecordSize, false);
  1801. helper->setCallback(reader->queryThorDiskCallback());
  1802. unsigned __int64 totalCount = 0;
  1803. size32_t recordSize = owner.diskSize.getFixedSize();
  1804. size32_t bufferSize = getBufferSize(recordSize);
  1805. while (!aborted && !reader->eos())
  1806. {
  1807. size32_t gotSize;
  1808. const char *nextRec = (const char *) reader->peek(bufferSize, gotSize);
  1809. if (!gotSize)
  1810. break;
  1811. gotSize = roundDown(gotSize, recordSize);
  1812. if (cursor)
  1813. {
  1814. const char *endRec = nextRec + gotSize;
  1815. loop
  1816. {
  1817. // This loop is the inner loop for memory disk counts - so keep it efficient!
  1818. if (nextRec >= endRec)
  1819. break;
  1820. if (!cursor->isFiltered(nextRec))
  1821. {
  1822. totalCount += helper->numValid(nextRec);
  1823. if (totalCount >= stopAfter)
  1824. break;
  1825. }
  1826. nextRec += recordSize;
  1827. }
  1828. }
  1829. else
  1830. totalCount += helper->numValid(gotSize, nextRec);
  1831. if (totalCount >= stopAfter)
  1832. {
  1833. totalCount = stopAfter;
  1834. break;
  1835. }
  1836. reader->skip(gotSize);
  1837. }
  1838. if (!aborted)
  1839. {
  1840. assert(!owner.serializer); // A count can never need serializing, surely!
  1841. if (outputRecordSize == 1)
  1842. *(byte *)recBuffer = (byte)totalCount;
  1843. else
  1844. {
  1845. assertex(outputRecordSize == sizeof(unsigned __int64));
  1846. *(unsigned __int64 *)recBuffer = totalCount;
  1847. }
  1848. output->putBuffer(recBuffer, outputRecordSize, false);
  1849. }
  1850. }
  1851. };
  1852. // Used when there is no key, variable records
  1853. class UnkeyedVariableCountRecordProcessor : public UnkeyedCountRecordProcessor
  1854. {
  1855. public:
  1856. UnkeyedVariableCountRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskCountActivity &_owner, IDirectReader *_reader)
  1857. : UnkeyedCountRecordProcessor(_cursor, _owner, _reader), deserializeSource(reader)
  1858. {
  1859. prefetcher.setown(owner.diskSize.queryOriginal()->createRowPrefetcher(owner.queryContext->queryCodeContext(), owner.basefactory->queryId()));
  1860. }
  1861. // This version is used for variable size rows
  1862. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  1863. {
  1864. unsigned outputRecordSize = owner.meta.getFixedSize();
  1865. void *recBuffer = output->getBuffer(outputRecordSize, false);
  1866. helper->setCallback(reader->queryThorDiskCallback());
  1867. unsigned __int64 totalCount = 0;
  1868. while (!aborted && !deserializeSource.eos())
  1869. {
  1870. prefetcher->readAhead(deserializeSource);
  1871. const byte *nextRec = deserializeSource.queryRow();
  1872. if (!cursor || !cursor->isFiltered(nextRec))
  1873. {
  1874. totalCount += helper->numValid(nextRec);
  1875. if (totalCount >= stopAfter)
  1876. {
  1877. totalCount = stopAfter;
  1878. break;
  1879. }
  1880. }
  1881. deserializeSource.finishedRow();
  1882. }
  1883. if (!aborted)
  1884. {
  1885. assert(!owner.serializer); // A count can never need serializing, surely!
  1886. if (outputRecordSize == 1)
  1887. *(byte *)recBuffer = (byte)totalCount;
  1888. else
  1889. {
  1890. assertex(outputRecordSize == sizeof(unsigned __int64));
  1891. *(unsigned __int64 *)recBuffer = totalCount;
  1892. }
  1893. output->putBuffer(recBuffer, outputRecordSize, false);
  1894. }
  1895. }
  1896. protected:
  1897. CThorContiguousRowBuffer deserializeSource;
  1898. Owned<ISourceRowPrefetcher> prefetcher;
  1899. };
  1900. IInMemoryFileProcessor *createUnkeyedCountRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskCountActivity &owner, bool variableDisk, IDirectReader *reader)
  1901. {
  1902. if (variableDisk)
  1903. return new UnkeyedVariableCountRecordProcessor(cursor, owner, reader);
  1904. else
  1905. return new UnkeyedCountRecordProcessor(cursor, owner, reader);
  1906. }
  1907. ISlaveActivityFactory *createRoxieDiskCountActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  1908. {
  1909. return new CRoxieDiskCountActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  1910. }
  1911. //================================================================================================
  1912. class CRoxieDiskAggregateActivity;
  1913. IInMemoryFileProcessor *createKeyedAggregateRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskAggregateActivity &owner);
  1914. IInMemoryFileProcessor *createUnkeyedAggregateRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskAggregateActivity &owner, bool variableDisk, IDirectReader *reader);
  1915. class CRoxieDiskAggregateActivity : public CRoxieDiskReadBaseActivity
  1916. {
  1917. friend class AggregateRecordProcessor;
  1918. protected:
  1919. IHThorDiskAggregateArg *helper;
  1920. public:
  1921. IMPLEMENT_IINTERFACE;
  1922. CRoxieDiskAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  1923. IInMemoryIndexManager *_manager,
  1924. unsigned _parallelPartNo, unsigned _numParallel, bool _forceUnkeyed)
  1925. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, _parallelPartNo, _numParallel, _forceUnkeyed)
  1926. {
  1927. onCreate();
  1928. helper = (IHThorDiskAggregateArg *) basehelper;
  1929. }
  1930. virtual bool needsRowAllocator()
  1931. {
  1932. return true;
  1933. }
  1934. virtual StringBuffer &toString(StringBuffer &ret) const
  1935. {
  1936. return ret.appendf("DiskAggregate %u", packet->queryHeader().activityId);
  1937. }
  1938. virtual void doProcess(IMessagePacker * output)
  1939. {
  1940. {
  1941. CriticalBlock p(pcrit);
  1942. processor.setown(isKeyed ? createKeyedAggregateRecordProcessor(cursor, *this) :
  1943. createUnkeyedAggregateRecordProcessor(cursor, *this, diskSize.isVariableSize(), manager->createReader(readPos, parallelPartNo, numParallel)));
  1944. }
  1945. processor->doQuery(output, 0, 0, 0);
  1946. }
  1947. };
  1948. //================================================================================================
  1949. class CParallelRoxieActivity : public CRoxieSlaveActivity
  1950. {
  1951. protected:
  1952. CIArrayOf<CRoxieDiskReadBaseActivity> parts;
  1953. unsigned numParallel;
  1954. CriticalSection parCrit;
  1955. Owned<IOutputRowDeserializer> deserializer;
  1956. public:
  1957. IMPLEMENT_IINTERFACE;
  1958. CParallelRoxieActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_factory, unsigned _numParallel)
  1959. : CRoxieSlaveActivity(_logctx, _packet, _hFactory, _factory), numParallel(_numParallel)
  1960. {
  1961. assertex(numParallel > 1);
  1962. }
  1963. virtual void abort()
  1964. {
  1965. ForEachItemIn(idx, parts)
  1966. {
  1967. parts.item(idx).abort();
  1968. }
  1969. }
  1970. virtual void setPartNo(bool filechanged) { throwUnexpected(); }
  1971. virtual StringBuffer &toString(StringBuffer &ret) const
  1972. {
  1973. return parts.item(0).toString(ret);
  1974. }
  1975. virtual const char *queryDynamicFileName() const
  1976. {
  1977. throwUnexpected();
  1978. }
  1979. virtual void setVariableFileInfo()
  1980. {
  1981. throwUnexpected();
  1982. }
  1983. virtual void doProcess(IMessagePacker * output) = 0;
  1984. virtual void processRow(CDummyMessagePacker &output) = 0;
  1985. virtual bool process()
  1986. {
  1987. if (numParallel == 1)
  1988. {
  1989. return parts.item(0).process();
  1990. }
  1991. else
  1992. {
  1993. MTIME_SECTION(timer, "CParallelRoxieActivity::process");
  1994. atomic_inc(&diskReadStarted);
  1995. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  1996. class casyncfor: public CAsyncFor
  1997. {
  1998. CIArrayOf<CRoxieDiskReadBaseActivity> &parts;
  1999. CParallelRoxieActivity &parent;
  2000. public:
  2001. casyncfor(CIArrayOf<CRoxieDiskReadBaseActivity> &_parts, CParallelRoxieActivity &_parent)
  2002. : parts(_parts), parent(_parent)
  2003. {
  2004. }
  2005. void Do(unsigned i)
  2006. {
  2007. try
  2008. {
  2009. CDummyMessagePacker d;
  2010. parts.item(i).doProcess(&d);
  2011. d.flush(true);
  2012. parent.processRow(d);
  2013. }
  2014. catch (IException *)
  2015. {
  2016. // if one throws exception, may as well abort the rest
  2017. parent.abort();
  2018. throw;
  2019. }
  2020. }
  2021. } afor(parts, *this);
  2022. afor.For(numParallel, numParallel);
  2023. //for (unsigned i = 0; i < numParallel; i++) afor.Do(i); // use this instead of line above to make them serial - handy for debugging!
  2024. logctx.flush(true, aborted);
  2025. if (aborted)
  2026. {
  2027. output->abort();
  2028. return false;
  2029. }
  2030. else
  2031. {
  2032. doProcess(output);
  2033. output->flush(true);
  2034. atomic_inc(&diskReadCompleted);
  2035. return true;
  2036. }
  2037. return true;
  2038. }
  2039. }
  2040. };
  2041. class CParallelRoxieDiskAggregateActivity : public CParallelRoxieActivity
  2042. {
  2043. protected:
  2044. IHThorDiskAggregateArg *helper;
  2045. OwnedConstRoxieRow finalRow;
  2046. public:
  2047. IMPLEMENT_IINTERFACE;
  2048. CParallelRoxieDiskAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  2049. IInMemoryIndexManager *_manager, unsigned _numParallel) :
  2050. CParallelRoxieActivity(_logctx, _packet, _hFactory, _aFactory, _numParallel)
  2051. {
  2052. helper = (IHThorDiskAggregateArg *) basehelper;
  2053. onCreate();
  2054. if (meta.needsSerialize())
  2055. {
  2056. // MORE - avoiding serializing to dummy would be more efficient...
  2057. deserializer.setown(meta.createRowDeserializer(queryContext->queryCodeContext(), basefactory->queryId()));
  2058. }
  2059. CRoxieDiskAggregateActivity *part0 = new CRoxieDiskAggregateActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, numParallel, false);
  2060. parts.append(*part0);
  2061. if (part0->queryKeyed())
  2062. {
  2063. numParallel = 1;
  2064. part0->setParallel(0, 1);
  2065. }
  2066. else
  2067. {
  2068. for (unsigned i = 1; i < numParallel; i++)
  2069. parts.append(*new CRoxieDiskAggregateActivity(_logctx, _packet, _hFactory, _aFactory, _manager, i, numParallel, true));
  2070. }
  2071. }
  2072. ~CParallelRoxieDiskAggregateActivity()
  2073. {
  2074. finalRow.clear();
  2075. }
  2076. virtual bool needsRowAllocator()
  2077. {
  2078. return true;
  2079. }
  2080. virtual void doProcess(IMessagePacker *output)
  2081. {
  2082. if (!aborted)
  2083. {
  2084. if (!finalRow)
  2085. {
  2086. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  2087. size32_t size = helper->clearAggregate(rowBuilder);
  2088. finalRow.setown(rowBuilder.finalizeRowClear(size));
  2089. }
  2090. //GH-RKC: This can probably be cleaner and more efficient using the OptimizedRowBuilder class introduced since I fixed this code
  2091. if (serializer)
  2092. serializeRow(output, finalRow);
  2093. else
  2094. {
  2095. size32_t size = meta.getRecordSize(finalRow);
  2096. appendBuffer(output, size, finalRow, meta.isVariableSize());
  2097. }
  2098. }
  2099. finalRow.clear();
  2100. helper->setCallback(NULL);
  2101. }
  2102. virtual void processRow(CDummyMessagePacker &d)
  2103. {
  2104. CriticalBlock c(parCrit);
  2105. MemoryBuffer &m = d.data;
  2106. RtlDynamicRowBuilder finalBuilder(rowAllocator, false);
  2107. if (deserializer)
  2108. {
  2109. Owned<ISerialStream> stream = createMemoryBufferSerialStream(m);
  2110. CThorStreamDeserializerSource rowSource(stream);
  2111. while (m.remaining())
  2112. {
  2113. RecordLengthType *rowLen = (RecordLengthType *) m.readDirect(sizeof(RecordLengthType));
  2114. if (!*rowLen)
  2115. break;
  2116. RecordLengthType len = *rowLen;
  2117. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  2118. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  2119. if (!finalBuilder.exists())
  2120. finalBuilder.swapWith(rowBuilder);
  2121. else
  2122. {
  2123. const void * deserialized = rowBuilder.finalizeRowClear(outsize);
  2124. helper->mergeAggregate(finalBuilder, deserialized);
  2125. ReleaseRoxieRow(deserialized);
  2126. }
  2127. }
  2128. }
  2129. else
  2130. {
  2131. RecordLengthType len = meta.getFixedSize();
  2132. while (m.remaining())
  2133. {
  2134. const void *row;
  2135. if (!meta.isFixedSize())
  2136. {
  2137. RecordLengthType *rowLen = (RecordLengthType *) m.readDirect(sizeof(RecordLengthType));
  2138. if (!*rowLen)
  2139. break;
  2140. len = *rowLen;
  2141. }
  2142. row = m.readDirect(len);
  2143. if (!finalBuilder.exists())
  2144. cloneRow(finalBuilder, row, meta);
  2145. else
  2146. helper->mergeAggregate(finalBuilder, row);
  2147. }
  2148. }
  2149. if (finalBuilder.exists())
  2150. {
  2151. size32_t finalSize = meta.getRecordSize(finalBuilder.getSelf()); // MORE - can probably track it above...
  2152. finalRow.setown(finalBuilder.finalizeRowClear(finalSize));
  2153. }
  2154. }
  2155. };
  2156. class CRoxieDiskAggregateActivityFactory : public CRoxieDiskBaseActivityFactory
  2157. {
  2158. public:
  2159. IMPLEMENT_IINTERFACE;
  2160. CRoxieDiskAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2161. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  2162. {
  2163. }
  2164. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  2165. {
  2166. if (parallelAggregate > 1)
  2167. return new CParallelRoxieDiskAggregateActivity(logctx, packet, helperFactory, this, manager, parallelAggregate);
  2168. else
  2169. return new CRoxieDiskAggregateActivity(logctx, packet, helperFactory, this, manager, 0, 1, false);
  2170. }
  2171. virtual StringBuffer &toString(StringBuffer &s) const
  2172. {
  2173. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  2174. }
  2175. };
  2176. //================================================================================================
  2177. // RecordProcessors used by Disk Aggregate activity.
  2178. // Note - the classes below could be commoned up to make the code smaller, but they have been deliberately unrolled to
  2179. // keep to a bare minimum the number of virtual calls/variable tests per record scanned. This is very speed critical.
  2180. class AggregateRecordProcessor : public RecordProcessor
  2181. {
  2182. public:
  2183. AggregateRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskAggregateActivity &_owner) : RecordProcessor(_cursor), owner(_owner)
  2184. {
  2185. helper = _owner.helper;
  2186. }
  2187. protected:
  2188. CRoxieDiskAggregateActivity &owner;
  2189. IHThorDiskAggregateArg *helper;
  2190. };
  2191. // Used when we have an in-memory key that matches at least some of the filter conditions
  2192. class KeyedAggregateRecordProcessor : public AggregateRecordProcessor
  2193. {
  2194. public:
  2195. KeyedAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskAggregateActivity &_owner) : AggregateRecordProcessor(_cursor, _owner)
  2196. {
  2197. helper->setCallback(cursor);
  2198. }
  2199. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2200. {
  2201. // doQuery needs to be as fast as possible - we are making a virtual call to it per query in order to avoid tests of loop-invariants within it
  2202. OptimizedRowBuilder rowBuilder(owner.rowAllocator, owner.meta, output, owner.serializer);
  2203. helper->clearAggregate(rowBuilder);
  2204. IInMemoryIndexCursor *lc = cursor;
  2205. lc->reset();
  2206. while (!aborted)
  2207. {
  2208. const void *nextCandidate = lc->nextMatch();
  2209. if (!nextCandidate)
  2210. break;
  2211. helper->processRow(rowBuilder, nextCandidate);
  2212. }
  2213. if (!aborted)
  2214. {
  2215. if (helper->processedAnyRows())
  2216. {
  2217. size32_t finalSize = owner.meta.getRecordSize(rowBuilder.getSelf());
  2218. rowBuilder.writeToOutput(finalSize, true);
  2219. }
  2220. }
  2221. }
  2222. };
  2223. IInMemoryFileProcessor *createKeyedAggregateRecordProcessor(IInMemoryIndexCursor *cursor, CRoxieDiskAggregateActivity &owner)
  2224. {
  2225. return new KeyedAggregateRecordProcessor(cursor, owner);
  2226. }
  2227. // Used when we have no key - fixed size records
  2228. class UnkeyedAggregateRecordProcessor : public AggregateRecordProcessor
  2229. {
  2230. public:
  2231. UnkeyedAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskAggregateActivity &_owner, IDirectReader *_reader)
  2232. : AggregateRecordProcessor(_cursor, _owner), reader(_reader)
  2233. {
  2234. helper->setCallback(reader->queryThorDiskCallback());
  2235. }
  2236. // Note that variable size record handler overrides this class
  2237. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2238. {
  2239. OptimizedRowBuilder rowBuilder(owner.rowAllocator, owner.meta, output, owner.serializer);
  2240. helper->clearAggregate(rowBuilder);
  2241. size32_t recordSize = owner.diskSize.getFixedSize();
  2242. size32_t bufferSize = getBufferSize(recordSize);
  2243. while (!aborted)
  2244. {
  2245. size32_t gotSize;
  2246. const char *firstRec = (const char *) reader->peek(bufferSize, gotSize);
  2247. if (!gotSize)
  2248. break;
  2249. gotSize = roundDown(gotSize, recordSize);
  2250. const char *nextRec = firstRec;
  2251. endRec = firstRec + gotSize;
  2252. // This loop is the inner loop for memory diskreads - so keep it efficient!
  2253. if (cursor) // Moved this test out of the loop below for speed!
  2254. {
  2255. while (nextRec <= endRec)
  2256. {
  2257. if (!cursor->isFiltered(nextRec))
  2258. helper->processRow(rowBuilder, nextRec);
  2259. nextRec += recordSize;
  2260. }
  2261. }
  2262. else
  2263. {
  2264. while (nextRec <= endRec)
  2265. {
  2266. helper->processRow(rowBuilder, nextRec);
  2267. nextRec += recordSize;
  2268. }
  2269. }
  2270. reader->skip(gotSize);
  2271. }
  2272. if (!aborted)
  2273. {
  2274. if (helper->processedAnyRows())
  2275. {
  2276. size32_t finalSize = owner.meta.getRecordSize(rowBuilder.getSelf());
  2277. rowBuilder.writeToOutput(finalSize, true);
  2278. }
  2279. }
  2280. }
  2281. protected:
  2282. Owned<IDirectReader> reader;
  2283. };
  2284. // Used when we have no key - variablesize records
  2285. class UnkeyedVariableAggregateRecordProcessor : public UnkeyedAggregateRecordProcessor
  2286. {
  2287. public:
  2288. UnkeyedVariableAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskAggregateActivity &_owner, IDirectReader *_reader)
  2289. : UnkeyedAggregateRecordProcessor(_cursor, _owner, _reader), deserializeSource(_reader)
  2290. {
  2291. prefetcher.setown(owner.diskSize.queryOriginal()->createRowPrefetcher(owner.queryContext->queryCodeContext(), owner.basefactory->queryId()));
  2292. }
  2293. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2294. {
  2295. OptimizedRowBuilder rowBuilder(owner.rowAllocator, owner.meta, output, owner.serializer);
  2296. helper->clearAggregate(rowBuilder);
  2297. while (!aborted && !deserializeSource.eos())
  2298. {
  2299. prefetcher->readAhead(deserializeSource);
  2300. const byte *nextRec = deserializeSource.queryRow();
  2301. if (!cursor || !cursor->isFiltered(nextRec))
  2302. {
  2303. helper->processRow(rowBuilder, nextRec);
  2304. }
  2305. deserializeSource.finishedRow();
  2306. }
  2307. if (!aborted)
  2308. {
  2309. if (helper->processedAnyRows())
  2310. {
  2311. size32_t finalSize = owner.meta.getRecordSize(rowBuilder.getSelf());
  2312. rowBuilder.writeToOutput(finalSize, true);
  2313. }
  2314. }
  2315. }
  2316. protected:
  2317. CThorContiguousRowBuffer deserializeSource;
  2318. Owned<ISourceRowPrefetcher> prefetcher;
  2319. };
  2320. IInMemoryFileProcessor *createUnkeyedAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, CRoxieDiskAggregateActivity &_owner, bool variableDisk, IDirectReader *_reader)
  2321. {
  2322. if (variableDisk)
  2323. return new UnkeyedVariableAggregateRecordProcessor(_cursor, _owner, _reader);
  2324. else
  2325. return new UnkeyedAggregateRecordProcessor(_cursor, _owner, _reader);
  2326. }
  2327. ISlaveActivityFactory *createRoxieDiskAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2328. {
  2329. return new CRoxieDiskAggregateActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  2330. }
  2331. //================================================================================================
  2332. class CRoxieDiskGroupAggregateActivity : public CRoxieDiskReadBaseActivity
  2333. {
  2334. protected:
  2335. IHThorDiskGroupAggregateArg *helper;
  2336. RowAggregator results;
  2337. void outputResults(IMessagePacker *output)
  2338. {
  2339. if (!aborted)
  2340. {
  2341. loop
  2342. {
  2343. Owned<AggregateRowBuilder> next = results.nextResult();
  2344. if (!next)
  2345. break;
  2346. unsigned rowSize = next->querySize();
  2347. OwnedConstRoxieRow row(next->finalizeRowClear());
  2348. if (serializer)
  2349. {
  2350. serializeRow(output, row);
  2351. }
  2352. else
  2353. {
  2354. void *recBuffer = output->getBuffer(rowSize, meta.isVariableSize());
  2355. memcpy(recBuffer, row, rowSize);
  2356. output->putBuffer(recBuffer, rowSize, meta.isVariableSize());
  2357. }
  2358. }
  2359. }
  2360. }
  2361. public:
  2362. IMPLEMENT_IINTERFACE;
  2363. CRoxieDiskGroupAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  2364. IInMemoryIndexManager *_manager,
  2365. unsigned partNo, unsigned numParts, bool _forceUnkeyed)
  2366. : CRoxieDiskReadBaseActivity(_logctx, _packet, _hFactory, _aFactory, _manager, partNo, numParts, _forceUnkeyed),
  2367. helper((IHThorDiskGroupAggregateArg *) basehelper),
  2368. results(*helper, *helper)
  2369. {
  2370. onCreate();
  2371. results.start(rowAllocator);
  2372. }
  2373. virtual bool needsRowAllocator()
  2374. {
  2375. return true;
  2376. }
  2377. virtual StringBuffer &toString(StringBuffer &ret) const
  2378. {
  2379. return ret.appendf("DiskGroupAggregate %u", packet->queryHeader().activityId);
  2380. }
  2381. virtual void doProcess(IMessagePacker * output)
  2382. {
  2383. {
  2384. CriticalBlock p(pcrit);
  2385. processor.setown(isKeyed ?
  2386. createKeyedGroupAggregateRecordProcessor(cursor, results, *helper) :
  2387. createUnkeyedGroupAggregateRecordProcessor(cursor, results, *helper, manager->createReader(readPos, parallelPartNo, numParallel),
  2388. queryContext->queryCodeContext(), basefactory->queryId()));
  2389. }
  2390. processor->doQuery(output, 0, 0, 0);
  2391. if (!aborted)
  2392. outputResults(output);
  2393. results.reset();
  2394. }
  2395. };
  2396. class CParallelRoxieDiskGroupAggregateActivity : public CParallelRoxieActivity
  2397. {
  2398. protected:
  2399. IHThorDiskGroupAggregateArg *helper;
  2400. RowAggregator resultAggregator;
  2401. Owned<IRowManager> rowManager;
  2402. public:
  2403. IMPLEMENT_IINTERFACE;
  2404. CParallelRoxieDiskGroupAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory,
  2405. IInMemoryIndexManager *_manager, unsigned _numParallel) :
  2406. CParallelRoxieActivity(_logctx, _packet, _hFactory, _aFactory, _numParallel),
  2407. helper((IHThorDiskGroupAggregateArg *) basehelper),
  2408. resultAggregator(*helper, *helper)
  2409. {
  2410. onCreate();
  2411. resultAggregator.start(rowAllocator);
  2412. if (meta.needsSerialize())
  2413. {
  2414. // MORE - avoiding serializing to dummy would be more efficient...
  2415. deserializer.setown(meta.createRowDeserializer(queryContext->queryCodeContext(), basefactory->queryId()));
  2416. }
  2417. CRoxieDiskGroupAggregateActivity *part0 = new CRoxieDiskGroupAggregateActivity(_logctx, _packet, _hFactory, _aFactory, _manager, 0, numParallel, false);
  2418. parts.append(*part0);
  2419. if (part0->queryKeyed())
  2420. {
  2421. numParallel = 1;
  2422. part0->setParallel(0, 1);
  2423. }
  2424. else
  2425. {
  2426. for (unsigned i = 1; i < numParallel; i++)
  2427. parts.append(*new CRoxieDiskGroupAggregateActivity(_logctx, _packet, _hFactory, _aFactory, _manager, i, numParallel, true));
  2428. }
  2429. }
  2430. virtual bool needsRowAllocator()
  2431. {
  2432. return true;
  2433. }
  2434. virtual void doProcess(IMessagePacker *output)
  2435. {
  2436. if (!aborted)
  2437. {
  2438. loop
  2439. {
  2440. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  2441. if (!next)
  2442. break;
  2443. unsigned rowSize = next->querySize();
  2444. OwnedConstRoxieRow row(next->finalizeRowClear());
  2445. if (serializer)
  2446. {
  2447. serializeRow(output, row);
  2448. }
  2449. else
  2450. {
  2451. void *recBuffer = output->getBuffer(rowSize, meta.isVariableSize());
  2452. memcpy(recBuffer, row, rowSize);
  2453. output->putBuffer(recBuffer, rowSize, meta.isVariableSize());
  2454. }
  2455. }
  2456. }
  2457. resultAggregator.reset();
  2458. helper->setCallback(NULL);
  2459. }
  2460. void processRow(CDummyMessagePacker &d)
  2461. {
  2462. CriticalBlock b(parCrit); // MORE - use a spinlock
  2463. MemoryBuffer &m = d.data;
  2464. Owned<ISerialStream> stream = createMemoryBufferSerialStream(m);
  2465. CThorStreamDeserializerSource rowSource(stream);
  2466. while (m.remaining())
  2467. {
  2468. const void *row;
  2469. if (meta.isFixedSize() && !deserializer)
  2470. {
  2471. row = m.readDirect(meta.getFixedSize());
  2472. resultAggregator.mergeElement(row);
  2473. }
  2474. else
  2475. {
  2476. RecordLengthType *rowLen = (RecordLengthType *) m.readDirect(sizeof(RecordLengthType));
  2477. if (!*rowLen)
  2478. break;
  2479. RecordLengthType len = *rowLen;
  2480. if (deserializer)
  2481. {
  2482. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  2483. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  2484. OwnedConstRoxieRow deserialized = rowBuilder.finalizeRowClear(outsize);
  2485. resultAggregator.mergeElement(deserialized);
  2486. }
  2487. else
  2488. {
  2489. row = m.readDirect(len);
  2490. resultAggregator.mergeElement(row);
  2491. }
  2492. }
  2493. }
  2494. }
  2495. };
  2496. class CRoxieDiskGroupAggregateActivityFactory : public CRoxieDiskBaseActivityFactory
  2497. {
  2498. public:
  2499. IMPLEMENT_IINTERFACE;
  2500. CRoxieDiskGroupAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2501. : CRoxieDiskBaseActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  2502. {
  2503. }
  2504. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  2505. {
  2506. if (parallelAggregate > 1)
  2507. return new CParallelRoxieDiskGroupAggregateActivity(logctx, packet, helperFactory, this, manager, parallelAggregate);
  2508. else
  2509. return new CRoxieDiskGroupAggregateActivity(logctx, packet, helperFactory, this, manager, 0, 1, false);
  2510. }
  2511. virtual StringBuffer &toString(StringBuffer &s) const
  2512. {
  2513. return CSlaveActivityFactory::toString(s.append("DiskRead "));
  2514. }
  2515. };
  2516. //================================================================================================
  2517. // RecordProcessors used by Disk Group Aggregate activity.
  2518. // Note - the classes below could be commoned up to make the code smaller, but they have been deliberately unrolled to
  2519. // keep to a bare minimum the number of virtual calls/variable tests per record scanned. This is very speed critical.
  2520. class GroupAggregateRecordProcessor : public RecordProcessor, implements IHThorGroupAggregateCallback
  2521. {
  2522. public:
  2523. IMPLEMENT_IINTERFACE;
  2524. GroupAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, RowAggregator &_results, IHThorDiskGroupAggregateArg &_helper)
  2525. : RecordProcessor(_cursor),
  2526. results(_results),
  2527. helper(_helper)
  2528. {
  2529. }
  2530. virtual void processRow(const void * next)
  2531. {
  2532. results.addRow(next);
  2533. }
  2534. protected:
  2535. RowAggregator &results;
  2536. IHThorDiskGroupAggregateArg &helper;
  2537. };
  2538. // Used when we have an in-memory key that matches at least some of the filter conditions
  2539. class KeyedGroupAggregateRecordProcessor : public GroupAggregateRecordProcessor
  2540. {
  2541. public:
  2542. KeyedGroupAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, RowAggregator &_results, IHThorDiskGroupAggregateArg &_helper)
  2543. : GroupAggregateRecordProcessor(_cursor, _results, _helper)
  2544. {
  2545. helper.setCallback(cursor);
  2546. }
  2547. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2548. {
  2549. // doQuery needs to be as fast as possible - we are making a virtual call to it per query in order to avoid tests of loop-invariants within it
  2550. IInMemoryIndexCursor *lc = cursor;
  2551. lc->reset();
  2552. while (!aborted)
  2553. {
  2554. const void *nextCandidate = lc->nextMatch();
  2555. if (!nextCandidate)
  2556. break;
  2557. helper.processRow(nextCandidate, this);
  2558. }
  2559. }
  2560. };
  2561. IInMemoryFileProcessor *createKeyedGroupAggregateRecordProcessor(IInMemoryIndexCursor *cursor, RowAggregator &results, IHThorDiskGroupAggregateArg &helper)
  2562. {
  2563. return new KeyedGroupAggregateRecordProcessor(cursor, results, helper);
  2564. }
  2565. // Used when we have no key, fixed size records. Variable size records use more derived class
  2566. class UnkeyedGroupAggregateRecordProcessor : public GroupAggregateRecordProcessor
  2567. {
  2568. public:
  2569. IMPLEMENT_IINTERFACE;
  2570. UnkeyedGroupAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, RowAggregator &_results, IHThorDiskGroupAggregateArg &_helper, IDirectReader *_reader)
  2571. : GroupAggregateRecordProcessor(_cursor, _results, _helper), reader(_reader)
  2572. {
  2573. helper.setCallback(reader->queryThorDiskCallback());
  2574. }
  2575. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2576. {
  2577. size32_t recordSize = helper.queryDiskRecordSize()->getFixedSize();
  2578. size32_t bufferSize = getBufferSize(recordSize);
  2579. while (!aborted && !reader->eos())
  2580. {
  2581. size32_t gotSize;
  2582. const char *firstRec = (const char *) reader->peek(bufferSize, gotSize);
  2583. if (!gotSize)
  2584. break;
  2585. gotSize = roundDown(gotSize, recordSize);
  2586. const char *nextRec = firstRec;
  2587. endRec = firstRec + gotSize;
  2588. // This loop is the inner loop for memory diskreads - so keep it efficient!
  2589. if (cursor)
  2590. {
  2591. while (nextRec <= endRec)
  2592. {
  2593. if (!cursor->isFiltered(nextRec))
  2594. helper.processRow(nextRec, this);
  2595. nextRec += recordSize;
  2596. }
  2597. }
  2598. else
  2599. {
  2600. helper.processRows(gotSize, firstRec, this);
  2601. }
  2602. reader->skip(gotSize);
  2603. }
  2604. }
  2605. protected:
  2606. Owned<IDirectReader> reader;
  2607. };
  2608. // Used when we have no key, variable size records.
  2609. class UnkeyedVariableGroupAggregateRecordProcessor : public UnkeyedGroupAggregateRecordProcessor
  2610. {
  2611. public:
  2612. UnkeyedVariableGroupAggregateRecordProcessor(IInMemoryIndexCursor *_cursor, RowAggregator &_results, IHThorDiskGroupAggregateArg &_helper, IDirectReader *_reader,
  2613. ICodeContext *ctx, unsigned activityId)
  2614. : UnkeyedGroupAggregateRecordProcessor(_cursor, _results, _helper, _reader), deserializeSource(_reader)
  2615. {
  2616. prefetcher.setown(helper.queryDiskRecordSize()->createRowPrefetcher(ctx, activityId));
  2617. }
  2618. virtual void doQuery(IMessagePacker *output, unsigned processed, unsigned __int64 rowLimit, unsigned __int64 stopAfter)
  2619. {
  2620. helper.setCallback(reader->queryThorDiskCallback());
  2621. while (!aborted && !deserializeSource.eos())
  2622. {
  2623. // This loop is the inner loop for memory diskreads - so keep it efficient!
  2624. prefetcher->readAhead(deserializeSource);
  2625. const byte *nextRec = deserializeSource.queryRow();
  2626. if (!cursor || !cursor->isFiltered(nextRec))
  2627. helper.processRow(nextRec, this);
  2628. deserializeSource.finishedRow();
  2629. }
  2630. }
  2631. protected:
  2632. CThorContiguousRowBuffer deserializeSource;
  2633. Owned<ISourceRowPrefetcher> prefetcher;
  2634. };
  2635. IInMemoryFileProcessor *createUnkeyedGroupAggregateRecordProcessor(IInMemoryIndexCursor *cursor, RowAggregator &results, IHThorDiskGroupAggregateArg &helper, IDirectReader *reader, ICodeContext *ctx, unsigned activityId)
  2636. {
  2637. if (helper.queryDiskRecordSize()->isVariableSize())
  2638. return new UnkeyedVariableGroupAggregateRecordProcessor(cursor, results, helper, reader, ctx, activityId);
  2639. else
  2640. return new UnkeyedGroupAggregateRecordProcessor(cursor, results, helper, reader);
  2641. }
  2642. ISlaveActivityFactory *createRoxieDiskGroupAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2643. {
  2644. return new CRoxieDiskGroupAggregateActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  2645. }
  2646. //================================================================================================
  2647. class CRoxieKeyedActivityFactory : public CSlaveActivityFactory
  2648. {
  2649. protected:
  2650. Owned<IKeyArray> keyArray;
  2651. Owned<TranslatorArray> layoutTranslators;
  2652. Owned<IDefRecordMeta> activityMeta;
  2653. CRoxieKeyedActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2654. : CSlaveActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  2655. {
  2656. }
  2657. public:
  2658. inline IKeyArray *queryKeyArray() const { return keyArray; }
  2659. inline TranslatorArray *queryLayoutTranslators() const { return layoutTranslators; }
  2660. inline IDefRecordMeta *queryActivityMeta() const { return activityMeta; }
  2661. };
  2662. class CRoxieIndexActivityFactory : public CRoxieKeyedActivityFactory
  2663. {
  2664. public:
  2665. IMPLEMENT_IINTERFACE;
  2666. CRoxieIndexActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  2667. : CRoxieKeyedActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  2668. {
  2669. }
  2670. void init(IHThorIndexReadBaseArg * helper, IPropertyTree &graphNode)
  2671. {
  2672. rtlDataAttr indexLayoutMeta;
  2673. size32_t indexLayoutSize;
  2674. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  2675. assertex(indexLayoutSize== 0);
  2676. MemoryBuffer m;
  2677. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  2678. activityMeta.setown(deserializeRecordMeta(m, true));
  2679. layoutTranslators.setown(new TranslatorArray);
  2680. bool variableFileName = (helper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0;
  2681. if (!variableFileName)
  2682. {
  2683. bool isOpt = (helper->getFlags() & TIRoptional) != 0;
  2684. datafile.setown(queryFactory.queryPackage().lookupFileName(helper->getFileName(), isOpt, true, queryFactory.queryWorkUnit()));
  2685. if (datafile)
  2686. keyArray.setown(datafile->getKeyArray(activityMeta, layoutTranslators, isOpt, queryFactory.queryChannel(), queryFactory.getEnableFieldTranslation()));
  2687. }
  2688. }
  2689. };
  2690. class CRoxieKeyedActivity : public CRoxieSlaveActivity
  2691. {
  2692. // Common base class for all activities that deal with keys - keyed join or indexread and its allies
  2693. protected:
  2694. Owned<IKeyManager> tlk;
  2695. Linked<TranslatorArray> layoutTranslators;
  2696. Linked<IKeyArray> keyArray;
  2697. IDefRecordMeta *activityMeta;
  2698. bool createSegmentMonitorsPending;
  2699. virtual void createSegmentMonitors() = 0;
  2700. virtual void setPartNo(bool filechanged)
  2701. {
  2702. if (!lastPartNo.partNo)
  2703. {
  2704. assertex(filechanged);
  2705. Owned<IKeyIndexSet> allKeys = createKeyIndexSet();
  2706. for (unsigned subpart = 0; subpart < keyArray->length(); subpart++)
  2707. {
  2708. IKeyIndexBase *kib = keyArray->queryKeyPart(subpart);
  2709. if (kib)
  2710. {
  2711. IKeyIndex *k = kib->queryPart(lastPartNo.fileNo);
  2712. if (k)
  2713. {
  2714. assertex(!k->isTopLevelKey());
  2715. allKeys->addIndex(LINK(k));
  2716. }
  2717. }
  2718. }
  2719. if (allKeys->numParts())
  2720. {
  2721. tlk.setown(createKeyMerger(allKeys, 0, 0, &logctx));
  2722. createSegmentMonitorsPending = true;
  2723. }
  2724. else
  2725. tlk.clear();
  2726. }
  2727. else
  2728. {
  2729. IKeyIndexBase *kib = keyArray->queryKeyPart(lastPartNo.partNo);
  2730. assertex(kib != NULL);
  2731. IKeyIndex *k = kib->queryPart(lastPartNo.fileNo);
  2732. if (filechanged)
  2733. {
  2734. tlk.setown(createKeyManager(k, 0, &logctx));
  2735. createSegmentMonitorsPending = true;
  2736. }
  2737. else
  2738. tlk->setKey(k);
  2739. }
  2740. }
  2741. virtual void setVariableFileInfo()
  2742. {
  2743. layoutTranslators.setown(new TranslatorArray);
  2744. keyArray.setown(varFileInfo->getKeyArray(activityMeta, layoutTranslators, isOpt, packet->queryHeader().channel, allowFieldTranslation));
  2745. }
  2746. CRoxieKeyedActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieKeyedActivityFactory *_aFactory)
  2747. : CRoxieSlaveActivity(_logctx, _packet, _hFactory, _aFactory),
  2748. keyArray(_aFactory->queryKeyArray()),
  2749. layoutTranslators(_aFactory->queryLayoutTranslators()),
  2750. activityMeta(_aFactory->queryActivityMeta()),
  2751. createSegmentMonitorsPending(true)
  2752. {
  2753. }
  2754. };
  2755. class CRoxieIndexActivity : public CRoxieKeyedActivity
  2756. {
  2757. // Common base class for indexread, indexcount and related activities
  2758. protected:
  2759. const CRoxieIndexActivityFactory *factory;
  2760. PartNoType *inputData; // list of channels
  2761. IHThorIndexReadBaseArg * indexHelper;
  2762. unsigned inputCount;
  2763. unsigned inputsDone;
  2764. unsigned processed;
  2765. unsigned keyprocessed;
  2766. unsigned steppingOffset;
  2767. unsigned steppingLength;
  2768. unsigned short numSkipFields;
  2769. unsigned numSeeks;
  2770. bool lastRowCompleteMatch;
  2771. CIndexTransformCallback callback;
  2772. SmartStepExtra stepExtra; // just used for flags - a little unnecessary...
  2773. const byte *steppingRow;
  2774. __int64 getCount()
  2775. {
  2776. assertex(!resent);
  2777. unsigned __int64 result = 0;
  2778. unsigned inputsDone = 0;
  2779. while (!aborted && inputsDone < inputCount)
  2780. {
  2781. checkPartChanged(inputData[inputsDone]);
  2782. if (tlk)
  2783. {
  2784. createSegmentMonitors();
  2785. result += tlk->getCount();
  2786. }
  2787. inputsDone++;
  2788. }
  2789. return result;
  2790. }
  2791. bool checkLimit(unsigned __int64 limit)
  2792. {
  2793. assertex(!resent);
  2794. unsigned __int64 result = 0;
  2795. unsigned inputsDone = 0;
  2796. bool ret = true;
  2797. while (!aborted && inputsDone < inputCount)
  2798. {
  2799. checkPartChanged(inputData[inputsDone]);
  2800. if (tlk)
  2801. {
  2802. createSegmentMonitors();
  2803. result += tlk->checkCount(limit-result);
  2804. if (result > limit)
  2805. {
  2806. ret = false;
  2807. break;
  2808. }
  2809. }
  2810. inputsDone++;
  2811. }
  2812. return ret;
  2813. }
  2814. public:
  2815. IMPLEMENT_IINTERFACE;
  2816. CRoxieIndexActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory, unsigned _steppingOffset)
  2817. : CRoxieKeyedActivity(_logctx, _packet, _hFactory, _aFactory),
  2818. factory(_aFactory),
  2819. steppingOffset(_steppingOffset),
  2820. stepExtra(SSEFreadAhead, NULL)
  2821. {
  2822. indexHelper = (IHThorIndexReadBaseArg *) basehelper;
  2823. variableFileName = (indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0;
  2824. isOpt = (indexHelper->getFlags() & TDRoptional) != 0;
  2825. inputData = NULL;
  2826. inputCount = 0;
  2827. inputsDone = 0;
  2828. processed = 0;
  2829. keyprocessed = 0;
  2830. numSkipFields = 0;
  2831. lastRowCompleteMatch = true; // default is we only return complete matches....
  2832. steppingLength = 0;
  2833. steppingRow = NULL;
  2834. numSeeks = 0;
  2835. if (packet->getSmartStepInfoLength())
  2836. {
  2837. const byte *smartStepInfoValue = packet->querySmartStepInfoData();
  2838. numSkipFields = * (unsigned short *) smartStepInfoValue;
  2839. smartStepInfoValue += sizeof(unsigned short);
  2840. steppingLength = * (unsigned short *) smartStepInfoValue;
  2841. smartStepInfoValue += sizeof(unsigned short);
  2842. unsigned flags = * (unsigned short *) smartStepInfoValue;
  2843. smartStepInfoValue += sizeof(unsigned short);
  2844. numSeeks = * (unsigned *) smartStepInfoValue;
  2845. smartStepInfoValue += sizeof(unsigned);
  2846. assertex(numSeeks); // Given that we put the first seek in here to there should always be at least one!
  2847. steppingRow = smartStepInfoValue; // the first of them...
  2848. stepExtra.set(flags, NULL);
  2849. #ifdef _DEBUG
  2850. logctx.CTXLOG("%d seek rows provided", numSeeks);
  2851. for (unsigned i = 0; i < numSeeks; i++)
  2852. {
  2853. StringBuffer b;
  2854. for (unsigned j = 0; j < steppingLength; j++)
  2855. b.appendf("%02x ", steppingRow[i*steppingLength + j]);
  2856. logctx.CTXLOG("Seek row %d: %s", i+1, b.str());
  2857. }
  2858. #endif
  2859. }
  2860. }
  2861. virtual void onCreate()
  2862. {
  2863. CRoxieKeyedActivity::onCreate();
  2864. inputData = (PartNoType *) serializedCreate.readDirect(0);
  2865. inputCount = (serializedCreate.length() - serializedCreate.getPos()) / sizeof(*inputData);
  2866. indexHelper->setCallback(&callback);
  2867. }
  2868. virtual const char *queryDynamicFileName() const
  2869. {
  2870. return indexHelper->getFileName();
  2871. }
  2872. virtual void createSegmentMonitors()
  2873. {
  2874. if (createSegmentMonitorsPending)
  2875. {
  2876. createSegmentMonitorsPending = false;
  2877. tlk->setLayoutTranslator(layoutTranslators->item(lastPartNo.fileNo));
  2878. indexHelper->createSegmentMonitors(tlk);
  2879. tlk->finishSegmentMonitors();
  2880. }
  2881. }
  2882. bool sendContinuation(IMessagePacker * output)
  2883. {
  2884. MemoryBuffer si;
  2885. unsigned short siLen = 0;
  2886. si.append(siLen);
  2887. si.append(lastRowCompleteMatch);
  2888. si.append(inputsDone);
  2889. si.append(processed);
  2890. si.append(keyprocessed);
  2891. si.append(lastPartNo.partNo);
  2892. si.append(lastPartNo.fileNo);
  2893. tlk->serializeCursorPos(si);
  2894. if (si.length() <= maxContinuationSize)
  2895. {
  2896. siLen = si.length() - sizeof(siLen);
  2897. si.writeDirect(0, sizeof(siLen), &siLen);
  2898. output->sendMetaInfo(si.toByteArray(), si.length());
  2899. logctx.flush(true, aborted);
  2900. output->flush(true);
  2901. return true;
  2902. }
  2903. else
  2904. return false;
  2905. }
  2906. void readContinuationInfo()
  2907. {
  2908. resentInfo.read(lastRowCompleteMatch);
  2909. resentInfo.read(inputsDone);
  2910. resentInfo.read(processed);
  2911. resentInfo.read(keyprocessed);
  2912. resentInfo.read(lastPartNo.partNo);
  2913. resentInfo.read(lastPartNo.fileNo);
  2914. setPartNo(true);
  2915. tlk->deserializeCursorPos(resentInfo);
  2916. assertex(resentInfo.remaining() == 0);
  2917. }
  2918. virtual void setPartNo(bool fileChanged)
  2919. {
  2920. // NOTE - may be used by both indexread and normalize...
  2921. if (steppingOffset) // MORE - may be other cases too - eg want output sorted and there are multiple subfiles...
  2922. {
  2923. unsigned i = 0;
  2924. Owned<IKeyIndexSet> allKeys = createKeyIndexSet();
  2925. while (!aborted && i < inputCount)
  2926. {
  2927. PartNoType &part = inputData[i];
  2928. lastPartNo.partNo = part.partNo;
  2929. lastPartNo.fileNo = part.fileNo; // This is a hack so that the translator can be retrieved. We don't support record translation properly when doing keymerging...)
  2930. // MORE - this code looks like it could be commoned up with code in CRoxieKeyedActivity::setPartNo
  2931. if (!lastPartNo.partNo)
  2932. {
  2933. for (unsigned subpart = 0; subpart < keyArray->length(); subpart++)
  2934. {
  2935. IKeyIndexBase *kib = keyArray->queryKeyPart(subpart);
  2936. if (kib)
  2937. {
  2938. IKeyIndex *k = kib->queryPart(lastPartNo.fileNo);
  2939. if (k)
  2940. {
  2941. assertex(!k->isTopLevelKey());
  2942. allKeys->addIndex(LINK(k));
  2943. }
  2944. }
  2945. }
  2946. }
  2947. else
  2948. {
  2949. IKeyIndexBase *kib = keyArray->queryKeyPart(part.partNo);
  2950. assertex(kib != NULL);
  2951. IKeyIndex *k = kib->queryPart(part.fileNo);
  2952. allKeys->addIndex(LINK(k));
  2953. }
  2954. i++;
  2955. }
  2956. if (allKeys->numParts())
  2957. tlk.setown(::createKeyMerger(allKeys, 0, steppingOffset, &logctx));
  2958. else
  2959. tlk.clear();
  2960. createSegmentMonitorsPending = true;
  2961. }
  2962. else
  2963. CRoxieKeyedActivity::setPartNo(fileChanged);
  2964. }
  2965. };
  2966. //================================================================================================
  2967. class CRoxieIndexReadActivity : public CRoxieIndexActivity, implements IIndexReadActivityInfo
  2968. {
  2969. protected:
  2970. IHThorCompoundReadExtra * readHelper;
  2971. public:
  2972. IMPLEMENT_IINTERFACE;
  2973. CRoxieIndexReadActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory, unsigned _steppingOffset)
  2974. : CRoxieIndexActivity(_logctx, _packet, _hFactory, _aFactory, _steppingOffset)
  2975. {
  2976. onCreate();
  2977. readHelper = (IHThorIndexReadArg *) basehelper;
  2978. if (resent)
  2979. readContinuationInfo();
  2980. }
  2981. virtual StringBuffer &toString(StringBuffer &ret) const
  2982. {
  2983. return ret.appendf("IndexRead %u", packet->queryHeader().activityId);
  2984. }
  2985. /* Notes on Global smart stepping implementation:
  2986. When smart stepping, I get from the Roxie server:
  2987. 1 or more seek positions
  2988. some flags
  2989. I can read from the index in an order that matches the seek positions order (because of index merger), and which match my hard filter (they may not match my postfilter)
  2990. I can skip forwards in the index to the first record GE a skip position
  2991. I am not going to try to implement a (possible future) flag to return mismatches after any but the last of the seek positions (yet)
  2992. I want to return M matching (keyed matches, seek field matches, and postfilter matches) rows for all provided seek positions
  2993. where M is 1 if SSEFonlyReturnFirstSeekMatch flag set, otherwise all...
  2994. THEN once we are beyond the last provided seek:
  2995. if returnMismatches flag set,
  2996. current row = (next row matching keyed filter)
  2997. if someNewAsYetUnnamedAndUnimplementedFlag flag set
  2998. //if the post filter matches then there may be scope for returning all records which match the seek fields of that first match
  2999. // But not very likely to help unless terms correlated, and may well hinder
  3000. return current row and all following rows matching keyed filter, seek data from current row, and postfilter
  3001. return next row matching keyed filter (even if doesn't match postfilter)
  3002. else
  3003. return next N rows matching keyed filter and postfilter (where N depends on readAheadManyResults flag - 1 if not set)
  3004. */
  3005. inline void advanceToNextSeek()
  3006. {
  3007. assertex(numSeeks != 0);
  3008. if (--numSeeks)
  3009. steppingRow += steppingLength;
  3010. else
  3011. steppingRow = NULL;
  3012. }
  3013. virtual bool process()
  3014. {
  3015. MTIME_SECTION(timer, "CRoxieIndexReadActivity ::process");
  3016. unsigned __int64 keyedLimit = readHelper->getKeyedLimit();
  3017. unsigned __int64 limit = readHelper->getRowLimit();
  3018. if (!resent && (keyedLimit != (unsigned __int64) -1) && ((keyedLimit > preabortIndexReadsThreshold) || (indexHelper->getFlags() & TIRcountkeyedlimit) != 0)) // Don't recheck the limit every time!
  3019. {
  3020. if (!checkLimit(keyedLimit))
  3021. {
  3022. limitExceeded(true);
  3023. return true;
  3024. }
  3025. }
  3026. unsigned __int64 stopAfter = readHelper->getChooseNLimit();
  3027. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3028. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  3029. unsigned totalSizeSent = 0;
  3030. unsigned skipped = 0;
  3031. unsigned processedBefore = processed;
  3032. unsigned keyprocessedBefore = keyprocessed;
  3033. bool continuationFailed = false;
  3034. const byte *rawSeek = NULL;
  3035. if (steppingRow)
  3036. rawSeek = steppingRow;
  3037. bool continuationNeeded = false;
  3038. while (!aborted && inputsDone < inputCount)
  3039. {
  3040. if (!resent || !steppingOffset) // Bit of a hack... In the resent case, we have already set up the tlk, and all keys are processed at once in the steppingOffset case (which makes checkPartChanged gives a false positive in this case)
  3041. checkPartChanged(inputData[inputsDone]);
  3042. if (tlk)
  3043. {
  3044. createSegmentMonitors();
  3045. tlk->reset(resent);
  3046. resent = false;
  3047. {
  3048. TransformCallbackAssociation associate(callback, tlk); // want to destroy this before we advance to next key...
  3049. while (!aborted && rawSeek ? tlk->lookupSkip(rawSeek, steppingOffset, steppingLength) : tlk->lookup(true))
  3050. {
  3051. rawSeek = NULL; // only want to do the seek first time we look for a particular seek value
  3052. keyprocessed++;
  3053. if ((keyedLimit != (unsigned __int64) -1) && keyprocessed > keyedLimit)
  3054. {
  3055. logctx.noteStatistic(STATS_ACCEPTED, keyprocessed-keyprocessedBefore, 1);
  3056. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3057. limitExceeded(true);
  3058. break;
  3059. }
  3060. atomic_inc(&indexRecordsRead);
  3061. size32_t transformedSize;
  3062. const byte * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  3063. int diff = 0;
  3064. if (steppingRow)
  3065. {
  3066. diff = memcmp(keyRow+steppingOffset, steppingRow, steppingLength);
  3067. assertex(diff >= 0);
  3068. }
  3069. while (diff > 0)
  3070. {
  3071. advanceToNextSeek();
  3072. if (!steppingRow)
  3073. break;
  3074. diff = memcmp(keyRow+steppingOffset, steppingRow, steppingLength);
  3075. if (diff < 0)
  3076. {
  3077. rawSeek = steppingRow;
  3078. break;
  3079. }
  3080. }
  3081. if (diff >= 0)
  3082. {
  3083. rowBuilder.ensureRow();
  3084. transformedSize = readHelper->transform(rowBuilder, keyRow);
  3085. callback.finishedRow();
  3086. if (transformedSize)
  3087. {
  3088. // Did get a match
  3089. processed++;
  3090. if (limit && processed > limit)
  3091. {
  3092. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3093. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3094. limitExceeded(false);
  3095. break;
  3096. }
  3097. if (processed > stopAfter)
  3098. {
  3099. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3100. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3101. logctx.flush(true, false);
  3102. output->flush(true);
  3103. return true;
  3104. }
  3105. rowBuilder.writeToOutput(transformedSize, true);
  3106. totalSizeSent += transformedSize;
  3107. if (totalSizeSent > indexReadChunkSize || (steppingOffset && !steppingRow && !stepExtra.readAheadManyResults()))
  3108. continuationNeeded = true;
  3109. lastRowCompleteMatch = true;
  3110. if (steppingRow && stepExtra.onlyReturnFirstSeekMatch())
  3111. advanceToNextSeek();
  3112. }
  3113. else
  3114. {
  3115. // Didn't get a match
  3116. if (steppingOffset && !steppingRow && stepExtra.returnMismatches())
  3117. {
  3118. transformedSize = readHelper->unfilteredTransform(rowBuilder, keyRow);
  3119. if (transformedSize) // will only be zero in odd situations where codegen can't work out how to transform (eg because of a skip)
  3120. {
  3121. callback.finishedRow();
  3122. rowBuilder.writeToOutput(transformedSize, true);
  3123. totalSizeSent += transformedSize;
  3124. continuationNeeded = true;
  3125. lastRowCompleteMatch = false;
  3126. }
  3127. }
  3128. else
  3129. {
  3130. atomic_inc(&postFiltered);
  3131. skipped++;
  3132. }
  3133. }
  3134. }
  3135. if (continuationNeeded && !continuationFailed)
  3136. {
  3137. if (logctx.queryTraceLevel() > 10)
  3138. logctx.CTXLOG("Indexread returning partial result set %d rows from %d seeks, %d scans, %d skips", processed-processedBefore, tlk->querySeeks(), tlk->queryScans(), tlk->querySkips());
  3139. if (sendContinuation(output))
  3140. {
  3141. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3142. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3143. return true;
  3144. }
  3145. else
  3146. {
  3147. // MORE - this is actually pretty fatal fo smart-stepping case
  3148. continuationFailed = true;
  3149. }
  3150. }
  3151. rowBuilder.clear();
  3152. }
  3153. }
  3154. }
  3155. if (steppingOffset)
  3156. inputsDone = inputCount;
  3157. else
  3158. inputsDone++;
  3159. }
  3160. if (tlk) // a very early abort can mean it is NULL.... MORE is this the right place to put it or should it be inside the loop??
  3161. {
  3162. if (logctx.queryTraceLevel() > 10 && !aborted)
  3163. logctx.CTXLOG("Indexread returning result set %d rows from %d seeks, %d scans, %d skips", processed-processedBefore, tlk->querySeeks(), tlk->queryScans(), tlk->querySkips());
  3164. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3165. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3166. }
  3167. logctx.flush(true, aborted);
  3168. if (aborted)
  3169. output->abort();
  3170. else
  3171. output->flush(true);
  3172. return !aborted;
  3173. }
  3174. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3175. {
  3176. return this;
  3177. }
  3178. virtual IKeyArray *getKeySet() const
  3179. {
  3180. return keyArray.getLink();
  3181. }
  3182. virtual const IResolvedFile *getVarFileInfo() const
  3183. {
  3184. return varFileInfo.getLink();
  3185. }
  3186. virtual TranslatorArray *getTranslators() const
  3187. {
  3188. return layoutTranslators.getLink();
  3189. }
  3190. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  3191. {
  3192. indexHelper->createSegmentMonitors(irc); // NOTE: they will merge;
  3193. }
  3194. virtual IRoxieServerActivity *queryActivity() { throwUnexpected(); }
  3195. virtual const RemoteActivityId &queryRemoteId() const { throwUnexpected(); }
  3196. };
  3197. //================================================================================================
  3198. class CRoxieIndexReadActivityFactory : public CRoxieIndexActivityFactory
  3199. {
  3200. unsigned steppingOffset;
  3201. public:
  3202. CRoxieIndexReadActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3203. : CRoxieIndexActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory)
  3204. {
  3205. Owned<IHThorIndexReadArg> helper = (IHThorIndexReadArg *) helperFactory();
  3206. init(helper, graphNode);
  3207. ISteppingMeta *rawMeta = helper->queryRawSteppingMeta();
  3208. if (rawMeta)
  3209. {
  3210. // MORE - should check all keys in maxFields list can actually be keyed.
  3211. const CFieldOffsetSize * fields = rawMeta->queryFields();
  3212. steppingOffset = fields[0].offset;
  3213. }
  3214. else
  3215. {
  3216. steppingOffset = 0;
  3217. }
  3218. }
  3219. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3220. {
  3221. return new CRoxieIndexReadActivity(logctx, packet, helperFactory, this, steppingOffset);
  3222. }
  3223. virtual StringBuffer &toString(StringBuffer &s) const
  3224. {
  3225. return CSlaveActivityFactory::toString(s.append("INDEXREAD "));
  3226. }
  3227. };
  3228. ISlaveActivityFactory *createRoxieIndexReadActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3229. {
  3230. return new CRoxieIndexReadActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  3231. }
  3232. //================================================================================================
  3233. //MORE: Very similar to the indexRead code, but I'm not sure it's worth commoning up....
  3234. class CRoxieIndexNormalizeActivity : public CRoxieIndexActivity
  3235. {
  3236. protected:
  3237. IHThorCompoundNormalizeExtra * normalizeHelper;
  3238. public:
  3239. IMPLEMENT_IINTERFACE;
  3240. CRoxieIndexNormalizeActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory)
  3241. : CRoxieIndexActivity(_logctx, _packet, _hFactory, _aFactory, 0) //MORE - stepping?
  3242. {
  3243. onCreate();
  3244. normalizeHelper = (IHThorIndexNormalizeArg *) basehelper;
  3245. if (resent)
  3246. readContinuationInfo();
  3247. }
  3248. virtual StringBuffer &toString(StringBuffer &ret) const
  3249. {
  3250. return ret.appendf("IndexNormalize %u", packet->queryHeader().activityId);
  3251. }
  3252. virtual bool process()
  3253. {
  3254. MTIME_SECTION(timer, "CRoxieIndexNormalizeActivity ::process");
  3255. unsigned __int64 keyedLimit = normalizeHelper->getKeyedLimit();
  3256. unsigned __int64 rowLimit = normalizeHelper->getRowLimit();
  3257. if (!resent && (keyedLimit != (unsigned __int64) -1) && (indexHelper->getFlags() & TIRcountkeyedlimit) != 0) // Don't recheck the limit every time!
  3258. {
  3259. if (!checkLimit(keyedLimit))
  3260. {
  3261. limitExceeded(true);
  3262. return true;
  3263. }
  3264. }
  3265. unsigned __int64 stopAfter = normalizeHelper->getChooseNLimit();
  3266. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3267. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  3268. unsigned totalSizeSent = 0;
  3269. unsigned skipped = 0;
  3270. unsigned processedBefore = processed;
  3271. bool continuationFailed = false;
  3272. while (!aborted && inputsDone < inputCount)
  3273. {
  3274. checkPartChanged(inputData[inputsDone]);
  3275. if (tlk)
  3276. {
  3277. createSegmentMonitors();
  3278. tlk->reset(resent);
  3279. resent = false;
  3280. TransformCallbackAssociation associate(callback, tlk);
  3281. while (!aborted && tlk->lookup(true))
  3282. {
  3283. keyprocessed++;
  3284. if (keyedLimit && processed > keyedLimit)
  3285. {
  3286. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3287. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3288. limitExceeded(true);
  3289. break;
  3290. }
  3291. atomic_inc(&indexRecordsRead);
  3292. if (normalizeHelper->first(tlk->queryKeyBuffer(callback.getFPosRef())))
  3293. {
  3294. do
  3295. {
  3296. rowBuilder.ensureRow();
  3297. size32_t transformedSize = normalizeHelper->transform(rowBuilder);
  3298. if (transformedSize)
  3299. {
  3300. processed++;
  3301. if (processed > rowLimit)
  3302. {
  3303. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3304. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3305. limitExceeded(false);
  3306. break;
  3307. }
  3308. if (processed > stopAfter)
  3309. {
  3310. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3311. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3312. logctx.flush(true, aborted);
  3313. output->flush(true);
  3314. return true;
  3315. }
  3316. totalSizeSent += rowBuilder.writeToOutput(transformedSize, true);
  3317. }
  3318. } while (normalizeHelper->next());
  3319. callback.finishedRow();
  3320. if (totalSizeSent > indexReadChunkSize && !continuationFailed)
  3321. {
  3322. if (sendContinuation(output))
  3323. {
  3324. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3325. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3326. return true;
  3327. }
  3328. else
  3329. continuationFailed = true;
  3330. }
  3331. }
  3332. else
  3333. {
  3334. atomic_inc(&postFiltered);
  3335. skipped++;
  3336. }
  3337. }
  3338. }
  3339. inputsDone++;
  3340. }
  3341. if (tlk) // a very early abort can mean it is NULL....
  3342. {
  3343. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3344. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3345. }
  3346. logctx.flush(true, aborted);
  3347. if (aborted)
  3348. output->abort();
  3349. else
  3350. output->flush(true);
  3351. return !aborted;
  3352. }
  3353. };
  3354. //================================================================================================
  3355. class CRoxieIndexNormalizeActivityFactory : public CRoxieIndexActivityFactory
  3356. {
  3357. public:
  3358. CRoxieIndexNormalizeActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3359. : CRoxieIndexActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory)
  3360. {
  3361. Owned<IHThorIndexNormalizeArg> helper = (IHThorIndexNormalizeArg *) helperFactory();
  3362. init(helper, graphNode);
  3363. }
  3364. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3365. {
  3366. return new CRoxieIndexNormalizeActivity(logctx, packet, helperFactory, this);
  3367. }
  3368. virtual StringBuffer &toString(StringBuffer &s) const
  3369. {
  3370. return CSlaveActivityFactory::toString(s.append("IndexNormalize "));
  3371. }
  3372. };
  3373. ISlaveActivityFactory *createRoxieIndexNormalizeActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3374. {
  3375. return new CRoxieIndexNormalizeActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  3376. }
  3377. //================================================================================================
  3378. class CRoxieIndexCountActivity : public CRoxieIndexActivity
  3379. {
  3380. protected:
  3381. IHThorCompoundCountExtra * countHelper;
  3382. IHThorSourceCountLimit * limitHelper;
  3383. unsigned __int64 choosenLimit;
  3384. unsigned __int64 rowLimit;
  3385. unsigned __int64 keyedLimit;
  3386. public:
  3387. IMPLEMENT_IINTERFACE;
  3388. CRoxieIndexCountActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory)
  3389. : CRoxieIndexActivity(_logctx, _packet, _hFactory, _aFactory, 0)
  3390. {
  3391. onCreate();
  3392. countHelper = (IHThorIndexCountArg *) basehelper;
  3393. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper->selectInterface(TAIsourcecountlimit_1));
  3394. assertex(!resent);
  3395. choosenLimit = countHelper->getChooseNLimit();
  3396. if (limitHelper)
  3397. {
  3398. rowLimit = limitHelper->getRowLimit();
  3399. keyedLimit = limitHelper->getKeyedLimit();
  3400. }
  3401. else
  3402. rowLimit = keyedLimit = (unsigned __int64) -1;
  3403. }
  3404. virtual StringBuffer &toString(StringBuffer &ret) const
  3405. {
  3406. return ret.appendf("IndexCount %u", packet->queryHeader().activityId);
  3407. }
  3408. virtual bool process()
  3409. {
  3410. MTIME_SECTION(timer, "CRoxieIndexCountActivity ::process");
  3411. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3412. unsigned skipped = 0;
  3413. unsigned processedBefore = processed;
  3414. unsigned __int64 count = 0;
  3415. while (!aborted && inputsDone < inputCount && count < choosenLimit)
  3416. {
  3417. checkPartChanged(inputData[inputsDone]);
  3418. if (tlk)
  3419. {
  3420. createSegmentMonitors();
  3421. tlk->reset(false);
  3422. if (countHelper->hasFilter())
  3423. {
  3424. callback.setManager(tlk);
  3425. while (!aborted && (count < choosenLimit) && tlk->lookup(true))
  3426. {
  3427. keyprocessed++;
  3428. atomic_inc(&indexRecordsRead);
  3429. count += countHelper->numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  3430. if (count > rowLimit)
  3431. limitExceeded(false);
  3432. else if (count > keyedLimit)
  3433. limitExceeded(true);
  3434. callback.finishedRow();
  3435. }
  3436. callback.setManager(NULL);
  3437. }
  3438. else
  3439. {
  3440. //MORE: GH->RKC There should be value in providing a choosenLimit to getCount()
  3441. //MORE: note that tlk->checkCount() is NOT suitable as it makes assumptions about the segmonitors (only checks leading ones)
  3442. count += tlk->getCount();
  3443. if (count > rowLimit)
  3444. limitExceeded(false);
  3445. else if (count > keyedLimit)
  3446. limitExceeded(true); // MORE - is this right?
  3447. }
  3448. }
  3449. inputsDone++;
  3450. }
  3451. if (!aborted && count)
  3452. {
  3453. if (count > choosenLimit)
  3454. count = choosenLimit;
  3455. processed++;
  3456. assertex(!serializer);
  3457. void *recBuffer = output->getBuffer(meta.getFixedSize(), false);
  3458. if (meta.getFixedSize() == 1)
  3459. *(byte *)recBuffer = (byte)count;
  3460. else
  3461. {
  3462. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  3463. *(unsigned __int64 *)recBuffer = count;
  3464. }
  3465. output->putBuffer(recBuffer, meta.getFixedSize(), false);
  3466. }
  3467. if (tlk) // a very early abort can mean it is NULL....
  3468. {
  3469. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3470. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3471. }
  3472. if (aborted)
  3473. output->abort();
  3474. else
  3475. output->flush(true);
  3476. return !aborted;
  3477. }
  3478. };
  3479. //================================================================================================
  3480. class CRoxieIndexCountActivityFactory : public CRoxieIndexActivityFactory
  3481. {
  3482. public:
  3483. CRoxieIndexCountActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3484. : CRoxieIndexActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory)
  3485. {
  3486. Owned<IHThorIndexCountArg> helper = (IHThorIndexCountArg *) helperFactory();
  3487. init(helper, graphNode);
  3488. }
  3489. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3490. {
  3491. return new CRoxieIndexCountActivity(logctx, packet, helperFactory, this);
  3492. }
  3493. virtual StringBuffer &toString(StringBuffer &s) const
  3494. {
  3495. return CSlaveActivityFactory::toString(s.append("INDEXCOUNT "));
  3496. }
  3497. };
  3498. ISlaveActivityFactory *createRoxieIndexCountActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3499. {
  3500. return new CRoxieIndexCountActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  3501. }
  3502. //================================================================================================
  3503. class CRoxieIndexAggregateActivity : public CRoxieIndexActivity
  3504. {
  3505. protected:
  3506. IHThorCompoundAggregateExtra * aggregateHelper;
  3507. public:
  3508. IMPLEMENT_IINTERFACE;
  3509. CRoxieIndexAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory)
  3510. : CRoxieIndexActivity(_logctx, _packet, _hFactory, _aFactory, 0)
  3511. {
  3512. onCreate();
  3513. aggregateHelper = (IHThorIndexAggregateArg *) basehelper;
  3514. assertex(!resent);
  3515. }
  3516. virtual StringBuffer &toString(StringBuffer &ret) const
  3517. {
  3518. return ret.appendf("IndexAggregate %u", packet->queryHeader().activityId);
  3519. }
  3520. virtual bool process()
  3521. {
  3522. MTIME_SECTION(timer, "CRoxieIndexAggregateActivity ::process");
  3523. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3524. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  3525. rowBuilder.ensureRow();
  3526. aggregateHelper->clearAggregate(rowBuilder);
  3527. unsigned skipped = 0;
  3528. unsigned processedBefore = processed;
  3529. while (!aborted && inputsDone < inputCount)
  3530. {
  3531. checkPartChanged(inputData[inputsDone]);
  3532. if (tlk)
  3533. {
  3534. createSegmentMonitors();
  3535. tlk->reset(false);
  3536. callback.setManager(tlk);
  3537. while (!aborted && tlk->lookup(true))
  3538. {
  3539. keyprocessed++;
  3540. atomic_inc(&indexRecordsRead);
  3541. aggregateHelper->processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  3542. callback.finishedRow();
  3543. }
  3544. callback.setManager(NULL);
  3545. }
  3546. inputsDone++;
  3547. }
  3548. if (!aborted && aggregateHelper->processedAnyRows())
  3549. {
  3550. processed++;
  3551. size32_t transformedSize = meta.getRecordSize(rowBuilder.getSelf());
  3552. rowBuilder.writeToOutput(transformedSize, true);
  3553. }
  3554. if (tlk) // a very early abort can mean it is NULL....
  3555. {
  3556. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3557. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  3558. }
  3559. logctx.flush(true, aborted);
  3560. if (aborted)
  3561. output->abort();
  3562. else
  3563. output->flush(true);
  3564. return !aborted;
  3565. }
  3566. };
  3567. //================================================================================================
  3568. class CRoxieIndexAggregateActivityFactory : public CRoxieIndexActivityFactory
  3569. {
  3570. public:
  3571. CRoxieIndexAggregateActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3572. : CRoxieIndexActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory)
  3573. {
  3574. Owned<IHThorIndexAggregateArg> helper = (IHThorIndexAggregateArg *) helperFactory();
  3575. init(helper, graphNode);
  3576. }
  3577. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3578. {
  3579. return new CRoxieIndexAggregateActivity(logctx, packet, helperFactory, this);
  3580. }
  3581. virtual StringBuffer &toString(StringBuffer &s) const
  3582. {
  3583. return CSlaveActivityFactory::toString(s.append("INDEXAGGREGATE "));
  3584. }
  3585. };
  3586. ISlaveActivityFactory *createRoxieIndexAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3587. {
  3588. return new CRoxieIndexAggregateActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  3589. }
  3590. //================================================================================================
  3591. class CRoxieIndexGroupAggregateActivity : public CRoxieIndexActivity, implements IHThorGroupAggregateCallback
  3592. {
  3593. protected:
  3594. IHThorCompoundGroupAggregateExtra * aggregateHelper;
  3595. RowAggregator results;
  3596. unsigned groupSegCount;
  3597. ThorActivityKind kind;
  3598. public:
  3599. IMPLEMENT_IINTERFACE;
  3600. CRoxieIndexGroupAggregateActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieIndexActivityFactory *_aFactory, ThorActivityKind _kind)
  3601. : CRoxieIndexActivity(_logctx, _packet, _hFactory, _aFactory, 0),
  3602. aggregateHelper((IHThorIndexGroupAggregateArg *) basehelper),
  3603. results(*aggregateHelper, *aggregateHelper), kind(_kind)
  3604. {
  3605. onCreate();
  3606. results.start(rowAllocator);
  3607. assertex(!resent);
  3608. groupSegCount = 0;
  3609. }
  3610. virtual bool needsRowAllocator()
  3611. {
  3612. return true;
  3613. }
  3614. virtual StringBuffer &toString(StringBuffer &ret) const
  3615. {
  3616. return ret.appendf("IndexGroupAggregate %u", packet->queryHeader().activityId);
  3617. }
  3618. virtual void processRow(const void * next)
  3619. {
  3620. results.addRow(next);
  3621. }
  3622. virtual void createSegmentMonitors()
  3623. {
  3624. if (createSegmentMonitorsPending)
  3625. {
  3626. unsigned groupSegSize;
  3627. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  3628. groupSegSize = aggregateHelper->getGroupSegmentMonitorsSize();
  3629. else
  3630. groupSegSize = 0;
  3631. tlk->setMergeBarrier(groupSegSize);
  3632. CRoxieIndexActivity::createSegmentMonitors();
  3633. if (groupSegSize)
  3634. {
  3635. // MORE - this code should be moved to somewhere common so ccdserver can share it
  3636. unsigned numSegs = tlk->ordinality();
  3637. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  3638. {
  3639. IKeySegmentMonitor *seg = tlk->item(segNo);
  3640. if (seg->getOffset()+seg->getSize()==groupSegSize)
  3641. {
  3642. groupSegCount = segNo+1;
  3643. break;
  3644. }
  3645. }
  3646. assertex(groupSegCount);
  3647. }
  3648. else
  3649. groupSegCount = 0;
  3650. }
  3651. }
  3652. virtual bool process()
  3653. {
  3654. MTIME_SECTION(timer, "CRoxieIndexGroupAggregateActivity ::process");
  3655. Owned<IRowManager> rowManager = roxiemem::createRowManager(0, NULL, logctx, NULL, true); // MORE - should not really use default limits
  3656. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3657. unsigned processedBefore = processed;
  3658. try
  3659. {
  3660. while (!aborted && inputsDone < inputCount)
  3661. {
  3662. checkPartChanged(inputData[inputsDone]);
  3663. if (tlk)
  3664. {
  3665. createSegmentMonitors();
  3666. tlk->reset(false);
  3667. callback.setManager(tlk);
  3668. while (!aborted && tlk->lookup(true))
  3669. {
  3670. if (groupSegCount && !layoutTranslators->item(lastPartNo.fileNo))
  3671. {
  3672. AggregateRowBuilder &rowBuilder = results.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  3673. callback.finishedRow();
  3674. if (kind == TAKindexgroupcount)
  3675. {
  3676. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  3677. aggregateHelper->processCountGrouping(rowBuilder, count-1);
  3678. }
  3679. if (!tlk->nextRange(groupSegCount))
  3680. break;
  3681. }
  3682. else
  3683. {
  3684. keyprocessed++;
  3685. atomic_inc(&indexRecordsRead);
  3686. aggregateHelper->processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  3687. callback.finishedRow();
  3688. }
  3689. }
  3690. callback.setManager(NULL);
  3691. }
  3692. inputsDone++;
  3693. }
  3694. if (!aborted)
  3695. {
  3696. loop
  3697. {
  3698. Owned<AggregateRowBuilder> next = results.nextResult();
  3699. if (!next)
  3700. break;
  3701. unsigned rowSize = next->querySize();
  3702. OwnedConstRoxieRow row(next->finalizeRowClear());
  3703. if (serializer)
  3704. {
  3705. serializeRow(output, row);
  3706. }
  3707. else
  3708. {
  3709. void *recBuffer = output->getBuffer(rowSize, meta.isVariableSize());
  3710. memcpy(recBuffer, row, rowSize);
  3711. output->putBuffer(recBuffer, rowSize, meta.isVariableSize());
  3712. }
  3713. }
  3714. }
  3715. }
  3716. catch (...)
  3717. {
  3718. results.reset(); // kill entries before the rowManager dies.
  3719. throw;
  3720. }
  3721. results.reset();
  3722. if (tlk) // a very early abort can mean it is NULL....
  3723. {
  3724. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  3725. logctx.noteStatistic(STATS_REJECTED, 0, 1);
  3726. }
  3727. logctx.flush(true, aborted);
  3728. if (aborted)
  3729. output->abort();
  3730. else
  3731. output->flush(true);
  3732. return !aborted;
  3733. }
  3734. };
  3735. //================================================================================================
  3736. class CRoxieIndexGroupAggregateActivityFactory : public CRoxieIndexActivityFactory
  3737. {
  3738. ThorActivityKind kind;
  3739. public:
  3740. CRoxieIndexGroupAggregateActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  3741. : CRoxieIndexActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory), kind(_kind)
  3742. {
  3743. Owned<IHThorIndexGroupAggregateArg> helper = (IHThorIndexGroupAggregateArg *) helperFactory();
  3744. init(helper, graphNode);
  3745. }
  3746. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3747. {
  3748. return new CRoxieIndexGroupAggregateActivity(logctx, packet, helperFactory, this, kind);
  3749. }
  3750. virtual StringBuffer &toString(StringBuffer &s) const
  3751. {
  3752. return CSlaveActivityFactory::toString(s.append("INDEXGROUPAGGREGATE "));
  3753. }
  3754. };
  3755. ISlaveActivityFactory *createRoxieIndexGroupAggregateActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  3756. {
  3757. return new CRoxieIndexGroupAggregateActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory, _kind);
  3758. }
  3759. //================================================================================================
  3760. class CRoxieFetchActivityFactory : public CSlaveActivityFactory
  3761. {
  3762. public:
  3763. IMPLEMENT_IINTERFACE;
  3764. Owned<IFileIOArray> fileArray;
  3765. CRoxieFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  3766. : CSlaveActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  3767. {
  3768. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  3769. IHThorFetchContext * fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  3770. bool variableFileName = (fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0;
  3771. if (!variableFileName)
  3772. {
  3773. bool isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  3774. datafile.setown(_queryFactory.queryPackage().lookupFileName(fetchContext->getFileName(), isOpt, true, _queryFactory.queryWorkUnit()));
  3775. if (datafile)
  3776. fileArray.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  3777. }
  3778. }
  3779. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const;
  3780. virtual StringBuffer &toString(StringBuffer &s) const
  3781. {
  3782. return CSlaveActivityFactory::toString(s.append("FETCH "));
  3783. }
  3784. inline IFileIO *getFilePart(unsigned partNo, offset_t &_base) const
  3785. {
  3786. return fileArray->getFilePart(partNo, _base);
  3787. }
  3788. };
  3789. class CRoxieFetchActivityBase : public CRoxieSlaveActivity
  3790. {
  3791. protected:
  3792. IHThorFetchBaseArg *helper;
  3793. IHThorFetchContext * fetchContext;
  3794. const CRoxieFetchActivityFactory *factory;
  3795. Owned<IFileIO> rawFile;
  3796. Owned<ISerialStream> rawStream;
  3797. CThorStreamDeserializerSource deserializeSource;
  3798. offset_t base;
  3799. char *inputData;
  3800. char *inputLimit;
  3801. Owned<IFileIOArray> varFiles;
  3802. bool needsRHS;
  3803. virtual size32_t doFetch(ARowBuilder & rowBuilder, offset_t pos, offset_t rawpos, void *inputData) = 0;
  3804. public:
  3805. IMPLEMENT_IINTERFACE;
  3806. CRoxieFetchActivityBase(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieFetchActivityFactory *_aFactory)
  3807. : CRoxieSlaveActivity(_logctx, _packet, _hFactory, _aFactory), factory(_aFactory)
  3808. {
  3809. helper = (IHThorFetchBaseArg *) basehelper;
  3810. fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  3811. base = 0;
  3812. variableFileName = (fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0;
  3813. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  3814. onCreate();
  3815. inputData = (char *) serializedCreate.readDirect(0);
  3816. inputLimit = inputData + (serializedCreate.length() - serializedCreate.getPos());
  3817. needsRHS = helper->transformNeedsRhs();
  3818. }
  3819. virtual const char *queryDynamicFileName() const
  3820. {
  3821. return fetchContext->getFileName();
  3822. }
  3823. virtual void setVariableFileInfo()
  3824. {
  3825. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, packet->queryHeader().channel));
  3826. }
  3827. virtual bool process();
  3828. virtual StringBuffer &toString(StringBuffer &ret) const
  3829. {
  3830. return ret.appendf("Fetch %u", packet->queryHeader().activityId);
  3831. }
  3832. virtual void setPartNo(bool filechanged);
  3833. };
  3834. bool CRoxieFetchActivityBase::process()
  3835. {
  3836. MTIME_SECTION(timer, "CRoxieFetchActivityBase::process");
  3837. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  3838. unsigned accepted = 0;
  3839. unsigned rejected = 0;
  3840. unsigned __int64 rowLimit = helper->getRowLimit();
  3841. OptimizedRowBuilder rowBuilder(rowAllocator, meta, output, serializer);
  3842. while (!aborted && inputData < inputLimit)
  3843. {
  3844. checkPartChanged(*(PartNoType *) inputData);
  3845. inputData += sizeof(PartNoType);
  3846. offset_t rp = *(offset_t *)inputData;
  3847. inputData += sizeof(offset_t);
  3848. unsigned rhsSize;
  3849. if (needsRHS)
  3850. {
  3851. rhsSize = *(unsigned *)inputData;
  3852. inputData += sizeof(unsigned);
  3853. }
  3854. else
  3855. rhsSize = 0;
  3856. offset_t pos;
  3857. if (isLocalFpos(rp))
  3858. pos = getLocalFposOffset(rp);
  3859. else
  3860. pos = rp-base;
  3861. unsigned thisSize = doFetch(rowBuilder, pos, rp, inputData);
  3862. inputData += rhsSize;
  3863. if (thisSize)
  3864. {
  3865. rowBuilder.writeToOutput(thisSize, true);
  3866. accepted++;
  3867. if (accepted > rowLimit)
  3868. {
  3869. logctx.noteStatistic(STATS_DISK_SEEKS, accepted+rejected, 1);
  3870. logctx.noteStatistic(STATS_ACCEPTED, accepted, 1);
  3871. logctx.noteStatistic(STATS_REJECTED, rejected, 1);
  3872. limitExceeded();
  3873. return true;
  3874. }
  3875. }
  3876. else
  3877. rejected++;
  3878. }
  3879. logctx.noteStatistic(STATS_DISK_SEEKS, accepted+rejected, 1);
  3880. logctx.noteStatistic(STATS_ACCEPTED, accepted, 1);
  3881. logctx.noteStatistic(STATS_REJECTED, rejected, 1);
  3882. logctx.flush(true, aborted);
  3883. if (aborted)
  3884. output->abort();
  3885. else
  3886. output->flush(true);
  3887. return !aborted;
  3888. }
  3889. class CRoxieFetchActivity : public CRoxieFetchActivityBase
  3890. {
  3891. Owned<IEngineRowAllocator> diskAllocator;
  3892. Owned<IOutputRowDeserializer> rowDeserializer;
  3893. public:
  3894. CRoxieFetchActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieFetchActivityFactory *_aFactory)
  3895. : CRoxieFetchActivityBase(_logctx, _packet, _hFactory, _aFactory)
  3896. {
  3897. IHThorFetchContext * fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  3898. IOutputMetaData *diskMeta = fetchContext->queryDiskRecordSize();
  3899. diskAllocator.setown(getRowAllocator(diskMeta, basefactory->queryId()));
  3900. rowDeserializer.setown(diskMeta->createRowDeserializer(queryContext->queryCodeContext(), basefactory->queryId()));
  3901. }
  3902. virtual size32_t doFetch(ARowBuilder & rowBuilder, offset_t pos, offset_t rawpos, void *inputData)
  3903. {
  3904. RtlDynamicRowBuilder diskRowBuilder(diskAllocator);
  3905. deserializeSource.reset(pos);
  3906. unsigned sizeRead = rowDeserializer->deserialize(diskRowBuilder.ensureRow(), deserializeSource);
  3907. OwnedConstRoxieRow rawBuffer = diskRowBuilder.finalizeRowClear(sizeRead);
  3908. // note the swapped parameters - left and right map to input and raw differently for JOIN vs FETCH
  3909. IHThorFetchArg *h = (IHThorFetchArg *) helper;
  3910. return h->transform(rowBuilder, rawBuffer, inputData, rawpos);
  3911. }
  3912. };
  3913. IRoxieSlaveActivity *CRoxieFetchActivityFactory::createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  3914. {
  3915. return new CRoxieFetchActivity(logctx, packet, helperFactory, this);
  3916. }
  3917. //------------------------------------------------------------------------------------
  3918. class CRoxieCSVFetchActivity : public CRoxieFetchActivityBase
  3919. {
  3920. CSVSplitter csvSplitter;
  3921. public:
  3922. CRoxieCSVFetchActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieFetchActivityFactory *_aFactory, unsigned _maxColumns)
  3923. : CRoxieFetchActivityBase(_logctx, _packet, _hFactory, _aFactory)
  3924. {
  3925. const char * quotes = NULL;
  3926. const char * separators = NULL;
  3927. const char * terminators = NULL;
  3928. const char * escapes = NULL;
  3929. const IResolvedFile *fileInfo = varFileInfo ? varFileInfo : factory->datafile;
  3930. if (fileInfo)
  3931. {
  3932. const IPropertyTree *options = fileInfo->queryProperties();
  3933. if (options)
  3934. {
  3935. quotes = options->queryProp("@csvQuote");
  3936. separators = options->queryProp("@csvSeparate");
  3937. terminators = options->queryProp("@csvTerminate");
  3938. escapes = options->queryProp("@csvEscape");
  3939. }
  3940. }
  3941. IHThorCsvFetchArg *h = (IHThorCsvFetchArg *) helper;
  3942. ICsvParameters *csvInfo = h->queryCsvParameters();
  3943. csvSplitter.init(_maxColumns, csvInfo, quotes, separators, terminators, escapes);
  3944. }
  3945. virtual size32_t doFetch(ARowBuilder & rowBuilder, offset_t pos, offset_t rawpos, void *inputData)
  3946. {
  3947. IHThorCsvFetchArg *h = (IHThorCsvFetchArg *) helper;
  3948. rawStream->reset(pos);
  3949. size32_t rowSize = 4096; // MORE - make configurable
  3950. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  3951. loop
  3952. {
  3953. size32_t avail;
  3954. const void *peek = rawStream->peek(rowSize, avail);
  3955. if (csvSplitter.splitLine(avail, (const byte *)peek) < rowSize || avail < rowSize)
  3956. break;
  3957. if (rowSize == maxRowSize)
  3958. throw MakeStringException(0, "Row too big");
  3959. if (rowSize >= maxRowSize/2)
  3960. rowSize = maxRowSize;
  3961. else
  3962. rowSize += rowSize;
  3963. }
  3964. return h->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData(), inputData, rawpos);
  3965. }
  3966. };
  3967. class CRoxieXMLFetchActivity : public CRoxieFetchActivityBase, implements IXMLSelect
  3968. {
  3969. Owned<IXMLParse> parser;
  3970. Owned<IColumnProvider> lastMatch;
  3971. Owned<IFileIOStream> rawStreamX;
  3972. unsigned streamBufferSize;
  3973. public:
  3974. IMPLEMENT_IINTERFACE;
  3975. CRoxieXMLFetchActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieFetchActivityFactory *_aFactory, unsigned _streamBufferSize)
  3976. : CRoxieFetchActivityBase(_logctx, _packet, _hFactory, _aFactory),
  3977. streamBufferSize(_streamBufferSize)
  3978. {
  3979. }
  3980. virtual size32_t doFetch(ARowBuilder & rowBuilder, offset_t pos, offset_t rawpos, void *inputData)
  3981. {
  3982. rawStreamX->seek(pos, IFSbegin);
  3983. try
  3984. {
  3985. while(!lastMatch)
  3986. if(!parser->next())
  3987. throw MakeStringException(ROXIE_RECORD_FETCH_ERROR, "XML parse error at position %"I64F"d", pos);
  3988. IHThorXmlFetchArg *h = (IHThorXmlFetchArg *) helper;
  3989. unsigned thisSize = h->transform(rowBuilder, lastMatch, inputData, rawpos);
  3990. lastMatch.clear();
  3991. parser->reset();
  3992. return thisSize;
  3993. }
  3994. catch (IException *E)
  3995. {
  3996. ::Release(E);
  3997. throw MakeStringException(ROXIE_RECORD_FETCH_ERROR, "XML parse error at position %"I64F"d", pos);
  3998. }
  3999. }
  4000. virtual void match(IColumnProvider & entry, offset_t startOffset, offset_t endOffset)
  4001. {
  4002. lastMatch.set(&entry);
  4003. }
  4004. virtual void setPartNo(bool filechanged)
  4005. {
  4006. CRoxieFetchActivityBase::setPartNo(filechanged);
  4007. rawStreamX.setown(createBufferedIOStream(rawFile, streamBufferSize));
  4008. parser.setown(createXMLParse(*rawStreamX, "/", *this));
  4009. }
  4010. };
  4011. void CRoxieFetchActivityBase::setPartNo(bool filechanged)
  4012. {
  4013. rawFile.setown(variableFileName ? varFiles->getFilePart(lastPartNo.partNo, base) : factory->getFilePart(lastPartNo.partNo, base)); // MORE - superfiles
  4014. assertex(rawFile != NULL);
  4015. rawStream.setown(createFileSerialStream(rawFile, 0, -1, 0));
  4016. deserializeSource.setStream(rawStream);
  4017. }
  4018. class CRoxieCSVFetchActivityFactory : public CRoxieFetchActivityFactory
  4019. {
  4020. unsigned maxColumns;
  4021. public:
  4022. CRoxieCSVFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4023. : CRoxieFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  4024. {
  4025. Owned<IHThorCsvFetchArg> helper = (IHThorCsvFetchArg*) helperFactory();
  4026. maxColumns = helper->getMaxColumns();
  4027. ICsvParameters *csvInfo = helper->queryCsvParameters();
  4028. assertex(!csvInfo->queryEBCDIC());
  4029. }
  4030. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4031. {
  4032. return new CRoxieCSVFetchActivity(logctx, packet, helperFactory, this, maxColumns);
  4033. }
  4034. };
  4035. class CRoxieXMLFetchActivityFactory : public CRoxieFetchActivityFactory
  4036. {
  4037. public:
  4038. CRoxieXMLFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4039. : CRoxieFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  4040. {
  4041. }
  4042. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4043. {
  4044. return new CRoxieXMLFetchActivity(logctx, packet, helperFactory, this, 4096);
  4045. }
  4046. };
  4047. ISlaveActivityFactory *createRoxieFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4048. {
  4049. return new CRoxieFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  4050. }
  4051. ISlaveActivityFactory *createRoxieCSVFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4052. {
  4053. return new CRoxieCSVFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  4054. }
  4055. ISlaveActivityFactory *createRoxieXMLFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4056. {
  4057. return new CRoxieXMLFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  4058. }
  4059. //================================================================================================
  4060. class CRoxieKeyedJoinIndexActivityFactory : public CRoxieKeyedActivityFactory
  4061. {
  4062. public:
  4063. IMPLEMENT_IINTERFACE;
  4064. CRoxieKeyedJoinIndexActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4065. : CRoxieKeyedActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  4066. {
  4067. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  4068. rtlDataAttr indexLayoutMeta;
  4069. size32_t indexLayoutSize;
  4070. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  4071. assertex(indexLayoutSize== 0);
  4072. MemoryBuffer m;
  4073. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  4074. activityMeta.setown(deserializeRecordMeta(m, true));
  4075. layoutTranslators.setown(new TranslatorArray);
  4076. bool variableFileName = (helper->getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0;
  4077. if (!variableFileName)
  4078. {
  4079. bool isOpt = (helper->getJoinFlags() & JFindexoptional) != 0;
  4080. datafile.setown(_queryFactory.queryPackage().lookupFileName(helper->getIndexFileName(), isOpt, true, _queryFactory.queryWorkUnit()));
  4081. if (datafile)
  4082. keyArray.setown(datafile->getKeyArray(activityMeta, layoutTranslators, isOpt, queryFactory.queryChannel(), queryFactory.getEnableFieldTranslation()));
  4083. }
  4084. }
  4085. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const;
  4086. virtual StringBuffer &toString(StringBuffer &s) const
  4087. {
  4088. return CSlaveActivityFactory::toString(s.append("KEYEDJOIN INDEX "));
  4089. }
  4090. };
  4091. class CRoxieKeyedJoinIndexActivity : public CRoxieKeyedActivity
  4092. {
  4093. IHThorKeyedJoinArg *helper;
  4094. const CRoxieKeyedJoinIndexActivityFactory *factory;
  4095. unsigned inputLength;
  4096. char *inputData;
  4097. Owned<IRoxieSlaveActivity> rootIndexActivity;
  4098. IIndexReadActivityInfo *rootIndex;
  4099. unsigned processed;
  4100. unsigned candidateCount;
  4101. unsigned keepCount;
  4102. unsigned inputDone;
  4103. public:
  4104. IMPLEMENT_IINTERFACE;
  4105. CRoxieKeyedJoinIndexActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieKeyedJoinIndexActivityFactory *_aFactory)
  4106. : factory(_aFactory), CRoxieKeyedActivity(_logctx, _packet, _hFactory, _aFactory)
  4107. {
  4108. helper = (IHThorKeyedJoinArg *) basehelper;
  4109. variableFileName = (helper->getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0;
  4110. inputDone = 0;
  4111. processed = 0;
  4112. candidateCount = 0;
  4113. keepCount = 0;
  4114. rootIndex = NULL;
  4115. onCreate();
  4116. inputData = (char *) serializedCreate.readDirect(0);
  4117. inputLength = (serializedCreate.length() - serializedCreate.getPos());
  4118. if (resent)
  4119. {
  4120. resentInfo.read(inputDone);
  4121. inputData += inputDone;
  4122. resentInfo.read(processed);
  4123. resentInfo.read(candidateCount);
  4124. resentInfo.read(keepCount);
  4125. resentInfo.read(lastPartNo.partNo);
  4126. resentInfo.read(lastPartNo.fileNo);
  4127. setPartNo(true);
  4128. tlk->deserializeCursorPos(resentInfo);
  4129. assertex(resentInfo.remaining() == 0);
  4130. }
  4131. }
  4132. ~CRoxieKeyedJoinIndexActivity()
  4133. {
  4134. }
  4135. virtual void deserializeExtra(MemoryBuffer &buff)
  4136. {
  4137. if (helper->getJoinFlags() & JFindexfromactivity)
  4138. {
  4139. RemoteActivityId indexActivityId(buff);
  4140. assertex(indexActivityId.activityId);
  4141. unsigned indexCtxLen;
  4142. buff.read(indexCtxLen);
  4143. const void *indexCtx = buff.readDirect(indexCtxLen);
  4144. //We create a packet for the index activity to use. Header, trace info and parentextract are clone of mine, context info is copied from buff
  4145. MemoryBuffer indexPacketData;
  4146. indexPacketData.append(sizeof(RoxiePacketHeader), &packet->queryHeader());
  4147. indexPacketData.append(packet->getTraceLength(), packet->queryTraceInfo());
  4148. const byte *parentExtract = (const byte *) packet->queryContextData();
  4149. unsigned parentExtractLen = *(unsigned*) parentExtract;
  4150. indexPacketData.append(parentExtractLen);
  4151. indexPacketData.append(parentExtractLen, parentExtract + sizeof(unsigned));
  4152. indexPacketData.append(indexCtxLen, indexCtx);
  4153. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) indexPacketData.toByteArray();
  4154. newHeader->continueSequence = 0;
  4155. newHeader->activityId = indexActivityId.activityId;
  4156. newHeader->queryHash = indexActivityId.queryHash;
  4157. Owned<IRoxieQueryPacket> indexPacket = createRoxiePacket(indexPacketData);
  4158. Owned<ISlaveActivityFactory> indexActivityFactory = factory->queryQueryFactory().getSlaveActivityFactory(indexActivityId.activityId);
  4159. assertex(indexActivityFactory != NULL);
  4160. rootIndexActivity.setown(indexActivityFactory->createActivity(logctx, indexPacket));
  4161. rootIndex = rootIndexActivity->queryIndexReadActivity();
  4162. varFileInfo.setown(rootIndex->getVarFileInfo());
  4163. layoutTranslators.setown(rootIndex->getTranslators());
  4164. keyArray.setown(rootIndex->getKeySet());
  4165. }
  4166. }
  4167. virtual const char *queryDynamicFileName() const
  4168. {
  4169. return helper->getIndexFileName();
  4170. }
  4171. virtual bool process();
  4172. virtual StringBuffer &toString(StringBuffer &ret) const
  4173. {
  4174. return ret.appendf("KeyedJoinIndex %u", packet->queryHeader().activityId);
  4175. }
  4176. virtual void createSegmentMonitors()
  4177. {
  4178. // This is called to create the segmonitors that apply to ALL rows - not the per-row ones
  4179. // At present there are none. However we should still set up the layout translation.
  4180. if (createSegmentMonitorsPending)
  4181. {
  4182. createSegmentMonitorsPending = false;
  4183. tlk->setLayoutTranslator(layoutTranslators->item(lastPartNo.fileNo));
  4184. }
  4185. }
  4186. };
  4187. IRoxieSlaveActivity *CRoxieKeyedJoinIndexActivityFactory::createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4188. {
  4189. return new CRoxieKeyedJoinIndexActivity(logctx, packet, helperFactory, this);
  4190. }
  4191. bool CRoxieKeyedJoinIndexActivity::process()
  4192. {
  4193. MTIME_SECTION(timer, "CRoxieKeyedJoinIndexActivity::process");
  4194. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  4195. IOutputMetaData *joinFieldsMeta = helper->queryJoinFieldsRecordSize();
  4196. Owned<IEngineRowAllocator> joinFieldsAllocator = getRowAllocator(joinFieldsMeta, basefactory->queryId());
  4197. OptimizedKJRowBuilder rowBuilder(joinFieldsAllocator, joinFieldsMeta, output);
  4198. unsigned __int64 rowLimit = helper->getRowLimit();
  4199. unsigned atmost = helper->getJoinLimit();
  4200. if (!atmost) atmost = (unsigned) -1;
  4201. unsigned abortLimit = helper->getMatchAbortLimit();
  4202. if (!abortLimit) abortLimit = (unsigned) -1;
  4203. if (abortLimit < atmost)
  4204. atmost = abortLimit;
  4205. unsigned keepLimit = helper->getKeepLimit();
  4206. unsigned joinFlags = helper->getJoinFlags();
  4207. if (joinFlags & (JFtransformMaySkip | JFfetchMayFilter))
  4208. keepLimit = 0;
  4209. if ((joinFlags & (JFexclude|JFleftouter)) == (JFexclude|JFleftouter) && (!(joinFlags & JFfetchMayFilter))) // For left-only joins, all we care about is existance of a match. Return as soon as we know that there is one
  4210. keepLimit = 1;
  4211. unsigned processedBefore = processed;
  4212. unsigned rejected = 0;
  4213. CachedOutputMetaData inputFields(helper->queryIndexReadInputRecordSize());
  4214. unsigned inputSize = inputFields.getFixedSize();
  4215. unsigned totalSizeSent = 0;
  4216. // Now go fetch the records
  4217. bool continuationFailed = false;
  4218. while (!aborted && inputDone < inputLength)
  4219. {
  4220. checkPartChanged(*(PartNoType *) inputData);
  4221. CJoinGroup *jg = *(CJoinGroup **) (inputData + sizeof(PartNoType)); // NOTE - this is a pointer in Roxie server's address space - don't go following it!
  4222. char *inputRow = inputData+sizeof(PartNoType)+sizeof(const void *);
  4223. if (inputFields.isVariableSize())
  4224. {
  4225. inputSize = *(unsigned *)inputRow;
  4226. inputRow += sizeof(unsigned);
  4227. }
  4228. if (tlk)
  4229. {
  4230. createSegmentMonitors();
  4231. helper->createSegmentMonitors(tlk, inputRow);
  4232. if (rootIndex)
  4233. rootIndex->mergeSegmentMonitors(tlk);
  4234. tlk->finishSegmentMonitors();
  4235. if (logctx.queryTraceLevel() >= 20)
  4236. {
  4237. StringBuffer out;
  4238. printKeyedValues(out, tlk, helper->queryIndexRecordSize());
  4239. logctx.CTXLOG("Using filter %s", out.str());
  4240. }
  4241. if (!resent && (atmost != (unsigned) -1) && ((atmost > preabortKeyedJoinsThreshold) || (joinFlags & JFcountmatchabortlimit) || (keepLimit != 0)))
  4242. {
  4243. unsigned __int64 precount = tlk->checkCount(atmost);
  4244. if (precount > atmost)
  4245. {
  4246. candidateCount = atmost+1;
  4247. if (logctx.queryTraceLevel() > 5)
  4248. logctx.CTXLOG("Pre-aborting since candidate count is at least %"I64F"d", precount);
  4249. }
  4250. else
  4251. {
  4252. if (logctx.queryTraceLevel() > 10)
  4253. logctx.CTXLOG("NOT Pre-aborting since candidate count is %"I64F"d", precount);
  4254. tlk->reset(false);
  4255. }
  4256. }
  4257. else
  4258. tlk->reset(resent);
  4259. resent = false;
  4260. while (candidateCount <= atmost)
  4261. {
  4262. if (tlk->lookup(true))
  4263. {
  4264. candidateCount++;
  4265. atomic_inc(&indexRecordsRead);
  4266. KLBlobProviderAdapter adapter(tlk);
  4267. offset_t recptr;
  4268. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  4269. if (helper->indexReadMatch(inputRow, indexRow, recptr, &adapter))
  4270. {
  4271. processed++;
  4272. if (keepLimit)
  4273. {
  4274. keepCount++;
  4275. if (keepCount > keepLimit)
  4276. break;
  4277. }
  4278. if (processed > rowLimit)
  4279. {
  4280. if (logctx.queryTraceLevel() > 1)
  4281. {
  4282. StringBuffer s;
  4283. logctx.CTXLOG("limit exceeded for %s", packet->queryHeader().toString(s).str());
  4284. }
  4285. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  4286. logctx.noteStatistic(STATS_REJECTED, rejected, 1);
  4287. limitExceeded();
  4288. return true;
  4289. }
  4290. unsigned totalSize = 0;
  4291. if (helper->diskAccessRequired())
  4292. {
  4293. const void *self = output->getBuffer(KEYEDJOIN_RECORD_SIZE(0), true);
  4294. KeyedJoinHeader *rec = (KeyedJoinHeader *) self;
  4295. rec->fpos = recptr;
  4296. rec->thisGroup = jg;
  4297. rec->partNo = lastPartNo.partNo;
  4298. output->putBuffer(self, KEYEDJOIN_RECORD_SIZE(0), true);
  4299. }
  4300. else
  4301. {
  4302. KLBlobProviderAdapter adapter(tlk);
  4303. totalSize = helper->extractJoinFields(rowBuilder, indexRow, recptr, &adapter);
  4304. rowBuilder.writeToOutput(totalSize, recptr, jg, lastPartNo.partNo);
  4305. }
  4306. totalSizeSent += KEYEDJOIN_RECORD_SIZE(totalSize);
  4307. if (totalSizeSent > indexReadChunkSize && !continuationFailed)
  4308. {
  4309. MemoryBuffer si;
  4310. unsigned short siLen = 0;
  4311. si.append(siLen);
  4312. si.append(inputDone);
  4313. si.append(processed);
  4314. si.append(candidateCount);
  4315. si.append(keepCount);
  4316. si.append(lastPartNo.partNo);
  4317. si.append(lastPartNo.fileNo);
  4318. tlk->serializeCursorPos(si);
  4319. if (si.length() <= maxContinuationSize)
  4320. {
  4321. siLen = si.length() - sizeof(siLen);
  4322. si.writeDirect(0, sizeof(siLen), &siLen);
  4323. output->sendMetaInfo(si.toByteArray(), si.length());
  4324. logctx.flush(true, aborted);
  4325. output->flush(true);
  4326. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  4327. logctx.noteStatistic(STATS_REJECTED, rejected, 1);
  4328. return true;
  4329. }
  4330. else
  4331. continuationFailed = true;
  4332. }
  4333. }
  4334. else
  4335. {
  4336. rejected++;
  4337. atomic_inc(&postFiltered);
  4338. }
  4339. }
  4340. else
  4341. break;
  4342. }
  4343. tlk->releaseSegmentMonitors();
  4344. }
  4345. // output an end marker for the matches to this group
  4346. KeyedJoinHeader *rec = (KeyedJoinHeader *) output->getBuffer(KEYEDJOIN_RECORD_SIZE(0), true);
  4347. rec->fpos = candidateCount;
  4348. rec->thisGroup = jg;
  4349. rec->partNo = (unsigned short) -1;
  4350. output->putBuffer(rec, KEYEDJOIN_RECORD_SIZE(0), true);
  4351. totalSizeSent += KEYEDJOIN_RECORD_SIZE(0); // note - don't interrupt here though - too complicated.
  4352. candidateCount = 0;
  4353. keepCount = 0;
  4354. inputData = inputRow + inputSize;
  4355. inputDone += sizeof(PartNoType) + sizeof(const void *);
  4356. if (inputFields.isVariableSize())
  4357. inputDone += sizeof(unsigned);
  4358. inputDone += inputSize;
  4359. }
  4360. if (tlk)
  4361. {
  4362. logctx.noteStatistic(STATS_ACCEPTED, processed-processedBefore, 1);
  4363. logctx.noteStatistic(STATS_REJECTED, rejected, 1);
  4364. }
  4365. logctx.flush(true, aborted);
  4366. if (aborted)
  4367. output->abort();
  4368. else
  4369. output->flush(true);
  4370. return !aborted;
  4371. }
  4372. //================================================================================================
  4373. ISlaveActivityFactory *createRoxieKeyedJoinIndexActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4374. {
  4375. return new CRoxieKeyedJoinIndexActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  4376. }
  4377. //================================================================================================
  4378. class CRoxieKeyedJoinFetchActivityFactory : public CSlaveActivityFactory
  4379. {
  4380. public:
  4381. IMPLEMENT_IINTERFACE;
  4382. Owned<IFileIOArray> fileArray;
  4383. CRoxieKeyedJoinFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4384. : CSlaveActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory)
  4385. {
  4386. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  4387. assertex(helper->diskAccessRequired());
  4388. bool variableFileName = (helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0;
  4389. if (!variableFileName)
  4390. {
  4391. bool isOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  4392. const char *fileName = helper->getFileName();
  4393. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, _queryFactory.queryWorkUnit()));
  4394. if (datafile)
  4395. fileArray.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  4396. }
  4397. }
  4398. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const;
  4399. virtual StringBuffer &toString(StringBuffer &s) const
  4400. {
  4401. return CSlaveActivityFactory::toString(s.append("KEYEDJOIN FETCH "));
  4402. }
  4403. IFileIO *getFilePart(unsigned partNo, offset_t &_base) const
  4404. {
  4405. return fileArray->getFilePart(partNo, _base);
  4406. }
  4407. };
  4408. class CRoxieKeyedJoinFetchActivity : public CRoxieSlaveActivity
  4409. {
  4410. IHThorKeyedJoinArg *helper;
  4411. Owned<IFileIO> rawFile;
  4412. const CRoxieKeyedJoinFetchActivityFactory *factory;
  4413. offset_t base;
  4414. const char *inputLimit;
  4415. const char *inputData;
  4416. Owned<IFileIOArray> varFiles;
  4417. Owned<ISerialStream> rawStream;
  4418. CThorStreamDeserializerSource deserializeSource;
  4419. virtual void setPartNo(bool filechanged)
  4420. {
  4421. rawFile.setown(variableFileName ? varFiles->getFilePart(lastPartNo.partNo, base) : factory->getFilePart(lastPartNo.partNo, base)); // MORE - superfiles
  4422. rawStream.setown(createFileSerialStream(rawFile, 0, -1, 0));
  4423. deserializeSource.setStream(rawStream);
  4424. }
  4425. public:
  4426. IMPLEMENT_IINTERFACE;
  4427. CRoxieKeyedJoinFetchActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CRoxieKeyedJoinFetchActivityFactory *_aFactory)
  4428. : factory(_aFactory),
  4429. CRoxieSlaveActivity(_logctx, _packet, _hFactory, _aFactory)
  4430. {
  4431. // MORE - no continuation row support?
  4432. base = 0;
  4433. helper = (IHThorKeyedJoinArg *) basehelper;
  4434. variableFileName = (helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0;
  4435. onCreate();
  4436. inputData = (const char *) serializedCreate.readDirect(0);
  4437. inputLimit = inputData + (serializedCreate.length() - serializedCreate.getPos());
  4438. }
  4439. ~CRoxieKeyedJoinFetchActivity()
  4440. {
  4441. }
  4442. virtual const char *queryDynamicFileName() const
  4443. {
  4444. return helper->getFileName();
  4445. }
  4446. virtual void setVariableFileInfo()
  4447. {
  4448. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, packet->queryHeader().channel));
  4449. }
  4450. virtual bool process();
  4451. virtual StringBuffer &toString(StringBuffer &ret) const
  4452. {
  4453. return ret.appendf("KeyedJoinFetch %u", packet->queryHeader().activityId);
  4454. }
  4455. };
  4456. bool CRoxieKeyedJoinFetchActivity::process()
  4457. {
  4458. MTIME_SECTION(timer, "CRoxieKeyedJoinFetchActivity::process");
  4459. // MORE - where we are returning everything there is an optimization or two to be had
  4460. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  4461. unsigned processed = 0;
  4462. unsigned skipped = 0;
  4463. unsigned __int64 rowLimit = helper->getRowLimit();
  4464. unsigned totalSizeSent = 0;
  4465. Owned<IOutputRowDeserializer> rowDeserializer = helper->queryDiskRecordSize()->createRowDeserializer(queryContext->queryCodeContext(), basefactory->queryId());
  4466. Owned<IEngineRowAllocator> diskAllocator = getRowAllocator(helper->queryDiskRecordSize(), basefactory->queryId());
  4467. RtlDynamicRowBuilder diskRowBuilder(diskAllocator);
  4468. IOutputMetaData *joinFieldsMeta = helper->queryJoinFieldsRecordSize();
  4469. Owned<IEngineRowAllocator> joinFieldsAllocator = getRowAllocator(joinFieldsMeta, basefactory->queryId());
  4470. OptimizedKJRowBuilder jfRowBuilder(joinFieldsAllocator, joinFieldsMeta, output);
  4471. CachedOutputMetaData inputFields(helper->queryFetchInputRecordSize());
  4472. size32_t inputSize = inputFields.getFixedSize();
  4473. while (!aborted && inputData < inputLimit)
  4474. {
  4475. checkPartChanged(*(PartNoType *) inputData);
  4476. inputData += sizeof(PartNoType);
  4477. offset_t rp;
  4478. memcpy(&rp, inputData, sizeof(rp));
  4479. offset_t pos;
  4480. if (isLocalFpos(rp))
  4481. pos = getLocalFposOffset(rp);
  4482. else
  4483. pos = rp-base;
  4484. deserializeSource.reset(pos);
  4485. unsigned sizeRead = rowDeserializer->deserialize(diskRowBuilder.ensureRow(), deserializeSource);
  4486. OwnedConstRoxieRow rawBuffer = diskRowBuilder.finalizeRowClear(sizeRead);
  4487. const KeyedJoinHeader *headerPtr = (KeyedJoinHeader *) inputData;
  4488. inputData = &headerPtr->rhsdata[0];
  4489. if (inputFields.isVariableSize())
  4490. {
  4491. memcpy(&inputSize, inputData, sizeof(inputSize));
  4492. inputData += sizeof(inputSize);
  4493. }
  4494. if (helper->fetchMatch(inputData, rawBuffer))
  4495. {
  4496. unsigned thisSize = helper->extractJoinFields(jfRowBuilder, rawBuffer, rp, (IBlobProvider*)NULL);
  4497. jfRowBuilder.writeToOutput(thisSize, headerPtr->fpos, headerPtr->thisGroup, headerPtr->partNo);
  4498. totalSizeSent += KEYEDJOIN_RECORD_SIZE(thisSize);
  4499. processed++;
  4500. if (processed > rowLimit)
  4501. {
  4502. logctx.noteStatistic(STATS_DISK_SEEKS, processed+skipped, 1);
  4503. logctx.noteStatistic(STATS_ACCEPTED, processed, 1);
  4504. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  4505. limitExceeded();
  4506. return true;
  4507. }
  4508. }
  4509. else
  4510. {
  4511. skipped++;
  4512. KeyedJoinHeader *out = (KeyedJoinHeader *) output->getBuffer(KEYEDJOIN_RECORD_SIZE(0), true);
  4513. out->fpos = 0;
  4514. out->thisGroup = headerPtr->thisGroup;
  4515. out->partNo = (unsigned short) -1;
  4516. output->putBuffer(out, KEYEDJOIN_RECORD_SIZE(0), true);
  4517. totalSizeSent += KEYEDJOIN_RECORD_SIZE(0);
  4518. }
  4519. inputData += inputSize;
  4520. }
  4521. logctx.noteStatistic(STATS_DISK_SEEKS, processed+skipped, 1);
  4522. logctx.noteStatistic(STATS_ACCEPTED, processed, 1);
  4523. logctx.noteStatistic(STATS_REJECTED, skipped, 1);
  4524. logctx.flush(true, aborted);
  4525. if (aborted)
  4526. {
  4527. output->abort();
  4528. if (logctx.queryTraceLevel() > 5)
  4529. {
  4530. StringBuffer s;
  4531. logctx.CTXLOG("CRoxieKeyedJoinFetchActivity aborted: %s", packet->queryHeader().toString(s).str());
  4532. }
  4533. }
  4534. else
  4535. {
  4536. output->flush(true);
  4537. if (logctx.queryTraceLevel() > 5)
  4538. {
  4539. StringBuffer s;
  4540. logctx.CTXLOG("CRoxieKeyedJoinFetchActivity completed: %d records returned(%d bytes), %d skipped: %s", processed, totalSizeSent, skipped, packet->queryHeader().toString(s).str());
  4541. }
  4542. }
  4543. return !aborted;
  4544. }
  4545. IRoxieSlaveActivity *CRoxieKeyedJoinFetchActivityFactory::createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4546. {
  4547. return new CRoxieKeyedJoinFetchActivity(logctx, packet, helperFactory, this);
  4548. }
  4549. ISlaveActivityFactory *createRoxieKeyedJoinFetchActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory)
  4550. {
  4551. return new CRoxieKeyedJoinFetchActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory);
  4552. }
  4553. //================================================================================================
  4554. class CRoxieRemoteActivity : public CRoxieSlaveActivity
  4555. {
  4556. protected:
  4557. IHThorRemoteArg * remoteHelper;
  4558. unsigned processed;
  4559. unsigned remoteId;
  4560. public:
  4561. IMPLEMENT_IINTERFACE;
  4562. CRoxieRemoteActivity(SlaveContextLogger &_logctx, IRoxieQueryPacket *_packet, HelperFactory *_hFactory, const CSlaveActivityFactory *_aFactory, unsigned _remoteId)
  4563. : CRoxieSlaveActivity(_logctx, _packet, _hFactory, _aFactory),
  4564. remoteId(_remoteId)
  4565. {
  4566. remoteHelper = (IHThorRemoteArg *) basehelper;
  4567. processed = 0;
  4568. onCreate();
  4569. }
  4570. virtual StringBuffer &toString(StringBuffer &ret) const
  4571. {
  4572. return ret.appendf("Remote %u", packet->queryHeader().activityId);
  4573. }
  4574. virtual const char *queryDynamicFileName() const
  4575. {
  4576. throwUnexpected();
  4577. }
  4578. virtual void setVariableFileInfo()
  4579. {
  4580. throwUnexpected();
  4581. }
  4582. virtual bool process()
  4583. {
  4584. MTIME_SECTION(timer, "CRoxieRemoteActivity ::process");
  4585. Owned<IMessagePacker> output = ROQ->createOutputStream(packet->queryHeader(), false, logctx);
  4586. unsigned __int64 rowLimit = remoteHelper->getRowLimit();
  4587. rtlRowBuilder remoteExtractBuilder;
  4588. remoteHelper->createParentExtract(remoteExtractBuilder);
  4589. Linked<IActivityGraph> remoteQuery = queryContext->queryChildGraph(remoteId);
  4590. Linked<IRoxieServerChildGraph> remoteGraph = remoteQuery->queryLoopGraph();
  4591. try
  4592. {
  4593. remoteGraph->beforeExecute();
  4594. Owned<IRoxieInput> input = remoteGraph->startOutput(0, remoteExtractBuilder.size(), remoteExtractBuilder.getbytes(), false);
  4595. while (!aborted)
  4596. {
  4597. const void * next = input->nextInGroup();
  4598. if (!next)
  4599. {
  4600. next = input->nextInGroup();
  4601. if (!next)
  4602. break;
  4603. }
  4604. size32_t nextSize = meta.getRecordSize(next);
  4605. //MORE - what about grouping?
  4606. processed++;
  4607. if (processed > rowLimit)
  4608. {
  4609. ReleaseRoxieRow(next);
  4610. limitExceeded();
  4611. break;
  4612. }
  4613. if (serializer)
  4614. serializeRow(output, next);
  4615. else
  4616. {
  4617. void * recBuffer = output->getBuffer(nextSize, meta.isVariableSize());
  4618. memcpy(recBuffer, next, nextSize);
  4619. output->putBuffer(recBuffer, nextSize, meta.isVariableSize());
  4620. }
  4621. ReleaseRoxieRow(next);
  4622. }
  4623. remoteGraph->afterExecute();
  4624. }
  4625. catch (IException *E)
  4626. {
  4627. remoteGraph->afterExecute();
  4628. if (aborted)
  4629. ::Release(E);
  4630. else
  4631. throw;
  4632. }
  4633. catch (...)
  4634. {
  4635. remoteGraph->afterExecute();
  4636. throw;
  4637. }
  4638. logctx.flush(true, aborted);
  4639. if (aborted)
  4640. output->abort();
  4641. else
  4642. output->flush(true);
  4643. return !aborted;
  4644. }
  4645. virtual void setPartNo(bool filechanged)
  4646. {
  4647. throwUnexpected();
  4648. }
  4649. };
  4650. //================================================================================================
  4651. class CRoxieRemoteActivityFactory : public CSlaveActivityFactory
  4652. {
  4653. unsigned remoteId;
  4654. public:
  4655. IMPLEMENT_IINTERFACE;
  4656. CRoxieRemoteActivityFactory(IPropertyTree &graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _remoteId)
  4657. : CSlaveActivityFactory(graphNode, _subgraphId, _queryFactory, _helperFactory), remoteId(_remoteId)
  4658. {
  4659. }
  4660. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4661. {
  4662. return new CRoxieRemoteActivity(logctx, packet, helperFactory, this, remoteId);
  4663. }
  4664. virtual StringBuffer &toString(StringBuffer &s) const
  4665. {
  4666. return CSlaveActivityFactory::toString(s.append("Remote "));
  4667. }
  4668. };
  4669. ISlaveActivityFactory *createRoxieRemoteActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _remoteId)
  4670. {
  4671. return new CRoxieRemoteActivityFactory(_graphNode, _subgraphId, _queryFactory, _helperFactory, _remoteId);
  4672. }
  4673. //================================================================================================
  4674. class CRoxieDummyActivityFactory : public CSlaveActivityFactory // not a real activity - just used to properly link files
  4675. {
  4676. protected:
  4677. Owned<const IResolvedFile> indexfile;
  4678. Owned<IKeyArray> keyArray;
  4679. Owned<IFileIOArray> fileArray;
  4680. TranslatorArray layoutTranslators;
  4681. public:
  4682. IMPLEMENT_IINTERFACE;
  4683. CRoxieDummyActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, bool isLoadDataOnly)
  4684. : CSlaveActivityFactory(_graphNode, _subgraphId, _queryFactory, NULL)
  4685. {
  4686. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  4687. return; // ignore 'spills'
  4688. try // operations does not want any missing file errors to be fatal, or throw traps - just log it
  4689. {
  4690. bool isOpt = _graphNode.getPropBool("att[@name='_isOpt']/@value") || pretendAllOpt;
  4691. if (queryNodeIndexName(_graphNode))
  4692. {
  4693. indexfile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeIndexName(_graphNode), isOpt, true, _queryFactory.queryWorkUnit()));
  4694. if (indexfile)
  4695. keyArray.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, queryFactory.queryChannel(), queryFactory.getEnableFieldTranslation()));
  4696. }
  4697. if (queryNodeFileName(_graphNode))
  4698. {
  4699. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isOpt, true, _queryFactory.queryWorkUnit()));
  4700. if (datafile)
  4701. fileArray.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  4702. }
  4703. }
  4704. catch(IException *E)
  4705. {
  4706. StringBuffer errors;
  4707. E->errorMessage(errors);
  4708. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  4709. E->Release();
  4710. }
  4711. }
  4712. virtual IRoxieSlaveActivity *createActivity(SlaveContextLogger &logctx, IRoxieQueryPacket *packet) const
  4713. {
  4714. throwUnexpected(); // don't actually want to create an activity
  4715. }
  4716. };
  4717. //================================================================================================
  4718. ISlaveActivityFactory *createRoxieDummyActivityFactory(IPropertyTree &_graphNode, unsigned _subgraphId, IQueryFactory &_queryFactory, bool isLoadDataOnly)
  4719. {
  4720. // MORE - bool isLoadDataOnly may need to be an enum if more than just LOADDATAONLY and suspended queries use this
  4721. return new CRoxieDummyActivityFactory(_graphNode, _subgraphId, _queryFactory, isLoadDataOnly);
  4722. }