ccdserver.cpp 882 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363
  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 "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "jlzw.hpp"
  27. #include "javahash.hpp"
  28. #include "javahash.tpp"
  29. #include "thorstep.ipp"
  30. #include "thorpipe.hpp"
  31. #include "thorfile.hpp"
  32. #include "eclhelper.hpp"
  33. #include "eclrtl_imp.hpp"
  34. #include "rtlfield_imp.hpp"
  35. #include "rtlds_imp.hpp"
  36. #include "rtlread_imp.hpp"
  37. #include "dafdesc.hpp"
  38. #include "dautils.hpp"
  39. namespace ccdserver_hqlhelper
  40. {
  41. #include "eclhelper_base.hpp"
  42. }
  43. #include "ccd.hpp"
  44. #include "ccdserver.hpp"
  45. #include "ccdcontext.hpp"
  46. #include "ccdactivities.hpp"
  47. #include "ccdquery.hpp"
  48. #include "ccdstate.hpp"
  49. #include "ccdqueue.ipp"
  50. #include "ccdsnmp.hpp"
  51. #include "ccddali.hpp"
  52. #include "jsmartsock.hpp"
  53. #include "dllserver.hpp"
  54. #include "workflow.hpp"
  55. #include "roxiemem.hpp"
  56. #include "roxierowbuff.hpp"
  57. #include "roxiehelper.hpp"
  58. #include "roxielmj.hpp"
  59. #include "roxierow.hpp"
  60. #include "thorplugin.hpp"
  61. #include "keybuild.hpp"
  62. #define MAX_HTTP_HEADERSIZE 8000
  63. #define MIN_PAYLOAD_SIZE 800
  64. #pragma warning(disable : 4355)
  65. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  66. #define PROBE
  67. #ifdef _DEBUG
  68. //#define FAKE_EXCEPTIONS
  69. //#define TRACE_JOINGROUPS
  70. //#define TRACE_SPLIT
  71. //#define _CHECK_HEAPSORT
  72. //#undef PARALLEL_EXECUTE
  73. //#define TRACE_SEEK_REQUESTS
  74. #endif
  75. using roxiemem::OwnedRoxieRow;
  76. using roxiemem::OwnedRoxieString;
  77. using roxiemem::OwnedConstRoxieRow;
  78. using roxiemem::IRowManager;
  79. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  80. #if _MSC_VER==1200
  81. #define protected public
  82. #endif
  83. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  84. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  85. inline void ReleaseRoxieRowSet(ConstPointerArray &data)
  86. {
  87. ForEachItemIn(idx, data)
  88. ReleaseRoxieRow(data.item(idx));
  89. data.kill();
  90. }
  91. //=================================================================================
  92. class RestartableThread : public CInterface
  93. {
  94. class MyThread : public Thread
  95. {
  96. Linked<RestartableThread> owner;
  97. public:
  98. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  99. {
  100. }
  101. virtual int run()
  102. {
  103. owner->started.signal();
  104. return owner->run();
  105. }
  106. };
  107. friend class MyThread;
  108. Semaphore started;
  109. Owned<MyThread> thread;
  110. CriticalSection crit;
  111. StringAttr name;
  112. public:
  113. RestartableThread(const char *_name) : name(_name)
  114. {
  115. }
  116. virtual void start(const char *namePrefix)
  117. {
  118. StringBuffer s(namePrefix);
  119. s.append(name);
  120. {
  121. CriticalBlock b(crit);
  122. assertex(!thread);
  123. thread.setown(new MyThread(this, s));
  124. thread->start();
  125. }
  126. started.wait();
  127. }
  128. virtual void join()
  129. {
  130. {
  131. Owned<Thread> tthread;
  132. {
  133. CriticalBlock b(crit);
  134. tthread.setown(thread.getClear());
  135. }
  136. if (tthread)
  137. tthread->join();
  138. }
  139. }
  140. virtual int run() = 0;
  141. };
  142. //================================================================================
  143. // default implementation - can be overridden for efficiency...
  144. bool IRoxieInput::nextGroup(ConstPointerArray & group)
  145. {
  146. // MORE - this should be replaced with a version that reads to a builder
  147. const void * next;
  148. while ((next = nextInGroup()) != NULL)
  149. group.append(next);
  150. if (group.ordinality())
  151. return true;
  152. return false;
  153. }
  154. void IRoxieInput::readAll(RtlLinkedDatasetBuilder &builder)
  155. {
  156. loop
  157. {
  158. const void *nextrec = nextInGroup();
  159. if (!nextrec)
  160. {
  161. nextrec = nextInGroup();
  162. if (!nextrec)
  163. break;
  164. builder.appendEOG();
  165. }
  166. builder.appendOwn(nextrec);
  167. }
  168. }
  169. inline const void * nextUngrouped(IRoxieInput * input)
  170. {
  171. const void * ret = input->nextInGroup();
  172. if (!ret)
  173. ret = input->nextInGroup();
  174. return ret;
  175. };
  176. //=================================================================================
  177. //The following don't link their arguments because that creates a circular reference
  178. //But I wish there was a better way
  179. class IndirectSlaveContext : public CInterface, implements IRoxieSlaveContext
  180. {
  181. public:
  182. IndirectSlaveContext(IRoxieSlaveContext * _ctx = NULL) : ctx(_ctx) {}
  183. IMPLEMENT_IINTERFACE
  184. void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  185. virtual ICodeContext *queryCodeContext()
  186. {
  187. return ctx->queryCodeContext();
  188. }
  189. virtual void checkAbort()
  190. {
  191. ctx->checkAbort();
  192. }
  193. virtual void notifyAbort(IException *E)
  194. {
  195. ctx->notifyAbort(E);
  196. }
  197. virtual IActivityGraph * queryChildGraph(unsigned id)
  198. {
  199. return ctx->queryChildGraph(id);
  200. }
  201. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  202. {
  203. ctx->noteChildGraph(id, childGraph) ;
  204. }
  205. virtual IRowManager &queryRowManager()
  206. {
  207. return ctx->queryRowManager();
  208. }
  209. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  210. {
  211. ctx->noteStatistic(statCode, value, count);
  212. }
  213. virtual void CTXLOG(const char *format, ...) const
  214. {
  215. va_list args;
  216. va_start(args, format);
  217. ctx->CTXLOGva(format, args);
  218. va_end(args);
  219. }
  220. virtual void CTXLOGva(const char *format, va_list args) const
  221. {
  222. ctx->CTXLOGva(format, args);
  223. }
  224. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  225. {
  226. ctx->CTXLOGa(category, prefix, text);
  227. }
  228. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  229. {
  230. va_list args;
  231. va_start(args, format);
  232. ctx->logOperatorExceptionVA(E, file, line, format, args);
  233. va_end(args);
  234. }
  235. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  236. {
  237. ctx->logOperatorExceptionVA(E, file, line, format, args);
  238. }
  239. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  240. {
  241. va_list args;
  242. va_start(args, format);
  243. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  244. va_end(args);
  245. }
  246. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  247. {
  248. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  249. }
  250. virtual void CTXLOGl(LogItem *log) const
  251. {
  252. ctx->CTXLOGl(log);
  253. }
  254. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  255. {
  256. return ctx->getLogPrefix(ret);
  257. }
  258. virtual unsigned queryTraceLevel() const
  259. {
  260. return ctx->queryTraceLevel();
  261. }
  262. virtual bool isIntercepted() const
  263. {
  264. return ctx->isIntercepted();
  265. }
  266. virtual bool isBlind() const
  267. {
  268. return ctx->isBlind();
  269. }
  270. virtual unsigned parallelJoinPreload()
  271. {
  272. return ctx->parallelJoinPreload();
  273. }
  274. virtual unsigned concatPreload()
  275. {
  276. return ctx->concatPreload();
  277. }
  278. virtual unsigned fetchPreload()
  279. {
  280. return ctx->fetchPreload();
  281. }
  282. virtual unsigned fullKeyedJoinPreload()
  283. {
  284. return ctx->fullKeyedJoinPreload();
  285. }
  286. virtual unsigned keyedJoinPreload()
  287. {
  288. return ctx->keyedJoinPreload();
  289. }
  290. virtual unsigned prefetchProjectPreload()
  291. {
  292. return ctx->prefetchProjectPreload();
  293. }
  294. virtual void addSlavesReplyLen(unsigned len)
  295. {
  296. ctx->addSlavesReplyLen(len);
  297. }
  298. virtual const char *queryAuthToken()
  299. {
  300. return ctx->queryAuthToken();
  301. }
  302. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  303. {
  304. return ctx->resolveLFN(filename, isOpt);
  305. }
  306. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  307. {
  308. return ctx->createLFN(filename, overwrite, extend, clusters);
  309. }
  310. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  311. {
  312. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  313. }
  314. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  315. {
  316. return ctx->getLibraryGraph(extra, parentActivity);
  317. }
  318. virtual void noteProcessed(const IRoxieContextLogger &_activityContext, const IRoxieServerActivity *_activity, unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  319. {
  320. ctx->noteProcessed(_activityContext, _activity, _idx, _processed, _totalCycles, _localCycles);
  321. }
  322. virtual IProbeManager *queryProbeManager() const
  323. {
  324. return ctx->queryProbeManager();
  325. }
  326. virtual IDebuggableContext *queryDebugContext() const
  327. {
  328. return ctx->queryDebugContext();
  329. }
  330. virtual bool queryTimeActivities() const
  331. {
  332. return ctx->queryTimeActivities();
  333. }
  334. virtual bool queryCheckingHeap() const
  335. {
  336. return ctx->queryCheckingHeap();
  337. }
  338. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  339. {
  340. ctx->printResults(output, name, sequence);
  341. }
  342. virtual void setWUState(WUState state)
  343. {
  344. ctx->setWUState(state);
  345. }
  346. virtual bool checkWuAborted()
  347. {
  348. return ctx->checkWuAborted();
  349. }
  350. virtual IWorkUnit *updateWorkUnit() const
  351. {
  352. return ctx->updateWorkUnit();
  353. }
  354. virtual IConstWorkUnit *queryWorkUnit() const
  355. {
  356. return ctx->queryWorkUnit();
  357. }
  358. virtual IRoxieServerContext *queryServerContext()
  359. {
  360. return ctx->queryServerContext();
  361. }
  362. virtual IWorkUnitRowReader *getWorkunitRowReader(const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  363. {
  364. return ctx->getWorkunitRowReader(name, sequence, xmlTransformer, rowAllocator, isGrouped);
  365. }
  366. protected:
  367. IRoxieSlaveContext * ctx;
  368. };
  369. //=================================================================================
  370. #define RESULT_FLUSH_THRESHOLD 10000u
  371. #ifdef _DEBUG
  372. #define SOAP_SPLIT_THRESHOLD 100u
  373. #define SOAP_SPLIT_RESERVE 200u
  374. #else
  375. #define SOAP_SPLIT_THRESHOLD 64000u
  376. #define SOAP_SPLIT_RESERVE 65535u
  377. #endif
  378. //=================================================================================
  379. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  380. {
  381. protected:
  382. IntArray dependencies; // things I am dependent on
  383. IntArray dependencyIndexes; // things I am dependent on
  384. IntArray dependencyControlIds; // things I am dependent on
  385. StringArray dependencyEdgeIds; // How to describe them to the debugger
  386. unsigned dependentCount; // things dependent on me
  387. mutable CriticalSection statsCrit;
  388. mutable __int64 processed;
  389. mutable __int64 started;
  390. mutable __int64 totalCycles;
  391. mutable __int64 localCycles;
  392. public:
  393. IMPLEMENT_IINTERFACE;
  394. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  395. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  396. {
  397. processed = 0;
  398. started = 0;
  399. totalCycles = 0;
  400. localCycles = 0;
  401. dependentCount = 0;
  402. }
  403. ~CRoxieServerActivityFactoryBase()
  404. {
  405. }
  406. StringBuffer &toString(StringBuffer &ret) const
  407. {
  408. return ret.appendf("%p", this);
  409. }
  410. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  411. {
  412. dependencies.append(_source);
  413. dependencyIndexes.append(_sourceIdx);
  414. dependencyControlIds.append(controlId);
  415. dependencyEdgeIds.append(edgeId);
  416. }
  417. virtual void noteDependent(unsigned target)
  418. {
  419. dependentCount++;
  420. }
  421. virtual IntArray &queryDependencies() { return dependencies; }
  422. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  423. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  424. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  425. virtual unsigned queryId() const { return id; }
  426. virtual unsigned querySubgraphId() const { return subgraphId; }
  427. virtual ThorActivityKind getKind() const { return kind; }
  428. virtual IOutputMetaData * queryOutputMeta() const
  429. {
  430. return meta;
  431. }
  432. virtual bool isSink() const
  433. {
  434. return false;
  435. }
  436. virtual bool isFunction() const
  437. {
  438. return false;
  439. }
  440. virtual bool isGraphInvariant() const
  441. {
  442. return false;
  443. }
  444. virtual IHThorArg &getHelper() const
  445. {
  446. return *helperFactory();
  447. }
  448. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  449. {
  450. arg.Release();
  451. throwUnexpected();
  452. }
  453. virtual void noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  454. {
  455. if (_processed || _totalCycles || _localCycles)
  456. {
  457. CriticalBlock b(statsCrit);
  458. #ifdef _DEBUG
  459. assertex(_totalCycles >= _localCycles);
  460. #endif
  461. processed += _processed;
  462. totalCycles += _totalCycles;
  463. localCycles += _localCycles;
  464. }
  465. }
  466. virtual void noteStarted() const
  467. {
  468. CriticalBlock b(statsCrit);
  469. started ++;
  470. }
  471. virtual void noteStarted(unsigned idx) const
  472. {
  473. throwUnexpected(); // should be implemented/required by multiOutput cases only
  474. }
  475. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  476. {
  477. CriticalBlock b(statsCrit);
  478. if (output == 0)
  479. {
  480. putStatsValue(&edge, "count", "sum", processed);
  481. if (started)
  482. putStatsValue(&edge, "started", "sum", started);
  483. }
  484. else
  485. ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  486. }
  487. virtual void getNodeProgressInfo(IPropertyTree &node) const
  488. {
  489. CActivityFactory::getNodeProgressInfo(node);
  490. CriticalBlock b(statsCrit);
  491. if (started)
  492. putStatsValue(&node, "_roxieStarted", "sum", started);
  493. if (totalCycles)
  494. putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  495. if (localCycles)
  496. putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  497. }
  498. virtual void resetNodeProgressInfo()
  499. {
  500. CActivityFactory::resetNodeProgressInfo();
  501. CriticalBlock b(statsCrit);
  502. started = 0;
  503. totalCycles = 0;
  504. localCycles = 0;
  505. }
  506. virtual void getActivityMetrics(StringBuffer &reply) const
  507. {
  508. CActivityFactory::getActivityMetrics(reply);
  509. CriticalBlock b(statsCrit);
  510. putStatsValue(reply, "_roxieStarted", "sum", started);
  511. putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  512. putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
  513. }
  514. virtual unsigned __int64 queryLocalCycles() const
  515. {
  516. return localCycles;
  517. }
  518. virtual IQueryFactory &queryQueryFactory() const
  519. {
  520. return CActivityFactory::queryQueryFactory();
  521. }
  522. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  523. {
  524. return CActivityFactory::queryChildQuery(idx, id);
  525. }
  526. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  527. {
  528. CActivityFactory::addChildQuery(id, childQuery);
  529. }
  530. virtual void createChildQueries(IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx) const
  531. {
  532. ForEachItemIn(idx, childQueries)
  533. {
  534. childGraphs.append(*createActivityGraph(NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx));
  535. }
  536. }
  537. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs) const
  538. {
  539. ForEachItemIn(idx, childGraphs)
  540. {
  541. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  542. childGraphs.item(idx).onCreate(ctx, colocalArg);
  543. }
  544. }
  545. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  546. {
  547. unsigned match = childQueryIndexes.find(childId);
  548. assertex(match != NotFound);
  549. Owned<IActivityGraph> graph = createActivityGraph(NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx);
  550. graph->onCreate(ctx, colocalArg);
  551. return graph.getClear();
  552. }
  553. virtual IRoxieServerSideCache *queryServerSideCache() const
  554. {
  555. return NULL; // Activities that wish to support server-side caching will need to do better....
  556. }
  557. virtual bool getEnableFieldTranslation() const
  558. {
  559. throwUnexpected(); // only implemented by index-related subclasses
  560. }
  561. virtual IDefRecordMeta *queryActivityMeta() const
  562. {
  563. throwUnexpected(); // only implemented by index-related subclasses
  564. }
  565. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  566. {
  567. mystats.noteStatistic(statCode, value, count);
  568. }
  569. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  570. {
  571. // Most activities have nothing to say...
  572. }
  573. };
  574. class CRoxieServerMultiInputInfo
  575. {
  576. private:
  577. UnsignedArray inputs;
  578. UnsignedArray inputIndexes;
  579. public:
  580. void set(unsigned idx, unsigned source, unsigned sourceidx)
  581. {
  582. if (idx==inputs.length())
  583. {
  584. inputs.append(source);
  585. inputIndexes.append(sourceidx);
  586. }
  587. else
  588. {
  589. while (!inputs.isItem(idx))
  590. {
  591. inputs.append(0);
  592. inputIndexes.append(0);
  593. }
  594. inputs.replace(source, idx);
  595. inputIndexes.replace(sourceidx, idx);
  596. }
  597. }
  598. unsigned get(unsigned idx, unsigned &sourceidx) const
  599. {
  600. if (inputs.isItem(idx))
  601. {
  602. sourceidx = inputIndexes.item(idx);
  603. return inputs.item(idx);
  604. }
  605. else
  606. return (unsigned) -1;
  607. }
  608. inline unsigned ordinality() const { return inputs.ordinality(); }
  609. };
  610. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  611. {
  612. private:
  613. CRoxieServerMultiInputInfo inputs;
  614. public:
  615. IMPLEMENT_IINTERFACE;
  616. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  617. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  618. {
  619. }
  620. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  621. {
  622. inputs.set(idx, source, sourceidx);
  623. }
  624. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  625. {
  626. return inputs.get(idx, sourceidx);
  627. }
  628. virtual unsigned numInputs() const { return inputs.ordinality(); }
  629. };
  630. class CWrappedException : public CInterface, implements IException
  631. {
  632. Owned<IException> wrapped;
  633. ThorActivityKind kind;
  634. unsigned queryId;
  635. public:
  636. IMPLEMENT_IINTERFACE;
  637. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  638. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  639. {
  640. }
  641. virtual int errorCode() const { return wrapped->errorCode(); }
  642. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  643. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  644. };
  645. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  646. {
  647. protected:
  648. unsigned input;
  649. unsigned inputidx;
  650. public:
  651. IMPLEMENT_IINTERFACE;
  652. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  653. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  654. {
  655. input = (unsigned) -1;
  656. inputidx = 0;
  657. }
  658. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  659. {
  660. if (idx != 0)
  661. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, __FILE__, __LINE__);
  662. if (input != -1)
  663. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() called twice for input = %d source = %d inputidx = %d sourceidx = %d at %s(%d)", id, input, source, inputidx, sourceidx, __FILE__, __LINE__);
  664. input = source;
  665. inputidx = sourceidx;
  666. }
  667. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  668. {
  669. if (!idx)
  670. {
  671. sourceidx = inputidx;
  672. return input;
  673. }
  674. return (unsigned) -1;
  675. }
  676. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  677. };
  678. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  679. {
  680. protected:
  681. unsigned numOutputs;
  682. unsigned __int64 *processedArray;
  683. bool *startedArray;
  684. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  685. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  686. {
  687. numOutputs = 0;
  688. processedArray = NULL;
  689. startedArray = NULL;
  690. }
  691. ~CRoxieServerMultiOutputFactory()
  692. {
  693. delete [] processedArray;
  694. delete [] startedArray;
  695. }
  696. void setNumOutputs(unsigned num)
  697. {
  698. numOutputs = num;
  699. if (!num)
  700. num = 1; // Even sink activities like to track how many records they process
  701. processedArray = new unsigned __int64[num];
  702. startedArray = new bool[num];
  703. for (unsigned i = 0; i < num; i++)
  704. {
  705. processedArray[i] = 0;
  706. startedArray[i] = 0;
  707. }
  708. }
  709. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  710. {
  711. assertex(numOutputs ? idx < numOutputs : idx==0);
  712. CriticalBlock b(statsCrit);
  713. putStatsValue(&edge, "count", "sum", processedArray[idx]);
  714. putStatsValue(&edge, "started", "sum", startedArray[idx]);
  715. }
  716. virtual void noteProcessed(unsigned idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  717. {
  718. assertex(numOutputs ? idx < numOutputs : idx==0);
  719. CriticalBlock b(statsCrit);
  720. processedArray[idx] += _processed;
  721. totalCycles += _totalCycles;
  722. localCycles += _localCycles;
  723. }
  724. virtual void noteStarted(unsigned idx) const
  725. {
  726. assertex(numOutputs ? idx < numOutputs : idx==0);
  727. CriticalBlock b(statsCrit);
  728. startedArray[idx] = true;
  729. }
  730. };
  731. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  732. {
  733. protected:
  734. bool isInternal;
  735. bool isRoot;
  736. unsigned usageCount;
  737. public:
  738. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  739. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  740. {
  741. usageCount = _usageCount;
  742. isRoot = _isRoot;
  743. isInternal = false; // filled in by derived class constructor
  744. }
  745. virtual bool isSink() const
  746. {
  747. //only a sink if a root activity
  748. return isRoot && !(isInternal && dependentCount && dependentCount==usageCount); // MORE - it's possible for this to get the answer wrong still, since usageCount does not include references from main procedure. Gavin?
  749. }
  750. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  751. {
  752. // There is no meaningful info to return along the dependency edge - we don't detect how many times the value has been read from the context
  753. // Just leave it blank is safest.
  754. }
  755. };
  756. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  757. const char *queryStateText(activityState state)
  758. {
  759. switch (state)
  760. {
  761. case STATEreset: return "reset";
  762. case STATEstarted: return "started";
  763. case STATEstopped: return "stopped";
  764. case STATEstarting: return "starting";
  765. default: return "unknown";
  766. }
  767. }
  768. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  769. class CParallelActivityExecutor : public CAsyncFor
  770. {
  771. public:
  772. unsigned parentExtractSize;
  773. const byte * parentExtract;
  774. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  775. activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  776. void Do(unsigned i)
  777. {
  778. activities.item(i).execute(parentExtractSize, parentExtract);
  779. }
  780. private:
  781. IRoxieServerActivityCopyArray & activities;
  782. };
  783. class CRoxieServerActivity : public CInterface, implements IRoxieServerActivity, implements IRoxieInput, implements IRoxieContextLogger
  784. {
  785. protected:
  786. IRoxieInput *input;
  787. IHThorArg &basehelper;
  788. IRoxieSlaveContext *ctx;
  789. const IRoxieServerActivityFactory *factory;
  790. IRoxieServerActivityCopyArray dependencies;
  791. IntArray dependencyControlIds;
  792. IArrayOf<IActivityGraph> childGraphs;
  793. CachedOutputMetaData meta;
  794. IHThorArg *colocalParent;
  795. IEngineRowAllocator *rowAllocator;
  796. CriticalSection statecrit;
  797. mutable StatsCollector stats;
  798. unsigned processed;
  799. unsigned __int64 totalCycles;
  800. unsigned activityId;
  801. activityState state;
  802. bool createPending;
  803. bool debugging;
  804. public:
  805. IMPLEMENT_IINTERFACE;
  806. CRoxieServerActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  807. : factory(_factory),
  808. basehelper(_factory->getHelper()),
  809. activityId(_factory->queryId())
  810. {
  811. input = NULL;
  812. ctx = NULL;
  813. meta.set(basehelper.queryOutputMeta());
  814. processed = 0;
  815. totalCycles = 0;
  816. if (factory)
  817. factory->createChildQueries(childGraphs, this, _probeManager, *this);
  818. state=STATEreset;
  819. rowAllocator = NULL;
  820. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  821. colocalParent = NULL;
  822. createPending = true;
  823. }
  824. CRoxieServerActivity(IHThorArg & _helper) : factory(NULL), basehelper(_helper)
  825. {
  826. activityId = 0;
  827. input = NULL;
  828. ctx = NULL;
  829. meta.set(basehelper.queryOutputMeta());
  830. processed = 0;
  831. totalCycles = 0;
  832. state=STATEreset;
  833. rowAllocator = NULL;
  834. debugging = false;
  835. colocalParent = NULL;
  836. createPending = true;
  837. }
  838. inline ~CRoxieServerActivity()
  839. {
  840. CriticalBlock cb(statecrit);
  841. if (traceStartStop)
  842. DBGLOG("%p destroy state=%s", this, queryStateText(state)); // Note- CTXLOG may not be safe
  843. if (state!=STATEreset)
  844. {
  845. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  846. state = STATEreset; // bit pointless but there you go...
  847. }
  848. basehelper.Release();
  849. ::Release(rowAllocator);
  850. }
  851. virtual const IRoxieContextLogger &queryLogCtx()const
  852. {
  853. return *this;
  854. }
  855. inline void createRowAllocator()
  856. {
  857. if (!rowAllocator)
  858. rowAllocator = ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activityId);
  859. }
  860. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  861. virtual void CTXLOG(const char *format, ...) const
  862. {
  863. va_list args;
  864. va_start(args, format);
  865. CTXLOGva(format, args);
  866. va_end(args);
  867. }
  868. virtual void CTXLOGva(const char *format, va_list args) const
  869. {
  870. StringBuffer text, prefix;
  871. getLogPrefix(prefix);
  872. text.valist_appendf(format, args);
  873. CTXLOGa(LOG_TRACING, prefix.str(), text.str());
  874. }
  875. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  876. {
  877. if (ctx)
  878. ctx->CTXLOGa(category, prefix, text);
  879. else
  880. DBGLOG("[%s] %s", prefix, text);
  881. }
  882. virtual void logOperatorException(IException *E, const char *file, unsigned line, const char *format, ...) const
  883. {
  884. va_list args;
  885. va_start(args, format);
  886. StringBuffer prefix;
  887. getLogPrefix(prefix);
  888. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  889. va_end(args);
  890. }
  891. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const
  892. {
  893. StringBuffer prefix;
  894. getLogPrefix(prefix);
  895. CTXLOGaeva(E, file, line, prefix.str(), format, args);
  896. }
  897. virtual void CTXLOGae(IException *E, const char *file, unsigned line, const char *prefix, const char *format, ...) const
  898. {
  899. va_list args;
  900. va_start(args, format);
  901. CTXLOGaeva(E, file, line, prefix, format, args);
  902. va_end(args);
  903. }
  904. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const
  905. {
  906. if (ctx)
  907. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  908. else
  909. {
  910. StringBuffer ss;
  911. ss.appendf("[%s] ERROR", prefix);
  912. if (E)
  913. ss.append(": ").append(E->errorCode());
  914. if (file)
  915. ss.appendf(": %s(%d) ", file, line);
  916. if (E)
  917. E->errorMessage(ss.append(": "));
  918. if (format)
  919. {
  920. ss.append(": ").valist_appendf(format, args);
  921. }
  922. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  923. }
  924. }
  925. virtual void CTXLOGl(LogItem *log) const
  926. {
  927. if (ctx)
  928. ctx->CTXLOGl(log);
  929. else
  930. {
  931. assert(ctx);
  932. log->Release(); // Should never happen
  933. }
  934. }
  935. virtual void noteStatistic(unsigned statCode, unsigned __int64 value, unsigned count) const
  936. {
  937. if (factory)
  938. factory->noteStatistic(statCode, value, count);
  939. if (ctx)
  940. ctx->noteStatistic(statCode, value, count);
  941. stats.noteStatistic(statCode, value, count);
  942. }
  943. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  944. {
  945. if (ctx)
  946. ctx->getLogPrefix(ret);
  947. return ret.append('@').append(activityId);
  948. }
  949. virtual bool isIntercepted() const
  950. {
  951. return ctx ? ctx->isIntercepted() : false;
  952. }
  953. virtual bool isBlind() const
  954. {
  955. return ctx ? ctx->isBlind() : blindLogging;
  956. }
  957. virtual unsigned queryTraceLevel() const
  958. {
  959. if (ctx)
  960. return ctx->queryTraceLevel();
  961. else
  962. return traceLevel;
  963. }
  964. virtual bool isPassThrough()
  965. {
  966. return false;
  967. }
  968. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  969. {
  970. return ctx->resolveLFN(filename, isOpt);
  971. }
  972. virtual const IResolvedFile *queryVarFileInfo() const
  973. {
  974. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  975. return NULL;
  976. }
  977. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  978. {
  979. throwUnexpected(); // should be implemented in more derived class wherever needed
  980. }
  981. virtual IRoxieSlaveContext *queryContext()
  982. {
  983. return ctx;
  984. }
  985. virtual IRoxieServerActivity *queryActivity() { return this; }
  986. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  987. virtual bool needsAllocator() const { return false; }
  988. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  989. {
  990. ctx = _ctx;
  991. colocalParent = _colocalParent;
  992. createPending = true;
  993. if (needsAllocator())
  994. createRowAllocator();
  995. processed = 0;
  996. totalCycles = 0;
  997. if (factory)
  998. factory->onCreateChildQueries(_ctx, &basehelper, childGraphs);
  999. }
  1000. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1001. {
  1002. //This should only be called after onStart has been called on the helper
  1003. assertex(!createPending);
  1004. assertex(state==STATEstarted);
  1005. unsigned startlen = out.length();
  1006. basehelper.serializeCreateContext(out);
  1007. basehelper.serializeStartContext(out);
  1008. if (queryTraceLevel() > 10)
  1009. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1010. }
  1011. virtual void serializeExtra(MemoryBuffer &out) {}
  1012. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1013. {
  1014. CriticalBlock cb(statecrit);
  1015. if (state != STATEreset && state != STATEstarting)
  1016. {
  1017. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1018. }
  1019. state=STATEstarted;
  1020. #ifdef TRACE_STARTSTOP
  1021. if (traceStartStop)
  1022. {
  1023. CTXLOG("start %d", activityId);
  1024. if (watchActivityId && watchActivityId==activityId)
  1025. {
  1026. CTXLOG("WATCH: start %d", activityId);
  1027. }
  1028. }
  1029. #endif
  1030. executeDependencies(parentExtractSize, parentExtract, 0);
  1031. if (input)
  1032. input->start(parentExtractSize, parentExtract, paused);
  1033. ensureCreated();
  1034. basehelper.onStart(parentExtract, NULL);
  1035. if (factory)
  1036. factory->noteStarted();
  1037. }
  1038. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1039. {
  1040. //MORE: Create a filtered list and then use asyncfor
  1041. ForEachItemIn(idx, dependencies)
  1042. {
  1043. if (dependencyControlIds.item(idx) == controlId)
  1044. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1045. }
  1046. }
  1047. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1048. {
  1049. ForEachItemIn(idx, dependencies)
  1050. {
  1051. if (dependencyControlIds.item(idx) == controlId)
  1052. dependencies.item(idx).stop(false);
  1053. }
  1054. }
  1055. virtual unsigned __int64 queryTotalCycles() const
  1056. {
  1057. return totalCycles;
  1058. }
  1059. virtual unsigned __int64 queryLocalCycles() const
  1060. {
  1061. __int64 ret = totalCycles;
  1062. if (input) ret -= input->queryTotalCycles();
  1063. if (ret < 0)
  1064. ret = 0;
  1065. return ret;
  1066. }
  1067. virtual IRoxieInput *queryInput(unsigned idx) const
  1068. {
  1069. if (idx==0)
  1070. return input;
  1071. else
  1072. return NULL;
  1073. }
  1074. void noteProcessed(unsigned _idx, unsigned _processed, unsigned __int64 _totalCycles, unsigned __int64 _localCycles) const
  1075. {
  1076. if (factory)
  1077. {
  1078. if (!debugging)
  1079. factory->noteProcessed(_idx, _processed, _totalCycles, _localCycles);
  1080. if (ctx)
  1081. ctx->noteProcessed(*this, this, _idx, _processed, _totalCycles, _localCycles);
  1082. }
  1083. }
  1084. inline void ensureCreated()
  1085. {
  1086. if (createPending)
  1087. {
  1088. createPending = false;
  1089. basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
  1090. }
  1091. }
  1092. inline void stop(bool aborting)
  1093. {
  1094. if (state != STATEstopped)
  1095. {
  1096. CriticalBlock cb(statecrit);
  1097. if (state != STATEstopped)
  1098. {
  1099. state=STATEstopped;
  1100. #ifdef TRACE_STARTSTOP
  1101. if (traceStartStop)
  1102. {
  1103. CTXLOG("stop %d", activityId);
  1104. if (watchActivityId && watchActivityId==activityId)
  1105. {
  1106. CTXLOG("WATCH: stop %d", activityId);
  1107. }
  1108. }
  1109. #endif
  1110. if (input)
  1111. input->stop(aborting);
  1112. }
  1113. }
  1114. }
  1115. inline void reset()
  1116. {
  1117. if (state != STATEreset)
  1118. {
  1119. CriticalBlock cb(statecrit);
  1120. if (state != STATEreset)
  1121. {
  1122. if (state==STATEstarted || state==STATEstarting)
  1123. {
  1124. CTXLOG("STATE: activity %d reset without stop", activityId);
  1125. stop(false);
  1126. }
  1127. if (ctx->queryTimeActivities())
  1128. {
  1129. stats.dumpStats(*this);
  1130. StringBuffer prefix, text;
  1131. getLogPrefix(prefix);
  1132. text.appendf("records processed - %d", processed);
  1133. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1134. text.clear().appendf("total time - %d us", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
  1135. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1136. text.clear().appendf("local time - %d us", (unsigned) (cycle_to_nanosec(queryLocalCycles())/1000));
  1137. CTXLOGa(LOG_STATISTICS, prefix.str(), text.str());
  1138. }
  1139. state = STATEreset;
  1140. #ifdef TRACE_STARTSTOP
  1141. if (traceStartStop)
  1142. {
  1143. CTXLOG("reset %d", activityId);
  1144. if (watchActivityId && watchActivityId==activityId)
  1145. {
  1146. CTXLOG("WATCH: reset %d", activityId);
  1147. }
  1148. }
  1149. #endif
  1150. ForEachItemIn(idx, dependencies)
  1151. dependencies.item(idx).reset();
  1152. noteProcessed(0, processed, totalCycles, queryLocalCycles());
  1153. if (input)
  1154. input->reset();
  1155. processed = 0;
  1156. totalCycles = 0;
  1157. }
  1158. }
  1159. }
  1160. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1161. {
  1162. dependencies.append(source);
  1163. dependencyControlIds.append(controlId);
  1164. }
  1165. virtual void resetEOF()
  1166. {
  1167. //would make more sense if the default implementation (and eof member) were in the base class
  1168. }
  1169. // Sink activities should override this....
  1170. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1171. {
  1172. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1173. }
  1174. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1175. {
  1176. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1177. }
  1178. virtual __int64 evaluate()
  1179. {
  1180. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1181. }
  1182. virtual IRoxieInput * querySelectOutput(unsigned id)
  1183. {
  1184. return NULL;
  1185. }
  1186. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  1187. {
  1188. return false;
  1189. }
  1190. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1191. {
  1192. assertex(!idx);
  1193. input = _in;
  1194. }
  1195. virtual IRoxieInput *queryOutput(unsigned idx)
  1196. {
  1197. if (idx == (unsigned) -1)
  1198. idx = 0;
  1199. return idx ? NULL : this;
  1200. }
  1201. virtual IOutputMetaData *queryOutputMeta() const
  1202. {
  1203. return meta.queryOriginal();
  1204. }
  1205. virtual unsigned queryId() const
  1206. {
  1207. return activityId;
  1208. }
  1209. virtual unsigned querySubgraphId() const
  1210. {
  1211. return factory->querySubgraphId();
  1212. }
  1213. virtual void checkAbort()
  1214. {
  1215. ctx->checkAbort();
  1216. }
  1217. IException *makeWrappedException(IException *e)
  1218. {
  1219. StringBuffer msg;
  1220. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1221. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1222. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1223. return e;
  1224. else
  1225. return new CWrappedException(e, activityKind, activityId);
  1226. }
  1227. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1228. {
  1229. }
  1230. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  1231. {
  1232. }
  1233. virtual void resetOutputsUsed()
  1234. {
  1235. }
  1236. virtual void noteOutputUsed()
  1237. {
  1238. }
  1239. virtual IRoxieServerSideCache *queryServerSideCache() const
  1240. {
  1241. return factory->queryServerSideCache();
  1242. }
  1243. virtual const IRoxieServerActivityFactory *queryFactory() const
  1244. {
  1245. return factory;
  1246. }
  1247. inline ThorActivityKind getKind() const
  1248. {
  1249. return factory->getKind();
  1250. }
  1251. inline bool isSink() const
  1252. {
  1253. return (factory != NULL) && factory->isSink();
  1254. }
  1255. };
  1256. //=====================================================================================================
  1257. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1258. {
  1259. protected:
  1260. IRoxieInput *input; // Don't use base class input field as we want to delay starts
  1261. bool prefiltered;
  1262. bool eof;
  1263. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1264. {
  1265. prefiltered = !any;
  1266. eof = prefiltered;
  1267. if (!prefiltered)
  1268. input->start(parentExtractSize, parentExtract, false);
  1269. else
  1270. {
  1271. if (traceStartStop)
  1272. CTXLOG("lateStart activity stopping input early as prefiltered");
  1273. input->stop(false);
  1274. }
  1275. }
  1276. public:
  1277. CRoxieServerLateStartActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1278. : CRoxieServerActivity(_factory, _probeManager)
  1279. {
  1280. input = NULL;
  1281. prefiltered = false;
  1282. eof = false;
  1283. }
  1284. virtual void stop(bool aborting)
  1285. {
  1286. if (!prefiltered)
  1287. {
  1288. input->stop(aborting);
  1289. }
  1290. else if (traceStartStop)
  1291. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1292. CRoxieServerActivity::stop(aborting);
  1293. }
  1294. virtual unsigned __int64 queryLocalCycles() const
  1295. {
  1296. __int64 localCycles = totalCycles - input->queryTotalCycles();
  1297. if (localCycles < 0)
  1298. localCycles = 0;
  1299. return localCycles;
  1300. }
  1301. virtual IRoxieInput *queryInput(unsigned idx) const
  1302. {
  1303. if (idx==0)
  1304. return input;
  1305. else
  1306. return NULL;
  1307. }
  1308. virtual void reset()
  1309. {
  1310. CRoxieServerActivity::reset();
  1311. input->reset();
  1312. prefiltered = false;
  1313. }
  1314. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1315. {
  1316. assertex(!idx);
  1317. input = _in;
  1318. }
  1319. };
  1320. //=====================================================================================================
  1321. atomic_t nextInstanceId;
  1322. extern unsigned getNextInstanceId()
  1323. {
  1324. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1325. }
  1326. atomic_t nextRuid;
  1327. ruid_t getNextRuid()
  1328. {
  1329. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1330. while (ret < RUID_FIRST)
  1331. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1332. return ret;
  1333. }
  1334. void setStartRuid(unsigned restarts)
  1335. {
  1336. atomic_set(&nextRuid, restarts * 0x10000);
  1337. atomic_set(&nextInstanceId, restarts * 10000);
  1338. }
  1339. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1340. class LimitSkipException : public CInterface, public IException
  1341. {
  1342. int code;
  1343. public:
  1344. LimitSkipException(int _code) { code = _code; }
  1345. IMPLEMENT_IINTERFACE;
  1346. virtual int errorCode() const { return code; }
  1347. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1348. virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
  1349. };
  1350. IException *makeLimitSkipException(bool isKeyed)
  1351. {
  1352. // We need to make sure what we throw is IException not something derived from it....
  1353. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1354. }
  1355. //=================================================================================
  1356. interface IRecordPullerCallback : extends IExceptionHandler
  1357. {
  1358. virtual void processRow(const void *row) = 0;
  1359. virtual void processEOG() = 0;
  1360. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1361. virtual void processDone() = 0;
  1362. };
  1363. class RecordPullerThread : public RestartableThread
  1364. {
  1365. protected:
  1366. IRoxieInput *input;
  1367. IRecordPullerCallback *helper;
  1368. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1369. bool groupAtOnce, eof, eog;
  1370. CriticalSection crit;
  1371. public:
  1372. RecordPullerThread(bool _groupAtOnce)
  1373. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1374. {
  1375. input = NULL;
  1376. helper = NULL;
  1377. eof = eog = FALSE;
  1378. }
  1379. inline unsigned __int64 queryTotalCycles() const
  1380. {
  1381. return input->queryTotalCycles();
  1382. }
  1383. void setInput(IRecordPullerCallback *_helper, IRoxieInput *_input)
  1384. {
  1385. helper = _helper;
  1386. input = _input;
  1387. }
  1388. IRoxieInput *queryInput() const
  1389. {
  1390. return input;
  1391. }
  1392. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1393. {
  1394. eof = false;
  1395. eog = false;
  1396. input->start(parentExtractSize, parentExtract, paused);
  1397. try
  1398. {
  1399. if (preload && !paused)
  1400. {
  1401. if (traceLevel > 4)
  1402. DBGLOG("Preload fetching first %d records", preload);
  1403. if (groupAtOnce)
  1404. pullGroups(preload);
  1405. else
  1406. pullRecords(preload);
  1407. }
  1408. if (eof)
  1409. {
  1410. if (traceLevel > 4)
  1411. DBGLOG("No need to start puller after preload");
  1412. helper->processDone();
  1413. }
  1414. else
  1415. {
  1416. if (!noThread)
  1417. {
  1418. StringBuffer logPrefix("[");
  1419. if (ctx) ctx->getLogPrefix(logPrefix);
  1420. logPrefix.append("] ");
  1421. RestartableThread::start(logPrefix);
  1422. started.wait();
  1423. }
  1424. }
  1425. }
  1426. catch (IException *e)
  1427. {
  1428. helper->fireException(e);
  1429. }
  1430. catch (...)
  1431. {
  1432. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  1433. }
  1434. }
  1435. void stop(bool aborting)
  1436. {
  1437. if (traceStartStop)
  1438. DBGLOG("RecordPullerThread::stop");
  1439. {
  1440. CriticalBlock c(crit); // stop is called on our consumer's thread. We need to take care calling stop for our input to make sure it is not in mid-nextInGroup etc etc.
  1441. input->stop(aborting);
  1442. }
  1443. RestartableThread::join();
  1444. }
  1445. void reset()
  1446. {
  1447. input->reset();
  1448. }
  1449. virtual int run()
  1450. {
  1451. started.signal();
  1452. try
  1453. {
  1454. if (groupAtOnce)
  1455. pullGroups((unsigned) -1);
  1456. else
  1457. pullRecords((unsigned) -1);
  1458. helper->processDone();
  1459. }
  1460. catch (IException *e)
  1461. {
  1462. helper->fireException(e);
  1463. }
  1464. catch (...)
  1465. {
  1466. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  1467. }
  1468. return 0;
  1469. }
  1470. void done()
  1471. {
  1472. helper->processDone();
  1473. }
  1474. bool pullRecords(unsigned preload)
  1475. {
  1476. if (eof)
  1477. return false;
  1478. while (preload)
  1479. {
  1480. const void * row;
  1481. {
  1482. CriticalBlock c(crit); // See comments in stop for why this is needed
  1483. row = input->nextInGroup();
  1484. }
  1485. if (row)
  1486. {
  1487. eog = false;
  1488. helper->processRow(row);
  1489. }
  1490. else if (!eog)
  1491. {
  1492. helper->processEOG();
  1493. eog = true;
  1494. }
  1495. else
  1496. {
  1497. eof = true;
  1498. return false;
  1499. }
  1500. if (preload != (unsigned) -1)
  1501. preload--;
  1502. }
  1503. return true;
  1504. }
  1505. void pullGroups(unsigned preload)
  1506. {
  1507. ConstPointerArray thisGroup;
  1508. unsigned rowsDone = 0;
  1509. while (preload && !eof)
  1510. {
  1511. const void *row;
  1512. {
  1513. CriticalBlock c(crit);
  1514. row = input->nextInGroup();
  1515. }
  1516. if (row)
  1517. {
  1518. thisGroup.append(row);
  1519. rowsDone++;
  1520. }
  1521. else if (thisGroup.length())
  1522. {
  1523. helper->processGroup(thisGroup);
  1524. thisGroup.kill();
  1525. if (preload != (unsigned) -1)
  1526. {
  1527. if (preload > rowsDone)
  1528. preload -= rowsDone;
  1529. else
  1530. break;
  1531. }
  1532. rowsDone = 0;
  1533. }
  1534. else
  1535. {
  1536. eof = true;
  1537. break;
  1538. }
  1539. }
  1540. }
  1541. };
  1542. //=================================================================================
  1543. #define READAHEAD_SIZE 1000
  1544. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  1545. class CRoxieServerReadAheadInput : public CInterface, implements IRoxieInput, implements IRecordPullerCallback
  1546. {
  1547. QueueOf<const void, true> buffer;
  1548. InterruptableSemaphore ready;
  1549. InterruptableSemaphore space;
  1550. CriticalSection crit;
  1551. bool eof;
  1552. bool disabled;
  1553. RecordPullerThread puller;
  1554. unsigned preload;
  1555. unsigned __int64 totalCycles;
  1556. IRoxieSlaveContext *ctx;
  1557. public:
  1558. IMPLEMENT_IINTERFACE;
  1559. CRoxieServerReadAheadInput(unsigned _preload) : puller(true), preload(_preload)
  1560. {
  1561. eof = false;
  1562. disabled = false;
  1563. totalCycles = 0;
  1564. ctx = NULL;
  1565. }
  1566. void onCreate(IRoxieSlaveContext *_ctx)
  1567. {
  1568. ctx = _ctx;
  1569. disabled = (ctx->queryDebugContext() != NULL);
  1570. }
  1571. virtual IRoxieServerActivity *queryActivity()
  1572. {
  1573. return puller.queryInput()->queryActivity();
  1574. }
  1575. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  1576. {
  1577. return puller.queryInput()->queryIndexReadActivity();
  1578. }
  1579. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1580. {
  1581. eof = false;
  1582. totalCycles = 0;
  1583. if (disabled)
  1584. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  1585. else
  1586. {
  1587. space.reinit(READAHEAD_SIZE);
  1588. ready.reinit();
  1589. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  1590. }
  1591. }
  1592. virtual void stop(bool aborting)
  1593. {
  1594. if (disabled)
  1595. puller.queryInput()->stop(aborting);
  1596. else
  1597. {
  1598. space.interrupt();
  1599. ready.interrupt();
  1600. puller.stop(aborting);
  1601. }
  1602. }
  1603. virtual void reset()
  1604. {
  1605. if (disabled)
  1606. puller.queryInput()->reset();
  1607. else
  1608. {
  1609. puller.reset();
  1610. ForEachItemIn(idx1, buffer)
  1611. ReleaseRoxieRow(buffer.item(idx1));
  1612. buffer.clear();
  1613. }
  1614. }
  1615. virtual void resetEOF()
  1616. {
  1617. throwUnexpected();
  1618. }
  1619. virtual IOutputMetaData * queryOutputMeta() const
  1620. {
  1621. return puller.queryInput()->queryOutputMeta();
  1622. }
  1623. virtual void checkAbort()
  1624. {
  1625. puller.queryInput()->checkAbort();
  1626. }
  1627. void setInput(unsigned idx, IRoxieInput *_in)
  1628. {
  1629. assertex(!idx);
  1630. puller.setInput(this, _in);
  1631. }
  1632. virtual unsigned __int64 queryTotalCycles() const
  1633. {
  1634. return totalCycles;
  1635. }
  1636. virtual unsigned __int64 queryLocalCycles() const
  1637. {
  1638. __int64 ret = totalCycles - puller.queryInput()->queryTotalCycles();
  1639. if (ret < 0) ret = 0;
  1640. return ret;
  1641. }
  1642. virtual IRoxieInput *queryInput(unsigned idx) const
  1643. {
  1644. return puller.queryInput()->queryInput(idx);
  1645. }
  1646. virtual const void * nextInGroup()
  1647. {
  1648. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  1649. if (disabled)
  1650. return puller.queryInput()->nextInGroup();
  1651. else
  1652. {
  1653. loop
  1654. {
  1655. {
  1656. CriticalBlock b(crit);
  1657. if (eof && !buffer.ordinality())
  1658. return NULL; // eof
  1659. }
  1660. ready.wait();
  1661. const void *ret;
  1662. {
  1663. CriticalBlock b(crit);
  1664. ret = buffer.dequeue();
  1665. }
  1666. space.signal();
  1667. return ret;
  1668. }
  1669. }
  1670. }
  1671. virtual unsigned queryId() const { throwUnexpected(); }
  1672. virtual bool fireException(IException *e)
  1673. {
  1674. // called from puller thread on failure
  1675. ready.interrupt(LINK(e));
  1676. space.interrupt(e);
  1677. return true;
  1678. }
  1679. virtual void processRow(const void *row)
  1680. {
  1681. {
  1682. CriticalBlock b(crit);
  1683. buffer.enqueue(row);
  1684. }
  1685. ready.signal();
  1686. space.wait();
  1687. }
  1688. virtual void processGroup(const ConstPointerArray &rows)
  1689. {
  1690. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  1691. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  1692. // if group was larger than max(space)
  1693. {
  1694. CriticalBlock b(crit);
  1695. ForEachItemIn(idx, rows)
  1696. buffer.enqueue(rows.item(idx));
  1697. buffer.enqueue(NULL);
  1698. }
  1699. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  1700. {
  1701. ready.signal();
  1702. space.wait();
  1703. }
  1704. }
  1705. virtual void processEOG()
  1706. {
  1707. // Used when output is not grouped - just ignore
  1708. }
  1709. virtual void processDone()
  1710. {
  1711. CriticalBlock b(crit);
  1712. eof = true;
  1713. ready.signal();
  1714. }
  1715. };
  1716. //=================================================================================
  1717. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  1718. {
  1719. protected:
  1720. IRoxieInput *input1;
  1721. Owned<CRoxieServerReadAheadInput> puller;
  1722. public:
  1723. CRoxieServerTwoInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1724. : CRoxieServerActivity(_factory, _probeManager)
  1725. {
  1726. input1 = NULL;
  1727. }
  1728. ~CRoxieServerTwoInputActivity()
  1729. {
  1730. }
  1731. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1732. {
  1733. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1734. input1->start(parentExtractSize, parentExtract, paused);
  1735. }
  1736. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  1737. {
  1738. if (puller)
  1739. puller->onCreate(_ctx);
  1740. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  1741. }
  1742. virtual void stop(bool aborting)
  1743. {
  1744. input1->stop(aborting);
  1745. CRoxieServerActivity::stop(aborting);
  1746. }
  1747. virtual unsigned __int64 queryLocalCycles() const
  1748. {
  1749. __int64 ret;
  1750. __int64 inputCycles = input->queryTotalCycles();
  1751. __int64 input1Cycles = input1->queryTotalCycles();
  1752. if (puller)
  1753. ret = totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  1754. else
  1755. ret = totalCycles - (inputCycles + input1Cycles);
  1756. if (ret < 0)
  1757. ret = 0;
  1758. return ret;
  1759. }
  1760. virtual IRoxieInput *queryInput(unsigned idx) const
  1761. {
  1762. switch (idx)
  1763. {
  1764. case 0:
  1765. return input;
  1766. case 1:
  1767. return input1;
  1768. default:
  1769. return NULL;
  1770. }
  1771. }
  1772. virtual void reset()
  1773. {
  1774. CRoxieServerActivity::reset();
  1775. if (input1)
  1776. input1->reset();
  1777. }
  1778. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1779. {
  1780. switch(idx)
  1781. {
  1782. case 0:
  1783. input = _in;
  1784. break;
  1785. case 1:
  1786. input1 = _in;
  1787. break;
  1788. default:
  1789. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  1790. }
  1791. }
  1792. };
  1793. //=================================================================================
  1794. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  1795. {
  1796. protected:
  1797. unsigned numInputs;
  1798. IRoxieInput **inputArray;
  1799. public:
  1800. CRoxieServerMultiInputBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1801. : CRoxieServerActivity(_factory, _probeManager), numInputs(_numInputs)
  1802. {
  1803. inputArray = new IRoxieInput*[numInputs];
  1804. for (unsigned i = 0; i < numInputs; i++)
  1805. inputArray[i] = NULL;
  1806. }
  1807. ~CRoxieServerMultiInputBaseActivity()
  1808. {
  1809. delete [] inputArray;
  1810. }
  1811. virtual unsigned __int64 queryLocalCycles() const
  1812. {
  1813. __int64 localCycles = totalCycles;
  1814. for (unsigned i = 0; i < numInputs; i++)
  1815. localCycles -= inputArray[i]->queryTotalCycles();
  1816. if (localCycles < 0)
  1817. localCycles = 0;
  1818. return localCycles;
  1819. }
  1820. virtual IRoxieInput *queryInput(unsigned idx) const
  1821. {
  1822. if (idx < numInputs)
  1823. return inputArray[idx];
  1824. else
  1825. return NULL;
  1826. }
  1827. virtual void reset()
  1828. {
  1829. for (unsigned i = 0; i < numInputs; i++)
  1830. inputArray[i]->reset();
  1831. CRoxieServerActivity::reset();
  1832. }
  1833. virtual void setInput(unsigned idx, IRoxieInput *_in)
  1834. {
  1835. inputArray[idx] = _in;
  1836. }
  1837. };
  1838. //=================================================================================
  1839. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  1840. {
  1841. public:
  1842. CRoxieServerMultiInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  1843. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  1844. {
  1845. }
  1846. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1847. {
  1848. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  1849. for (unsigned i = 0; i < numInputs; i++)
  1850. {
  1851. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  1852. }
  1853. }
  1854. virtual void stop(bool aborting)
  1855. {
  1856. for (unsigned i = 0; i < numInputs; i++)
  1857. {
  1858. inputArray[i]->stop(aborting);
  1859. }
  1860. CRoxieServerMultiInputBaseActivity::stop(aborting);
  1861. }
  1862. };
  1863. //=====================================================================================================
  1864. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  1865. {
  1866. protected:
  1867. bool executed;
  1868. CriticalSection ecrit;
  1869. Owned<IException> exception;
  1870. public:
  1871. CRoxieServerInternalSinkActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1872. : CRoxieServerActivity(_factory, _probeManager)
  1873. {
  1874. executed = false;
  1875. }
  1876. virtual void reset()
  1877. {
  1878. executed = false;
  1879. exception.clear();
  1880. CRoxieServerActivity::reset();
  1881. }
  1882. virtual IRoxieInput *queryOutput(unsigned idx)
  1883. {
  1884. return NULL;
  1885. }
  1886. virtual const void *nextInGroup()
  1887. {
  1888. throwUnexpected(); // I am nobody's input
  1889. }
  1890. virtual void onExecute() = 0;
  1891. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1892. {
  1893. CriticalBlock b(ecrit);
  1894. if (exception)
  1895. throw exception.getLink();
  1896. if (!executed)
  1897. {
  1898. try
  1899. {
  1900. start(parentExtractSize, parentExtract, false);
  1901. {
  1902. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // unfortunately this is not really best place for seeing in debugger.
  1903. onExecute();
  1904. }
  1905. stop(false);
  1906. executed = true;
  1907. }
  1908. catch (IException *E)
  1909. {
  1910. exception.set(E); // (or maybe makeWrappedException?)
  1911. stop(true);
  1912. throw;
  1913. }
  1914. catch (...)
  1915. {
  1916. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__));
  1917. stop(true);
  1918. throw;
  1919. }
  1920. }
  1921. }
  1922. };
  1923. //=================================================================================
  1924. class CRoxieServerQueryPacket : public CInterface, implements IRoxieServerQueryPacket
  1925. {
  1926. protected:
  1927. Owned<IMessageResult> result;
  1928. Owned<IRoxieQueryPacket> packet;
  1929. Linked<IRoxieServerQueryPacket> continuation;
  1930. unsigned hash;
  1931. unsigned seq;
  1932. unsigned lastDebugSequence;
  1933. Owned<IRoxieQueryPacket> lastDebugResponse;
  1934. ILRUChain *prev;
  1935. ILRUChain *next;
  1936. bool delayed;
  1937. public:
  1938. IMPLEMENT_IINTERFACE;
  1939. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  1940. {
  1941. hash = 0;
  1942. seq = 0;
  1943. prev = NULL;
  1944. next = NULL;
  1945. delayed = false;
  1946. lastDebugSequence = 0;
  1947. }
  1948. virtual IRoxieQueryPacket *queryPacket() const
  1949. {
  1950. return packet;
  1951. }
  1952. virtual bool isContinuation() const
  1953. {
  1954. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  1955. }
  1956. virtual bool isDelayed() const
  1957. {
  1958. return delayed;
  1959. }
  1960. virtual bool isEnd() const
  1961. {
  1962. return false;
  1963. }
  1964. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  1965. {
  1966. return false;
  1967. }
  1968. virtual bool hasResult() const
  1969. {
  1970. return result != NULL;
  1971. }
  1972. virtual bool hasContinuation() const
  1973. {
  1974. return continuation != NULL;
  1975. }
  1976. virtual void setDelayed(bool _delayed)
  1977. {
  1978. delayed = _delayed;
  1979. }
  1980. virtual void setPacket(IRoxieQueryPacket *_packet)
  1981. {
  1982. packet.setown(_packet);
  1983. }
  1984. virtual void setSequence(unsigned _seq)
  1985. {
  1986. assertex(!IsShared());
  1987. seq = _seq;
  1988. }
  1989. virtual unsigned getSequence() const
  1990. {
  1991. return seq;
  1992. }
  1993. IMessageResult *getResult()
  1994. {
  1995. return result.getLink();
  1996. }
  1997. IMessageResult *queryResult()
  1998. {
  1999. return result;
  2000. }
  2001. void setResult(IMessageResult *r)
  2002. {
  2003. result.setown(r);
  2004. }
  2005. IRoxieServerQueryPacket *queryContinuation()
  2006. {
  2007. return continuation;
  2008. }
  2009. void setContinuation(IRoxieServerQueryPacket *c)
  2010. {
  2011. continuation.setown(c);
  2012. }
  2013. virtual unsigned queryHash() const
  2014. {
  2015. return hash;
  2016. }
  2017. virtual void setHash(unsigned _hash)
  2018. {
  2019. hash = _hash;
  2020. }
  2021. virtual ILRUChain *queryPrev() const { return prev; }
  2022. virtual ILRUChain *queryNext() const { return next; }
  2023. virtual void setPrev(ILRUChain *p) { prev = p; }
  2024. virtual void setNext(ILRUChain *n) { next = n; }
  2025. virtual void unchain()
  2026. {
  2027. if (prev && next)
  2028. {
  2029. prev->setNext(next);
  2030. next->setPrev(prev);
  2031. }
  2032. next = NULL;
  2033. prev = NULL;
  2034. }
  2035. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2036. {
  2037. if (sequence == lastDebugSequence)
  2038. return lastDebugResponse.getLink();
  2039. else if (sequence > lastDebugSequence)
  2040. {
  2041. lastDebugResponse.clear();
  2042. return NULL;
  2043. }
  2044. else
  2045. throwUnexpected();
  2046. }
  2047. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2048. {
  2049. lastDebugSequence = sequence;
  2050. lastDebugResponse.set(response);
  2051. }
  2052. };
  2053. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2054. {
  2055. public:
  2056. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2057. {
  2058. }
  2059. virtual bool isEnd() const
  2060. {
  2061. return true;
  2062. }
  2063. };
  2064. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2065. {
  2066. unsigned __int64 rowLimit;
  2067. unsigned __int64 keyedLimit;
  2068. unsigned __int64 stopAfter;
  2069. public:
  2070. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2071. {
  2072. rowLimit = _rowLimit;
  2073. keyedLimit = _keyedLimit;
  2074. stopAfter = _stopAfter;
  2075. }
  2076. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2077. {
  2078. _rowLimit = rowLimit;
  2079. _keyedLimit = keyedLimit;
  2080. _stopAfter = stopAfter;
  2081. return true;
  2082. }
  2083. };
  2084. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2085. {
  2086. protected:
  2087. unsigned cacheTableSize;
  2088. unsigned cacheTableSpace;
  2089. IRoxieServerQueryPacket **cacheTable;
  2090. mutable ILRUChain *prev;
  2091. mutable ILRUChain *next;
  2092. mutable CriticalSection crit;
  2093. virtual ILRUChain *queryPrev() const { return prev; }
  2094. virtual ILRUChain *queryNext() const { return next; }
  2095. virtual void setPrev(ILRUChain *p) { prev = p; }
  2096. virtual void setNext(ILRUChain *n) { next = n; }
  2097. virtual void unchain()
  2098. {
  2099. prev->setNext(next);
  2100. next->setPrev(prev);
  2101. next = NULL;
  2102. prev = NULL;
  2103. }
  2104. void moveToHead(IRoxieServerQueryPacket *mru)
  2105. {
  2106. mru->unchain();
  2107. mru->setNext(next);
  2108. next->setPrev(mru);
  2109. mru->setPrev(this);
  2110. next = mru;
  2111. }
  2112. IRoxieServerQueryPacket *removeLRU()
  2113. {
  2114. if (next==this)
  2115. assertex(next != this);
  2116. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2117. goer->unchain(); // NOTE - this will modify the value of next
  2118. return goer;
  2119. }
  2120. void removeEntry(IRoxieServerQueryPacket *goer)
  2121. {
  2122. unsigned v = goer->queryHash() % cacheTableSize;
  2123. loop
  2124. {
  2125. IRoxieServerQueryPacket *found = cacheTable[v];
  2126. assertex(found);
  2127. if (found == goer)
  2128. {
  2129. cacheTable[v] = NULL;
  2130. unsigned vn = v;
  2131. loop
  2132. {
  2133. vn++;
  2134. if (vn==cacheTableSize) vn = 0;
  2135. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2136. if (!found2)
  2137. break;
  2138. unsigned vm = found2->queryHash() % cacheTableSize;
  2139. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2140. {
  2141. cacheTable[v] = found2;
  2142. v = vn;
  2143. cacheTable[v] = NULL;
  2144. }
  2145. }
  2146. cacheTableSpace++;
  2147. break;
  2148. }
  2149. v++;
  2150. if (v==cacheTableSize)
  2151. v = 0;
  2152. }
  2153. goer->Release();
  2154. }
  2155. public:
  2156. CRoxieServerSideCache(unsigned _cacheSize)
  2157. {
  2158. cacheTableSize = (_cacheSize*4)/3;
  2159. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2160. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2161. cacheTableSpace = _cacheSize;
  2162. prev = this;
  2163. next = this;
  2164. }
  2165. ~CRoxieServerSideCache()
  2166. {
  2167. for (unsigned i = 0; i < cacheTableSize; i++)
  2168. {
  2169. ::Release(cacheTable[i]);
  2170. }
  2171. delete [] cacheTable;
  2172. }
  2173. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2174. {
  2175. unsigned hash = p->hash();
  2176. unsigned et = hash % cacheTableSize;
  2177. if (traceServerSideCache)
  2178. {
  2179. StringBuffer s;
  2180. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2181. }
  2182. CriticalBlock b(crit);
  2183. loop
  2184. {
  2185. IRoxieServerQueryPacket *found = cacheTable[et];
  2186. if (!found)
  2187. return NULL;
  2188. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2189. {
  2190. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2191. if (traceServerSideCache)
  2192. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2193. logctx.noteStatistic(STATS_SERVERCACHEHIT, 1, 1);
  2194. return NULL;
  2195. // Because IMessageResult cannot be replayed, this echeme is flawed. I'm leaving the code here just as a stats gatherer to see how useful it would have been....
  2196. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2197. //ret->setResult(found->getResult());
  2198. //return ret;
  2199. }
  2200. et++;
  2201. if (et == cacheTableSize)
  2202. et = 0;
  2203. }
  2204. }
  2205. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2206. {
  2207. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2208. {
  2209. unsigned hash = out->queryPacket()->hash();
  2210. out->setHash(hash);
  2211. unsigned et = hash % cacheTableSize;
  2212. if (traceServerSideCache)
  2213. {
  2214. StringBuffer s;
  2215. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2216. }
  2217. CriticalBlock b(crit);
  2218. loop
  2219. {
  2220. IRoxieServerQueryPacket *found = cacheTable[et];
  2221. if (!found)
  2222. {
  2223. if (cacheTableSpace)
  2224. {
  2225. out->setResult(LINK(in));
  2226. cacheTable[et] = LINK(out);
  2227. cacheTableSpace--;
  2228. moveToHead(out);
  2229. break;
  2230. }
  2231. else
  2232. {
  2233. IRoxieServerQueryPacket *goer = removeLRU();
  2234. removeEntry(goer);
  2235. et = hash % cacheTableSize;
  2236. continue;
  2237. }
  2238. }
  2239. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2240. {
  2241. moveToHead(found);
  2242. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2243. // multiple copies of a slave query are in-flight at once.
  2244. }
  2245. et++;
  2246. if (et == cacheTableSize)
  2247. et = 0;
  2248. }
  2249. }
  2250. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2251. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2252. }
  2253. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2254. // identical queries are in-flight at the same time. But if we can make it persistant between queries that will
  2255. // more than make up for it
  2256. };
  2257. class CRowArrayMessageUnpackCursor : public CInterface, implements IMessageUnpackCursor
  2258. {
  2259. ConstPointerArray &data;
  2260. Linked<IMessageResult> result;
  2261. public:
  2262. IMPLEMENT_IINTERFACE;
  2263. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2264. : data(_data), result(_result)
  2265. {
  2266. }
  2267. virtual bool atEOF() const
  2268. {
  2269. return data.length()==0;
  2270. }
  2271. virtual bool isSerialized() const
  2272. {
  2273. return false;
  2274. }
  2275. virtual const void * getNext(int length)
  2276. {
  2277. if (!data.length())
  2278. return NULL;
  2279. const void *ret = data.item(0);
  2280. data.remove(0);
  2281. return ret;
  2282. }
  2283. };
  2284. // MORE - should possibly move more over to the lazy version used in indexread?
  2285. class CRowArrayMessageResult : public CInterface, implements IMessageResult
  2286. {
  2287. ConstPointerArray data;
  2288. IRowManager &rowManager;
  2289. bool variableSize;
  2290. public:
  2291. IMPLEMENT_IINTERFACE;
  2292. CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
  2293. {
  2294. }
  2295. ~CRowArrayMessageResult()
  2296. {
  2297. ReleaseRoxieRowSet(data);
  2298. }
  2299. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2300. {
  2301. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2302. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2303. }
  2304. virtual const void *getMessageHeader(unsigned &length) const
  2305. {
  2306. throwUnexpected(); // should never get called - I don't have a header available
  2307. length = 0;
  2308. return NULL;
  2309. }
  2310. virtual const void *getMessageMetadata(unsigned &length) const
  2311. {
  2312. length = 0;
  2313. return NULL;
  2314. }
  2315. virtual void discard() const
  2316. {
  2317. throwUnexpected();
  2318. }
  2319. void append(const void *row)
  2320. {
  2321. data.append(row);
  2322. }
  2323. };
  2324. void throwRemoteException(IMessageUnpackCursor *extra)
  2325. {
  2326. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2327. if (rowlen)
  2328. {
  2329. char *xml = (char *) extra->getNext(*rowlen);
  2330. ReleaseRoxieRow(rowlen);
  2331. Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
  2332. ReleaseRoxieRow(xml);
  2333. unsigned code = p->getPropInt("Code", 0);
  2334. const char *msg = p->queryProp("Message");
  2335. if (!msg)
  2336. msg = xml;
  2337. throw MakeStringException(code, "%s", msg);
  2338. }
  2339. throwUnexpected();
  2340. }
  2341. class CRemoteResultAdaptor :public CInterface, implements IRoxieInput, implements IExceptionHandler
  2342. {
  2343. friend class CRemoteResultMerger;
  2344. class CRemoteResultMerger
  2345. {
  2346. class HeapEntry : public CInterface
  2347. {
  2348. private:
  2349. CRemoteResultAdaptor &adaptor;
  2350. IMessageUnpackCursor *cursor;
  2351. public:
  2352. const void *current;
  2353. bool isLast;
  2354. bool lastIsComplete;
  2355. IRoxieServerQueryPacket *packet;
  2356. unsigned seq;
  2357. public:
  2358. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  2359. {
  2360. cursor = _cursor;
  2361. lastIsComplete = _lastIsComplete;
  2362. return next();
  2363. }
  2364. public:
  2365. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  2366. {
  2367. cursor = NULL;
  2368. current = NULL;
  2369. isLast = false;
  2370. lastIsComplete = true;
  2371. }
  2372. ~HeapEntry()
  2373. {
  2374. ::Release(packet);
  2375. ::Release(cursor);
  2376. ReleaseRoxieRow(current);
  2377. }
  2378. bool isCompleteMatch() const
  2379. {
  2380. if (!isLast || lastIsComplete)
  2381. return true;
  2382. else
  2383. return false;
  2384. }
  2385. const void *next()
  2386. {
  2387. if (cursor)
  2388. {
  2389. ReleaseClearRoxieRow(current);
  2390. current = adaptor.getRow(cursor);
  2391. isLast = cursor->atEOF();
  2392. if (!current)
  2393. {
  2394. cursor->Release();
  2395. cursor = NULL;
  2396. }
  2397. }
  2398. return current;
  2399. }
  2400. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  2401. {
  2402. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  2403. unsigned skipped = 0;
  2404. loop
  2405. {
  2406. int c = compare->docompare(current, seek, numFields);
  2407. //If larger than the seek values, then we may be allowed to return an inexact match,
  2408. //if equal then it is required to be an exact match,
  2409. if (c > 0)
  2410. {
  2411. if (!requireExactMatch || isCompleteMatch())
  2412. break;
  2413. }
  2414. else if ((c == 0) && isCompleteMatch())
  2415. break;
  2416. skipped++;
  2417. if (!next())
  2418. break;
  2419. }
  2420. return skipped;
  2421. }
  2422. };
  2423. CRemoteResultAdaptor &adaptor;
  2424. CIArrayOf<HeapEntry> heapEntries;
  2425. UnsignedArray heap;
  2426. IRowManager *rowManager;
  2427. unsigned numPending;
  2428. unsigned numFields;
  2429. bool endSeen;
  2430. bool remakePending;
  2431. IRangeCompare *compare;
  2432. bool deferredContinuation;
  2433. inline int doCompare(unsigned l, unsigned r)
  2434. {
  2435. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  2436. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  2437. return ret;
  2438. }
  2439. void makeHeap()
  2440. {
  2441. /* Permute blocks to establish the heap property
  2442. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  2443. The children of p must both be greater than or equal to p
  2444. The parent of a child c is given by p = (c-1)/2
  2445. */
  2446. unsigned i;
  2447. unsigned n = heap.length();
  2448. unsigned *s = heap.getArray();
  2449. for (i=1; i<n; i++)
  2450. {
  2451. unsigned r = s[i];
  2452. int c = i; /* child */
  2453. while (c > 0)
  2454. {
  2455. int p = (c-1)/2; /* parent */
  2456. if ( doCompare( s[c], s[p] ) >= 0 )
  2457. break;
  2458. s[c] = s[p];
  2459. s[p] = r;
  2460. c = p;
  2461. }
  2462. }
  2463. remakePending = false;
  2464. }
  2465. void remakeHeap()
  2466. {
  2467. /* The row associated with block[0] will have changed
  2468. This code restores the heap property
  2469. */
  2470. unsigned p = 0; /* parent */
  2471. unsigned n = heap.length();
  2472. unsigned *s = heap.getArray();
  2473. while (1)
  2474. {
  2475. unsigned c = p*2 + 1; /* child */
  2476. if ( c >= n )
  2477. break;
  2478. /* Select smaller child */
  2479. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  2480. /* If child is greater or equal than parent then we are done */
  2481. if ( doCompare( s[c], s[p] ) >= 0 )
  2482. break;
  2483. /* Swap parent and child */
  2484. unsigned r = s[c];
  2485. s[c] = s[p];
  2486. s[p] = r;
  2487. /* child becomes parent */
  2488. p = c;
  2489. }
  2490. remakePending = false;
  2491. }
  2492. void append(IRoxieServerQueryPacket *p, unsigned seq)
  2493. {
  2494. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  2495. IMessageResult *result = p->queryResult();
  2496. assertex(result);
  2497. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2498. {
  2499. heapEntries.append(h);
  2500. heap.append(heap.ordinality());
  2501. }
  2502. else
  2503. h.Release();
  2504. }
  2505. void removeHeap(unsigned idx)
  2506. {
  2507. heapEntries.remove(idx);
  2508. ForEachItemIn(i, heap)
  2509. {
  2510. unsigned v = heap.item(i);
  2511. assertex(v != idx);
  2512. if (v > idx)
  2513. heap.replace(v-1, i);
  2514. }
  2515. }
  2516. bool isCompleteMatchFlag(IMessageResult *result)
  2517. {
  2518. unsigned metaLen;
  2519. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  2520. if (metaLen)
  2521. {
  2522. unsigned short continuationLen = *(unsigned short *) metaInfo;
  2523. if (continuationLen >= sizeof(bool))
  2524. {
  2525. metaInfo += sizeof(unsigned short);
  2526. return *(bool *) metaInfo;
  2527. }
  2528. }
  2529. return true; // if no continuation info, last row was complete.
  2530. }
  2531. public:
  2532. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  2533. {
  2534. init(NULL, NULL);
  2535. }
  2536. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  2537. {
  2538. if (meta)
  2539. {
  2540. numFields = meta->getNumFields();
  2541. compare = meta->queryCompare();
  2542. }
  2543. else
  2544. {
  2545. numFields = 0;
  2546. compare = NULL;
  2547. }
  2548. rowManager = _rowManager;
  2549. numPending = 0;
  2550. endSeen = false;
  2551. remakePending = false;
  2552. deferredContinuation = false;
  2553. }
  2554. void reset()
  2555. {
  2556. heapEntries.kill();
  2557. heap.kill();
  2558. numPending = 0;
  2559. endSeen = false;
  2560. remakePending = false;
  2561. deferredContinuation = false;
  2562. }
  2563. inline bool noteEndSeen()
  2564. {
  2565. bool hadSeen = endSeen;
  2566. if (!endSeen)
  2567. makeHeap();
  2568. endSeen = true;
  2569. return !hadSeen;
  2570. }
  2571. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  2572. {
  2573. if (!p->isContinuation())
  2574. append(p, seq);
  2575. else
  2576. {
  2577. ForEachItemIn(idx, heapEntries)
  2578. {
  2579. HeapEntry &h = heapEntries.item(idx);
  2580. if (h.packet == p)
  2581. {
  2582. IMessageResult *result = p->queryResult();
  2583. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  2584. {
  2585. heap.zap(idx);
  2586. removeHeap(idx);
  2587. }
  2588. numPending--;
  2589. if (!numPending)
  2590. makeHeap();
  2591. return;
  2592. }
  2593. }
  2594. }
  2595. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  2596. return;
  2597. }
  2598. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  2599. {
  2600. HeapEntry &entry = heapEntries.item(idx);
  2601. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  2602. if (!entry.current)
  2603. {
  2604. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  2605. if (continuation)
  2606. {
  2607. continuation->Link();
  2608. entry.packet->Release();
  2609. entry.packet = continuation;
  2610. if (continuation->hasResult())
  2611. {
  2612. IMessageResult *result = continuation->queryResult();
  2613. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2614. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2615. }
  2616. else
  2617. {
  2618. if (continuation->isDelayed())
  2619. {
  2620. continuation->setDelayed(false);
  2621. MemoryBuffer serializedSkip;
  2622. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  2623. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  2624. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2625. adaptor.sentsome.signal();
  2626. }
  2627. numPending++;
  2628. }
  2629. }
  2630. else
  2631. {
  2632. heap.zap(idx);
  2633. removeHeap(idx);
  2634. idx--;
  2635. }
  2636. }
  2637. return skipped;
  2638. }
  2639. const void * nextSteppedGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  2640. {
  2641. // We discard all rows < seekval from all entries in heap
  2642. // If this results in additional slave requests, we return NULL so that we can wait for them
  2643. // If not, we rebuild the heap (if any were skipped) and return the first row
  2644. deferredContinuation = false;
  2645. if (heap.length())
  2646. {
  2647. unsigned skipped = 0;
  2648. unsigned idx = 0;
  2649. while(heapEntries.isItem(idx))
  2650. {
  2651. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  2652. idx++;
  2653. }
  2654. if (numPending)
  2655. return NULL; // can't answer yet, need more results from slaves
  2656. else
  2657. {
  2658. if (skipped)
  2659. makeHeap();
  2660. return next(wasCompleteMatch, stepExtra);
  2661. }
  2662. }
  2663. else
  2664. return NULL;
  2665. }
  2666. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  2667. {
  2668. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  2669. if (continuation)
  2670. {
  2671. if (continuation->isDelayed() && canDefer)
  2672. {
  2673. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2674. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  2675. deferredContinuation = true;
  2676. }
  2677. else
  2678. {
  2679. deferredContinuation = false;
  2680. continuation->Link();
  2681. topEntry.packet->Release();
  2682. topEntry.packet = continuation;
  2683. if (continuation->hasResult())
  2684. {
  2685. IMessageResult *result = continuation->queryResult();
  2686. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  2687. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  2688. }
  2689. else
  2690. {
  2691. if (continuation->isDelayed()) // has the continuation been requested yet?
  2692. {
  2693. continuation->Link();
  2694. topEntry.packet->Release();
  2695. topEntry.packet = continuation;
  2696. continuation->setDelayed(false);
  2697. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  2698. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  2699. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  2700. adaptor.sentsome.signal();
  2701. }
  2702. numPending++; // we are waiting for one that is already in flight
  2703. }
  2704. }
  2705. return true; // next not known yet
  2706. }
  2707. else
  2708. return false;
  2709. }
  2710. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  2711. {
  2712. OwnedConstRoxieRow ret;
  2713. if (heap.length())
  2714. {
  2715. if (deferredContinuation)
  2716. {
  2717. unsigned top = heap.item(0);
  2718. HeapEntry &topEntry = heapEntries.item(top);
  2719. doContinuation(topEntry, false);
  2720. return NULL;
  2721. }
  2722. if (remakePending)
  2723. remakeHeap();
  2724. unsigned top = heap.item(0);
  2725. HeapEntry &topEntry = heapEntries.item(top);
  2726. ret.set(topEntry.current);
  2727. wasCompleteMatch = topEntry.isCompleteMatch();
  2728. const void *next = topEntry.next();
  2729. if (!next)
  2730. {
  2731. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  2732. {
  2733. unsigned last = heap.pop();
  2734. if (heap.length())
  2735. heap.replace(last, 0);
  2736. removeHeap(top);
  2737. }
  2738. }
  2739. remakePending = true;
  2740. }
  2741. return ret.getClear();
  2742. }
  2743. bool ready()
  2744. {
  2745. return endSeen && numPending == 0;
  2746. }
  2747. };
  2748. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  2749. {
  2750. if (serverSideCache && !debugContext)
  2751. {
  2752. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  2753. if (ret)
  2754. {
  2755. p->Release();
  2756. cached = true;
  2757. return ret;
  2758. }
  2759. }
  2760. cached = false;
  2761. return new CRoxieServerQueryPacket(p);
  2762. }
  2763. #ifdef _DEBUG
  2764. void dumpPending()
  2765. {
  2766. CriticalBlock b(pendingCrit);
  2767. ForEachItemIn(idx, pending)
  2768. {
  2769. IRoxieServerQueryPacket &p = pending.item(idx);
  2770. StringBuffer s;
  2771. unsigned __int64 dummy;
  2772. if (p.isEnd())
  2773. s.append("END");
  2774. else if (p.isLimit(dummy, dummy, dummy))
  2775. s.append("LIMIT");
  2776. else
  2777. {
  2778. IRoxieQueryPacket *i = p.queryPacket();
  2779. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  2780. if (i)
  2781. {
  2782. RoxiePacketHeader &header = i->queryHeader();
  2783. header.toString(s);
  2784. }
  2785. }
  2786. DBGLOG("Pending %d %s", idx, s.str());
  2787. }
  2788. }
  2789. #endif
  2790. void abortPending()
  2791. {
  2792. CriticalBlock b(pendingCrit);
  2793. ForEachItemIn(idx, pending)
  2794. {
  2795. IRoxieServerQueryPacket &p = pending.item(idx);
  2796. if (!p.hasResult())
  2797. {
  2798. IRoxieQueryPacket *i = p.queryPacket();
  2799. if (i)
  2800. {
  2801. RoxiePacketHeader &header = i->queryHeader();
  2802. ROQ->sendAbort(header, activity.queryLogCtx());
  2803. }
  2804. }
  2805. }
  2806. pending.kill();
  2807. }
  2808. void checkDelayed()
  2809. {
  2810. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  2811. {
  2812. bool allDelayed = true;
  2813. CriticalBlock b(pendingCrit);
  2814. unsigned sendIdx = (unsigned) -1;
  2815. ForEachItemIn(idx, pending)
  2816. {
  2817. IRoxieServerQueryPacket &p = pending.item(idx);
  2818. if (p.queryPacket())
  2819. {
  2820. if (p.isDelayed())
  2821. {
  2822. if (sendIdx == (unsigned) -1)
  2823. sendIdx = idx;
  2824. }
  2825. else if (!p.hasResult())
  2826. {
  2827. allDelayed = false;
  2828. break;
  2829. }
  2830. }
  2831. }
  2832. if (allDelayed && sendIdx != (unsigned) -1)
  2833. {
  2834. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2835. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  2836. pending.item(sendIdx).setDelayed(false);
  2837. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  2838. sentsome.signal();
  2839. }
  2840. }
  2841. else if (deferredStart)
  2842. {
  2843. CriticalBlock b(pendingCrit);
  2844. ForEachItemIn(idx, pending)
  2845. {
  2846. IRoxieServerQueryPacket &p = pending.item(idx);
  2847. if (p.isDelayed())
  2848. {
  2849. if (activity.queryLogCtx().queryTraceLevel() > 10)
  2850. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  2851. p.setDelayed(false);
  2852. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  2853. sentsome.signal();
  2854. }
  2855. }
  2856. deferredStart = false;
  2857. }
  2858. }
  2859. void retryPending()
  2860. {
  2861. CriticalBlock b(pendingCrit);
  2862. checkDelayed();
  2863. ForEachItemIn(idx, pending)
  2864. {
  2865. IRoxieServerQueryPacket &p = pending.item(idx);
  2866. if (!p.hasResult() && !p.isDelayed())
  2867. {
  2868. IRoxieQueryPacket *i = p.queryPacket();
  2869. if (i)
  2870. {
  2871. if (!i->queryHeader().retry())
  2872. {
  2873. StringBuffer s;
  2874. IException *E = MakeStringException(ROXIE_MULTICAST_ERROR, "Failed to get response from slave(s) for %s in activity %d", i->queryHeader().toString(s).str(), queryId());
  2875. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  2876. throw E;
  2877. }
  2878. if (!localSlave)
  2879. {
  2880. ROQ->sendPacket(i, activity.queryLogCtx());
  2881. atomic_inc(&retriesSent);
  2882. }
  2883. }
  2884. }
  2885. }
  2886. }
  2887. class ChannelBuffer
  2888. {
  2889. protected:
  2890. unsigned bufferLeft;
  2891. MemoryBuffer buffer;
  2892. char *nextBuf;
  2893. unsigned overflowSequence;
  2894. unsigned channel; // == bonded channel
  2895. bool needsFlush;
  2896. InterruptableSemaphore flowController;
  2897. const CRemoteResultAdaptor &owner;
  2898. CriticalSection crit;
  2899. public:
  2900. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
  2901. {
  2902. overflowSequence = 0;
  2903. needsFlush = false;
  2904. bufferLeft = 0;
  2905. nextBuf = NULL;
  2906. }
  2907. void init(unsigned minSize)
  2908. {
  2909. assertex(!buffer.length());
  2910. if (minSize < MIN_PAYLOAD_SIZE)
  2911. minSize = MIN_PAYLOAD_SIZE;
  2912. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  2913. unsigned bufferSize = headerSize+minSize;
  2914. if (bufferSize < mtu_size)
  2915. bufferSize = mtu_size;
  2916. buffer.reserveTruncate(bufferSize);
  2917. bufferLeft = bufferSize - headerSize;
  2918. assertex(buffer.toByteArray());
  2919. nextBuf = (char *) buffer.toByteArray() + headerSize;
  2920. needsFlush = false;
  2921. }
  2922. inline IRoxieQueryPacket *flush()
  2923. {
  2924. CriticalBlock cb(crit);
  2925. Owned<IRoxieQueryPacket> ret;
  2926. if (needsFlush)
  2927. {
  2928. buffer.setLength(nextBuf - buffer.toByteArray());
  2929. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  2930. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  2931. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  2932. byte * tgt = (byte*)(h+1);
  2933. owner.copyHeader(tgt, channel);
  2934. ret.setown(createRoxiePacket(buffer));
  2935. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  2936. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  2937. else
  2938. overflowSequence++;
  2939. needsFlush = false;
  2940. bufferLeft = 0;
  2941. if (owner.flowControlled)
  2942. {
  2943. CriticalUnblock cub(crit);
  2944. while (!flowController.wait(1000))
  2945. {
  2946. StringBuffer s;
  2947. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  2948. }
  2949. }
  2950. }
  2951. return ret.getClear();
  2952. }
  2953. inline void signal()
  2954. {
  2955. if (owner.flowControlled)
  2956. flowController.signal();
  2957. }
  2958. inline void interrupt(IException *e)
  2959. {
  2960. flowController.interrupt(e);
  2961. }
  2962. inline void *getBuffer(unsigned size)
  2963. {
  2964. CriticalBlock cb(crit);
  2965. if (bufferLeft >= size)
  2966. {
  2967. needsFlush = true;
  2968. void * ret = nextBuf;
  2969. nextBuf += size;
  2970. bufferLeft -= size;
  2971. return ret;
  2972. }
  2973. else if (!needsFlush)
  2974. {
  2975. init(size);
  2976. return getBuffer(size);
  2977. }
  2978. else if (owner.mergeOrder)
  2979. {
  2980. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  2981. }
  2982. else
  2983. return NULL; // will force it to flush and start a new packet
  2984. }
  2985. };
  2986. private:
  2987. friend class CRemoteResultMerger;
  2988. bool allread;
  2989. bool contextCached;
  2990. bool preserveOrder;
  2991. InterruptableSemaphore sentsome;
  2992. Owned <IMessageCollator> mc;
  2993. Owned<IMessageUnpackCursor> mu;
  2994. Owned<IMessageResult> mr;
  2995. ChannelBuffer **buffers;
  2996. IHThorArg &helper;
  2997. unsigned __int64 stopAfter;
  2998. unsigned resendSequence;
  2999. IHThorArg *colocalArg;
  3000. IArrayOf<IRoxieServerQueryPacket> pending;
  3001. CriticalSection pendingCrit;
  3002. IRoxieServerSideCache *serverSideCache;
  3003. unsigned sentSequence;
  3004. Owned<IOutputRowDeserializer> deserializer;
  3005. Owned<IEngineRowAllocator> rowAllocator;
  3006. CRemoteResultMerger merger;
  3007. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3008. MemoryBuffer tempRowBuffer;
  3009. Owned<ISerialStream> bufferStream;
  3010. CThorStreamDeserializerSource rowSource;
  3011. protected:
  3012. IRowManager *rowManager;
  3013. IRoxieInput *owner;
  3014. unsigned __int64 rowLimit;
  3015. unsigned __int64 keyedLimit;
  3016. IRoxieServerErrorHandler *errorHandler;
  3017. CachedOutputMetaData meta;
  3018. public:
  3019. ISteppingMeta *mergeOrder;
  3020. IRoxieSlaveContext *ctx;
  3021. IDebuggableContext *debugContext;
  3022. IRoxieServerActivity &activity;
  3023. unsigned parentExtractSize;
  3024. const byte * parentExtract;
  3025. bool flowControlled;
  3026. bool deferredStart;
  3027. MemoryBuffer logInfo;
  3028. MemoryBuffer cachedContext;
  3029. const RemoteActivityId &remoteId;
  3030. ruid_t ruid;
  3031. mutable CriticalSection buffersCrit;
  3032. unsigned processed;
  3033. unsigned __int64 totalCycles;
  3034. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3035. const void *getRow(IMessageUnpackCursor *mu)
  3036. {
  3037. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3038. return mu->getNext(meta.getFixedSize());
  3039. else
  3040. {
  3041. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3042. if (rowlen)
  3043. {
  3044. RecordLengthType len = *rowlen;
  3045. ReleaseRoxieRow(rowlen);
  3046. const void *slaveRec = mu->getNext(len);
  3047. if (deserializer && mu->isSerialized())
  3048. {
  3049. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3050. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3051. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3052. ReleaseRoxieRow(slaveRec);
  3053. return rowBuilder.finalizeRowClear(outsize);
  3054. }
  3055. else
  3056. return slaveRec;
  3057. }
  3058. else
  3059. return NULL;
  3060. }
  3061. }
  3062. private:
  3063. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3064. {
  3065. CriticalBlock cb(buffersCrit);
  3066. ChannelBuffer *b = buffers[channel];
  3067. if (!b && force)
  3068. {
  3069. if (!contextCached)
  3070. {
  3071. logInfo.clear();
  3072. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3073. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3074. if (activity.queryLogCtx().isIntercepted())
  3075. loggingFlags |= LOGGING_INTERCEPTED;
  3076. if (ctx->queryTimeActivities())
  3077. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3078. if (activity.queryLogCtx().isBlind())
  3079. loggingFlags |= LOGGING_BLIND;
  3080. if (ctx->queryCheckingHeap())
  3081. loggingFlags |= LOGGING_CHECKINGHEAP;
  3082. if (ctx->queryWorkUnit())
  3083. loggingFlags |= LOGGING_WUID;
  3084. if (debugContext)
  3085. {
  3086. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3087. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3088. MemoryBuffer bpInfo;
  3089. debugContext->serialize(bpInfo);
  3090. bpInfo.append((__uint64)(memsize_t) &activity);
  3091. logInfo.append((unsigned short) bpInfo.length());
  3092. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3093. }
  3094. else
  3095. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3096. StringBuffer logPrefix;
  3097. activity.queryLogCtx().getLogPrefix(logPrefix);
  3098. logInfo.append(logPrefix);
  3099. activity.serializeCreateStartContext(cachedContext.clear());
  3100. activity.serializeExtra(cachedContext);
  3101. if (activity.queryVarFileInfo())
  3102. {
  3103. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3104. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3105. }
  3106. contextCached = true;
  3107. }
  3108. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3109. }
  3110. return b;
  3111. }
  3112. void processRow(const void *got)
  3113. {
  3114. processed++;
  3115. if (processed > rowLimit)
  3116. {
  3117. ReleaseRoxieRow(got);
  3118. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3119. throwUnexpected();
  3120. }
  3121. else if (processed > keyedLimit)
  3122. {
  3123. ReleaseRoxieRow(got);
  3124. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3125. throwUnexpected();
  3126. }
  3127. }
  3128. public:
  3129. IMPLEMENT_IINTERFACE;
  3130. CRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3131. : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
  3132. {
  3133. rowLimit = (unsigned __int64) -1;
  3134. keyedLimit = (unsigned __int64) -1;
  3135. contextCached = false;
  3136. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3137. buffers = new ChannelBuffer*[numChannels+1];
  3138. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3139. parentExtractSize = 0;
  3140. parentExtract = NULL;
  3141. owner = NULL;
  3142. mergeOrder = NULL;
  3143. deferredStart = false;
  3144. processed = 0;
  3145. totalCycles = 0;
  3146. sentSequence = 0;
  3147. serverSideCache = activity.queryServerSideCache();
  3148. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3149. rowSource.setStream(bufferStream);
  3150. }
  3151. ~CRemoteResultAdaptor()
  3152. {
  3153. if (mc)
  3154. {
  3155. ROQ->queryReceiveManager()->detachCollator(mc);
  3156. mc.clear();
  3157. }
  3158. for (unsigned channel = 0; channel <= numChannels; channel++)
  3159. {
  3160. delete(buffers[channel]);
  3161. }
  3162. delete [] buffers;
  3163. }
  3164. void setMeta(IOutputMetaData *newmeta)
  3165. {
  3166. meta.set(newmeta);
  3167. }
  3168. virtual IRoxieServerActivity *queryActivity()
  3169. {
  3170. return &activity;
  3171. }
  3172. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3173. {
  3174. return NULL;
  3175. }
  3176. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3177. {
  3178. mergeOrder = _mergeOrder;
  3179. deferredStart = true;
  3180. }
  3181. void send(IRoxieQueryPacket *p)
  3182. {
  3183. if (p)
  3184. {
  3185. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3186. assertex(p->queryHeader().uid==ruid);
  3187. // MORE: Maybe we should base the fastlane flag on some other
  3188. // criteria !! (i.e A Roxie server prediction based on the
  3189. // activity type/activity behaviour/expected reply size .. etc).
  3190. //
  3191. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3192. // But this could still cause too many reply packets on the fatlane
  3193. // (higher priority output Q), which may cause the activities on the
  3194. // low priority output Q to not get service on time.
  3195. if ((colocalArg == 0) && // not a child query activity??
  3196. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3197. (p->queryHeader().overflowSequence == 0) &&
  3198. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3199. p->queryHeader().retries |= ROXIE_FASTLANE;
  3200. if (p->queryHeader().channel)
  3201. {
  3202. bool cached = false;
  3203. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3204. if (deferredStart)
  3205. rsqp->setDelayed(true);
  3206. rsqp->setSequence(sentSequence++);
  3207. {
  3208. CriticalBlock b(pendingCrit);
  3209. pending.append(*rsqp);
  3210. }
  3211. if (!deferredStart)
  3212. {
  3213. if (!cached)
  3214. ROQ->sendPacket(p, activity.queryLogCtx());
  3215. sentsome.signal();
  3216. }
  3217. }
  3218. else
  3219. {
  3220. // Care is needed here. If I send the packet before I add to the pending there is a danger that I'll get results that I discard
  3221. // Need to add first, then send
  3222. unsigned i;
  3223. bool allCached = true;
  3224. for (i = 1; i <= numChannels; i++)
  3225. {
  3226. IRoxieQueryPacket *q = p->clonePacket(i);
  3227. bool thisChannelCached;
  3228. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3229. if (!thisChannelCached)
  3230. allCached = false;
  3231. rsqp->setSequence(sentSequence++);
  3232. if (deferredStart)
  3233. {
  3234. rsqp->setDelayed(true);
  3235. }
  3236. {
  3237. CriticalBlock b(pendingCrit);
  3238. pending.append(*rsqp);
  3239. }
  3240. if (!deferredStart)
  3241. sentsome.signal();
  3242. }
  3243. if (!allCached && !deferredStart)
  3244. ROQ->sendPacket(p, activity.queryLogCtx());
  3245. buffers[0]->signal(); // since replies won't come back on that channel...
  3246. p->Release();
  3247. }
  3248. }
  3249. }
  3250. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3251. {
  3252. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3253. size += sizeof(PartNoType);
  3254. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3255. char *buffer = (char *) b->getBuffer(size);
  3256. if (!buffer)
  3257. {
  3258. send(b->flush());
  3259. buffer = (char *) b->getBuffer(size);
  3260. }
  3261. PartNoType sp;
  3262. sp.partNo = partNo;
  3263. sp.fileNo = fileNo;
  3264. memcpy(buffer, &sp, sizeof(sp));
  3265. buffer += sizeof(sp);
  3266. return buffer;
  3267. }
  3268. void injectResult(IMessageResult *result)
  3269. {
  3270. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3271. f->setSequence(sentSequence++);
  3272. f->setResult(result);
  3273. CriticalBlock b(pendingCrit);
  3274. pending.append(*f);
  3275. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3276. }
  3277. void flush()
  3278. {
  3279. for (unsigned channel = 0; channel <= numChannels; channel++)
  3280. {
  3281. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3282. if (b)
  3283. send(b->flush());
  3284. }
  3285. }
  3286. void interruptBuffers(IException *e)
  3287. {
  3288. for (unsigned channel = 0; channel <= numChannels; channel++)
  3289. {
  3290. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3291. if (b)
  3292. b->interrupt(LINK(e));
  3293. }
  3294. }
  3295. void senddone()
  3296. {
  3297. CriticalBlock b(pendingCrit);
  3298. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3299. sentsome.signal();
  3300. }
  3301. bool fireException(IException *e)
  3302. {
  3303. {
  3304. CriticalBlock b(pendingCrit);
  3305. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3306. }
  3307. interruptBuffers(e);
  3308. if (mc)
  3309. mc->interrupt(LINK(e));
  3310. sentsome.interrupt(e);
  3311. return true;
  3312. }
  3313. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  3314. {
  3315. owner = _owner;
  3316. errorHandler = _errorHandler;
  3317. ctx = _ctx;
  3318. debugContext = ctx->queryDebugContext();
  3319. colocalArg = _colocalArg;
  3320. if (meta.needsSerializeDisk())
  3321. {
  3322. deserializer.setown(meta.createDiskDeserializer(_ctx->queryCodeContext(), activity.queryId()));
  3323. rowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(meta.queryOriginal(), activity.queryId()));
  3324. }
  3325. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3326. deferredStart = true;
  3327. }
  3328. virtual unsigned queryId() const
  3329. {
  3330. return owner->queryId();
  3331. }
  3332. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3333. {
  3334. #ifdef TRACE_STARTSTOP
  3335. if (traceStartStop)
  3336. activity.queryLogCtx().CTXLOG("RRAonstart");
  3337. #endif
  3338. sentsome.reinit();
  3339. ruid = getNextRuid();
  3340. rowManager = &ctx->queryRowManager();
  3341. if (mergeOrder)
  3342. merger.init(mergeOrder, rowManager);
  3343. if (mc)
  3344. {
  3345. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  3346. }
  3347. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  3348. allread = false;
  3349. mu.clear();
  3350. contextCached = false;
  3351. processed = 0;
  3352. totalCycles = 0;
  3353. resendSequence = 0;
  3354. sentSequence = 0;
  3355. for (unsigned channel = 0; channel <= numChannels; channel++)
  3356. {
  3357. delete(buffers[channel]);
  3358. buffers[channel] = NULL;
  3359. }
  3360. flush();
  3361. parentExtractSize = _parentExtractSize;
  3362. parentExtract = _parentExtract;
  3363. }
  3364. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  3365. {
  3366. #ifdef TRACE_STARTSTOP
  3367. if (traceStartStop)
  3368. activity.queryLogCtx().CTXLOG("RRAstart");
  3369. #endif
  3370. owner->start(parentExtractSize, parentExtract, paused);
  3371. totalCycles = 0;
  3372. }
  3373. void checkAbort()
  3374. {
  3375. owner->checkAbort();
  3376. }
  3377. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  3378. {
  3379. if (ctx->queryProbeManager())
  3380. {
  3381. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  3382. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  3383. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  3384. }
  3385. {
  3386. CriticalBlock b(pendingCrit);
  3387. if (pending.length())
  3388. {
  3389. #ifdef _DEBUG
  3390. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  3391. #endif
  3392. assertex(pending.length()==0);
  3393. }
  3394. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  3395. }
  3396. sentsome.signal();
  3397. rowLimit = _rowLimit;
  3398. keyedLimit = _keyedLimit;
  3399. stopAfter = _stopAfter;
  3400. }
  3401. virtual void stop(bool aborting)
  3402. {
  3403. #ifdef TRACE_STARTSTOP
  3404. if (traceStartStop)
  3405. activity.queryLogCtx().CTXLOG("RRAstop");
  3406. #endif
  3407. onStop(aborting);
  3408. owner->stop(aborting);
  3409. }
  3410. void onStop(bool aborting)
  3411. {
  3412. #ifdef TRACE_STARTSTOP
  3413. if (traceStartStop)
  3414. activity.queryLogCtx().CTXLOG("RRAonstop");
  3415. #endif
  3416. abortPending();
  3417. interruptBuffers(NULL);
  3418. sentsome.interrupt();
  3419. if (mc) // May not be set if start() chain threw exception
  3420. mc->interrupt();
  3421. }
  3422. virtual void reset()
  3423. {
  3424. #ifdef TRACE_STARTSTOP
  3425. if (traceStartStop)
  3426. activity.queryLogCtx().CTXLOG("RRAreset");
  3427. #endif
  3428. owner->reset();
  3429. onReset();
  3430. }
  3431. virtual void resetEOF()
  3432. {
  3433. throwUnexpected();
  3434. }
  3435. virtual void onReset()
  3436. {
  3437. #ifdef TRACE_STARTSTOP
  3438. if (traceStartStop)
  3439. activity.queryLogCtx().CTXLOG("RRAonreset");
  3440. #endif
  3441. if (mc)
  3442. ROQ->queryReceiveManager()->detachCollator(mc);
  3443. merger.reset();
  3444. pending.kill();
  3445. if (mc && ctx)
  3446. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  3447. mc.clear(); // Or we won't free memory for graphs that get recreated
  3448. mu.clear(); //ditto
  3449. deferredStart = false;
  3450. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  3451. }
  3452. virtual IOutputMetaData * queryOutputMeta() const
  3453. {
  3454. return helper.queryOutputMeta();
  3455. }
  3456. virtual unsigned __int64 queryTotalCycles() const
  3457. {
  3458. return totalCycles;
  3459. }
  3460. virtual unsigned __int64 queryLocalCycles() const
  3461. {
  3462. return owner->queryLocalCycles();
  3463. }
  3464. virtual IRoxieInput *queryInput(unsigned idx) const
  3465. {
  3466. return owner->queryInput(idx);
  3467. }
  3468. const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3469. {
  3470. if (activity.queryLogCtx().queryTraceLevel() > 20)
  3471. {
  3472. StringBuffer recstr;
  3473. unsigned i;
  3474. for (i = 0; i < seekLen; i++)
  3475. {
  3476. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  3477. }
  3478. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextSteppedGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  3479. }
  3480. assertex(mergeOrder);
  3481. if (deferredStart)
  3482. {
  3483. CriticalBlock b(pendingCrit);
  3484. ForEachItemIn(idx, pending)
  3485. {
  3486. IRoxieServerQueryPacket &p = pending.item(idx);
  3487. if (p.isDelayed())
  3488. {
  3489. p.setDelayed(false);
  3490. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3491. activity.queryLogCtx().CTXLOG("About to send deferred start from nextSteppedGE, setting requireExact to %d", !stepExtra.returnMismatches());
  3492. MemoryBuffer serializedSkip;
  3493. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3494. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3495. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3496. sentsome.signal();
  3497. }
  3498. }
  3499. deferredStart = false;
  3500. }
  3501. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3502. if (processed==stopAfter)
  3503. return NULL;
  3504. if (allread)
  3505. return NULL;
  3506. loop
  3507. {
  3508. if (merger.ready())
  3509. {
  3510. const void *got = merger.nextSteppedGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  3511. if (got)
  3512. {
  3513. processRow(got);
  3514. return got;
  3515. }
  3516. }
  3517. if (!reload()) // MORE - should pass the seek info here...
  3518. return NULL;
  3519. }
  3520. }
  3521. virtual const void *nextInGroup()
  3522. {
  3523. // If we are merging then we need to do a heapsort on all
  3524. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  3525. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3526. {
  3527. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextInGroup()");
  3528. }
  3529. loop
  3530. {
  3531. checkDelayed();
  3532. if (processed==stopAfter)
  3533. return NULL;
  3534. if (allread)
  3535. return NULL;
  3536. // If we can still consume from the merger or the most recently retrieved mu, do so.
  3537. const void *got = NULL;
  3538. if (mergeOrder && merger.ready())
  3539. {
  3540. bool matched = true;
  3541. got = merger.next(matched, dummySmartStepExtra);
  3542. }
  3543. else if (mu)
  3544. got = getRow(mu);
  3545. if (got)
  3546. {
  3547. processRow(got);
  3548. return got;
  3549. }
  3550. if (!reload())
  3551. return NULL;
  3552. }
  3553. }
  3554. bool reload()
  3555. {
  3556. // Wait for something to be returned from a slave....
  3557. mu.clear();
  3558. sentsome.wait();
  3559. // must be at least an endMarker on the queue since sentsome was signalled
  3560. {
  3561. CriticalBlock b(pendingCrit);
  3562. IRoxieServerQueryPacket &top = pending.item(0);
  3563. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  3564. {
  3565. pending.remove(0);
  3566. return true;
  3567. }
  3568. else if (top.isEnd())
  3569. {
  3570. pending.remove(0);
  3571. allread = true;
  3572. if (activity.queryLogCtx().queryTraceLevel() > 5)
  3573. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  3574. return false;
  3575. }
  3576. else if (mergeOrder)
  3577. {
  3578. unsigned idx = 0;
  3579. bool added = false;
  3580. while (pending.isItem(idx))
  3581. {
  3582. IRoxieServerQueryPacket &item = pending.item(idx);
  3583. if (item.isEnd())
  3584. {
  3585. if (merger.noteEndSeen())
  3586. {
  3587. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  3588. added = true;
  3589. }
  3590. break;
  3591. }
  3592. else if (item.hasResult())
  3593. {
  3594. merger.noteResult(&item, item.getSequence());
  3595. pending.remove(idx);
  3596. added = true;
  3597. }
  3598. else if (item.isContinuation())
  3599. idx++;
  3600. else
  3601. break;
  3602. }
  3603. if (added)
  3604. return true;
  3605. }
  3606. else if (top.hasResult())
  3607. {
  3608. mr.setown(pending.item(0).getResult());
  3609. mu.setown(mr->getCursor(rowManager));
  3610. pending.remove(0);
  3611. return true;
  3612. }
  3613. }
  3614. getNextUnpacker();
  3615. return true;
  3616. }
  3617. void getNextUnpacker()
  3618. {
  3619. mu.clear();
  3620. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  3621. loop
  3622. {
  3623. checkDelayed();
  3624. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  3625. owner->checkAbort();
  3626. bool anyActivity;
  3627. if (ctxTraceLevel > 5)
  3628. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  3629. mr.setown(mc->getNextResult(timeout, anyActivity));
  3630. if (ctxTraceLevel > 6)
  3631. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  3632. owner->checkAbort();
  3633. if (mr)
  3634. {
  3635. unsigned roxieHeaderLen;
  3636. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  3637. #ifdef _DEBUG
  3638. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  3639. #endif
  3640. if (ctxTraceLevel > 5)
  3641. {
  3642. StringBuffer s;
  3643. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  3644. }
  3645. CriticalBlock b(pendingCrit);
  3646. unsigned idx = 0;
  3647. IRoxieServerQueryPacket *original = NULL;
  3648. IRoxieQueryPacket *op;
  3649. while (pending.isItem(idx))
  3650. {
  3651. original = &pending.item(idx);
  3652. op = original->queryPacket();
  3653. if (op && header.matchPacket(op->queryHeader()))
  3654. break;
  3655. original = NULL;
  3656. idx++;
  3657. }
  3658. if (!original || original->hasResult())
  3659. {
  3660. switch (header.activityId)
  3661. {
  3662. case ROXIE_FILECALLBACK:
  3663. {
  3664. // tell slave to abort
  3665. //if (ctxTraceLevel > 5)
  3666. {
  3667. StringBuffer s;
  3668. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  3669. }
  3670. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3671. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3672. if (len)
  3673. {
  3674. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3675. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3676. const char *rowdata = (const char *) row.get();
  3677. // bool isOpt = * (bool *) rowdata;
  3678. // bool isLocal = * (bool *) (rowdata+1);
  3679. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  3680. }
  3681. else
  3682. throwUnexpected();
  3683. break;
  3684. }
  3685. // MORE - ROXIE_ALIVE perhaps should go here too
  3686. case ROXIE_TRACEINFO:
  3687. {
  3688. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3689. loop
  3690. {
  3691. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3692. if (rowlen)
  3693. {
  3694. char *logInfo = (char *) extra->getNext(*rowlen);
  3695. MemoryBuffer buf;
  3696. buf.setBuffer(*rowlen, logInfo, false);
  3697. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3698. ReleaseRoxieRow(rowlen);
  3699. ReleaseRoxieRow(logInfo);
  3700. }
  3701. else
  3702. break;
  3703. }
  3704. break;
  3705. }
  3706. default:
  3707. if (ctxTraceLevel > 3)
  3708. activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
  3709. mr->discard();
  3710. break;
  3711. }
  3712. mr.clear();
  3713. }
  3714. else
  3715. {
  3716. atomic_inc(&resultsReceived);
  3717. switch (header.activityId)
  3718. {
  3719. case ROXIE_DEBUGCALLBACK:
  3720. {
  3721. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3722. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3723. if (len)
  3724. {
  3725. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3726. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3727. char *rowdata = (char *) row.get();
  3728. if (ctxTraceLevel > 5)
  3729. {
  3730. StringBuffer s;
  3731. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  3732. }
  3733. MemoryBuffer slaveInfo;
  3734. slaveInfo.setBuffer(*rowlen, rowdata, false);
  3735. unsigned debugSequence;
  3736. slaveInfo.read(debugSequence);
  3737. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  3738. if (!reply)
  3739. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  3740. if (reply)
  3741. {
  3742. original->setDebugResponse(debugSequence, reply);
  3743. ROQ->sendPacket(reply, activity.queryLogCtx());
  3744. }
  3745. }
  3746. else
  3747. throwUnexpected();
  3748. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3749. // Leave original message on pending queue in original location - this is not a reply to it.
  3750. break;
  3751. }
  3752. case ROXIE_FILECALLBACK:
  3753. {
  3754. // we need to send back to the slave a message containing the file info requested.
  3755. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  3756. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  3757. if (len)
  3758. {
  3759. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  3760. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  3761. const char *rowdata = (const char *) row.get();
  3762. bool isOpt = * (bool *) rowdata;
  3763. bool isLocal = * (bool *) (rowdata+1);
  3764. const char *lfn = rowdata+2;
  3765. if (ctxTraceLevel > 5)
  3766. {
  3767. StringBuffer s;
  3768. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  3769. }
  3770. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  3771. }
  3772. else
  3773. throwUnexpected();
  3774. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  3775. // Leave original message on pending queue in original location - this is not a reply to it.
  3776. break;
  3777. }
  3778. case ROXIE_KEYEDLIMIT_EXCEEDED:
  3779. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  3780. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  3781. throwUnexpected();
  3782. case ROXIE_LIMIT_EXCEEDED:
  3783. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  3784. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  3785. throwUnexpected();
  3786. case ROXIE_TRACEINFO:
  3787. {
  3788. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  3789. loop
  3790. {
  3791. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  3792. if (rowlen)
  3793. {
  3794. char *logInfo = (char *) extra->getNext(*rowlen);
  3795. MemoryBuffer buf;
  3796. buf.setBuffer(*rowlen, logInfo, false);
  3797. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  3798. ReleaseRoxieRow(rowlen);
  3799. ReleaseRoxieRow(logInfo);
  3800. }
  3801. else
  3802. break;
  3803. }
  3804. break;
  3805. }
  3806. case ROXIE_EXCEPTION:
  3807. if (ctxTraceLevel > 1)
  3808. {
  3809. StringBuffer s;
  3810. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  3811. }
  3812. op->queryHeader().noteException(header.retries);
  3813. if (op->queryHeader().allChannelsFailed())
  3814. {
  3815. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  3816. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  3817. throwRemoteException(exceptionData);
  3818. }
  3819. // Leave it on pending queue in original location
  3820. break;
  3821. case ROXIE_ALIVE:
  3822. if (ctxTraceLevel > 4)
  3823. {
  3824. StringBuffer s;
  3825. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  3826. }
  3827. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  3828. // Leave it on pending queue in original location
  3829. break;
  3830. default:
  3831. if (header.retries & ROXIE_RETRIES_MASK)
  3832. atomic_inc(&retriesNeeded);
  3833. unsigned metaLen;
  3834. const void *metaData = mr->getMessageMetadata(metaLen);
  3835. if (metaLen)
  3836. {
  3837. // We got back first chunk but there is more.
  3838. // resend the packet, with the cursor info provided.
  3839. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  3840. if (ctxTraceLevel > 1)
  3841. {
  3842. StringBuffer s;
  3843. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3844. }
  3845. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  3846. {
  3847. StringBuffer s;
  3848. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  3849. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  3850. throwUnexpected();
  3851. }
  3852. MemoryBuffer nextQuery;
  3853. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  3854. nextQuery.append(metaLen, metaData);
  3855. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  3856. nextQuery.append(op->getContextLength(), op->queryContextData());
  3857. if (resendSequence == CONTINUESEQUENCE_MAX)
  3858. {
  3859. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  3860. resendSequence = 1;
  3861. }
  3862. else
  3863. resendSequence++;
  3864. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  3865. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  3866. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  3867. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  3868. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  3869. fqp->setSequence(original->getSequence());
  3870. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  3871. original->setContinuation(LINK(fqp));
  3872. if (mergeOrder)
  3873. fqp->setDelayed(true);
  3874. else
  3875. {
  3876. ROQ->sendPacket(resend, activity.queryLogCtx());
  3877. sentsome.signal();
  3878. }
  3879. // Note that we don't attempt to cache results that have continuation records - too tricky !
  3880. }
  3881. else
  3882. {
  3883. if (serverSideCache)
  3884. serverSideCache->noteCachedResult(original, mr);
  3885. }
  3886. unsigned channel = header.channel;
  3887. {
  3888. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  3889. if (b)
  3890. b->signal();
  3891. }
  3892. original->setResult(mr.getClear());
  3893. sentsome.signal();
  3894. return;
  3895. }
  3896. }
  3897. }
  3898. else
  3899. {
  3900. if (!anyActivity)
  3901. {
  3902. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  3903. retryPending();
  3904. }
  3905. }
  3906. }
  3907. }
  3908. inline unsigned headerLength() const
  3909. {
  3910. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  3911. }
  3912. void copyHeader(byte *tgt, unsigned channel) const
  3913. {
  3914. unsigned len = logInfo.length();
  3915. memcpy(tgt, logInfo.toByteArray(), len);
  3916. tgt += len;
  3917. *(unsigned *) tgt = parentExtractSize;
  3918. tgt += sizeof(unsigned);
  3919. memcpy(tgt, parentExtract, parentExtractSize);
  3920. tgt += parentExtractSize;
  3921. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  3922. tgt += cachedContext.length();
  3923. }
  3924. };
  3925. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  3926. {
  3927. Owned <IException> exception;
  3928. bool skipping;
  3929. ConstPointerArray buff;
  3930. unsigned index;
  3931. bool pulled;
  3932. void pullInput()
  3933. {
  3934. try
  3935. {
  3936. if (exception)
  3937. throw exception.getClear();
  3938. unsigned __int64 count = 0;
  3939. loop
  3940. {
  3941. const void * next = CRemoteResultAdaptor::nextInGroup();
  3942. if (next == NULL)
  3943. {
  3944. next = CRemoteResultAdaptor::nextInGroup();
  3945. if(next == NULL)
  3946. break;
  3947. buff.append(NULL);
  3948. }
  3949. count++;
  3950. if (count > rowLimit)
  3951. {
  3952. ReleaseRoxieRow(next);
  3953. ReleaseRoxieRowSet(buff);
  3954. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  3955. throwUnexpected();
  3956. }
  3957. else if (count > keyedLimit)
  3958. {
  3959. ReleaseRoxieRow(next);
  3960. ReleaseRoxieRowSet(buff);
  3961. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  3962. throwUnexpected();
  3963. }
  3964. buff.append(next);
  3965. }
  3966. }
  3967. catch (IException *E)
  3968. {
  3969. if (QUERYINTERFACE(E, LimitSkipException))
  3970. {
  3971. Owned<IException> cleanup = E;
  3972. ReleaseRoxieRowSet(buff);
  3973. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  3974. if (onfail)
  3975. buff.append(onfail);
  3976. }
  3977. else
  3978. throw;
  3979. }
  3980. pulled = true;
  3981. }
  3982. public:
  3983. CSkippableRemoteResultAdaptor(const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  3984. CRemoteResultAdaptor(_remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  3985. {
  3986. skipping = _skipping;
  3987. index = 0;
  3988. pulled = false;
  3989. }
  3990. void setException(IException *E)
  3991. {
  3992. exception.setown(E);
  3993. }
  3994. virtual void onReset()
  3995. {
  3996. while (buff.isItem(index))
  3997. ReleaseRoxieRow(buff.item(index++));
  3998. buff.kill();
  3999. pulled = false;
  4000. exception.clear();
  4001. CRemoteResultAdaptor::onReset();
  4002. }
  4003. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4004. {
  4005. index = 0;
  4006. pulled = false;
  4007. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4008. }
  4009. virtual const void * nextSteppedGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4010. {
  4011. // MORE - not sure what we need to do about the skip case... but we need at least this to prevent issues with exception getting lost
  4012. if (exception)
  4013. throw exception.getClear();
  4014. return CRemoteResultAdaptor::nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4015. }
  4016. virtual const void *nextInGroup()
  4017. {
  4018. if (skipping)
  4019. {
  4020. if(!pulled)
  4021. pullInput();
  4022. if(buff.isItem(index))
  4023. {
  4024. const void * next = buff.item(index++);
  4025. if(next)
  4026. processed++;
  4027. return next;
  4028. }
  4029. return NULL;
  4030. }
  4031. else
  4032. {
  4033. if (exception)
  4034. throw exception.getClear();
  4035. return CRemoteResultAdaptor::nextInGroup();
  4036. }
  4037. }
  4038. };
  4039. //=================================================================================
  4040. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4041. {
  4042. IHThorApplyArg &helper;
  4043. public:
  4044. CRoxieServerApplyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4045. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorApplyArg &) basehelper)
  4046. {
  4047. }
  4048. virtual void onExecute()
  4049. {
  4050. helper.start();
  4051. loop
  4052. {
  4053. const void * next = input->nextInGroup();
  4054. if (!next)
  4055. {
  4056. next = input->nextInGroup();
  4057. if (!next)
  4058. break;
  4059. }
  4060. helper.apply(next);
  4061. ReleaseRoxieRow(next);
  4062. }
  4063. helper.end();
  4064. }
  4065. };
  4066. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4067. {
  4068. bool isRoot;
  4069. public:
  4070. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4071. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4072. {
  4073. }
  4074. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4075. {
  4076. return new CRoxieServerApplyActivity(this, _probeManager);
  4077. }
  4078. virtual bool isSink() const
  4079. {
  4080. return isRoot;
  4081. }
  4082. };
  4083. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4084. {
  4085. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4086. }
  4087. //=================================================================================
  4088. class CRoxieServerNullActivity : public CRoxieServerActivity
  4089. {
  4090. public:
  4091. CRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4092. : CRoxieServerActivity(_factory, _probeManager)
  4093. {
  4094. }
  4095. virtual const void *nextInGroup()
  4096. {
  4097. return NULL;
  4098. }
  4099. };
  4100. IRoxieServerActivity * createRoxieServerNullActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4101. {
  4102. return new CRoxieServerNullActivity(_factory, _probeManager);
  4103. }
  4104. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4105. {
  4106. public:
  4107. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4108. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4109. {
  4110. }
  4111. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4112. {
  4113. return new CRoxieServerNullActivity(this, _probeManager);
  4114. }
  4115. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4116. {
  4117. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4118. }
  4119. };
  4120. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4121. {
  4122. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4123. }
  4124. //=================================================================================
  4125. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4126. {
  4127. public:
  4128. CRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4129. : CRoxieServerActivity(_factory, _probeManager)
  4130. {
  4131. }
  4132. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4133. {
  4134. return input->gatherConjunctions(collector);
  4135. }
  4136. virtual void resetEOF()
  4137. {
  4138. input->resetEOF();
  4139. }
  4140. virtual const void *nextInGroup()
  4141. {
  4142. const void * next = input->nextInGroup();
  4143. if (next)
  4144. processed++;
  4145. return next;
  4146. }
  4147. virtual bool isPassThrough()
  4148. {
  4149. return true;
  4150. }
  4151. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4152. {
  4153. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4154. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4155. if (next)
  4156. processed++;
  4157. return next;
  4158. }
  4159. IInputSteppingMeta * querySteppingMeta()
  4160. {
  4161. return input->querySteppingMeta();
  4162. }
  4163. };
  4164. IRoxieServerActivity * createRoxieServerPassThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4165. {
  4166. return new CRoxieServerPassThroughActivity(_factory, _probeManager);
  4167. }
  4168. //=================================================================================
  4169. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4170. {
  4171. protected:
  4172. bool eof;
  4173. bool first;
  4174. public:
  4175. CRoxieServerChildBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4176. : CRoxieServerActivity(_factory, _probeManager)
  4177. {
  4178. eof = false;
  4179. first = true;
  4180. }
  4181. ~CRoxieServerChildBaseActivity()
  4182. {
  4183. }
  4184. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4185. {
  4186. eof = false;
  4187. first = true;
  4188. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4189. }
  4190. };
  4191. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4192. {
  4193. public:
  4194. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4195. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4196. {
  4197. }
  4198. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4199. {
  4200. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4201. }
  4202. };
  4203. //=================================================================================
  4204. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4205. {
  4206. IHThorChildIteratorArg &helper;
  4207. public:
  4208. CRoxieServerChildIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4209. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4210. {
  4211. }
  4212. virtual bool needsAllocator() const { return true; }
  4213. virtual const void *nextInGroup()
  4214. {
  4215. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4216. if (eof)
  4217. return NULL;
  4218. bool ok;
  4219. if (first)
  4220. {
  4221. ok = helper.first();
  4222. first = false;
  4223. }
  4224. else
  4225. ok = helper.next();
  4226. try
  4227. {
  4228. while (ok)
  4229. {
  4230. processed++;
  4231. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4232. unsigned outSize = helper.transform(rowBuilder);
  4233. if (outSize)
  4234. return rowBuilder.finalizeRowClear(outSize);
  4235. ok = helper.next();
  4236. }
  4237. }
  4238. catch (IException *E)
  4239. {
  4240. throw makeWrappedException(E);
  4241. }
  4242. eof = true;
  4243. return NULL;
  4244. }
  4245. };
  4246. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4247. {
  4248. public:
  4249. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4250. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4251. {
  4252. }
  4253. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4254. {
  4255. return new CRoxieServerChildIteratorActivity(this, _probeManager);
  4256. }
  4257. };
  4258. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4259. {
  4260. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4261. }
  4262. //=================================================================================
  4263. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4264. {
  4265. IHThorChildNormalizeArg &helper;
  4266. public:
  4267. CRoxieServerChildNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4268. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4269. {
  4270. }
  4271. virtual bool needsAllocator() const { return true; }
  4272. virtual const void *nextInGroup()
  4273. {
  4274. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4275. if (eof)
  4276. return NULL;
  4277. bool ok;
  4278. if (first)
  4279. {
  4280. ok = helper.first();
  4281. first = false;
  4282. }
  4283. else
  4284. ok = helper.next();
  4285. if (ok)
  4286. {
  4287. try
  4288. {
  4289. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4290. do {
  4291. unsigned outSize = helper.transform(rowBuilder);
  4292. if (outSize)
  4293. {
  4294. processed++;
  4295. return rowBuilder.finalizeRowClear(outSize);
  4296. }
  4297. ok = helper.next();
  4298. }
  4299. while (ok);
  4300. }
  4301. catch (IException *E)
  4302. {
  4303. throw makeWrappedException(E);
  4304. }
  4305. }
  4306. eof = true;
  4307. return NULL;
  4308. }
  4309. };
  4310. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  4311. {
  4312. public:
  4313. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4314. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4315. {
  4316. }
  4317. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4318. {
  4319. return new CRoxieServerChildNormalizeActivity(this, _probeManager);
  4320. }
  4321. };
  4322. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4323. {
  4324. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4325. }
  4326. //=================================================================================
  4327. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  4328. {
  4329. IHThorChildAggregateArg &helper;
  4330. public:
  4331. CRoxieServerChildAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4332. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  4333. {
  4334. }
  4335. virtual bool needsAllocator() const { return true; }
  4336. virtual const void *nextInGroup()
  4337. {
  4338. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4339. if (eof)
  4340. return NULL;
  4341. eof = true;
  4342. processed++;
  4343. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4344. helper.clearAggregate(rowBuilder);
  4345. helper.processRows(rowBuilder);
  4346. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  4347. return rowBuilder.finalizeRowClear(finalSize);
  4348. }
  4349. };
  4350. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4351. {
  4352. public:
  4353. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4354. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4355. {
  4356. }
  4357. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4358. {
  4359. return new CRoxieServerChildAggregateActivity(this, _probeManager);
  4360. }
  4361. };
  4362. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4363. {
  4364. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4365. }
  4366. //=================================================================================
  4367. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  4368. {
  4369. IHThorChildGroupAggregateArg &helper;
  4370. RowAggregator aggregated;
  4371. public:
  4372. IMPLEMENT_IINTERFACE
  4373. CRoxieServerChildGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4374. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  4375. aggregated(helper, helper)
  4376. {
  4377. }
  4378. void processRow(const void * next)
  4379. {
  4380. aggregated.addRow(next);
  4381. }
  4382. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4383. {
  4384. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4385. aggregated.start(rowAllocator);
  4386. }
  4387. virtual void reset()
  4388. {
  4389. aggregated.reset();
  4390. CRoxieServerChildBaseActivity::reset();
  4391. }
  4392. virtual bool needsAllocator() const { return true; }
  4393. virtual const void *nextInGroup()
  4394. {
  4395. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4396. if (eof)
  4397. return NULL;
  4398. if (first)
  4399. {
  4400. helper.processRows(this);
  4401. first = false;
  4402. }
  4403. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  4404. if (next)
  4405. {
  4406. processed++;
  4407. return next->finalizeRowClear();
  4408. }
  4409. eof = true;
  4410. return NULL;
  4411. }
  4412. };
  4413. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  4414. {
  4415. public:
  4416. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4417. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4418. {
  4419. }
  4420. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4421. {
  4422. return new CRoxieServerChildGroupAggregateActivity(this, _probeManager);
  4423. }
  4424. };
  4425. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4426. {
  4427. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4428. }
  4429. //=================================================================================
  4430. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  4431. {
  4432. IHThorChildThroughNormalizeArg &helper;
  4433. const void * lastInput;
  4434. unsigned numProcessedLastGroup;
  4435. bool ok;
  4436. public:
  4437. CRoxieServerChildThroughNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4438. : CRoxieServerChildBaseActivity(_factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  4439. {
  4440. lastInput = NULL;
  4441. numProcessedLastGroup = 0;
  4442. ok = false;
  4443. }
  4444. virtual void stop(bool aborting)
  4445. {
  4446. CRoxieServerChildBaseActivity::stop(aborting);
  4447. ReleaseRoxieRow(lastInput);
  4448. lastInput = NULL;
  4449. }
  4450. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4451. {
  4452. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  4453. numProcessedLastGroup = processed;
  4454. ok = false;
  4455. }
  4456. virtual bool needsAllocator() const { return true; }
  4457. virtual const void *nextInGroup()
  4458. {
  4459. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4460. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4461. loop
  4462. {
  4463. if (ok)
  4464. ok = helper.next();
  4465. while (!ok)
  4466. {
  4467. ReleaseRoxieRow(lastInput);
  4468. lastInput = input->nextInGroup();
  4469. if (!lastInput)
  4470. {
  4471. if (numProcessedLastGroup != processed)
  4472. {
  4473. numProcessedLastGroup = processed;
  4474. return NULL;
  4475. }
  4476. lastInput = input->nextInGroup();
  4477. if (!lastInput)
  4478. return NULL;
  4479. }
  4480. ok = helper.first(lastInput);
  4481. }
  4482. try
  4483. {
  4484. do
  4485. {
  4486. unsigned outSize = helper.transform(rowBuilder);
  4487. if (outSize)
  4488. {
  4489. processed++;
  4490. return rowBuilder.finalizeRowClear(outSize);
  4491. }
  4492. ok = helper.next();
  4493. } while (ok);
  4494. }
  4495. catch (IException *E)
  4496. {
  4497. throw makeWrappedException(E);
  4498. }
  4499. }
  4500. }
  4501. };
  4502. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  4503. {
  4504. public:
  4505. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4506. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4507. {
  4508. }
  4509. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4510. {
  4511. return new CRoxieServerChildThroughNormalizeActivity(this, _probeManager);
  4512. }
  4513. };
  4514. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4515. {
  4516. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4517. }
  4518. //=================================================================================
  4519. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  4520. {
  4521. IHThorLinkedRawIteratorArg &helper;
  4522. public:
  4523. CRoxieServerLinkedRawIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4524. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  4525. {
  4526. }
  4527. virtual const void *nextInGroup()
  4528. {
  4529. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4530. const void *ret =helper.next();
  4531. if (ret)
  4532. {
  4533. LinkRoxieRow(ret);
  4534. processed++;
  4535. }
  4536. return ret;
  4537. }
  4538. };
  4539. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  4540. {
  4541. public:
  4542. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4543. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4544. {
  4545. }
  4546. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4547. {
  4548. return new CRoxieServerLinkedRawIteratorActivity(this, _probeManager);
  4549. }
  4550. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4551. {
  4552. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4553. }
  4554. };
  4555. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4556. {
  4557. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4558. }
  4559. //=================================================================================
  4560. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  4561. {
  4562. public:
  4563. CRoxieServerDatasetResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4564. : CRoxieServerActivity(_factory, _probeManager)
  4565. {
  4566. }
  4567. virtual const void *nextInGroup()
  4568. {
  4569. throwUnexpected();
  4570. }
  4571. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  4572. {
  4573. try
  4574. {
  4575. start(parentExtractSize, parentExtract, false);
  4576. {
  4577. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4578. MemoryBuffer result;
  4579. IRecordSize * inputMeta = input->queryOutputMeta();
  4580. loop
  4581. {
  4582. const void *nextrec = input->nextInGroup();
  4583. if (!nextrec)
  4584. {
  4585. nextrec = input->nextInGroup();
  4586. if (!nextrec)
  4587. break;
  4588. }
  4589. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  4590. ReleaseRoxieRow(nextrec);
  4591. }
  4592. retSize = result.length();
  4593. ret = result.detach();
  4594. }
  4595. stop(false);
  4596. reset();
  4597. }
  4598. catch(IException *E)
  4599. {
  4600. ctx->notifyAbort(E);
  4601. stop(true);
  4602. reset();
  4603. throw;
  4604. }
  4605. catch(...)
  4606. {
  4607. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  4608. ctx->notifyAbort(E);
  4609. stop(true);
  4610. reset();
  4611. throw;
  4612. }
  4613. }
  4614. };
  4615. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  4616. {
  4617. bool isRoot;
  4618. public:
  4619. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4620. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  4621. {
  4622. }
  4623. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4624. {
  4625. return new CRoxieServerDatasetResultActivity(this, _probeManager);
  4626. }
  4627. virtual bool isSink() const
  4628. {
  4629. return isRoot;
  4630. }
  4631. };
  4632. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  4633. {
  4634. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  4635. }
  4636. //=================================================================================
  4637. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  4638. {
  4639. IHThorInlineTableArg &helper;
  4640. __uint64 curRow;
  4641. __uint64 numRows;
  4642. public:
  4643. CRoxieServerInlineTableActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4644. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  4645. {
  4646. }
  4647. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4648. {
  4649. curRow = 0;
  4650. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4651. numRows = helper.numRows();
  4652. }
  4653. virtual bool needsAllocator() const { return true; }
  4654. virtual const void *nextInGroup()
  4655. {
  4656. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4657. // Filtering empty rows, returns the next valid row
  4658. while (curRow < numRows)
  4659. {
  4660. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4661. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  4662. if (outSize)
  4663. {
  4664. processed++;
  4665. return rowBuilder.finalizeRowClear(outSize);
  4666. }
  4667. }
  4668. return NULL;
  4669. }
  4670. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4671. {
  4672. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4673. }
  4674. };
  4675. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  4676. {
  4677. public:
  4678. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4679. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4680. {
  4681. }
  4682. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4683. {
  4684. return new CRoxieServerInlineTableActivity(this, _probeManager);
  4685. }
  4686. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4687. {
  4688. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  4689. }
  4690. };
  4691. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4692. {
  4693. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4694. }
  4695. //=================================================================================
  4696. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  4697. {
  4698. IHThorWorkunitReadArg &helper;
  4699. Owned<IWorkUnitRowReader> wuReader; // MORE - can we use IRoxieInput instead?
  4700. public:
  4701. CRoxieServerWorkUnitReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4702. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  4703. {
  4704. }
  4705. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  4706. {
  4707. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  4708. if (!ctx->queryServerContext())
  4709. {
  4710. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  4711. }
  4712. }
  4713. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4714. {
  4715. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4716. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  4717. OwnedRoxieString fromWuid(helper.getWUID());
  4718. if (fromWuid)
  4719. UNIMPLEMENTED;
  4720. wuReader.setown(ctx->getWorkunitRowReader(helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  4721. // MORE _ should that be in onCreate?
  4722. }
  4723. virtual void reset()
  4724. {
  4725. wuReader.clear();
  4726. CRoxieServerActivity::reset();
  4727. };
  4728. virtual bool needsAllocator() const { return true; }
  4729. virtual const void *nextInGroup()
  4730. {
  4731. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  4732. const void *ret = wuReader->nextInGroup();
  4733. if (ret)
  4734. processed++;
  4735. return ret;
  4736. }
  4737. virtual void setInput(unsigned idx, IRoxieInput *_in)
  4738. {
  4739. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  4740. }
  4741. };
  4742. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  4743. {
  4744. public:
  4745. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4746. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  4747. {
  4748. }
  4749. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  4750. {
  4751. return new CRoxieServerWorkUnitReadActivity(this, _probeManager);
  4752. }
  4753. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4754. {
  4755. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  4756. }
  4757. };
  4758. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  4759. {
  4760. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  4761. }
  4762. //=================================================================================
  4763. interface ILocalGraphEx : public IEclGraphResults
  4764. {
  4765. public:
  4766. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  4767. virtual IRoxieInput * createResultIterator(unsigned id) = 0;
  4768. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  4769. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id) = 0;
  4770. };
  4771. class CSafeRoxieInput : public CInterface, implements IRoxieInput
  4772. {
  4773. public:
  4774. CSafeRoxieInput(IRoxieInput * _input) : input(_input) {}
  4775. IMPLEMENT_IINTERFACE
  4776. virtual IOutputMetaData * queryOutputMeta() const
  4777. {
  4778. return input->queryOutputMeta();
  4779. }
  4780. virtual unsigned queryId() const
  4781. {
  4782. return input->queryId();
  4783. }
  4784. virtual unsigned __int64 queryTotalCycles() const
  4785. {
  4786. return input->queryTotalCycles();
  4787. }
  4788. virtual unsigned __int64 queryLocalCycles() const
  4789. {
  4790. return input->queryLocalCycles();
  4791. }
  4792. virtual IRoxieInput *queryInput(unsigned idx) const
  4793. {
  4794. return input->queryInput(idx);
  4795. }
  4796. virtual IRoxieServerActivity *queryActivity()
  4797. {
  4798. return input->queryActivity();
  4799. }
  4800. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4801. {
  4802. return input->queryIndexReadActivity();
  4803. }
  4804. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4805. {
  4806. CriticalBlock procedure(cs);
  4807. input->start(parentExtractSize, parentExtract, paused);
  4808. }
  4809. virtual void stop(bool aborting)
  4810. {
  4811. CriticalBlock procedure(cs);
  4812. input->stop(aborting);
  4813. }
  4814. virtual void reset()
  4815. {
  4816. CriticalBlock procedure(cs);
  4817. input->reset();
  4818. }
  4819. virtual void resetEOF()
  4820. {
  4821. CriticalBlock procedure(cs);
  4822. input->resetEOF();
  4823. }
  4824. virtual void checkAbort()
  4825. {
  4826. CriticalBlock procedure(cs);
  4827. input->checkAbort();
  4828. }
  4829. virtual const void *nextInGroup()
  4830. {
  4831. CriticalBlock procedure(cs);
  4832. return input->nextInGroup();
  4833. }
  4834. virtual bool nextGroup(ConstPointerArray & group)
  4835. {
  4836. CriticalBlock procedure(cs);
  4837. return input->nextGroup(group);
  4838. }
  4839. private:
  4840. CriticalSection cs;
  4841. Linked<IRoxieInput> input;
  4842. };
  4843. //=================================================================================
  4844. class CPseudoRoxieInput : public CInterface, implements IRoxieInput
  4845. {
  4846. protected:
  4847. unsigned __int64 totalCycles;
  4848. public:
  4849. IMPLEMENT_IINTERFACE;
  4850. CPseudoRoxieInput()
  4851. {
  4852. totalCycles = 0;
  4853. }
  4854. virtual unsigned __int64 queryTotalCycles() const
  4855. {
  4856. return totalCycles;
  4857. }
  4858. virtual unsigned __int64 queryLocalCycles() const
  4859. {
  4860. return totalCycles;
  4861. }
  4862. virtual IRoxieInput *queryInput(unsigned idx) const
  4863. {
  4864. return NULL;
  4865. }
  4866. virtual IRoxieServerActivity *queryActivity()
  4867. {
  4868. throwUnexpected();
  4869. }
  4870. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  4871. {
  4872. throwUnexpected();
  4873. }
  4874. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  4875. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  4876. virtual void stop(bool aborting) { }
  4877. virtual void reset() { totalCycles = 0; }
  4878. virtual void checkAbort() { }
  4879. virtual unsigned queryId() const { throwUnexpected(); }
  4880. virtual void resetEOF() { }
  4881. };
  4882. class CIndirectRoxieInput : public CPseudoRoxieInput
  4883. {
  4884. public:
  4885. CIndirectRoxieInput(IRoxieInput * _input = NULL) : input(_input)
  4886. {
  4887. }
  4888. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4889. {
  4890. input->start(parentExtractSize, parentExtract, paused);
  4891. }
  4892. virtual void stop(bool aborting)
  4893. {
  4894. input->stop(aborting);
  4895. }
  4896. virtual void reset()
  4897. {
  4898. input->reset();
  4899. totalCycles = 0;
  4900. }
  4901. virtual void checkAbort()
  4902. {
  4903. input->checkAbort();
  4904. }
  4905. virtual const void * nextInGroup()
  4906. {
  4907. return input->nextInGroup();
  4908. }
  4909. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4910. {
  4911. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  4912. }
  4913. virtual unsigned __int64 queryLocalCycles() const
  4914. {
  4915. __int64 ret = totalCycles - input->queryTotalCycles();
  4916. if (ret < 0)
  4917. ret = 0;
  4918. return ret;
  4919. }
  4920. virtual IRoxieInput *queryInput(unsigned idx) const
  4921. {
  4922. return input->queryInput(idx);
  4923. }
  4924. virtual unsigned queryId() const
  4925. {
  4926. return input->queryId();
  4927. }
  4928. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4929. {
  4930. return input->gatherConjunctions(collector);
  4931. }
  4932. virtual void resetEOF()
  4933. {
  4934. input->resetEOF();
  4935. }
  4936. virtual unsigned numConcreteOutputs() const
  4937. {
  4938. return input->numConcreteOutputs();
  4939. }
  4940. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  4941. {
  4942. return input->queryConcreteInput(idx);
  4943. }
  4944. virtual IOutputMetaData * queryOutputMeta() const
  4945. {
  4946. return input->queryOutputMeta();
  4947. }
  4948. virtual IRoxieServerActivity *queryActivity()
  4949. {
  4950. return input->queryActivity();
  4951. }
  4952. void setInput(IRoxieInput * _input)
  4953. {
  4954. input = _input;
  4955. }
  4956. protected:
  4957. IRoxieInput * input;
  4958. };
  4959. class CExtractMapperInput : public CIndirectRoxieInput
  4960. {
  4961. unsigned savedParentExtractSize;
  4962. const byte * savedParentExtract;
  4963. public:
  4964. CExtractMapperInput(IRoxieInput * _input = NULL) : CIndirectRoxieInput(_input)
  4965. {
  4966. savedParentExtractSize = 0;
  4967. savedParentExtract = NULL;
  4968. }
  4969. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4970. {
  4971. input->start(savedParentExtractSize, savedParentExtract, paused);
  4972. }
  4973. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  4974. {
  4975. savedParentExtractSize = _savedParentExtractSize;
  4976. savedParentExtract = _savedParentExtract;
  4977. }
  4978. };
  4979. class CGraphResult : public CInterface, implements IGraphResult
  4980. {
  4981. CriticalSection cs;
  4982. byte **rowset;
  4983. size32_t count;
  4984. bool complete;
  4985. void clear()
  4986. {
  4987. CriticalBlock func(cs);
  4988. rtlReleaseRowset(count, rowset);
  4989. rowset = NULL;
  4990. count = 0;
  4991. complete = false;
  4992. }
  4993. public:
  4994. IMPLEMENT_IINTERFACE
  4995. CGraphResult()
  4996. {
  4997. complete = false; // dummy result is not supposed to be used...
  4998. rowset = NULL;
  4999. count = 0;
  5000. }
  5001. CGraphResult(size32_t _count, byte **_rowset)
  5002. : count(_count), rowset(_rowset)
  5003. {
  5004. complete = true;
  5005. }
  5006. ~CGraphResult()
  5007. {
  5008. clear();
  5009. }
  5010. // interface IGraphResult
  5011. virtual IRoxieInput * createIterator()
  5012. {
  5013. if (!complete)
  5014. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5015. return new CGraphResultIterator(this);
  5016. }
  5017. virtual void getLinkedResult(unsigned & countResult, byte * * & result)
  5018. {
  5019. if (!complete)
  5020. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5021. result = rtlLinkRowset(rowset);
  5022. countResult = count;
  5023. }
  5024. //other
  5025. const void * getRow(unsigned i)
  5026. {
  5027. CriticalBlock func(cs);
  5028. if (i >= count)
  5029. return NULL;
  5030. const void * ret = rowset[i];
  5031. if (ret) LinkRoxieRow(ret);
  5032. return ret;
  5033. }
  5034. protected:
  5035. class CGraphResultIterator : public CPseudoRoxieInput
  5036. {
  5037. unsigned i;
  5038. Linked<CGraphResult> result;
  5039. public:
  5040. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5041. IMPLEMENT_IINTERFACE
  5042. public:
  5043. virtual const void * nextInGroup()
  5044. {
  5045. return result->getRow(i++);
  5046. }
  5047. };
  5048. };
  5049. //=================================================================================
  5050. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5051. {
  5052. IHThorLocalResultReadArg &helper;
  5053. Owned<IRoxieInput> iter;
  5054. ILocalGraphEx * graph;
  5055. unsigned graphId;
  5056. unsigned sequence;
  5057. public:
  5058. CRoxieServerLocalResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5059. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5060. {
  5061. graph = NULL;
  5062. sequence = 0;
  5063. }
  5064. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5065. {
  5066. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5067. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5068. sequence = helper.querySequence();
  5069. }
  5070. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5071. {
  5072. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5073. iter.setown(graph->createResultIterator(sequence));
  5074. }
  5075. virtual void reset()
  5076. {
  5077. iter.clear();
  5078. CRoxieServerActivity::reset();
  5079. };
  5080. virtual const void *nextInGroup()
  5081. {
  5082. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5083. const void * next = iter->nextInGroup();
  5084. if (next)
  5085. {
  5086. processed++;
  5087. atomic_inc(&rowsIn);
  5088. }
  5089. return next;
  5090. }
  5091. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5092. {
  5093. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5094. }
  5095. };
  5096. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  5097. {
  5098. unsigned graphId;
  5099. public:
  5100. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5101. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5102. {
  5103. }
  5104. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5105. {
  5106. return new CRoxieServerLocalResultReadActivity(this, _probeManager, graphId);
  5107. }
  5108. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5109. {
  5110. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5111. }
  5112. };
  5113. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5114. {
  5115. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5116. }
  5117. //=================================================================================
  5118. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  5119. {
  5120. IHThorLocalResultReadArg &helper;
  5121. Owned<IRoxieInput> streamInput;
  5122. unsigned sequence;
  5123. public:
  5124. CRoxieServerLocalResultStreamReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5125. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  5126. {
  5127. sequence = 0;
  5128. }
  5129. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5130. {
  5131. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5132. sequence = helper.querySequence();
  5133. }
  5134. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5135. {
  5136. assertex(streamInput != NULL);
  5137. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5138. streamInput->start(parentExtractSize, parentExtract, paused);
  5139. }
  5140. virtual void stop(bool aborting)
  5141. {
  5142. CRoxieServerActivity::stop(aborting);
  5143. streamInput->stop(aborting);
  5144. }
  5145. virtual void reset()
  5146. {
  5147. streamInput->reset();
  5148. CRoxieServerActivity::reset();
  5149. };
  5150. virtual const void *nextInGroup()
  5151. {
  5152. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5153. const void * next = streamInput->nextInGroup();
  5154. if (next)
  5155. {
  5156. processed++;
  5157. atomic_inc(&rowsIn);
  5158. }
  5159. return next;
  5160. }
  5161. virtual bool querySetStreamInput(unsigned id, IRoxieInput * _input)
  5162. {
  5163. if (id == sequence)
  5164. {
  5165. streamInput.set(_input);
  5166. return true;
  5167. }
  5168. return false;
  5169. }
  5170. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5171. {
  5172. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5173. }
  5174. };
  5175. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  5176. {
  5177. public:
  5178. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5179. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5180. {
  5181. }
  5182. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5183. {
  5184. return new CRoxieServerLocalResultStreamReadActivity(this, _probeManager);
  5185. }
  5186. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5187. {
  5188. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  5189. }
  5190. };
  5191. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5192. {
  5193. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5194. }
  5195. //=====================================================================================================
  5196. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  5197. {
  5198. IHThorLocalResultWriteArg &helper;
  5199. ILocalGraphEx * graph;
  5200. unsigned graphId;
  5201. public:
  5202. CRoxieServerLocalResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5203. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  5204. {
  5205. graph = NULL;
  5206. }
  5207. virtual bool needsAllocator() const { return true; }
  5208. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5209. {
  5210. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5211. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5212. }
  5213. virtual void onExecute()
  5214. {
  5215. RtlLinkedDatasetBuilder builder(rowAllocator);
  5216. input->readAll(builder);
  5217. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5218. graph->setResult(helper.querySequence(), result);
  5219. }
  5220. IRoxieInput * querySelectOutput(unsigned id)
  5221. {
  5222. if (id == helper.querySequence())
  5223. {
  5224. executed = true;
  5225. return LINK(input);
  5226. }
  5227. return NULL;
  5228. }
  5229. };
  5230. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5231. {
  5232. unsigned graphId;
  5233. public:
  5234. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5235. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5236. {
  5237. isInternal = true;
  5238. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  5239. }
  5240. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5241. {
  5242. return new CRoxieServerLocalResultWriteActivity(this, _probeManager, graphId);
  5243. }
  5244. };
  5245. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5246. {
  5247. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5248. }
  5249. //=====================================================================================================
  5250. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  5251. {
  5252. IHThorDictionaryResultWriteArg &helper;
  5253. ILocalGraphEx * graph;
  5254. unsigned graphId;
  5255. public:
  5256. CRoxieServerDictionaryResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5257. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  5258. {
  5259. graph = NULL;
  5260. }
  5261. virtual bool needsAllocator() const { return true; }
  5262. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5263. {
  5264. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5265. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5266. }
  5267. virtual void onExecute()
  5268. {
  5269. unsigned sequence = helper.querySequence();
  5270. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  5271. loop
  5272. {
  5273. const void *row = input->nextInGroup();
  5274. if (!row)
  5275. {
  5276. row = input->nextInGroup();
  5277. if (!row)
  5278. break;
  5279. }
  5280. builder.appendOwn(row);
  5281. processed++;
  5282. }
  5283. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5284. graph->setResult(helper.querySequence(), result);
  5285. }
  5286. IRoxieInput * querySelectOutput(unsigned id)
  5287. {
  5288. if (id == helper.querySequence())
  5289. {
  5290. executed = true;
  5291. return LINK(input);
  5292. }
  5293. return NULL;
  5294. }
  5295. };
  5296. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5297. {
  5298. unsigned graphId;
  5299. public:
  5300. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5301. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot), graphId(_graphId)
  5302. {
  5303. isInternal = true;
  5304. }
  5305. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5306. {
  5307. return new CRoxieServerDictionaryResultWriteActivity(this, _probeManager, graphId);
  5308. }
  5309. };
  5310. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  5311. {
  5312. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId, _isRoot);
  5313. }
  5314. //=================================================================================
  5315. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  5316. {
  5317. protected:
  5318. IHThorGraphLoopResultReadArg &helper;
  5319. Owned<IRoxieInput> iter;
  5320. ILocalGraphEx * graph;
  5321. unsigned graphId;
  5322. unsigned sequence;
  5323. public:
  5324. CRoxieServerGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5325. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  5326. {
  5327. graph = NULL;
  5328. sequence = 0;
  5329. }
  5330. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5331. {
  5332. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  5333. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5334. }
  5335. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5336. {
  5337. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5338. if (iter)
  5339. iter->start(parentExtractSize, parentExtract, paused);
  5340. else
  5341. {
  5342. sequence = helper.querySequence();
  5343. if ((int)sequence >= 0)
  5344. {
  5345. try
  5346. {
  5347. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5348. }
  5349. catch (IException * E)
  5350. {
  5351. throw makeWrappedException(E);
  5352. }
  5353. }
  5354. }
  5355. }
  5356. virtual void stop(bool aborting)
  5357. {
  5358. if (iter)
  5359. iter->stop(aborting);
  5360. CRoxieServerActivity::stop(aborting);
  5361. }
  5362. virtual void reset()
  5363. {
  5364. if (iter)
  5365. iter->reset();
  5366. iter.clear();
  5367. CRoxieServerActivity::reset();
  5368. };
  5369. virtual const void *nextInGroup()
  5370. {
  5371. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5372. const void * next = iter ? iter->nextInGroup() : NULL;
  5373. if (next)
  5374. {
  5375. processed++;
  5376. atomic_inc(&rowsIn);
  5377. }
  5378. return next;
  5379. }
  5380. virtual void setInput(unsigned idx, IRoxieInput *_in)
  5381. {
  5382. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5383. }
  5384. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  5385. {
  5386. ensureCreated();
  5387. basehelper.onStart(parentExtract, NULL);
  5388. processor.noteUseIteration(helper.querySequence());
  5389. }
  5390. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  5391. {
  5392. //helper already initialised from the gratherIterationUsage() call.
  5393. iter.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  5394. }
  5395. virtual IInputSteppingMeta * querySteppingMeta()
  5396. {
  5397. assertex(iter);
  5398. return iter->querySteppingMeta();
  5399. }
  5400. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5401. {
  5402. assertex(iter);
  5403. return iter->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5404. }
  5405. };
  5406. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  5407. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  5408. {
  5409. public:
  5410. CRoxieServerInternalGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  5411. : CRoxieServerGraphLoopResultReadActivity(_factory, _probeManager, _graphId)
  5412. {
  5413. sequence = _sequence;
  5414. }
  5415. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5416. {
  5417. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5418. if ((int)sequence >= 0)
  5419. {
  5420. try
  5421. {
  5422. iter.setown(graph->createGraphLoopResultIterator(sequence));
  5423. }
  5424. catch (IException * E)
  5425. {
  5426. throw makeWrappedException(E);
  5427. }
  5428. }
  5429. }
  5430. };
  5431. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  5432. {
  5433. unsigned graphId;
  5434. public:
  5435. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  5436. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  5437. {
  5438. }
  5439. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5440. {
  5441. return new CRoxieServerGraphLoopResultReadActivity(this, _probeManager, graphId);
  5442. }
  5443. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5444. {
  5445. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  5446. }
  5447. };
  5448. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  5449. {
  5450. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  5451. }
  5452. //=====================================================================================================
  5453. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  5454. {
  5455. IHThorGraphLoopResultWriteArg &helper;
  5456. ILocalGraphEx * graph;
  5457. unsigned graphId;
  5458. public:
  5459. CRoxieServerGraphLoopResultWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5460. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
  5461. {
  5462. graph = NULL;
  5463. }
  5464. virtual bool needsAllocator() const { return true; }
  5465. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  5466. {
  5467. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  5468. graph = static_cast<ILocalGraphEx *>(_ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5469. }
  5470. virtual void onExecute()
  5471. {
  5472. RtlLinkedDatasetBuilder builder(rowAllocator);
  5473. input->readAll(builder);
  5474. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  5475. graph->setGraphLoopResult(result);
  5476. }
  5477. virtual IRoxieInput *queryOutput(unsigned idx)
  5478. {
  5479. if (idx==0)
  5480. return this;
  5481. else
  5482. return NULL;
  5483. }
  5484. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5485. {
  5486. return input->gatherConjunctions(collector);
  5487. }
  5488. virtual void resetEOF()
  5489. {
  5490. input->resetEOF();
  5491. }
  5492. virtual const void *nextInGroup()
  5493. {
  5494. const void * next = input->nextInGroup();
  5495. if (next)
  5496. processed++;
  5497. return next;
  5498. }
  5499. virtual bool isPassThrough()
  5500. {
  5501. return true;
  5502. }
  5503. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5504. {
  5505. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5506. const void * next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5507. if (next)
  5508. processed++;
  5509. return next;
  5510. }
  5511. IInputSteppingMeta * querySteppingMeta()
  5512. {
  5513. return input->querySteppingMeta();
  5514. }
  5515. virtual IOutputMetaData * queryOutputMeta() const
  5516. {
  5517. return input->queryOutputMeta();
  5518. }
  5519. };
  5520. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  5521. {
  5522. unsigned graphId;
  5523. public:
  5524. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5525. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, true), graphId(_graphId)
  5526. {
  5527. isInternal = true;
  5528. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  5529. }
  5530. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5531. {
  5532. return new CRoxieServerGraphLoopResultWriteActivity(this, _probeManager, graphId);
  5533. }
  5534. };
  5535. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, unsigned _graphId)
  5536. {
  5537. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _graphId);
  5538. }
  5539. #if 0
  5540. //=====================================================================================================
  5541. CHThorLocalResultSpillActivity::CHThorLocalResultSpillActivity(IAgentContext &_agent, ActivityId const & _id, IHThorLocalResultSpillArg &_arg)
  5542. : CHThorSimpleActivityBase(_agent, _id, _arg), helper(_arg)
  5543. {
  5544. next = NULL;
  5545. }
  5546. void CHThorLocalResultSpillActivity::ready()
  5547. {
  5548. CHThorSimpleActivityBase::ready();
  5549. next = input->nextInGroup();
  5550. grouped = input->isGrouped();
  5551. rowdata.clear();
  5552. }
  5553. const void * CHThorLocalResultSpillActivity::nextInGroup()
  5554. {
  5555. const void * ret = next;
  5556. next = input->nextInGroup();
  5557. if (!ret && !next)
  5558. return NULL;
  5559. if (ret)
  5560. {
  5561. size32_t thisSize = outputMeta->getRecordSize(ret);
  5562. rowdata.append(thisSize, ret);
  5563. if (grouped)
  5564. rowdata.append(next == NULL);
  5565. }
  5566. return ret;
  5567. }
  5568. void CHThorLocalResultSpillActivity::done()
  5569. {
  5570. loop
  5571. {
  5572. const void * ret = nextInGroup();
  5573. if (!ret)
  5574. {
  5575. ret = nextInGroup();
  5576. if (!ret)
  5577. break;
  5578. }
  5579. ReleaseRoxieRow(ret);
  5580. }
  5581. agent.setLocalResult(helper.querySequence(), rowdata.length(), rowdata.toByteArray());
  5582. CHThorSimpleActivityBase::done();
  5583. }
  5584. #endif
  5585. //=================================================================================
  5586. class CRoxieServerDedupActivity : public CRoxieServerActivity
  5587. {
  5588. protected:
  5589. IHThorDedupArg &helper;
  5590. unsigned numKept;
  5591. unsigned numToKeep;
  5592. public:
  5593. CRoxieServerDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5594. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5595. {
  5596. numKept = 0;
  5597. numToKeep = 0;
  5598. }
  5599. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5600. {
  5601. numKept = 0;
  5602. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5603. numToKeep = helper.numToKeep();
  5604. }
  5605. };
  5606. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  5607. {
  5608. IRangeCompare * stepCompare;
  5609. const void *prev;
  5610. public:
  5611. CRoxieServerDedupKeepLeftActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5612. : CRoxieServerDedupActivity(_factory, _probeManager)
  5613. {
  5614. prev = NULL;
  5615. stepCompare = NULL;
  5616. }
  5617. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5618. {
  5619. prev = NULL;
  5620. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5621. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  5622. stepCompare = NULL;
  5623. if (stepMeta)
  5624. stepCompare = stepMeta->queryCompare();
  5625. }
  5626. virtual void reset()
  5627. {
  5628. ReleaseClearRoxieRow(prev);
  5629. CRoxieServerDedupActivity::reset();
  5630. }
  5631. virtual const void * nextInGroup()
  5632. {
  5633. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5634. const void * next;
  5635. loop
  5636. {
  5637. next = input->nextInGroup();
  5638. if (!prev || !next || !helper.matches(prev,next))
  5639. {
  5640. numKept = 0;
  5641. break;
  5642. }
  5643. if (numKept < numToKeep-1)
  5644. {
  5645. numKept++;
  5646. break;
  5647. }
  5648. ReleaseRoxieRow(next);
  5649. }
  5650. ReleaseRoxieRow(prev);
  5651. prev = next;
  5652. if (next)
  5653. {
  5654. LinkRoxieRow(next);
  5655. processed++;
  5656. }
  5657. return next;
  5658. }
  5659. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5660. {
  5661. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5662. const void * next;
  5663. loop
  5664. {
  5665. next = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  5666. //If the record was an in-exact match from the index then return it immediately
  5667. //and don't cause it to dedup following legal records.
  5668. if (!wasCompleteMatch)
  5669. {
  5670. assertex(stepExtra.returnMismatches());
  5671. return next;
  5672. }
  5673. if (!prev || !next || !helper.matches(prev,next))
  5674. {
  5675. numKept = 0;
  5676. break;
  5677. }
  5678. if (numKept < numToKeep-1)
  5679. {
  5680. numKept++;
  5681. break;
  5682. }
  5683. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  5684. if (stepExtra.returnMismatches())
  5685. {
  5686. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  5687. //condition to advance
  5688. if (stepCompare->docompare(next, seek, numFields) != 0)
  5689. {
  5690. wasCompleteMatch = false;
  5691. break;
  5692. }
  5693. }
  5694. ReleaseRoxieRow(next);
  5695. }
  5696. ReleaseRoxieRow(prev);
  5697. prev = next;
  5698. if (next)
  5699. {
  5700. LinkRoxieRow(next);
  5701. processed++;
  5702. }
  5703. return next;
  5704. }
  5705. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5706. {
  5707. return input->gatherConjunctions(collector);
  5708. }
  5709. virtual void resetEOF()
  5710. {
  5711. input->resetEOF();
  5712. }
  5713. IInputSteppingMeta * querySteppingMeta()
  5714. {
  5715. return input->querySteppingMeta();
  5716. }
  5717. };
  5718. //=================================================================================
  5719. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  5720. {
  5721. const void *kept;
  5722. bool first;
  5723. public:
  5724. CRoxieServerDedupKeepRightActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5725. : CRoxieServerDedupActivity(_factory, _probeManager)
  5726. {
  5727. kept = NULL;
  5728. first = true;
  5729. }
  5730. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5731. {
  5732. first = true;
  5733. kept = NULL;
  5734. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  5735. }
  5736. virtual void reset()
  5737. {
  5738. ReleaseClearRoxieRow(kept);
  5739. CRoxieServerActivity::reset();
  5740. }
  5741. virtual const void * nextInGroup()
  5742. {
  5743. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5744. if (first)
  5745. {
  5746. kept = input->nextInGroup();
  5747. first = false;
  5748. }
  5749. const void * next;
  5750. loop
  5751. {
  5752. next = input->nextInGroup();
  5753. if (!kept || !next || !helper.matches(kept,next))
  5754. {
  5755. numKept = 0;
  5756. break;
  5757. }
  5758. if (numKept < numToKeep-1)
  5759. {
  5760. numKept++;
  5761. break;
  5762. }
  5763. ReleaseRoxieRow(kept);
  5764. kept = next;
  5765. }
  5766. const void * ret = kept;
  5767. kept = next;
  5768. // CTXLOG("dedup returns %p", ret);
  5769. if (ret) processed++;
  5770. return ret;
  5771. }
  5772. };
  5773. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  5774. {
  5775. IHThorDedupArg &helper;
  5776. unsigned survivorIndex;
  5777. ConstPointerArray survivors;
  5778. bool keepLeft;
  5779. bool eof;
  5780. bool first;
  5781. ICompare *primaryCompare;
  5782. public:
  5783. CRoxieServerDedupAllActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  5784. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  5785. {
  5786. keepLeft = _keepLeft;
  5787. primaryCompare = helper.queryComparePrimary();
  5788. eof = false;
  5789. first = true;
  5790. survivorIndex = 0;
  5791. }
  5792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5793. {
  5794. eof = false;
  5795. first = true;
  5796. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5797. }
  5798. virtual void reset()
  5799. {
  5800. #ifdef _DEBUG
  5801. while (survivors.isItem(survivorIndex))
  5802. {
  5803. ReleaseRoxieRow(survivors.item(survivorIndex++));
  5804. }
  5805. #endif
  5806. survivors.kill();
  5807. eof = false;
  5808. first = true;
  5809. CRoxieServerActivity::reset();
  5810. }
  5811. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  5812. {
  5813. for (unsigned idxL = first; idxL < last; idxL++)
  5814. {
  5815. const void * left = group.item(idxL);
  5816. if (left)
  5817. {
  5818. for (unsigned idxR = first; idxR < last; idxR++)
  5819. {
  5820. const void * right = group.item(idxR);
  5821. if ((idxL != idxR) && right)
  5822. {
  5823. if (helper.matches(left, right))
  5824. {
  5825. if (keepLeft)
  5826. {
  5827. group.replace(NULL, idxR);
  5828. ReleaseRoxieRow(right);
  5829. }
  5830. else
  5831. {
  5832. group.replace(NULL, idxL);
  5833. ReleaseRoxieRow(left);
  5834. break;
  5835. }
  5836. }
  5837. }
  5838. }
  5839. }
  5840. }
  5841. }
  5842. void dedupRangeIndirect(unsigned first, unsigned last, void *** index)
  5843. {
  5844. for (unsigned idxL = first; idxL < last; idxL++)
  5845. {
  5846. void * left = *(index[idxL]);
  5847. if (left)
  5848. {
  5849. for (unsigned idxR = first; idxR < last; idxR++)
  5850. {
  5851. void * right = *(index[idxR]);
  5852. if ((idxL != idxR) && right)
  5853. {
  5854. if (helper.matches(left, right))
  5855. {
  5856. if (keepLeft)
  5857. {
  5858. *(index[idxR]) = NULL;
  5859. ReleaseRoxieRow(right);
  5860. }
  5861. else
  5862. {
  5863. *(index[idxL]) = NULL;
  5864. ReleaseRoxieRow(left);
  5865. break;
  5866. }
  5867. }
  5868. }
  5869. }
  5870. }
  5871. }
  5872. }
  5873. bool calcNextDedupAll()
  5874. {
  5875. survivors.kill();
  5876. survivorIndex = 0;
  5877. ConstPointerArray group;
  5878. if (eof || !input->nextGroup(group))
  5879. {
  5880. eof = true;
  5881. return false;
  5882. }
  5883. unsigned max = group.ordinality();
  5884. if (primaryCompare)
  5885. {
  5886. //hard, if not impossible, to hit this code once optimisations in place
  5887. MemoryAttr indexbuff(max*sizeof(void **));
  5888. void *** index = (void ***)indexbuff.bufferBase();
  5889. qsortvecstable(const_cast<void * *>(group.getArray()), max, *primaryCompare, index);
  5890. unsigned first = 0;
  5891. for (unsigned idx = 1; idx < max; idx++)
  5892. {
  5893. if (primaryCompare->docompare(*(index[first]), *(index[idx])) != 0)
  5894. {
  5895. dedupRangeIndirect(first, idx, index);
  5896. first = idx;
  5897. }
  5898. }
  5899. dedupRangeIndirect(first, max, index);
  5900. for(unsigned idx2=0; idx2<max; ++idx2)
  5901. {
  5902. void * cur = *(index[idx2]);
  5903. if(cur)
  5904. survivors.append(cur);
  5905. }
  5906. }
  5907. else
  5908. {
  5909. dedupRange(0, max, group);
  5910. for(unsigned idx=0; idx<max; ++idx)
  5911. {
  5912. const void * cur = group.item(idx);
  5913. if(cur)
  5914. survivors.append(cur);
  5915. }
  5916. }
  5917. return true;
  5918. }
  5919. virtual const void *nextInGroup()
  5920. {
  5921. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  5922. if (first)
  5923. {
  5924. calcNextDedupAll();
  5925. first = false;
  5926. }
  5927. while (survivors.isItem(survivorIndex))
  5928. {
  5929. const void *ret = survivors.item(survivorIndex++);
  5930. if (ret)
  5931. {
  5932. processed++;
  5933. return ret;
  5934. }
  5935. }
  5936. calcNextDedupAll();
  5937. return NULL;
  5938. }
  5939. };
  5940. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  5941. {
  5942. bool compareAll;
  5943. bool keepLeft;
  5944. public:
  5945. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5946. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  5947. {
  5948. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  5949. compareAll = helper->compareAll();
  5950. keepLeft = helper->keepLeft();
  5951. }
  5952. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  5953. {
  5954. if (compareAll)
  5955. return new CRoxieServerDedupAllActivity(this, _probeManager, keepLeft);
  5956. else if (keepLeft)
  5957. return new CRoxieServerDedupKeepLeftActivity(this, _probeManager);
  5958. else
  5959. return new CRoxieServerDedupKeepRightActivity(this, _probeManager);
  5960. }
  5961. };
  5962. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  5963. {
  5964. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  5965. }
  5966. //=================================================================================
  5967. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  5968. {
  5969. bool eof;
  5970. IHThorHashDedupArg &helper;
  5971. class HashDedupElement
  5972. {
  5973. public:
  5974. HashDedupElement(unsigned _hash, const void *_keyRow)
  5975. : hash(_hash), keyRow(_keyRow)
  5976. {
  5977. }
  5978. ~HashDedupElement()
  5979. {
  5980. ReleaseRoxieRow(keyRow);
  5981. }
  5982. inline unsigned queryHash() const
  5983. {
  5984. return hash;
  5985. }
  5986. inline const void *queryRow() const
  5987. {
  5988. return keyRow;
  5989. }
  5990. private:
  5991. unsigned hash;
  5992. const void *keyRow;
  5993. };
  5994. class HashDedupTable : public SuperHashTable
  5995. {
  5996. public:
  5997. HashDedupTable(IHThorHashDedupArg & _helper, unsigned _activityId)
  5998. : helper(_helper),
  5999. activityId(_activityId),
  6000. keySize(helper.queryKeySize())
  6001. {
  6002. }
  6003. virtual ~HashDedupTable() { releaseAll(); }
  6004. virtual unsigned getHashFromElement(const void *et) const
  6005. {
  6006. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6007. return element->queryHash();
  6008. }
  6009. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6010. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6011. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6012. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6013. {
  6014. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6015. if (fphash != element->queryHash())
  6016. return false;
  6017. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6018. }
  6019. virtual void onAdd(void *et) {}
  6020. virtual void onRemove(void *et)
  6021. {
  6022. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6023. delete element;
  6024. }
  6025. void onCreate(IRoxieSlaveContext *ctx)
  6026. {
  6027. keyRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(keySize.queryOriginal(), activityId));
  6028. }
  6029. void reset()
  6030. {
  6031. kill();
  6032. }
  6033. bool insert(const void * row)
  6034. {
  6035. unsigned hash = helper.queryHash()->hash(row);
  6036. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6037. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6038. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6039. if (find(hash, keyRow.get()))
  6040. return false;
  6041. addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
  6042. return true;
  6043. }
  6044. private:
  6045. IHThorHashDedupArg & helper;
  6046. CachedOutputMetaData keySize;
  6047. Owned<IEngineRowAllocator> keyRowAllocator;
  6048. unsigned activityId;
  6049. } table;
  6050. public:
  6051. CRoxieServerHashDedupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6052. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, activityId)
  6053. {
  6054. eof = false;
  6055. }
  6056. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6057. {
  6058. eof = false;
  6059. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6060. }
  6061. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  6062. {
  6063. CRoxieServerActivity::onCreate(ctx, colocalParent);
  6064. table.onCreate(ctx);
  6065. }
  6066. virtual void reset()
  6067. {
  6068. table.reset();
  6069. eof = false;
  6070. CRoxieServerActivity::reset();
  6071. }
  6072. virtual const void *nextInGroup()
  6073. {
  6074. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6075. while(!eof)
  6076. {
  6077. const void * next = input->nextInGroup();
  6078. if(!next)
  6079. {
  6080. if (table.count() == 0)
  6081. eof = true;
  6082. table.reset();
  6083. return NULL;
  6084. }
  6085. if(table.insert(next))
  6086. return next;
  6087. else
  6088. ReleaseRoxieRow(next);
  6089. }
  6090. return NULL;
  6091. }
  6092. };
  6093. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  6094. {
  6095. public:
  6096. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6097. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6098. {
  6099. }
  6100. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6101. {
  6102. return new CRoxieServerHashDedupActivity(this, _probeManager);
  6103. }
  6104. };
  6105. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6106. {
  6107. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6108. }
  6109. //=================================================================================
  6110. class CRoxieServerRollupActivity : public CRoxieServerActivity
  6111. {
  6112. IHThorRollupArg &helper;
  6113. OwnedConstRoxieRow left;
  6114. OwnedConstRoxieRow prev;
  6115. OwnedConstRoxieRow right;
  6116. bool readFirstRow;
  6117. public:
  6118. CRoxieServerRollupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6119. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  6120. {
  6121. readFirstRow = false;
  6122. }
  6123. ~CRoxieServerRollupActivity()
  6124. {
  6125. }
  6126. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6127. {
  6128. readFirstRow = false;
  6129. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6130. }
  6131. virtual void reset()
  6132. {
  6133. left.clear();
  6134. prev.clear();
  6135. right.clear();
  6136. CRoxieServerActivity::reset();
  6137. }
  6138. virtual bool needsAllocator() const { return true; }
  6139. virtual const void * nextInGroup()
  6140. {
  6141. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6142. if (!readFirstRow)
  6143. {
  6144. left.setown(input->nextInGroup());
  6145. prev.set(left);
  6146. readFirstRow = true;
  6147. }
  6148. loop
  6149. {
  6150. right.setown(input->nextInGroup());
  6151. if(!prev || !right || !helper.matches(prev,right))
  6152. {
  6153. const void * ret = left.getClear();
  6154. if(ret)
  6155. processed++;
  6156. left.setown(right.getClear());
  6157. prev.set(left);
  6158. return ret;
  6159. }
  6160. try
  6161. {
  6162. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6163. unsigned outSize = helper.transform(rowBuilder, left, right);
  6164. if (outSize)
  6165. left.setown(rowBuilder.finalizeRowClear(outSize));
  6166. if (helper.getFlags() & RFrolledismatchleft)
  6167. prev.set(left);
  6168. else
  6169. prev.set(right);
  6170. }
  6171. catch(IException * E)
  6172. {
  6173. throw makeWrappedException(E);
  6174. }
  6175. }
  6176. }
  6177. };
  6178. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  6179. {
  6180. public:
  6181. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6182. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6183. {
  6184. }
  6185. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6186. {
  6187. return new CRoxieServerRollupActivity(this, _probeManager);
  6188. }
  6189. };
  6190. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6191. {
  6192. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6193. }
  6194. //=================================================================================
  6195. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  6196. {
  6197. IHThorNormalizeArg &helper;
  6198. unsigned numThisRow;
  6199. unsigned curRow;
  6200. const void *buffer;
  6201. unsigned numProcessedLastGroup;
  6202. public:
  6203. CRoxieServerNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6204. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  6205. {
  6206. buffer = NULL;
  6207. numThisRow = 0;
  6208. curRow = 0;
  6209. numProcessedLastGroup = 0;
  6210. }
  6211. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6212. {
  6213. numThisRow = 0;
  6214. curRow = 0;
  6215. numProcessedLastGroup = 0;
  6216. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6217. }
  6218. virtual void reset()
  6219. {
  6220. ReleaseClearRoxieRow(buffer);
  6221. CRoxieServerActivity::reset();
  6222. }
  6223. virtual bool needsAllocator() const { return true; }
  6224. virtual const void * nextInGroup()
  6225. {
  6226. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6227. loop
  6228. {
  6229. while (curRow == numThisRow)
  6230. {
  6231. if (buffer)
  6232. ReleaseClearRoxieRow(buffer);
  6233. buffer = input->nextInGroup();
  6234. if (!buffer && (processed == numProcessedLastGroup))
  6235. buffer = input->nextInGroup();
  6236. if (!buffer)
  6237. {
  6238. numProcessedLastGroup = processed;
  6239. return NULL;
  6240. }
  6241. curRow = 0;
  6242. numThisRow = helper.numExpandedRows(buffer);
  6243. }
  6244. try
  6245. {
  6246. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6247. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  6248. if (actualSize != 0)
  6249. {
  6250. processed++;
  6251. return rowBuilder.finalizeRowClear(actualSize);
  6252. }
  6253. }
  6254. catch (IException *E)
  6255. {
  6256. throw makeWrappedException(E);
  6257. }
  6258. }
  6259. }
  6260. };
  6261. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  6262. {
  6263. public:
  6264. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6265. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6266. {
  6267. }
  6268. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6269. {
  6270. return new CRoxieServerNormalizeActivity(this, _probeManager);
  6271. }
  6272. };
  6273. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6274. {
  6275. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6276. }
  6277. //=================================================================================
  6278. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  6279. {
  6280. IHThorNormalizeChildArg &helper;
  6281. unsigned numThisRow;
  6282. unsigned curRow;
  6283. const void *buffer;
  6284. unsigned numProcessedLastGroup;
  6285. INormalizeChildIterator * cursor;
  6286. const void * curChildRow;
  6287. bool advanceInput()
  6288. {
  6289. loop
  6290. {
  6291. ReleaseClearRoxieRow(buffer);
  6292. buffer = input->nextInGroup();
  6293. if (!buffer && (processed == numProcessedLastGroup))
  6294. buffer = input->nextInGroup();
  6295. if (!buffer)
  6296. {
  6297. numProcessedLastGroup = processed;
  6298. return false;
  6299. }
  6300. curChildRow = cursor->first(buffer);
  6301. if (curChildRow)
  6302. {
  6303. curRow = 0;
  6304. return true;
  6305. }
  6306. }
  6307. }
  6308. public:
  6309. CRoxieServerNormalizeChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6310. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  6311. {
  6312. buffer = NULL;
  6313. cursor = NULL;
  6314. numThisRow = 0;
  6315. curRow = 0;
  6316. numProcessedLastGroup = 0;
  6317. curChildRow = NULL;
  6318. }
  6319. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6320. {
  6321. numThisRow = 0;
  6322. curRow = 0;
  6323. numProcessedLastGroup = 0;
  6324. curChildRow = NULL;
  6325. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6326. cursor = helper.queryIterator();
  6327. }
  6328. virtual void stop(bool aborting)
  6329. {
  6330. CRoxieServerActivity::stop(aborting);
  6331. }
  6332. virtual void reset()
  6333. {
  6334. cursor = NULL;
  6335. ReleaseClearRoxieRow(buffer);
  6336. CRoxieServerActivity::reset();
  6337. }
  6338. virtual bool needsAllocator() const { return true; }
  6339. const void *nextInGroup()
  6340. {
  6341. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6342. loop
  6343. {
  6344. if (!buffer)
  6345. {
  6346. if (!advanceInput())
  6347. return NULL;
  6348. }
  6349. try
  6350. {
  6351. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  6352. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  6353. curChildRow = cursor->next();
  6354. if (!curChildRow)
  6355. ReleaseClearRoxieRow(buffer);
  6356. if (outSize != 0)
  6357. {
  6358. processed++;
  6359. return rowBuilder.finalizeRowClear(outSize);
  6360. }
  6361. }
  6362. catch (IException *E)
  6363. {
  6364. throw makeWrappedException(E);
  6365. }
  6366. }
  6367. }
  6368. };
  6369. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  6370. {
  6371. public:
  6372. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6373. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6374. {
  6375. }
  6376. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6377. {
  6378. return new CRoxieServerNormalizeChildActivity(this, _probeManager);
  6379. }
  6380. };
  6381. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6382. {
  6383. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6384. }
  6385. //=================================================================================
  6386. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  6387. {
  6388. IHThorNormalizeLinkedChildArg &helper;
  6389. OwnedConstRoxieRow curParent;
  6390. OwnedConstRoxieRow curChild;
  6391. unsigned numProcessedLastGroup;
  6392. bool advanceInput()
  6393. {
  6394. loop
  6395. {
  6396. curParent.setown(input->nextInGroup());
  6397. if (!curParent && (processed == numProcessedLastGroup))
  6398. curParent.setown(input->nextInGroup());
  6399. if (!curParent)
  6400. {
  6401. numProcessedLastGroup = processed;
  6402. return false;
  6403. }
  6404. curChild.set(helper.first(curParent));
  6405. if (curChild)
  6406. return true;
  6407. }
  6408. }
  6409. public:
  6410. CRoxieServerNormalizeLinkedChildActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6411. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  6412. {
  6413. numProcessedLastGroup = 0;
  6414. }
  6415. ~CRoxieServerNormalizeLinkedChildActivity()
  6416. {
  6417. }
  6418. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6419. {
  6420. numProcessedLastGroup = 0;
  6421. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6422. }
  6423. virtual void reset()
  6424. {
  6425. curParent.clear();
  6426. curChild.clear();
  6427. CRoxieServerActivity::reset();
  6428. }
  6429. const void *nextInGroup()
  6430. {
  6431. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  6432. loop
  6433. {
  6434. if (!curParent)
  6435. {
  6436. if (!advanceInput())
  6437. return NULL;
  6438. }
  6439. try
  6440. {
  6441. const void *ret = curChild.getClear();
  6442. curChild.set(helper.next());
  6443. if (!curChild)
  6444. curParent.clear();
  6445. if (ret)
  6446. {
  6447. processed++;
  6448. return ret;
  6449. }
  6450. }
  6451. catch (IException *E)
  6452. {
  6453. throw makeWrappedException(E);
  6454. }
  6455. }
  6456. }
  6457. };
  6458. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  6459. {
  6460. public:
  6461. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6462. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  6463. {
  6464. }
  6465. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  6466. {
  6467. return new CRoxieServerNormalizeLinkedChildActivity(this, _probeManager);
  6468. }
  6469. };
  6470. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  6471. {
  6472. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  6473. }
  6474. //=================================================================================
  6475. interface ISortAlgorithm : extends IInterface
  6476. {
  6477. virtual void prepare(IRoxieInput *input) = 0;
  6478. virtual const void *next() = 0;
  6479. virtual void reset() = 0;
  6480. };
  6481. class CQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6482. {
  6483. unsigned curIndex;
  6484. ConstPointerArray sorted;
  6485. ICompare *compare;
  6486. public:
  6487. CQuickSortAlgorithm(ICompare *_compare) : compare(_compare)
  6488. {
  6489. curIndex = 0;
  6490. }
  6491. virtual void prepare(IRoxieInput *input)
  6492. {
  6493. curIndex = 0;
  6494. if (input->nextGroup(sorted))
  6495. qsortvec(const_cast<void * *>(sorted.getArray()), sorted.ordinality(), *compare);
  6496. }
  6497. virtual const void *next()
  6498. {
  6499. if (sorted.isItem(curIndex))
  6500. return sorted.item(curIndex++);
  6501. return NULL;
  6502. }
  6503. virtual void reset()
  6504. {
  6505. while (sorted.isItem(curIndex))
  6506. ReleaseRoxieRow(sorted.item(curIndex++));
  6507. curIndex = 0;
  6508. sorted.kill();
  6509. }
  6510. };
  6511. class CSpillingQuickSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>, implements roxiemem::IBufferedRowCallback
  6512. {
  6513. enum {
  6514. InitialSortElements = 0,
  6515. //The number of rows that can be added without entering a critical section, and therefore also the number
  6516. //of rows that might not get freed when memory gets tight.
  6517. CommitStep=32
  6518. };
  6519. roxiemem::DynamicRoxieOutputRowArray rowsToSort;
  6520. roxiemem::RoxieSimpleInputRowArray sorted;
  6521. ICompare *compare;
  6522. IRoxieSlaveContext * ctx;
  6523. Owned<IDiskMerger> diskMerger;
  6524. Owned<IRowStream> diskReader;
  6525. Owned<IOutputMetaData> rowMeta;
  6526. unsigned activityId;
  6527. public:
  6528. CSpillingQuickSortAlgorithm(ICompare *_compare, IRoxieSlaveContext * _ctx, IOutputMetaData * _rowMeta, unsigned _activityId)
  6529. : rowsToSort(&_ctx->queryRowManager(), InitialSortElements, CommitStep), ctx(_ctx), compare(_compare), rowMeta(_rowMeta), activityId(_activityId)
  6530. {
  6531. ctx->queryRowManager().addRowBuffer(this);
  6532. }
  6533. ~CSpillingQuickSortAlgorithm()
  6534. {
  6535. ctx->queryRowManager().removeRowBuffer(this);
  6536. diskReader.clear();
  6537. }
  6538. virtual void prepare(IRoxieInput *input)
  6539. {
  6540. loop
  6541. {
  6542. const void * next = input->nextInGroup();
  6543. if (!next)
  6544. break;
  6545. if (!rowsToSort.append(next))
  6546. {
  6547. {
  6548. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6549. //We should have been called back to free any committed rows, but occasionally it may not (e.g., if
  6550. //the problem is global memory is exhausted) - in which case force a spill here (but add any pending
  6551. //rows first).
  6552. if (rowsToSort.numCommitted() != 0)
  6553. {
  6554. rowsToSort.flush();
  6555. spillRows();
  6556. }
  6557. //Ensure new rows are written to the head of the array. It needs to be a separate call because
  6558. //spillRows() cannot shift active row pointer since it can be called from any thread
  6559. rowsToSort.flush();
  6560. }
  6561. if (!rowsToSort.append(next))
  6562. {
  6563. ReleaseRoxieRow(next);
  6564. throw MakeStringException(ROXIEMM_MEMORY_LIMIT_EXCEEDED, "Insufficient memory to append sort row");
  6565. }
  6566. }
  6567. }
  6568. rowsToSort.flush();
  6569. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6570. if (diskMerger)
  6571. {
  6572. spillRows();
  6573. rowsToSort.kill();
  6574. diskReader.setown(diskMerger->merge(compare));
  6575. }
  6576. else
  6577. {
  6578. unsigned numRows = rowsToSort.numCommitted();
  6579. if (numRows)
  6580. {
  6581. const void * * rows = rowsToSort.getBlock(numRows);
  6582. //MORE: Should this be parallel? Should that be dependent on whether it is grouped? Should be a hint.
  6583. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6584. }
  6585. sorted.transferFrom(rowsToSort);
  6586. }
  6587. }
  6588. virtual const void *next()
  6589. {
  6590. if(diskReader)
  6591. return diskReader->nextRow();
  6592. return sorted.dequeue();
  6593. }
  6594. virtual void reset()
  6595. {
  6596. //MORE: This could transfer any row pointer from sorted back to rowsToSort. It would trade
  6597. //fewer heap allocations with not freeing up the memory from large group sorts.
  6598. rowsToSort.clearRows();
  6599. sorted.kill();
  6600. //Disk reader must be cleared before the merger - or the files may still be locked.
  6601. diskReader.clear();
  6602. diskMerger.clear();
  6603. }
  6604. //interface roxiemem::IBufferedRowCallback
  6605. virtual unsigned getPriority() const
  6606. {
  6607. //Spill global sorts before grouped sorts
  6608. if (rowMeta->isGrouped())
  6609. return 20;
  6610. return 10;
  6611. }
  6612. virtual bool freeBufferedRows(bool critical)
  6613. {
  6614. roxiemem::RoxieOutputRowArrayLock block(rowsToSort);
  6615. return spillRows();
  6616. }
  6617. protected:
  6618. bool spillRows()
  6619. {
  6620. unsigned numRows = rowsToSort.numCommitted();
  6621. if (numRows == 0)
  6622. return false;
  6623. const void * * rows = rowsToSort.getBlock(numRows);
  6624. qsortvec(const_cast<void * *>(rows), numRows, *compare);
  6625. Owned<IRowWriter> out = queryMerger()->createWriteBlock();
  6626. for (unsigned i= 0; i < numRows; i++)
  6627. {
  6628. out->putRow(rows[i]);
  6629. }
  6630. rowsToSort.noteSpilled(numRows);
  6631. return true;
  6632. }
  6633. IDiskMerger * queryMerger()
  6634. {
  6635. if (!diskMerger)
  6636. {
  6637. unsigned __int64 seq = (memsize_t)this ^ get_cycles_now();
  6638. StringBuffer spillBasename;
  6639. spillBasename.append(tempDirectory).append(PATHSEPCHAR).appendf("spill_sort_%"I64F"u", seq);
  6640. Owned<IRowLinkCounter> linker = new RoxieRowLinkCounter();
  6641. Owned<IRowInterfaces> rowInterfaces = createRowInterfaces(rowMeta, activityId, ctx->queryCodeContext());
  6642. diskMerger.setown(createDiskMerger(rowInterfaces, linker, spillBasename));
  6643. }
  6644. return diskMerger;
  6645. }
  6646. };
  6647. #define INSERTION_SORT_BLOCKSIZE 1024
  6648. class SortedBlock : public CInterface, implements IInterface
  6649. {
  6650. unsigned sequence;
  6651. const void **rows;
  6652. unsigned length;
  6653. unsigned pos;
  6654. SortedBlock(const SortedBlock &);
  6655. public:
  6656. IMPLEMENT_IINTERFACE;
  6657. SortedBlock(unsigned _sequence, IRowManager *rowManager, unsigned activityId) : sequence(_sequence)
  6658. {
  6659. rows = (const void **) rowManager->allocate(INSERTION_SORT_BLOCKSIZE * sizeof(void *), activityId);
  6660. length = 0;
  6661. pos = 0;
  6662. }
  6663. ~SortedBlock()
  6664. {
  6665. while (pos < length)
  6666. ReleaseRoxieRow(rows[pos++]);
  6667. ReleaseRoxieRow(rows);
  6668. }
  6669. int compareTo(SortedBlock *r, ICompare *compare)
  6670. {
  6671. int rc = compare->docompare(rows[pos], r->rows[r->pos]);
  6672. if (!rc)
  6673. rc = sequence - r->sequence;
  6674. return rc;
  6675. }
  6676. const void *next()
  6677. {
  6678. if (pos < length)
  6679. return rows[pos++];
  6680. else
  6681. return NULL;
  6682. }
  6683. inline bool eof()
  6684. {
  6685. return pos==length;
  6686. }
  6687. bool insert(const void *next, ICompare *_compare )
  6688. {
  6689. unsigned b = length;
  6690. if (b == INSERTION_SORT_BLOCKSIZE)
  6691. return false;
  6692. else if (b < 7)
  6693. {
  6694. while (b)
  6695. {
  6696. if (_compare->docompare(next, rows[b-1]) >= 0)
  6697. break;
  6698. b--;
  6699. }
  6700. if (b != length)
  6701. memmove(&rows[b+1], &rows[b], (length - b) * sizeof(void *));
  6702. rows[b] = next;
  6703. length++;
  6704. return true;
  6705. }
  6706. else
  6707. {
  6708. unsigned int a = 0;
  6709. while ((int)a<b)
  6710. {
  6711. int i = (a+b)/2;
  6712. int rc = _compare->docompare(next, rows[i]);
  6713. if (rc>=0)
  6714. a = i+1;
  6715. else
  6716. b = i;
  6717. }
  6718. if (a != length)
  6719. memmove(&rows[a+1], &rows[a], (length - a) * sizeof(void *));
  6720. rows[a] = next;
  6721. length++;
  6722. return true;
  6723. }
  6724. }
  6725. };
  6726. class CInsertionSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6727. {
  6728. SortedBlock *curBlock;
  6729. unsigned blockNo;
  6730. IArrayOf<SortedBlock> blocks;
  6731. unsigned activityId;
  6732. IRowManager *rowManager;
  6733. ICompare *compare;
  6734. void newBlock()
  6735. {
  6736. blocks.append(*curBlock);
  6737. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6738. }
  6739. inline static int doCompare(SortedBlock &l, SortedBlock &r, ICompare *compare)
  6740. {
  6741. return l.compareTo(&r, compare);
  6742. }
  6743. void makeHeap()
  6744. {
  6745. /* Permute blocks to establish the heap property
  6746. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  6747. The children of p must both be greater than or equal to p
  6748. The parent of a child c is given by p = (c-1)/2
  6749. */
  6750. unsigned i;
  6751. unsigned n = blocks.length();
  6752. SortedBlock **s = blocks.getArray();
  6753. for (i=1; i<n; i++)
  6754. {
  6755. SortedBlock * r = s[i];
  6756. int c = i; /* child */
  6757. while (c > 0)
  6758. {
  6759. int p = (c-1)/2; /* parent */
  6760. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6761. break;
  6762. s[c] = s[p];
  6763. s[p] = r;
  6764. c = p;
  6765. }
  6766. }
  6767. }
  6768. void remakeHeap()
  6769. {
  6770. /* The row associated with block[0] will have changed
  6771. This code restores the heap property
  6772. */
  6773. unsigned p = 0; /* parent */
  6774. unsigned n = blocks.length();
  6775. SortedBlock **s = blocks.getArray();
  6776. while (1)
  6777. {
  6778. unsigned c = p*2 + 1; /* child */
  6779. if ( c >= n )
  6780. break;
  6781. /* Select smaller child */
  6782. if ( c+1 < n && doCompare( blocks.item(c+1), blocks.item(c), compare ) < 0 ) c += 1;
  6783. /* If child is greater or equal than parent then we are done */
  6784. if ( doCompare( blocks.item(c), blocks.item(p), compare ) >= 0 )
  6785. break;
  6786. /* Swap parent and child */
  6787. SortedBlock *r = s[c];
  6788. s[c] = s[p];
  6789. s[p] = r;
  6790. /* child becomes parent */
  6791. p = c;
  6792. }
  6793. }
  6794. public:
  6795. CInsertionSortAlgorithm(ICompare *_compare, IRowManager *_rowManager, unsigned _activityId)
  6796. : compare(_compare)
  6797. {
  6798. rowManager = _rowManager;
  6799. activityId = _activityId;
  6800. curBlock = NULL;
  6801. blockNo = 0;
  6802. }
  6803. virtual void reset()
  6804. {
  6805. blocks.kill();
  6806. delete curBlock;
  6807. curBlock = NULL;
  6808. blockNo = 0;
  6809. }
  6810. virtual void prepare(IRoxieInput *input)
  6811. {
  6812. blockNo = 0;
  6813. curBlock = new SortedBlock(blockNo++, rowManager, activityId);
  6814. loop
  6815. {
  6816. const void *next = input->nextInGroup();
  6817. if (!next)
  6818. break;
  6819. if (!curBlock->insert(next, compare))
  6820. {
  6821. newBlock();
  6822. curBlock->insert(next, compare);
  6823. }
  6824. }
  6825. if (blockNo > 1)
  6826. {
  6827. blocks.append(*curBlock);
  6828. curBlock = NULL;
  6829. makeHeap();
  6830. }
  6831. }
  6832. virtual const void * next()
  6833. {
  6834. const void *ret;
  6835. if (blockNo==1) // single block case..
  6836. {
  6837. ret = curBlock->next();
  6838. }
  6839. else if (blocks.length())
  6840. {
  6841. SortedBlock &top = blocks.item(0);
  6842. ret = top.next();
  6843. if (top.eof())
  6844. blocks.replace(blocks.popGet(), 0);
  6845. remakeHeap();
  6846. }
  6847. else
  6848. ret = NULL;
  6849. return ret;
  6850. }
  6851. };
  6852. class CHeapSortAlgorithm : implements CInterfaceOf<ISortAlgorithm>
  6853. {
  6854. unsigned curIndex;
  6855. ConstPointerArray sorted;
  6856. bool inputAlreadySorted;
  6857. IntArray sequences;
  6858. bool eof;
  6859. ICompare *compare;
  6860. #ifdef _CHECK_HEAPSORT
  6861. void checkHeap() const
  6862. {
  6863. unsigned n = sorted.ordinality();
  6864. if (n)
  6865. {
  6866. ICompare *_compare = compare;
  6867. void **s = sorted.getArray();
  6868. int *sq = sequences.getArray();
  6869. unsigned p;
  6870. #if 0
  6871. CTXLOG("------------------------%d entries-----------------", n);
  6872. for (p = 0; p < n; p++)
  6873. {
  6874. CTXLOG("HEAP %d: %d %.10s", p, sq[p], s[p] ? s[p] : "..");
  6875. }
  6876. #endif
  6877. for (p = 0; p < n; p++)
  6878. {
  6879. unsigned c = p*2+1;
  6880. if (c<n)
  6881. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6882. c++;
  6883. if (c<n)
  6884. assertex(!s[c] || (docompare(p, c, _compare, s, sq) <= 0));
  6885. }
  6886. }
  6887. }
  6888. #else
  6889. inline void checkHeap() const {}
  6890. #endif
  6891. const void *removeHeap()
  6892. {
  6893. unsigned n = sorted.ordinality();
  6894. if (n)
  6895. {
  6896. const void *ret = sorted.item(0);
  6897. if (n > 1 && ret)
  6898. {
  6899. ICompare *_compare = compare;
  6900. const void **s = sorted.getArray();
  6901. int *sq = sequences.getArray();
  6902. unsigned v = 0; // vacancy
  6903. loop
  6904. {
  6905. unsigned c = 2*v + 1;
  6906. if (c < n)
  6907. {
  6908. unsigned f = c; // favourite to fill it
  6909. c++;
  6910. if (c < n && s[c] && (!s[f] || (docompare(f, c, _compare, s, sq) > 0))) // is the smaller of the children
  6911. f = c;
  6912. sq[v] = sq[f];
  6913. if ((s[v] = s[f]) != NULL)
  6914. v = f;
  6915. else
  6916. break;
  6917. }
  6918. else
  6919. {
  6920. s[v] = NULL;
  6921. break;
  6922. }
  6923. }
  6924. }
  6925. checkHeap();
  6926. return ret;
  6927. }
  6928. else
  6929. return NULL;
  6930. }
  6931. static inline int docompare(unsigned l, unsigned r, ICompare *_compare, const void **s, int *sq)
  6932. {
  6933. int rc = _compare->docompare(s[l], s[r]);
  6934. if (!rc)
  6935. rc = sq[l] - sq[r];
  6936. return rc;
  6937. }
  6938. void insertHeap(const void *next)
  6939. {
  6940. // Upside-down heap sort
  6941. // Maintain a heap where every parent is lower than each of its children
  6942. // Root (at node 0) is lowest record seen, nodes 2n+1, 2n+2 are the children
  6943. // To insert a row, add it at end then keep swapping with parent as long as parent is greater
  6944. // To remove a row, take row 0, then recreate heap by replacing it with smaller of two children and so on down the tree
  6945. // Nice features:
  6946. // 1. Deterministic
  6947. // 2. Sort time can be overlapped with upstream/downstream processes - there is no delay between receiving last record from input and deliveriing first to output
  6948. // 3. Already sorted case can be spotted at zero cost while reading.
  6949. // 4. If you don't read all the results, you don't have to complete the sort
  6950. // BUT it is NOT stable, so we have to use a parallel array of sequence numbers
  6951. unsigned n = sorted.ordinality();
  6952. sorted.append(next);
  6953. sequences.append(n);
  6954. if (!n)
  6955. return;
  6956. ICompare *_compare = compare;
  6957. const void **s = sorted.getArray();
  6958. if (inputAlreadySorted)
  6959. {
  6960. if (_compare->docompare(next, s[n-1]) >= 0)
  6961. return;
  6962. else
  6963. {
  6964. // MORE - could delay creating sequences until now...
  6965. inputAlreadySorted = false;
  6966. }
  6967. }
  6968. int *sq = sequences.getArray();
  6969. unsigned q = n;
  6970. while (n)
  6971. {
  6972. unsigned parent = (n-1) / 2;
  6973. const void *p = s[parent];
  6974. if (_compare->docompare(p, next) <= 0)
  6975. break;
  6976. s[n] = p;
  6977. sq[n] = sq[parent];
  6978. s[parent] = next;
  6979. sq[parent] = q;
  6980. n = parent;
  6981. }
  6982. }
  6983. public:
  6984. CHeapSortAlgorithm(ICompare *_compare) : compare(_compare)
  6985. {
  6986. inputAlreadySorted = true;
  6987. curIndex = 0;
  6988. eof = false;
  6989. }
  6990. virtual void reset()
  6991. {
  6992. eof = false;
  6993. if (inputAlreadySorted)
  6994. {
  6995. while (sorted.isItem(curIndex))
  6996. ReleaseRoxieRow(sorted.item(curIndex++));
  6997. sorted.kill();
  6998. }
  6999. else
  7000. {
  7001. ReleaseRoxieRowSet(sorted);
  7002. }
  7003. inputAlreadySorted = true;
  7004. sequences.kill();
  7005. }
  7006. virtual void prepare(IRoxieInput *input)
  7007. {
  7008. inputAlreadySorted = true;
  7009. curIndex = 0;
  7010. eof = false;
  7011. assertex(sorted.ordinality()==0);
  7012. const void *next = input->nextInGroup();
  7013. if (!next)
  7014. {
  7015. eof = true;
  7016. return;
  7017. }
  7018. loop
  7019. {
  7020. insertHeap(next);
  7021. next = input->nextInGroup();
  7022. if (!next)
  7023. break;
  7024. }
  7025. checkHeap();
  7026. }
  7027. virtual const void * next()
  7028. {
  7029. if (inputAlreadySorted)
  7030. {
  7031. if (sorted.isItem(curIndex))
  7032. {
  7033. return sorted.item(curIndex++);
  7034. }
  7035. else
  7036. return NULL;
  7037. }
  7038. else
  7039. return removeHeap();
  7040. }
  7041. };
  7042. typedef enum {heapSort, insertionSort, quickSort, spillingQuickSort, unknownSort } RoxieSortAlgorithm;
  7043. class CRoxieServerSortActivity : public CRoxieServerActivity
  7044. {
  7045. protected:
  7046. IHThorSortArg &helper;
  7047. ICompare *compare;
  7048. Owned<ISortAlgorithm> sorter;
  7049. bool readInput;
  7050. RoxieSortAlgorithm sortAlgorithm;
  7051. unsigned sortFlags;
  7052. public:
  7053. CRoxieServerSortActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7054. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7055. {
  7056. compare = helper.queryCompare();
  7057. readInput = false;
  7058. }
  7059. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7060. {
  7061. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7062. switch (sortAlgorithm)
  7063. {
  7064. case heapSort:
  7065. sorter.setown(new CHeapSortAlgorithm(compare));
  7066. break;
  7067. case insertionSort:
  7068. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7069. break;
  7070. case quickSort:
  7071. sorter.setown(new CQuickSortAlgorithm(compare));
  7072. break;
  7073. case spillingQuickSort:
  7074. sorter.setown(new CSpillingQuickSortAlgorithm(compare, ctx, meta, activityId));
  7075. break;
  7076. case unknownSort:
  7077. sorter.clear(); // create it later....
  7078. break;
  7079. default:
  7080. throwUnexpected();
  7081. break;
  7082. }
  7083. }
  7084. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7085. {
  7086. assertex(!readInput);
  7087. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7088. }
  7089. virtual void reset()
  7090. {
  7091. if (sorter)
  7092. sorter->reset();
  7093. readInput = false;
  7094. CRoxieServerActivity::reset();
  7095. }
  7096. virtual const void * nextInGroup()
  7097. {
  7098. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7099. if (!readInput)
  7100. {
  7101. if (sortAlgorithm == unknownSort)
  7102. {
  7103. sorter.clear();
  7104. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
  7105. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7106. if (useAlgorithm)
  7107. {
  7108. if (stricmp(useAlgorithm, "quicksort")==0)
  7109. {
  7110. if (sortFlags & TAFstable)
  7111. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7112. sorter.setown(new CQuickSortAlgorithm(compare));
  7113. }
  7114. else if (stricmp(useAlgorithm, "heapsort")==0)
  7115. sorter.setown(new CHeapSortAlgorithm(compare));
  7116. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7117. sorter.setown(new CInsertionSortAlgorithm(compare, &ctx->queryRowManager(), activityId));
  7118. else
  7119. {
  7120. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7121. if (sortFlags & TAFunstable)
  7122. sorter.setown(new CQuickSortAlgorithm(compare));
  7123. else
  7124. sorter.setown(new CHeapSortAlgorithm(compare));
  7125. }
  7126. }
  7127. else
  7128. sorter.setown(new CHeapSortAlgorithm(compare)); // shouldn't really happen but there was a vintage of codegen that did not set the flag when algorithm not specified...
  7129. }
  7130. sorter->prepare(input);
  7131. readInput = true;
  7132. }
  7133. const void *ret = sorter->next();
  7134. if (ret)
  7135. processed++;
  7136. else
  7137. {
  7138. sorter->reset();
  7139. readInput = false; // ready for next group
  7140. }
  7141. return ret;
  7142. }
  7143. };
  7144. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7145. {
  7146. RoxieSortAlgorithm sortAlgorithm;
  7147. unsigned sortFlags;
  7148. public:
  7149. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7150. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7151. {
  7152. sortAlgorithm = heapSort;
  7153. sortFlags = TAFstable;
  7154. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7155. IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
  7156. if (sortMethod)
  7157. {
  7158. sortFlags = sortMethod->getAlgorithmFlags();
  7159. if (sortFlags & TAFunstable)
  7160. sortAlgorithm = quickSort;
  7161. if (!(sortFlags & TAFconstant))
  7162. sortAlgorithm = unknownSort;
  7163. else
  7164. {
  7165. OwnedRoxieString useAlgorithm(sortMethod->getAlgorithm());
  7166. if (useAlgorithm)
  7167. {
  7168. if (stricmp(useAlgorithm, "quicksort")==0)
  7169. {
  7170. if (sortFlags & TAFstable)
  7171. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7172. sortAlgorithm = quickSort;
  7173. }
  7174. else if (stricmp(useAlgorithm, "spillingquicksort")==0)
  7175. {
  7176. if (sortFlags & TAFstable)
  7177. throw MakeStringException(ROXIE_UNKNOWN_ALGORITHM, "Invalid stable sort algorithm %s requested", useAlgorithm.get());
  7178. sortAlgorithm = spillingQuickSort;
  7179. }
  7180. else if (stricmp(useAlgorithm, "heapsort")==0)
  7181. sortAlgorithm = heapSort; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection
  7182. else if (stricmp(useAlgorithm, "insertionsort")==0)
  7183. sortAlgorithm = insertionSort;
  7184. else
  7185. {
  7186. WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", useAlgorithm.get());
  7187. if (sortFlags & TAFunstable)
  7188. sortAlgorithm = quickSort;
  7189. else
  7190. sortAlgorithm = heapSort;
  7191. }
  7192. }
  7193. }
  7194. }
  7195. }
  7196. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7197. {
  7198. return new CRoxieServerSortActivity(this, _probeManager, sortAlgorithm, sortFlags);
  7199. }
  7200. };
  7201. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7202. {
  7203. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7204. }
  7205. //=====================================================================================================
  7206. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7207. {
  7208. IHThorSortedArg &helper;
  7209. ICompare * compare;
  7210. const void *prev;
  7211. IRangeCompare * stepCompare;
  7212. public:
  7213. CRoxieServerSortedActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7214. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7215. {
  7216. prev = NULL;
  7217. compare = helper.queryCompare();
  7218. stepCompare = NULL;
  7219. }
  7220. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7221. {
  7222. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7223. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7224. if (stepMeta)
  7225. stepCompare = stepMeta->queryCompare();
  7226. prev = NULL;
  7227. }
  7228. virtual void reset()
  7229. {
  7230. ReleaseClearRoxieRow(prev);
  7231. CRoxieServerActivity::reset();
  7232. }
  7233. virtual const void * nextInGroup()
  7234. {
  7235. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7236. const void *ret = input->nextInGroup();
  7237. if (ret && prev && compare->docompare(prev, ret) > 0)
  7238. {
  7239. // MORE - better to give mismatching rows that indexes?
  7240. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7241. }
  7242. ReleaseRoxieRow(prev);
  7243. prev = ret;
  7244. if (ret)
  7245. {
  7246. LinkRoxieRow(prev);
  7247. processed++;
  7248. }
  7249. return ret;
  7250. }
  7251. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7252. {
  7253. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7254. const void *ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  7255. if (ret && prev && compare->docompare(prev, ret) > 0)
  7256. {
  7257. // MORE - better to give mismatching rows that indexes?
  7258. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7259. }
  7260. ReleaseRoxieRow(prev);
  7261. prev = ret;
  7262. if (ret)
  7263. {
  7264. LinkRoxieRow(prev);
  7265. processed++;
  7266. }
  7267. return ret;
  7268. }
  7269. IInputSteppingMeta * querySteppingMeta()
  7270. {
  7271. return input->querySteppingMeta();
  7272. }
  7273. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7274. {
  7275. return input->gatherConjunctions(collector);
  7276. }
  7277. virtual void resetEOF()
  7278. {
  7279. input->resetEOF();
  7280. }
  7281. };
  7282. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7283. {
  7284. public:
  7285. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7286. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7287. {
  7288. }
  7289. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7290. {
  7291. return new CRoxieServerSortedActivity(this, _probeManager);
  7292. }
  7293. };
  7294. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7295. {
  7296. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7297. }
  7298. //=====================================================================================================
  7299. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7300. {
  7301. /*
  7302. BE VERY CAREFUL - this code is tricky.
  7303. Note that starts and stops (and resets) can occur in strange orders
  7304. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7305. The last stop should call the upstream stop.
  7306. The first reset should call the upstream reset.
  7307. The calculation of whether a row is needed for other (yet to come) outputs needs to work correctly even if the output in question has
  7308. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7309. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7310. ignored in the minIndex calculation
  7311. */
  7312. public:
  7313. IHThorArg &helper;
  7314. unsigned activeOutputs;
  7315. unsigned numOutputs;
  7316. unsigned numOriginalOutputs;
  7317. QueueOf<const void, true> buffer;
  7318. CriticalSection crit;
  7319. CriticalSection crit2;
  7320. unsigned tailIdx;
  7321. unsigned headIdx;
  7322. Owned<IException> error;
  7323. class OutputAdaptor : public CInterface, implements IRoxieInput
  7324. {
  7325. bool eof, eofpending, stopped;
  7326. public:
  7327. CRoxieServerThroughSpillActivity *parent;
  7328. unsigned idx;
  7329. unsigned oid;
  7330. unsigned processed;
  7331. unsigned __int64 totalCycles;
  7332. public:
  7333. IMPLEMENT_IINTERFACE;
  7334. OutputAdaptor()
  7335. {
  7336. parent = NULL;
  7337. oid = 0;
  7338. idx = 0;
  7339. processed = 0;
  7340. totalCycles = 0;
  7341. eofpending = false;
  7342. eof = false;
  7343. stopped = false;
  7344. }
  7345. ~OutputAdaptor()
  7346. {
  7347. if (traceStartStop)
  7348. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7349. }
  7350. void init()
  7351. {
  7352. if (traceStartStop)
  7353. DBGLOG("%p init Input adaptor %d", this, oid);
  7354. idx = 0;
  7355. processed = 0;
  7356. totalCycles = 0;
  7357. eofpending = false;
  7358. eof = false;
  7359. stopped = false;
  7360. }
  7361. virtual unsigned queryId() const
  7362. {
  7363. return parent->queryId();
  7364. }
  7365. virtual IRoxieServerActivity *queryActivity()
  7366. {
  7367. return parent;
  7368. }
  7369. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7370. {
  7371. return parent->queryIndexReadActivity();
  7372. }
  7373. virtual unsigned __int64 queryTotalCycles() const
  7374. {
  7375. return totalCycles;
  7376. }
  7377. virtual unsigned __int64 queryLocalCycles() const
  7378. {
  7379. return 0;
  7380. }
  7381. virtual IRoxieInput *queryInput(unsigned idx) const
  7382. {
  7383. return parent->queryInput(idx);
  7384. }
  7385. virtual const void * nextInGroup()
  7386. {
  7387. ActivityTimer t(totalCycles, timeActivities, parent->ctx->queryDebugContext());
  7388. if (eof)
  7389. return NULL;
  7390. const void *ret = parent->readBuffered(idx, oid);
  7391. #ifdef TRACE_SPLIT
  7392. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  7393. #endif
  7394. idx++;
  7395. if (ret)
  7396. {
  7397. processed++;
  7398. eofpending = false;
  7399. }
  7400. else if (eofpending)
  7401. eof = true;
  7402. else
  7403. eofpending = true;
  7404. return ret;
  7405. }
  7406. virtual IOutputMetaData * queryOutputMeta() const
  7407. {
  7408. return parent->queryOutputMeta();
  7409. }
  7410. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7411. {
  7412. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  7413. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  7414. // for minIndex to give the correct answers
  7415. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  7416. if (traceStartStop)
  7417. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  7418. parent->start(oid, parentExtractSize, parentExtract, paused);
  7419. }
  7420. virtual void stop(bool aborting)
  7421. {
  7422. if (traceStartStop)
  7423. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  7424. if (!stopped)
  7425. {
  7426. parent->stop(oid, idx, aborting); // NOTE - may call init()
  7427. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  7428. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  7429. }
  7430. };
  7431. virtual void reset()
  7432. {
  7433. if (traceStartStop)
  7434. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  7435. parent->reset(oid);
  7436. parent->noteProcessed(oid, processed, 0, 0);
  7437. processed = 0;
  7438. idx = 0; // value should not be relevant really but this is the safest...
  7439. stopped = false;
  7440. };
  7441. virtual void resetEOF()
  7442. {
  7443. parent->resetEOF();
  7444. }
  7445. virtual void checkAbort()
  7446. {
  7447. parent->checkAbort();
  7448. }
  7449. } *adaptors;
  7450. bool *used;
  7451. unsigned nextFreeOutput()
  7452. {
  7453. unsigned i = numOutputs;
  7454. while (i)
  7455. {
  7456. i--;
  7457. if (!used[i])
  7458. return i;
  7459. }
  7460. throwUnexpected();
  7461. }
  7462. unsigned minIndex(unsigned exceptOid)
  7463. {
  7464. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  7465. // this is trying to determine whethwe any of the adaptors will in the future read a given record
  7466. unsigned minIdx = (unsigned) -1;
  7467. for (unsigned i = 0; i < numOutputs; i++)
  7468. {
  7469. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  7470. minIdx = adaptors[i].idx;
  7471. }
  7472. return minIdx;
  7473. }
  7474. void initOutputs()
  7475. {
  7476. activeOutputs = numOutputs;
  7477. for (unsigned i = 0; i < numOriginalOutputs; i++)
  7478. if (used[i])
  7479. adaptors[i].init();
  7480. state = STATEstarting;
  7481. }
  7482. public:
  7483. CRoxieServerThroughSpillActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  7484. : CRoxieServerActivity(_factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  7485. {
  7486. numOriginalOutputs = numOutputs;
  7487. adaptors = new OutputAdaptor[numOutputs];
  7488. used = new bool[numOutputs];
  7489. for (unsigned i = 0; i < numOutputs; i++)
  7490. {
  7491. adaptors[i].parent = this;
  7492. adaptors[i].oid = i;
  7493. used[i] = false;
  7494. }
  7495. tailIdx = 0;
  7496. headIdx = 0;
  7497. activeOutputs = numOutputs;
  7498. }
  7499. ~CRoxieServerThroughSpillActivity()
  7500. {
  7501. delete [] adaptors;
  7502. delete [] used;
  7503. }
  7504. const void *readBuffered(unsigned idx, unsigned oid)
  7505. {
  7506. CriticalBlock b(crit);
  7507. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // NOTE - time spent waiting for crit not included here. Is that right?
  7508. if (idx == headIdx) // test once without getting the crit2 sec
  7509. {
  7510. CriticalUnblock b1(crit);
  7511. CriticalBlock b2(crit2);
  7512. if (error)
  7513. {
  7514. throw error.getLink();
  7515. }
  7516. if (idx == headIdx) // test again now that we have it
  7517. {
  7518. try
  7519. {
  7520. const void *row = input->nextInGroup();
  7521. CriticalBlock b3(crit);
  7522. headIdx++;
  7523. if (activeOutputs==1)
  7524. {
  7525. #ifdef TRACE_SPLIT
  7526. CTXLOG("spill %d optimised return of %p", activityId, row);
  7527. #endif
  7528. return row; // optimization for the case where only one output still active.
  7529. }
  7530. buffer.enqueue(row);
  7531. }
  7532. catch (IException *E)
  7533. {
  7534. #ifdef TRACE_SPLIT
  7535. CTXLOG("spill %d caught exception", activityId);
  7536. #endif
  7537. error.set(E);
  7538. throw;
  7539. }
  7540. catch (...)
  7541. {
  7542. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  7543. error.set(E);
  7544. throw E;
  7545. }
  7546. }
  7547. }
  7548. idx -= tailIdx;
  7549. if (!idx)
  7550. {
  7551. unsigned min = minIndex(oid);
  7552. if (min > tailIdx)
  7553. {
  7554. tailIdx++;
  7555. const void *ret = buffer.dequeue(); // no need to link - last puller
  7556. #ifdef TRACE_SPLIT
  7557. CTXLOG("last puller return of %p", ret);
  7558. #endif
  7559. return ret;
  7560. }
  7561. }
  7562. const void *ret = buffer.item(idx);
  7563. if (ret) LinkRoxieRow(ret);
  7564. #ifdef TRACE_SPLIT
  7565. CTXLOG("standard return of %p", ret);
  7566. #endif
  7567. return ret;
  7568. }
  7569. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7570. {
  7571. CriticalBlock b(crit);
  7572. if (error)
  7573. throw error.getLink();
  7574. if (factory)
  7575. factory->noteStarted(oid);
  7576. if (traceStartStop)
  7577. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7578. if (state != STATEstarted)
  7579. {
  7580. if (state != STATEstarting)
  7581. initOutputs();
  7582. tailIdx = 0;
  7583. headIdx = 0;
  7584. error.clear();
  7585. try
  7586. {
  7587. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7588. }
  7589. catch (IException *E)
  7590. {
  7591. #ifdef TRACE_SPLIT
  7592. CTXLOG("spill %d caught exception in start", activityId);
  7593. #endif
  7594. error.set(E);
  7595. throw;
  7596. }
  7597. catch (...)
  7598. {
  7599. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  7600. error.set(E);
  7601. throw E;
  7602. }
  7603. }
  7604. }
  7605. void stop(unsigned oid, unsigned idx, bool aborting)
  7606. {
  7607. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  7608. CriticalBlock b(crit);
  7609. #ifdef TRACE_STARTSTOP
  7610. if (traceStartStop)
  7611. {
  7612. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7613. if (watchActivityId && watchActivityId==activityId)
  7614. {
  7615. CTXLOG("WATCH: stop %d", activityId);
  7616. }
  7617. }
  7618. #endif
  7619. if (state != STATEstarting && state != STATEstarted)
  7620. initOutputs();
  7621. if (activeOutputs > 1)
  7622. {
  7623. if (tailIdx==idx)
  7624. {
  7625. // Discard all buffered rows that are there purely for this adaptor to read them
  7626. unsigned min = minIndex(oid);
  7627. if (min != (unsigned) -1)
  7628. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  7629. // Should never happen though if there are still some active.
  7630. // there may be a small window where adaptors are blocked on the semaphore...
  7631. {
  7632. #ifdef TRACE_SPLIT
  7633. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  7634. #endif
  7635. while (tailIdx < min)
  7636. {
  7637. ReleaseRoxieRow(buffer.dequeue());
  7638. tailIdx++;
  7639. }
  7640. }
  7641. }
  7642. activeOutputs--;
  7643. return;
  7644. }
  7645. #ifdef TRACE_SPLIT
  7646. CTXLOG("%p: All outputs done", this);
  7647. #endif
  7648. activeOutputs = numOutputs;
  7649. CRoxieServerActivity::stop(aborting);
  7650. };
  7651. void reset(unsigned oid)
  7652. {
  7653. if (traceStartStop)
  7654. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  7655. activeOutputs = numOutputs;
  7656. while (buffer.ordinality())
  7657. ReleaseRoxieRow(buffer.dequeue());
  7658. error.clear();
  7659. if (state != STATEreset) // make sure input is only reset once
  7660. CRoxieServerActivity::reset();
  7661. };
  7662. virtual unsigned __int64 queryLocalCycles() const
  7663. {
  7664. return 0;
  7665. }
  7666. virtual const void *nextInGroup()
  7667. {
  7668. throwUnexpected(); // Internal logic error - we are not anybody's input
  7669. }
  7670. virtual IOutputMetaData * queryOutputMeta() const
  7671. {
  7672. // if (outputMeta)
  7673. // return outputMeta;
  7674. // else
  7675. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  7676. }
  7677. virtual IRoxieInput *queryOutput(unsigned idx)
  7678. {
  7679. if (idx==(unsigned)-1)
  7680. idx = nextFreeOutput(); // MORE - what is this used for?
  7681. assertex(idx < numOriginalOutputs);
  7682. assertex(!used[idx]);
  7683. used[idx] = true;
  7684. return &adaptors[idx];
  7685. }
  7686. virtual void resetOutputsUsed()
  7687. {
  7688. numOutputs = 1;
  7689. activeOutputs = 1;
  7690. // MORE RKC->GH should we be clearing the used array here? anywhere?
  7691. }
  7692. virtual void noteOutputUsed()
  7693. {
  7694. assertex(numOutputs < numOriginalOutputs);
  7695. numOutputs++;
  7696. activeOutputs = numOutputs;
  7697. }
  7698. virtual bool isPassThrough()
  7699. {
  7700. return numOutputs==1;
  7701. }
  7702. };
  7703. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  7704. {
  7705. public:
  7706. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7707. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7708. {
  7709. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  7710. setNumOutputs(helper->getTempUsageCount() + 1);
  7711. }
  7712. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs)
  7713. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit)
  7714. {
  7715. setNumOutputs(_numOutputs);
  7716. }
  7717. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7718. {
  7719. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7720. }
  7721. };
  7722. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7723. {
  7724. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7725. }
  7726. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs)
  7727. {
  7728. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs);
  7729. }
  7730. //----------------------------------------------------------------------------------------------
  7731. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  7732. {
  7733. public:
  7734. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7735. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  7736. {
  7737. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  7738. setNumOutputs(helper->numBranches());
  7739. }
  7740. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  7741. {
  7742. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  7743. }
  7744. };
  7745. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  7746. {
  7747. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  7748. }
  7749. //=====================================================================================================
  7750. #define PIPE_BUFSIZE 0x8000
  7751. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  7752. {
  7753. StringBuffer msg;
  7754. if(pipe->hasError())
  7755. {
  7756. try
  7757. {
  7758. char error[512];
  7759. size32_t sz = pipe->readError(sizeof(error), error);
  7760. if(sz && sz!=(size32_t)-1)
  7761. msg.append(", stderr: '").append(sz, error).append("'");
  7762. }
  7763. catch (IException *e)
  7764. {
  7765. EXCLOG(e, "Error reading pipe stderr");
  7766. e->Release();
  7767. }
  7768. }
  7769. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  7770. }
  7771. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  7772. {
  7773. IHThorPipeReadArg &helper;
  7774. Owned<IPipeProcess> pipe;
  7775. StringAttr pipeCommand;
  7776. Owned<IOutputRowDeserializer> rowDeserializer;
  7777. Owned<IReadRowStream> readTransformer;
  7778. bool groupSignalled;
  7779. public:
  7780. CRoxieServerPipeReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7781. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  7782. {
  7783. groupSignalled = true;
  7784. }
  7785. virtual bool needsAllocator() const { return true; }
  7786. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7787. {
  7788. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7789. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7790. }
  7791. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7792. {
  7793. groupSignalled = true; // i.e. don't start with a NULL row
  7794. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7795. if (!readTransformer)
  7796. {
  7797. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  7798. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  7799. }
  7800. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7801. openPipe(pipeProgram);
  7802. }
  7803. virtual void stop(bool aborting)
  7804. {
  7805. CRoxieServerActivity::stop(aborting);
  7806. pipe.clear();
  7807. readTransformer->setStream(NULL);
  7808. }
  7809. virtual const void *nextInGroup()
  7810. {
  7811. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7812. while (!waitForPipe())
  7813. {
  7814. if (!pipe)
  7815. return NULL;
  7816. if (helper.getPipeFlags() & TPFgroupeachrow)
  7817. {
  7818. if (!groupSignalled)
  7819. {
  7820. groupSignalled = true;
  7821. return NULL;
  7822. }
  7823. }
  7824. }
  7825. const void *ret = readTransformer->next();
  7826. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7827. processed++;
  7828. groupSignalled = false;
  7829. return ret;
  7830. }
  7831. protected:
  7832. bool waitForPipe()
  7833. {
  7834. if (!pipe)
  7835. return false; // done
  7836. if (!readTransformer->eos())
  7837. return true;
  7838. verifyPipe();
  7839. return false;
  7840. }
  7841. void openPipe(char const * cmd)
  7842. {
  7843. pipeCommand.setown(cmd);
  7844. pipe.setown(createPipeProcess());
  7845. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  7846. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  7847. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  7848. readTransformer->setStream(pipeReader.get());
  7849. }
  7850. void verifyPipe()
  7851. {
  7852. if (pipe)
  7853. {
  7854. unsigned err = pipe->wait();
  7855. if(err && !(helper.getPipeFlags() & TPFnofail))
  7856. {
  7857. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  7858. }
  7859. pipe.clear();
  7860. }
  7861. }
  7862. };
  7863. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  7864. {
  7865. IHThorPipeThroughArg &helper;
  7866. RecordPullerThread puller;
  7867. Owned<IPipeProcess> pipe;
  7868. StringAttr pipeCommand;
  7869. InterruptableSemaphore pipeVerified;
  7870. InterruptableSemaphore pipeOpened;
  7871. CachedOutputMetaData inputMeta;
  7872. Owned<IOutputRowSerializer> rowSerializer;
  7873. Owned<IOutputRowDeserializer> rowDeserializer;
  7874. Owned<IPipeWriteXformHelper> writeTransformer;
  7875. Owned<IReadRowStream> readTransformer;
  7876. bool firstRead;
  7877. bool recreate;
  7878. bool inputExhausted;
  7879. bool groupSignalled;
  7880. public:
  7881. CRoxieServerPipeThroughActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7882. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  7883. {
  7884. recreate = helper.recreateEachRow();
  7885. groupSignalled = true;
  7886. firstRead = false;
  7887. inputExhausted = false;
  7888. }
  7889. virtual bool needsAllocator() const { return true; }
  7890. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  7891. {
  7892. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  7893. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  7894. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  7895. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  7896. }
  7897. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7898. {
  7899. firstRead = true;
  7900. inputExhausted = false;
  7901. groupSignalled = true; // i.e. don't start with a NULL row
  7902. pipeVerified.reinit();
  7903. pipeOpened.reinit();
  7904. writeTransformer->ready();
  7905. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7906. if (!readTransformer)
  7907. {
  7908. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  7909. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  7910. }
  7911. if(!recreate)
  7912. {
  7913. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  7914. openPipe(pipeProgram);
  7915. }
  7916. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  7917. }
  7918. virtual void setInput(unsigned idx, IRoxieInput *_in)
  7919. {
  7920. if (idx)
  7921. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  7922. puller.setInput(this, _in);
  7923. inputMeta.set(_in->queryOutputMeta());
  7924. }
  7925. virtual void stop(bool aborting)
  7926. {
  7927. pipeVerified.interrupt(NULL);
  7928. pipeOpened.interrupt(NULL);
  7929. puller.stop(aborting);
  7930. CRoxieServerActivity::stop(aborting);
  7931. pipe.clear();
  7932. readTransformer->setStream(NULL);
  7933. }
  7934. virtual void reset()
  7935. {
  7936. puller.reset();
  7937. CRoxieServerActivity::reset();
  7938. }
  7939. virtual const void *nextInGroup()
  7940. {
  7941. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  7942. while (!waitForPipe())
  7943. {
  7944. if (!pipe)
  7945. return NULL;
  7946. if (helper.getPipeFlags() & TPFgroupeachrow)
  7947. {
  7948. if (!groupSignalled)
  7949. {
  7950. groupSignalled = true;
  7951. return NULL;
  7952. }
  7953. }
  7954. }
  7955. const void *ret = readTransformer->next();
  7956. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  7957. processed++;
  7958. groupSignalled = false;
  7959. return ret;
  7960. }
  7961. virtual void processRow(const void *row)
  7962. {
  7963. // called from puller thread
  7964. if(recreate)
  7965. openPipe(helper.getNameFromRow(row));
  7966. writeTransformer->writeTranslatedText(row, pipe);
  7967. ReleaseRoxieRow(row);
  7968. if(recreate)
  7969. {
  7970. closePipe();
  7971. pipeVerified.wait();
  7972. }
  7973. }
  7974. virtual void processDone()
  7975. {
  7976. // called from puller thread
  7977. if(recreate)
  7978. {
  7979. inputExhausted = true;
  7980. pipeOpened.signal();
  7981. }
  7982. else
  7983. {
  7984. closePipe();
  7985. pipeVerified.wait();
  7986. }
  7987. }
  7988. virtual void processEOG()
  7989. {
  7990. }
  7991. void processGroup(const ConstPointerArray &)
  7992. {
  7993. throwUnexpected();
  7994. }
  7995. virtual bool fireException(IException *e)
  7996. {
  7997. pipeOpened.interrupt(LINK(e));
  7998. pipeVerified.interrupt(e);
  7999. return true;
  8000. }
  8001. private:
  8002. bool waitForPipe()
  8003. {
  8004. if (firstRead)
  8005. {
  8006. pipeOpened.wait();
  8007. firstRead = false;
  8008. }
  8009. if (!pipe)
  8010. return false; // done
  8011. if (!readTransformer->eos())
  8012. return true;
  8013. verifyPipe();
  8014. if (recreate && !inputExhausted)
  8015. pipeOpened.wait();
  8016. return false;
  8017. }
  8018. void openPipe(char const * cmd)
  8019. {
  8020. pipeCommand.setown(cmd);
  8021. pipe.setown(createPipeProcess());
  8022. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8023. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8024. writeTransformer->writeHeader(pipe);
  8025. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8026. readTransformer->setStream(pipeReader.get());
  8027. pipeOpened.signal();
  8028. }
  8029. void closePipe()
  8030. {
  8031. writeTransformer->writeFooter(pipe);
  8032. pipe->closeInput();
  8033. }
  8034. void verifyPipe()
  8035. {
  8036. if (pipe)
  8037. {
  8038. unsigned err = pipe->wait();
  8039. if(err && !(helper.getPipeFlags() & TPFnofail))
  8040. {
  8041. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8042. }
  8043. pipe.clear();
  8044. pipeVerified.signal();
  8045. }
  8046. }
  8047. };
  8048. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8049. {
  8050. IHThorPipeWriteArg &helper;
  8051. Owned<IPipeProcess> pipe;
  8052. StringAttr pipeCommand;
  8053. CachedOutputMetaData inputMeta;
  8054. Owned<IOutputRowSerializer> rowSerializer;
  8055. Owned<IPipeWriteXformHelper> writeTransformer;
  8056. bool firstRead;
  8057. bool recreate;
  8058. bool inputExhausted;
  8059. public:
  8060. CRoxieServerPipeWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8061. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorPipeWriteArg &)basehelper)
  8062. {
  8063. recreate = helper.recreateEachRow();
  8064. firstRead = false;
  8065. inputExhausted = false;
  8066. }
  8067. virtual bool needsAllocator() const { return true; }
  8068. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  8069. {
  8070. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  8071. inputMeta.set(input->queryOutputMeta());
  8072. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8073. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8074. }
  8075. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8076. {
  8077. firstRead = true;
  8078. inputExhausted = false;
  8079. writeTransformer->ready();
  8080. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8081. if(!recreate)
  8082. {
  8083. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8084. openPipe(pipeProgram);
  8085. }
  8086. }
  8087. virtual void stop(bool aborting)
  8088. {
  8089. CRoxieServerActivity::stop(aborting);
  8090. pipe.clear();
  8091. }
  8092. virtual void onExecute()
  8093. {
  8094. loop
  8095. {
  8096. const void *row = input->nextInGroup();
  8097. if (!row)
  8098. {
  8099. row = input->nextInGroup();
  8100. if (!row)
  8101. break;
  8102. }
  8103. processed++;
  8104. if(recreate)
  8105. openPipe(helper.getNameFromRow(row));
  8106. writeTransformer->writeTranslatedText(row, pipe);
  8107. ReleaseRoxieRow(row);
  8108. if(recreate)
  8109. closePipe();
  8110. }
  8111. closePipe();
  8112. }
  8113. private:
  8114. void openPipe(char const * cmd)
  8115. {
  8116. pipeCommand.setown(cmd);
  8117. pipe.setown(createPipeProcess());
  8118. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8119. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8120. writeTransformer->writeHeader(pipe);
  8121. }
  8122. void closePipe()
  8123. {
  8124. writeTransformer->writeFooter(pipe);
  8125. pipe->closeInput();
  8126. unsigned err = pipe->wait();
  8127. if(err && !(helper.getPipeFlags() & TPFnofail))
  8128. {
  8129. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8130. }
  8131. pipe.clear();
  8132. }
  8133. };
  8134. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8135. {
  8136. public:
  8137. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8138. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8139. {
  8140. }
  8141. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8142. {
  8143. return new CRoxieServerPipeReadActivity(this, _probeManager);
  8144. }
  8145. };
  8146. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8147. {
  8148. public:
  8149. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8150. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8151. {
  8152. }
  8153. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8154. {
  8155. return new CRoxieServerPipeThroughActivity(this, _probeManager);
  8156. }
  8157. };
  8158. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8159. {
  8160. public:
  8161. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8162. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8163. {
  8164. }
  8165. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8166. {
  8167. return new CRoxieServerPipeWriteActivity(this, _probeManager);
  8168. }
  8169. };
  8170. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8171. {
  8172. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8173. }
  8174. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8175. {
  8176. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8177. }
  8178. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8179. {
  8180. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8181. }
  8182. //=====================================================================================================
  8183. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8184. {
  8185. IHThorStreamedIteratorArg &helper;
  8186. Owned<IRowStream> rows;
  8187. public:
  8188. CRoxieServerStreamedIteratorActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8189. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8190. {
  8191. }
  8192. ~CRoxieServerStreamedIteratorActivity()
  8193. {
  8194. }
  8195. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8196. {
  8197. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8198. rows.setown(helper.createInput());
  8199. }
  8200. virtual void stop(bool aborting)
  8201. {
  8202. if (rows)
  8203. {
  8204. rows->stop();
  8205. rows.clear();
  8206. }
  8207. CRoxieServerActivity::stop(aborting);
  8208. }
  8209. virtual const void *nextInGroup()
  8210. {
  8211. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8212. assertex(rows != NULL);
  8213. const void * next = rows->nextRow();
  8214. if (next)
  8215. processed++;
  8216. return next;
  8217. }
  8218. };
  8219. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8220. {
  8221. public:
  8222. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8223. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8224. {
  8225. }
  8226. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8227. {
  8228. return new CRoxieServerStreamedIteratorActivity(this, _probeManager);
  8229. }
  8230. };
  8231. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8232. {
  8233. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8234. }
  8235. //=====================================================================================================
  8236. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8237. {
  8238. IHThorFilterArg &helper;
  8239. bool anyThisGroup;
  8240. IRangeCompare * stepCompare;
  8241. public:
  8242. CRoxieServerFilterActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8243. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8244. {
  8245. anyThisGroup = false;
  8246. stepCompare = NULL;
  8247. }
  8248. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8249. {
  8250. anyThisGroup = false;
  8251. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8252. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8253. stepCompare = NULL;
  8254. if (!eof)
  8255. {
  8256. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8257. if (stepMeta)
  8258. stepCompare = stepMeta->queryCompare();
  8259. }
  8260. }
  8261. virtual const void * nextInGroup()
  8262. {
  8263. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8264. if (eof)
  8265. return NULL;
  8266. loop
  8267. {
  8268. const void * ret = input->nextInGroup();
  8269. if (!ret)
  8270. {
  8271. //stop returning two NULLs in a row.
  8272. if (anyThisGroup)
  8273. {
  8274. anyThisGroup = false;
  8275. return NULL;
  8276. }
  8277. ret = input->nextInGroup();
  8278. if (!ret)
  8279. {
  8280. eof = true;
  8281. return NULL; // eof...
  8282. }
  8283. }
  8284. if (helper.isValid(ret))
  8285. {
  8286. anyThisGroup = true;
  8287. processed++;
  8288. return ret;
  8289. }
  8290. ReleaseRoxieRow(ret);
  8291. }
  8292. }
  8293. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8294. {
  8295. //Could assert that this isn't grouped
  8296. // MORE - will need rethinking once we rethink the nextSteppedGE interface for global smart-stepping.
  8297. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8298. if (eof)
  8299. return NULL;
  8300. loop
  8301. {
  8302. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8303. if (!ret)
  8304. {
  8305. eof = true;
  8306. return NULL;
  8307. }
  8308. if (!wasCompleteMatch)
  8309. {
  8310. anyThisGroup = false; // RKC->GH - is this right??
  8311. return ret;
  8312. }
  8313. if (helper.isValid(ret))
  8314. {
  8315. anyThisGroup = true;
  8316. processed++;
  8317. return ret;
  8318. }
  8319. if (!stepExtra.returnMismatches())
  8320. {
  8321. ReleaseRoxieRow(ret);
  8322. return nextInGroup();
  8323. }
  8324. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8325. //condition to advance
  8326. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8327. {
  8328. wasCompleteMatch = false;
  8329. anyThisGroup = false; // WHY?
  8330. return ret;
  8331. }
  8332. ReleaseRoxieRow(ret);
  8333. }
  8334. }
  8335. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8336. {
  8337. return input->gatherConjunctions(collector);
  8338. }
  8339. virtual void resetEOF()
  8340. {
  8341. eof = prefiltered;
  8342. anyThisGroup = false;
  8343. input->resetEOF();
  8344. }
  8345. IInputSteppingMeta * querySteppingMeta()
  8346. {
  8347. return input->querySteppingMeta();
  8348. }
  8349. };
  8350. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  8351. {
  8352. public:
  8353. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8354. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8355. {
  8356. }
  8357. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8358. {
  8359. return new CRoxieServerFilterActivity(this, _probeManager);
  8360. }
  8361. };
  8362. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8363. {
  8364. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8365. }
  8366. //=====================================================================================================
  8367. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  8368. {
  8369. IHThorFilterGroupArg &helper;
  8370. unsigned curIndex;
  8371. ConstPointerArray gathered;
  8372. IRangeCompare * stepCompare;
  8373. public:
  8374. CRoxieServerFilterGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8375. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  8376. {
  8377. curIndex = 0;
  8378. stepCompare = NULL;
  8379. }
  8380. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8381. {
  8382. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8383. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  8384. assertex(eof == !helper.canMatchAny());
  8385. curIndex = 0;
  8386. stepCompare = NULL;
  8387. if (!eof)
  8388. {
  8389. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  8390. if (inputStepping)
  8391. stepCompare = inputStepping->queryCompare();
  8392. }
  8393. }
  8394. virtual void reset()
  8395. {
  8396. releaseGathered();
  8397. CRoxieServerLateStartActivity::reset();
  8398. }
  8399. inline void releaseGathered()
  8400. {
  8401. while (gathered.isItem(curIndex))
  8402. ReleaseRoxieRow(gathered.item(curIndex++));
  8403. gathered.kill();
  8404. }
  8405. virtual const void * nextInGroup()
  8406. {
  8407. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8408. loop
  8409. {
  8410. if (eof)
  8411. return NULL;
  8412. if (gathered.ordinality())
  8413. {
  8414. if (gathered.isItem(curIndex))
  8415. {
  8416. const void * ret = gathered.item(curIndex++);
  8417. processed++;
  8418. return ret;
  8419. }
  8420. curIndex = 0;
  8421. gathered.kill();
  8422. return NULL;
  8423. }
  8424. const void * ret = input->nextInGroup();
  8425. while (ret)
  8426. {
  8427. gathered.append(ret);
  8428. ret = input->nextInGroup();
  8429. }
  8430. unsigned num = gathered.ordinality();
  8431. if (num != 0)
  8432. {
  8433. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8434. ReleaseRoxieRowSet(gathered); // read next group
  8435. }
  8436. else
  8437. eof = true;
  8438. }
  8439. }
  8440. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8441. {
  8442. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8443. if (eof)
  8444. return NULL;
  8445. if (gathered.ordinality())
  8446. {
  8447. while (gathered.isItem(curIndex))
  8448. {
  8449. const void * ret = gathered.item(curIndex++);
  8450. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  8451. {
  8452. processed++;
  8453. return ret;
  8454. }
  8455. ReleaseRoxieRow(ret);
  8456. }
  8457. curIndex = 0;
  8458. gathered.kill();
  8459. //nextSteppedGE never returns an end of group marker.
  8460. }
  8461. //Not completely sure about this - it could lead the the start of a group being skipped,
  8462. //so the group filter could potentially work on a different group. If so, we'd need to check the
  8463. //next fields were a subset of the grouping fields - more an issue for the group activity.
  8464. //MORE: What do we do with wasCompleteMatch? something like the following????
  8465. #if 0
  8466. loop
  8467. {
  8468. const void * ret;
  8469. if (stepExtra.returnMismatches())
  8470. {
  8471. bool matchedCompletely = true;
  8472. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8473. if (!wasCompleteMatch)
  8474. return ret;
  8475. }
  8476. else
  8477. ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8478. #endif
  8479. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  8480. while (ret)
  8481. {
  8482. gathered.append(ret);
  8483. ret = input->nextInGroup();
  8484. }
  8485. unsigned num = gathered.ordinality();
  8486. if (num != 0)
  8487. {
  8488. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  8489. ReleaseRoxieRowSet(gathered); // read next group
  8490. }
  8491. else
  8492. eof = true;
  8493. return nextUngrouped(this);
  8494. }
  8495. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  8496. {
  8497. return input->gatherConjunctions(collector);
  8498. }
  8499. virtual void resetEOF()
  8500. {
  8501. eof = false;
  8502. releaseGathered();
  8503. input->resetEOF();
  8504. }
  8505. IInputSteppingMeta * querySteppingMeta()
  8506. {
  8507. return input->querySteppingMeta();
  8508. }
  8509. };
  8510. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  8511. {
  8512. public:
  8513. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8514. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8515. {
  8516. }
  8517. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8518. {
  8519. return new CRoxieServerFilterGroupActivity(this, _probeManager);
  8520. }
  8521. };
  8522. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8523. {
  8524. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8525. }
  8526. //=================================================================================
  8527. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  8528. {
  8529. IHThorSideEffectArg &helper;
  8530. CriticalSection ecrit;
  8531. Owned<IException> exception;
  8532. bool executed;
  8533. public:
  8534. CRoxieServerSideEffectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8535. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  8536. {
  8537. executed = false;
  8538. }
  8539. virtual const void * nextInGroup()
  8540. {
  8541. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8542. CriticalBlock b(ecrit);
  8543. if (exception)
  8544. throw(exception.getLink());
  8545. if (!executed)
  8546. {
  8547. try
  8548. {
  8549. executed = true;
  8550. helper.action();
  8551. }
  8552. catch(IException *E)
  8553. {
  8554. exception.set(E);
  8555. throw;
  8556. }
  8557. }
  8558. return NULL;
  8559. }
  8560. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  8561. {
  8562. CriticalBlock b(ecrit);
  8563. if (exception)
  8564. throw(exception.getLink());
  8565. if (!executed)
  8566. {
  8567. try
  8568. {
  8569. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8570. executed = true;
  8571. start(parentExtractSize, parentExtract, false);
  8572. helper.action();
  8573. stop(false);
  8574. }
  8575. catch(IException *E)
  8576. {
  8577. ctx->notifyAbort(E);
  8578. stop(true);
  8579. exception.set(E);
  8580. throw;
  8581. }
  8582. }
  8583. }
  8584. virtual void reset()
  8585. {
  8586. executed = false;
  8587. exception.clear();
  8588. CRoxieServerActivity::reset();
  8589. }
  8590. };
  8591. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  8592. {
  8593. bool isRoot;
  8594. public:
  8595. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8596. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  8597. {
  8598. }
  8599. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8600. {
  8601. return new CRoxieServerSideEffectActivity(this, _probeManager);
  8602. }
  8603. virtual bool isSink() const
  8604. {
  8605. return isRoot && !meta.queryOriginal();
  8606. }
  8607. };
  8608. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  8609. {
  8610. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  8611. }
  8612. //=================================================================================
  8613. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  8614. {
  8615. IHThorActionArg &helper;
  8616. public:
  8617. CRoxieServerActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8618. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorActionArg &)basehelper)
  8619. {
  8620. }
  8621. virtual void onExecute()
  8622. {
  8623. helper.action();
  8624. }
  8625. };
  8626. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  8627. {
  8628. public:
  8629. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8630. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  8631. {
  8632. }
  8633. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8634. {
  8635. return new CRoxieServerActionActivity(this, _probeManager);
  8636. }
  8637. };
  8638. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  8639. {
  8640. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  8641. }
  8642. //=================================================================================
  8643. class CRoxieServerSampleActivity : public CRoxieServerActivity
  8644. {
  8645. IHThorSampleArg &helper;
  8646. unsigned numSamples;
  8647. unsigned numToSkip;
  8648. unsigned whichSample;
  8649. bool anyThisGroup;
  8650. bool eof;
  8651. public:
  8652. CRoxieServerSampleActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8653. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  8654. {
  8655. numSamples = 0;
  8656. numToSkip = 0;
  8657. whichSample = 0;
  8658. anyThisGroup = false;
  8659. eof = false;
  8660. }
  8661. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8662. {
  8663. anyThisGroup = false;
  8664. eof = false;
  8665. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8666. numSamples = helper.getProportion();
  8667. whichSample = helper.getSampleNumber();
  8668. numToSkip = (whichSample ? whichSample-1 : 0);
  8669. }
  8670. virtual const void * nextInGroup()
  8671. {
  8672. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8673. if (eof)
  8674. return NULL;
  8675. loop
  8676. {
  8677. const void * ret = input->nextInGroup();
  8678. if (!ret)
  8679. {
  8680. //this does work with groups - may or may not be useful...
  8681. //reset the sample for each group.... probably best.
  8682. numToSkip = (whichSample ? whichSample-1 : 0);
  8683. if (anyThisGroup)
  8684. {
  8685. anyThisGroup = false;
  8686. return NULL;
  8687. }
  8688. ret = input->nextInGroup();
  8689. if (!ret)
  8690. {
  8691. eof = true;
  8692. return NULL; // eof...
  8693. }
  8694. }
  8695. if (numToSkip == 0)
  8696. {
  8697. anyThisGroup = true;
  8698. numToSkip = numSamples-1;
  8699. processed++;
  8700. return ret;
  8701. }
  8702. numToSkip--;
  8703. ReleaseRoxieRow(ret);
  8704. }
  8705. }
  8706. };
  8707. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  8708. {
  8709. public:
  8710. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8711. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8712. {
  8713. }
  8714. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8715. {
  8716. return new CRoxieServerSampleActivity(this, _probeManager);
  8717. }
  8718. };
  8719. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8720. {
  8721. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8722. }
  8723. //=================================================================================
  8724. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  8725. {
  8726. IHThorChooseSetsArg &helper;
  8727. unsigned numSets;
  8728. unsigned * setCounts;
  8729. bool done;
  8730. public:
  8731. CRoxieServerChooseSetsActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8732. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  8733. {
  8734. setCounts = NULL;
  8735. numSets = 0;
  8736. done = false;
  8737. }
  8738. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8739. {
  8740. done = false;
  8741. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8742. numSets = helper.getNumSets();
  8743. setCounts = new unsigned[numSets];
  8744. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8745. helper.setCounts(setCounts);
  8746. }
  8747. virtual void reset()
  8748. {
  8749. delete [] setCounts;
  8750. setCounts = NULL;
  8751. CRoxieServerActivity::reset();
  8752. }
  8753. virtual const void * nextInGroup()
  8754. {
  8755. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8756. if (done)
  8757. return NULL;
  8758. loop
  8759. {
  8760. const void * ret = input->nextInGroup();
  8761. if (!ret)
  8762. {
  8763. ret = input->nextInGroup();
  8764. if (!ret)
  8765. {
  8766. done = true;
  8767. return NULL;
  8768. }
  8769. }
  8770. processed++;
  8771. switch (helper.getRecordAction(ret))
  8772. {
  8773. case 2:
  8774. done = true;
  8775. return ret;
  8776. case 1:
  8777. return ret;
  8778. }
  8779. ReleaseRoxieRow(ret);
  8780. }
  8781. }
  8782. };
  8783. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  8784. {
  8785. public:
  8786. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8787. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8788. {
  8789. }
  8790. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8791. {
  8792. return new CRoxieServerChooseSetsActivity(this, _probeManager);
  8793. }
  8794. };
  8795. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8796. {
  8797. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8798. }
  8799. //=================================================================================
  8800. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  8801. {
  8802. protected:
  8803. IHThorChooseSetsExArg &helper;
  8804. unsigned numSets;
  8805. unsigned curIndex;
  8806. unsigned * setCounts;
  8807. count_t * limits;
  8808. bool done;
  8809. ConstPointerArray gathered;
  8810. virtual bool includeRow(const void * row) = 0;
  8811. virtual void calculateSelection() = 0;
  8812. public:
  8813. CRoxieServerChooseSetsExActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8814. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  8815. {
  8816. setCounts = NULL;
  8817. limits = NULL;
  8818. done = false;
  8819. curIndex = 0;
  8820. numSets = 0;
  8821. }
  8822. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8823. {
  8824. done = false;
  8825. curIndex = 0;
  8826. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8827. numSets = helper.getNumSets();
  8828. setCounts = new unsigned[numSets];
  8829. memset(setCounts, 0, sizeof(unsigned)*numSets);
  8830. limits = (count_t *)calloc(sizeof(count_t), numSets);
  8831. helper.getLimits(limits);
  8832. }
  8833. virtual void reset()
  8834. {
  8835. delete [] setCounts;
  8836. setCounts = NULL;
  8837. free(limits);
  8838. limits = NULL;
  8839. while (gathered.isItem(curIndex))
  8840. ReleaseRoxieRow(gathered.item(curIndex++));
  8841. gathered.kill();
  8842. CRoxieServerActivity::reset();
  8843. }
  8844. virtual const void * nextInGroup()
  8845. {
  8846. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  8847. if (gathered.ordinality() == 0)
  8848. {
  8849. curIndex = 0;
  8850. if (!input->nextGroup(gathered))
  8851. {
  8852. done = true;
  8853. return NULL;
  8854. }
  8855. ForEachItemIn(idx1, gathered)
  8856. {
  8857. unsigned category = helper.getCategory(gathered.item(idx1));
  8858. if (category)
  8859. setCounts[category-1]++;
  8860. }
  8861. calculateSelection();
  8862. }
  8863. while (gathered.isItem(curIndex))
  8864. {
  8865. const void * row = gathered.item(curIndex);
  8866. gathered.replace(NULL, curIndex);
  8867. curIndex++;
  8868. if (includeRow(row))
  8869. {
  8870. processed++;
  8871. return row;
  8872. }
  8873. ReleaseRoxieRow(row);
  8874. }
  8875. gathered.kill();
  8876. return NULL;
  8877. }
  8878. };
  8879. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  8880. {
  8881. unsigned * numToSkip;
  8882. public:
  8883. CRoxieServerChooseSetsLastActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8884. {
  8885. numToSkip = NULL;
  8886. }
  8887. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8888. {
  8889. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8890. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  8891. }
  8892. virtual void reset()
  8893. {
  8894. free(numToSkip);
  8895. numToSkip = NULL;
  8896. CRoxieServerChooseSetsExActivity::reset();
  8897. }
  8898. protected:
  8899. virtual void calculateSelection()
  8900. {
  8901. for (unsigned idx=0; idx < numSets; idx++)
  8902. {
  8903. if (setCounts[idx] < limits[idx])
  8904. numToSkip[idx] = 0;
  8905. else
  8906. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  8907. }
  8908. }
  8909. virtual bool includeRow(const void * row)
  8910. {
  8911. unsigned category = helper.getCategory(row);
  8912. if (category)
  8913. {
  8914. if (numToSkip[category-1] == 0)
  8915. return true;
  8916. numToSkip[category-1]--;
  8917. }
  8918. return false;
  8919. }
  8920. };
  8921. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  8922. {
  8923. count_t * counter;
  8924. public:
  8925. CRoxieServerChooseSetsEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_factory, _probeManager)
  8926. {
  8927. counter = NULL;
  8928. }
  8929. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8930. {
  8931. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  8932. counter = (count_t *)calloc(sizeof(count_t), numSets);
  8933. }
  8934. virtual void reset()
  8935. {
  8936. free(counter);
  8937. counter = NULL;
  8938. CRoxieServerChooseSetsExActivity::reset();
  8939. }
  8940. protected:
  8941. virtual void calculateSelection()
  8942. {
  8943. }
  8944. virtual bool includeRow(const void * row)
  8945. {
  8946. unsigned category = helper.getCategory(row);
  8947. if (category)
  8948. {
  8949. assertex(category <= numSets);
  8950. counter[category-1] += limits[category-1];
  8951. if(counter[category-1] >= setCounts[category-1])
  8952. {
  8953. counter[category-1] -= setCounts[category-1];
  8954. return true;
  8955. }
  8956. }
  8957. return false;
  8958. }
  8959. };
  8960. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  8961. {
  8962. public:
  8963. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8964. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8965. {
  8966. }
  8967. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8968. {
  8969. return new CRoxieServerChooseSetsEnthActivity(this, _probeManager);
  8970. }
  8971. };
  8972. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8973. {
  8974. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8975. }
  8976. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  8977. {
  8978. public:
  8979. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8980. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  8981. {
  8982. }
  8983. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  8984. {
  8985. return new CRoxieServerChooseSetsLastActivity(this, _probeManager);
  8986. }
  8987. };
  8988. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  8989. {
  8990. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  8991. }
  8992. //=================================================================================
  8993. class CRoxieServerEnthActivity : public CRoxieServerActivity
  8994. {
  8995. IHThorEnthArg &helper;
  8996. unsigned __int64 numerator;
  8997. unsigned __int64 denominator;
  8998. unsigned __int64 counter;
  8999. bool eof;
  9000. public:
  9001. CRoxieServerEnthActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9002. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9003. {
  9004. eof = false;
  9005. numerator = denominator = counter = 0;
  9006. }
  9007. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9008. {
  9009. eof = false;
  9010. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9011. numerator = helper.getProportionNumerator();
  9012. denominator = helper.getProportionDenominator();
  9013. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9014. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9015. if (counter >= denominator)
  9016. counter %= denominator;
  9017. }
  9018. inline bool wanted()
  9019. {
  9020. counter += numerator;
  9021. if(counter >= denominator)
  9022. {
  9023. counter -= denominator;
  9024. return true;
  9025. }
  9026. return false;
  9027. }
  9028. virtual const void * nextInGroup()
  9029. {
  9030. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9031. if (eof)
  9032. return NULL;
  9033. const void * ret;
  9034. loop
  9035. {
  9036. ret = input->nextInGroup();
  9037. if(!ret) //end of group
  9038. ret = input->nextInGroup();
  9039. if(!ret) //eof
  9040. {
  9041. eof = true;
  9042. return ret;
  9043. }
  9044. if (wanted())
  9045. return ret;
  9046. ReleaseRoxieRow(ret);
  9047. }
  9048. }
  9049. };
  9050. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9051. {
  9052. public:
  9053. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9054. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9055. {
  9056. }
  9057. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9058. {
  9059. return new CRoxieServerEnthActivity(this, _probeManager);
  9060. }
  9061. };
  9062. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9063. {
  9064. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9065. }
  9066. //=================================================================================
  9067. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9068. {
  9069. IHThorAggregateArg &helper;
  9070. bool eof;
  9071. bool isInputGrouped;
  9072. bool abortEarly;
  9073. public:
  9074. CRoxieServerAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9075. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9076. {
  9077. eof = false;
  9078. isInputGrouped = false;
  9079. abortEarly = false;
  9080. }
  9081. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9082. {
  9083. eof = false;
  9084. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9085. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9086. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9087. }
  9088. virtual bool needsAllocator() const { return true; }
  9089. virtual const void * nextInGroup()
  9090. {
  9091. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9092. if (eof)
  9093. return NULL;
  9094. const void * next = input->nextInGroup();
  9095. if (!next && isInputGrouped)
  9096. {
  9097. eof = true;
  9098. return NULL;
  9099. }
  9100. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9101. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9102. if (next)
  9103. {
  9104. finalSize = helper.processFirst(rowBuilder, next);
  9105. ReleaseRoxieRow(next);
  9106. if (!abortEarly)
  9107. {
  9108. loop
  9109. {
  9110. next = input->nextInGroup();
  9111. if (!next)
  9112. break;
  9113. finalSize = helper.processNext(rowBuilder, next);
  9114. ReleaseRoxieRow(next);
  9115. }
  9116. }
  9117. }
  9118. if (!isInputGrouped) // either read all, or aborted early
  9119. eof = true;
  9120. processed++;
  9121. return rowBuilder.finalizeRowClear(finalSize);
  9122. }
  9123. };
  9124. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  9125. {
  9126. public:
  9127. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9128. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9129. {
  9130. }
  9131. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9132. {
  9133. return new CRoxieServerAggregateActivity(this, _probeManager);
  9134. }
  9135. };
  9136. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9137. {
  9138. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9139. }
  9140. //=================================================================================
  9141. typedef unsigned t_hashPrefix;
  9142. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  9143. {
  9144. IHThorHashAggregateArg &helper;
  9145. RowAggregator aggregated;
  9146. bool eof;
  9147. bool gathered;
  9148. bool isGroupedAggregate;
  9149. public:
  9150. CRoxieServerHashAggregateActivity(const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  9151. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  9152. isGroupedAggregate(_isGroupedAggregate),
  9153. aggregated(helper, helper)
  9154. {
  9155. eof = false;
  9156. gathered = false;
  9157. }
  9158. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9159. {
  9160. eof = false;
  9161. gathered = false;
  9162. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9163. }
  9164. virtual void reset()
  9165. {
  9166. aggregated.reset();
  9167. CRoxieServerActivity::reset();
  9168. }
  9169. virtual bool needsAllocator() const { return true; }
  9170. virtual const void * nextInGroup()
  9171. {
  9172. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9173. if (eof)
  9174. return NULL;
  9175. if (!gathered)
  9176. {
  9177. aggregated.start(rowAllocator);
  9178. bool eog = true;
  9179. loop
  9180. {
  9181. const void * next = input->nextInGroup();
  9182. if (!next)
  9183. {
  9184. if (isGroupedAggregate)
  9185. {
  9186. if (eog)
  9187. eof = true;
  9188. break;
  9189. }
  9190. next = input->nextInGroup();
  9191. if (!next)
  9192. break;
  9193. }
  9194. eog = false;
  9195. aggregated.addRow(next);
  9196. ReleaseRoxieRow(next);
  9197. }
  9198. gathered = true;
  9199. }
  9200. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  9201. if (next)
  9202. {
  9203. processed++;
  9204. return next->finalizeRowClear();
  9205. }
  9206. if (!isGroupedAggregate)
  9207. eof = true;
  9208. aggregated.reset();
  9209. gathered = false;
  9210. return NULL;
  9211. }
  9212. };
  9213. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  9214. {
  9215. public:
  9216. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9217. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9218. {
  9219. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  9220. }
  9221. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9222. {
  9223. return new CRoxieServerHashAggregateActivity(this, isGroupedAggregate, _probeManager);
  9224. }
  9225. protected:
  9226. bool isGroupedAggregate;
  9227. };
  9228. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9229. {
  9230. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9231. }
  9232. //=================================================================================
  9233. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  9234. {
  9235. IHThorDegroupArg &helper;
  9236. bool eof;
  9237. public:
  9238. CRoxieServerDegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9239. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
  9240. {
  9241. eof = false;
  9242. }
  9243. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9244. {
  9245. eof = false;
  9246. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9247. }
  9248. virtual const void * nextInGroup()
  9249. {
  9250. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9251. if (eof)
  9252. return NULL;
  9253. const void * ret = input->nextInGroup();
  9254. if (!ret)
  9255. ret = input->nextInGroup();
  9256. if (ret)
  9257. processed++;
  9258. else
  9259. eof = true;
  9260. return ret;
  9261. }
  9262. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9263. {
  9264. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9265. if (eof)
  9266. return NULL;
  9267. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  9268. if (ret)
  9269. processed++;
  9270. else
  9271. eof = true;
  9272. return ret;
  9273. }
  9274. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9275. {
  9276. return input->gatherConjunctions(collector);
  9277. }
  9278. virtual void resetEOF()
  9279. {
  9280. eof = false;
  9281. input->resetEOF();
  9282. }
  9283. IInputSteppingMeta * querySteppingMeta()
  9284. {
  9285. return input->querySteppingMeta();
  9286. }
  9287. };
  9288. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  9289. {
  9290. public:
  9291. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9292. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9293. {
  9294. }
  9295. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9296. {
  9297. return new CRoxieServerDegroupActivity(this, _probeManager);
  9298. }
  9299. };
  9300. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9301. {
  9302. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9303. }
  9304. //=================================================================================
  9305. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  9306. {
  9307. IHThorDiskReadArg &helper;
  9308. bool needTransform;
  9309. bool eof;
  9310. bool anyThisGroup;
  9311. unsigned __int64 rowLimit;
  9312. unsigned __int64 choosenLimit;
  9313. public:
  9314. CRoxieServerSpillReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9315. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  9316. {
  9317. needTransform = helper.needTransform();
  9318. rowLimit = (unsigned __int64) -1;
  9319. choosenLimit = 0;
  9320. eof = false;
  9321. anyThisGroup = false;
  9322. }
  9323. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9324. {
  9325. anyThisGroup = false;
  9326. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9327. if (helper.canMatchAny())
  9328. eof = false;
  9329. else
  9330. eof = true;
  9331. choosenLimit = helper.getChooseNLimit();
  9332. rowLimit = helper.getRowLimit();
  9333. helper.setCallback(NULL); // members should not be called - change if they are
  9334. }
  9335. virtual bool needsAllocator() const { return true; }
  9336. virtual const void * nextInGroup()
  9337. {
  9338. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9339. if (eof)
  9340. return NULL;
  9341. if (processed==choosenLimit)
  9342. {
  9343. eof = true;
  9344. return NULL;
  9345. }
  9346. if (needTransform)
  9347. {
  9348. loop
  9349. {
  9350. const void *in = input->nextInGroup();
  9351. if (!in)
  9352. {
  9353. if (anyThisGroup)
  9354. {
  9355. anyThisGroup = false;
  9356. return NULL;
  9357. }
  9358. in = input->nextInGroup();
  9359. if (!in)
  9360. {
  9361. eof = true;
  9362. return NULL; // eof...
  9363. }
  9364. }
  9365. unsigned outSize;
  9366. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9367. try
  9368. {
  9369. outSize = helper.transform(rowBuilder, in);
  9370. ReleaseRoxieRow(in);
  9371. }
  9372. catch (IException *E)
  9373. {
  9374. throw makeWrappedException(E);
  9375. }
  9376. if (outSize)
  9377. {
  9378. anyThisGroup = true;
  9379. processed++;
  9380. if (processed==rowLimit)
  9381. {
  9382. if (traceLevel > 4)
  9383. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9384. helper.onLimitExceeded();
  9385. }
  9386. return rowBuilder.finalizeRowClear(outSize);
  9387. }
  9388. }
  9389. }
  9390. else
  9391. {
  9392. const void *ret = input->nextInGroup();
  9393. if (ret)
  9394. {
  9395. processed++;
  9396. if (processed==rowLimit)
  9397. {
  9398. if (traceLevel > 4)
  9399. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  9400. ReleaseClearRoxieRow(ret);
  9401. helper.onLimitExceeded(); // should not return
  9402. throwUnexpected();
  9403. }
  9404. }
  9405. return ret;
  9406. }
  9407. }
  9408. };
  9409. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  9410. {
  9411. public:
  9412. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9413. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  9414. {
  9415. }
  9416. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9417. {
  9418. return new CRoxieServerSpillReadActivity(this, _probeManager);
  9419. }
  9420. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  9421. {
  9422. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
  9423. setInput(0, source, sourceIdx);
  9424. else
  9425. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  9426. }
  9427. };
  9428. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  9429. {
  9430. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  9431. }
  9432. //=================================================================================
  9433. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  9434. {
  9435. public:
  9436. CRoxieServerSpillWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9437. : CRoxieServerActivity(_factory, _probeManager)
  9438. {
  9439. }
  9440. ~CRoxieServerSpillWriteActivity()
  9441. {
  9442. }
  9443. virtual const void *nextInGroup()
  9444. {
  9445. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  9446. return input->nextInGroup();
  9447. }
  9448. };
  9449. //==================================================================================
  9450. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9451. {
  9452. protected:
  9453. Owned<IExtRowWriter> outSeq;
  9454. Owned<IOutputRowSerializer> rowSerializer;
  9455. Linked<IFileIOStream> diskout;
  9456. bool blockcompressed;
  9457. bool extend;
  9458. bool overwrite;
  9459. bool encrypted;
  9460. bool grouped;
  9461. IHThorDiskWriteArg &helper;
  9462. StringBuffer lfn; // logical filename
  9463. CachedOutputMetaData diskmeta;
  9464. Owned<IRoxieWriteHandler> writer;
  9465. bool tallycrc;
  9466. unsigned __int64 uncompressedBytesWritten;
  9467. CRC32 crc;
  9468. void updateWorkUnitResult(unsigned __int64 reccount)
  9469. {
  9470. assertex(writer);
  9471. // MORE - a lot of this is common with hthor
  9472. if(lfn.length()) //this is required as long as temp files don't get a name which can be stored in the WU and automatically deleted by the WU
  9473. {
  9474. WorkunitUpdate wu = ctx->updateWorkUnit();
  9475. if (wu)
  9476. {
  9477. unsigned flags = helper.getFlags();
  9478. WUFileKind fileKind;
  9479. if (TDXtemporary & flags)
  9480. fileKind = WUFileTemporary;
  9481. else if(TDXjobtemp & flags)
  9482. fileKind = WUFileJobOwned;
  9483. else if(TDWowned & flags)
  9484. fileKind = WUFileOwned;
  9485. else
  9486. fileKind = WUFileStandard;
  9487. StringArray clusters;
  9488. writer->getClusters(clusters);
  9489. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  9490. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  9491. {
  9492. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9493. if (result)
  9494. {
  9495. result->setResultTotalRowCount(reccount);
  9496. result->setResultStatus(ResultStatusCalculated);
  9497. if (helper.getFlags() & TDWresult)
  9498. result->setResultFilename(lfn.str());
  9499. else
  9500. result->setResultLogicalName(lfn.str());
  9501. }
  9502. }
  9503. }
  9504. }
  9505. }
  9506. void resolve()
  9507. {
  9508. OwnedRoxieString rawLogicalName = helper.getFileName();
  9509. assertex(rawLogicalName);
  9510. assertex((helper.getFlags() & TDXtemporary) == 0);
  9511. StringArray clusters;
  9512. unsigned clusterIdx = 0;
  9513. while(true)
  9514. {
  9515. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9516. if(!cluster)
  9517. break;
  9518. clusters.append(cluster);
  9519. clusterIdx++;
  9520. }
  9521. if (clusters.length())
  9522. {
  9523. if (extend)
  9524. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  9525. }
  9526. else
  9527. {
  9528. if (roxieName.length())
  9529. clusters.append(roxieName.str());
  9530. else
  9531. clusters.append(".");
  9532. }
  9533. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters)); // MORE - if there's a workunit, use if for scope.
  9534. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  9535. }
  9536. public:
  9537. CRoxieServerDiskWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9538. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDiskWriteArg &)basehelper)
  9539. {
  9540. extend = ((helper.getFlags() & TDWextend) != 0);
  9541. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  9542. grouped = false; // don't think we need to support it...
  9543. diskmeta.set(helper.queryDiskRecordSize());
  9544. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
  9545. encrypted = false; // set later
  9546. tallycrc = true;
  9547. uncompressedBytesWritten = 0;
  9548. }
  9549. ~CRoxieServerDiskWriteActivity()
  9550. {
  9551. }
  9552. virtual bool needsAllocator() const
  9553. {
  9554. return true;
  9555. }
  9556. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9557. {
  9558. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9559. resolve();
  9560. Owned<IFileIO> io;
  9561. void *ekey;
  9562. size32_t ekeylen;
  9563. helper.getEncryptKey(ekeylen, ekey);
  9564. Owned<ICompressor> ecomp;
  9565. if (ekeylen!=0)
  9566. {
  9567. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  9568. memset(ekey,0,ekeylen);
  9569. rtlFree(ekey);
  9570. encrypted = true;
  9571. blockcompressed = true;
  9572. }
  9573. if (blockcompressed)
  9574. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
  9575. else
  9576. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  9577. if (!io)
  9578. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  9579. diskout.setown(createBufferedIOStream(io));
  9580. if (extend)
  9581. diskout->seek(0, IFSend);
  9582. tallycrc = !factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
  9583. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, ctx->queryCodeContext());
  9584. rowSerializer.set(rowIf->queryRowSerializer());
  9585. unsigned rwFlags = rw_autoflush;
  9586. if(grouped)
  9587. rwFlags |= rw_grouped;
  9588. if(tallycrc)
  9589. rwFlags |= rw_crc;
  9590. if(!factory->queryQueryFactory().getDebugValueBool("skipFileFormatCrcCheck", false) && !(helper.getFlags() & TDRnocrccheck))
  9591. rwFlags |= rw_crc;
  9592. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  9593. }
  9594. virtual void stop(bool aborting)
  9595. {
  9596. if (aborting)
  9597. {
  9598. if (writer)
  9599. writer->finish(false, this);
  9600. }
  9601. else
  9602. {
  9603. outSeq->flush(&crc);
  9604. updateWorkUnitResult(processed);
  9605. uncompressedBytesWritten = outSeq->getPosition();
  9606. writer->finish(true, this);
  9607. }
  9608. writer.clear();
  9609. CRoxieServerActivity::stop(aborting);
  9610. }
  9611. virtual void reset()
  9612. {
  9613. CRoxieServerActivity::reset();
  9614. diskout.clear();
  9615. outSeq.clear();
  9616. writer.clear();
  9617. uncompressedBytesWritten = 0;
  9618. crc.reset();
  9619. }
  9620. virtual void onExecute()
  9621. {
  9622. loop
  9623. {
  9624. const void *nextrec = input->nextInGroup();
  9625. if (!nextrec)
  9626. {
  9627. nextrec = input->nextInGroup();
  9628. if (!nextrec)
  9629. break;
  9630. }
  9631. processed++;
  9632. outSeq->putRow(nextrec);
  9633. }
  9634. }
  9635. virtual void setFileProperties(IFileDescriptor *desc) const
  9636. {
  9637. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  9638. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  9639. if (blockcompressed)
  9640. {
  9641. // caller has already set @size from file size...
  9642. fileProps.setPropBool("@blockCompressed", true);
  9643. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9644. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  9645. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  9646. partProps.setPropInt64("@size", uncompressedBytesWritten);
  9647. }
  9648. else if (tallycrc)
  9649. partProps.setPropInt64("@fileCrc", crc.get());
  9650. if (encrypted)
  9651. fileProps.setPropBool("@encrypted", true);
  9652. fileProps.setPropInt64("@recordCount", processed);
  9653. unsigned flags = helper.getFlags();
  9654. if (flags & TDWpersist)
  9655. fileProps.setPropBool("@persistent", true);
  9656. if (grouped)
  9657. fileProps.setPropBool("@grouped", true);
  9658. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  9659. fileProps.setPropBool("@owned", true);
  9660. if (flags & TDWresult)
  9661. fileProps.setPropBool("@result", true);
  9662. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9663. if (workUnit)
  9664. {
  9665. SCMStringBuffer owner, wuid, job;
  9666. fileProps.setProp("@owner", workUnit->getUser(owner).str());
  9667. fileProps.setProp("@workunit", workUnit->getWuid(wuid).str());
  9668. fileProps.setProp("@job", workUnit->getJobName(job).str());
  9669. }
  9670. if (flags & TDWexpires)
  9671. setExpiryTime(fileProps, helper.getExpiryDays());
  9672. if (flags & TDWupdate)
  9673. {
  9674. unsigned eclCRC;
  9675. unsigned __int64 totalCRC;
  9676. helper.getUpdateCRCs(eclCRC, totalCRC);
  9677. fileProps.setPropInt("@eclCRC", eclCRC);
  9678. fileProps.setPropInt64("@totalCRC", totalCRC);
  9679. }
  9680. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  9681. IRecordSize * inputMeta = input->queryOutputMeta();
  9682. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  9683. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  9684. const char *recordECL = helper.queryRecordECL();
  9685. if (recordECL && *recordECL)
  9686. fileProps.setProp("ECL", recordECL);
  9687. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  9688. }
  9689. virtual IUserDescriptor *queryUserDescriptor() const
  9690. {
  9691. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  9692. if (workUnit)
  9693. return workUnit->queryUserDescriptor();
  9694. else
  9695. return NULL;
  9696. }
  9697. virtual bool isOutputTransformed() const { return false; }
  9698. };
  9699. //=================================================================================
  9700. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  9701. {
  9702. IHThorCsvWriteArg &csvHelper;
  9703. CSVOutputStream csvOutput;
  9704. public:
  9705. CRoxieServerCsvWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9706. : CRoxieServerDiskWriteActivity(_factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  9707. {
  9708. csvOutput.init(csvHelper.queryCsvParameters(), false);
  9709. }
  9710. virtual void onExecute()
  9711. {
  9712. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  9713. if (header)
  9714. {
  9715. csvOutput.beginLine();
  9716. csvOutput.writeHeaderLn(strlen(header), header);
  9717. diskout->write(csvOutput.length(), csvOutput.str());
  9718. }
  9719. loop
  9720. {
  9721. const void *nextrec = input->nextInGroup();
  9722. if (!nextrec)
  9723. {
  9724. nextrec = input->nextInGroup();
  9725. if (!nextrec)
  9726. break;
  9727. }
  9728. processed++;
  9729. csvOutput.beginLine();
  9730. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  9731. csvOutput.endLine();
  9732. diskout->write(csvOutput.length(), csvOutput.str());
  9733. ReleaseRoxieRow(nextrec);
  9734. }
  9735. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  9736. if (footer)
  9737. {
  9738. csvOutput.beginLine();
  9739. csvOutput.writeHeaderLn(strlen(footer), footer);
  9740. diskout->write(csvOutput.length(), csvOutput.str());
  9741. }
  9742. }
  9743. virtual void setFileProperties(IFileDescriptor *desc) const
  9744. {
  9745. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9746. IPropertyTree &props = desc->queryProperties();
  9747. props.setProp("@format","utf8n");
  9748. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  9749. StringBuffer separator;
  9750. OwnedRoxieString rs(csvParameters->getSeparator(0));
  9751. const char *s = rs;
  9752. while (s && *s)
  9753. {
  9754. if (',' == *s)
  9755. separator.append("\\,");
  9756. else
  9757. separator.append(*s);
  9758. ++s;
  9759. }
  9760. props.setProp("@csvSeparate", separator.str());
  9761. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  9762. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  9763. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  9764. props.setProp("@kind", "csv");
  9765. }
  9766. virtual bool isOutputTransformed() const { return true; }
  9767. };
  9768. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  9769. {
  9770. IHThorXmlWriteArg &xmlHelper;
  9771. StringAttr rowTag;
  9772. public:
  9773. CRoxieServerXmlWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9774. : CRoxieServerDiskWriteActivity(_factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper))
  9775. {
  9776. }
  9777. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9778. {
  9779. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  9780. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  9781. if (!xmlpath)
  9782. rowTag.set("Row");
  9783. else
  9784. {
  9785. const char *path = xmlpath;
  9786. if (*path == '/') path++;
  9787. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  9788. rowTag.set(path);
  9789. }
  9790. }
  9791. virtual void onExecute()
  9792. {
  9793. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  9794. const char *header = suppliedHeader;
  9795. if (!header) header = "<Dataset>\n";
  9796. diskout->write(strlen(header), header);
  9797. CommonXmlWriter xmlOutput(xmlHelper.getXmlFlags());
  9798. loop
  9799. {
  9800. OwnedConstRoxieRow nextrec = input->nextInGroup();
  9801. if (!nextrec)
  9802. {
  9803. nextrec.setown(input->nextInGroup());
  9804. if (!nextrec)
  9805. break;
  9806. }
  9807. processed++;
  9808. xmlOutput.clear().outputBeginNested(rowTag, false);
  9809. xmlHelper.toXML((const byte *)nextrec.get(), xmlOutput);
  9810. xmlOutput.outputEndNested(rowTag);
  9811. diskout->write(xmlOutput.length(), xmlOutput.str());
  9812. }
  9813. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  9814. const char * footer = suppliedFooter;
  9815. if (!footer) footer = "</Dataset>\n";
  9816. diskout->write(strlen(footer), footer);
  9817. }
  9818. virtual void reset()
  9819. {
  9820. CRoxieServerDiskWriteActivity::reset();
  9821. rowTag.clear();
  9822. }
  9823. virtual void setFileProperties(IFileDescriptor *desc) const
  9824. {
  9825. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  9826. desc->queryProperties().setProp("@format","utf8n");
  9827. desc->queryProperties().setProp("@rowTag",rowTag.get());
  9828. desc->queryProperties().setProp("@kind", "xml");
  9829. }
  9830. virtual bool isOutputTransformed() const { return true; }
  9831. };
  9832. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  9833. {
  9834. bool isRoot;
  9835. bool isTemp;
  9836. public:
  9837. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9838. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  9839. {
  9840. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  9841. isTemp = (helper.getFlags() & TDXtemporary) != 0;
  9842. setNumOutputs(helper->getTempUsageCount());
  9843. if (_kind!=TAKdiskwrite)
  9844. assertex(numOutputs == 0);
  9845. }
  9846. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  9847. {
  9848. switch (numOutputs)
  9849. {
  9850. case 0:
  9851. switch (kind)
  9852. {
  9853. case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(this, _probeManager);
  9854. case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(this, _probeManager);
  9855. case TAKxmlwrite: return new CRoxieServerXmlWriteActivity(this, _probeManager);
  9856. };
  9857. throwUnexpected();
  9858. case 1:
  9859. return new CRoxieServerSpillWriteActivity(this, _probeManager);
  9860. default:
  9861. return new CRoxieServerThroughSpillActivity(this, _probeManager, numOutputs);
  9862. }
  9863. }
  9864. virtual bool isSink() const
  9865. {
  9866. return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
  9867. }
  9868. };
  9869. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  9870. {
  9871. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  9872. }
  9873. //=================================================================================
  9874. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  9875. {
  9876. IHThorIndexWriteArg &helper;
  9877. bool overwrite;
  9878. Owned<ClusterWriteHandler> clusterHandler;
  9879. Owned<IRoxieWriteHandler> writer;
  9880. unsigned __int64 reccount;
  9881. unsigned int fileCrc;
  9882. StringBuffer filename;
  9883. void updateWorkUnitResult()
  9884. {
  9885. if(filename.length()) //this is required as long as temp files don't get a name which can be stored in the WU and automatically deleted by the WU
  9886. {
  9887. WorkunitUpdate wu = ctx->updateWorkUnit();
  9888. if (wu)
  9889. {
  9890. if (!(helper.getFlags() & TDXtemporary) && helper.getSequence() >= 0)
  9891. {
  9892. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  9893. if (result)
  9894. {
  9895. result->setResultTotalRowCount(reccount);
  9896. result->setResultStatus(ResultStatusCalculated);
  9897. result->setResultLogicalName(filename.str());
  9898. }
  9899. }
  9900. if(clusterHandler)
  9901. clusterHandler->finish(writer->queryFile());
  9902. }
  9903. CTXLOG("Created roxie index file %s", filename.str());
  9904. }
  9905. }
  9906. virtual void resolve()
  9907. {
  9908. StringArray clusters;
  9909. unsigned clusterIdx = 0;
  9910. while(true)
  9911. {
  9912. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  9913. if(!cluster)
  9914. break;
  9915. clusters.append(cluster);
  9916. clusterIdx++;
  9917. }
  9918. if (roxieName.length())
  9919. clusters.append(roxieName.str());
  9920. else
  9921. clusters.append(".");
  9922. OwnedRoxieString fname(helper.getFileName());
  9923. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  9924. filename.set(writer->queryFile()->queryFilename());
  9925. if (writer->queryFile()->exists())
  9926. {
  9927. if (overwrite)
  9928. {
  9929. CTXLOG("Removing existing %s from DFS",filename.str());
  9930. writer->queryFile()->remove();
  9931. }
  9932. else
  9933. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  9934. }
  9935. }
  9936. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  9937. {
  9938. size32_t nameLen;
  9939. char * nameBuff;
  9940. size32_t valueLen;
  9941. char * valueBuff;
  9942. unsigned idx = 0;
  9943. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  9944. {
  9945. StringBuffer name(nameLen, nameBuff);
  9946. StringBuffer value(valueLen, valueBuff);
  9947. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  9948. {
  9949. OwnedRoxieString fname(helper.getFileName());
  9950. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  9951. }
  9952. if(!validateXMLTag(name.str()))
  9953. {
  9954. OwnedRoxieString fname(helper.getFileName());
  9955. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  9956. }
  9957. if(!metadata)
  9958. metadata.setown(createPTree("metadata"));
  9959. metadata->setProp(name.str(), value.str());
  9960. }
  9961. }
  9962. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  9963. {
  9964. if(!metadata)
  9965. metadata.setown(createPTree("metadata"));
  9966. metadata->setProp("_record_ECL", helper.queryRecordECL());
  9967. void * layoutMetaBuff;
  9968. size32_t layoutMetaSize;
  9969. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  9970. {
  9971. metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  9972. rtlFree(layoutMetaBuff);
  9973. }
  9974. }
  9975. public:
  9976. CRoxieServerIndexWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9977. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  9978. {
  9979. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  9980. reccount = 0;
  9981. }
  9982. ~CRoxieServerIndexWriteActivity()
  9983. {
  9984. }
  9985. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9986. {
  9987. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9988. resolve();
  9989. }
  9990. virtual void onExecute()
  9991. {
  9992. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  9993. size32_t maxDiskRecordSize;
  9994. if (isVariable)
  9995. maxDiskRecordSize = 0x8000;
  9996. else
  9997. {
  9998. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
  9999. if (maxDiskRecordSize > 0x8000)
  10000. throw MakeStringException(99, "Index minimum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10001. }
  10002. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10003. unsigned __int64 fileSize = 0;
  10004. fileCrc = -1;
  10005. OwnedRoxieString dsName(helper.getFileName());
  10006. if (dsName.get())
  10007. {
  10008. Owned<const IResolvedFile> dsFileInfo = resolveLFN(dsName, false);
  10009. if (dsFileInfo)
  10010. {
  10011. fileSize = dsFileInfo->getFileSize();
  10012. }
  10013. }
  10014. {
  10015. Owned<IFileIO> io;
  10016. try
  10017. {
  10018. io.setown(writer->queryFile()->open(IFOcreate));
  10019. }
  10020. catch(IException * e)
  10021. {
  10022. e->Release();
  10023. clearKeyStoreCache(false);
  10024. io.setown(writer->queryFile()->open(IFOcreate));
  10025. }
  10026. if(!io)
  10027. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10028. Owned<IFileIOStream> out = createIOStream(io);
  10029. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10030. if (helper.getFlags() & TIWrowcompress)
  10031. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10032. else if (!(helper.getFlags() & TIWnolzwcompress))
  10033. flags |= HTREE_COMPRESSED_KEY;
  10034. if (isVariable)
  10035. flags |= HTREE_VARSIZE;
  10036. Owned<IPropertyTree> metadata;
  10037. buildUserMetadata(metadata);
  10038. buildLayoutMetadata(metadata);
  10039. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10040. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, fileSize, nodeSize, helper.getKeyedSize(), 0);
  10041. class BcWrapper : implements IBlobCreator
  10042. {
  10043. IKeyBuilder *builder;
  10044. public:
  10045. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10046. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10047. {
  10048. return builder->createBlob(size, (const char *) ptr);
  10049. }
  10050. } bc(builder);
  10051. // Loop thru the results
  10052. loop
  10053. {
  10054. OwnedConstRoxieRow nextrec(input->nextInGroup());
  10055. if (!nextrec)
  10056. {
  10057. nextrec.setown(input->nextInGroup());
  10058. if (!nextrec)
  10059. break;
  10060. }
  10061. try
  10062. {
  10063. unsigned __int64 fpos;
  10064. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10065. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10066. builder->processKeyData(rowBuffer, fpos, thisSize);
  10067. }
  10068. catch(IException * e)
  10069. {
  10070. throw makeWrappedException(e);
  10071. }
  10072. reccount++;
  10073. }
  10074. if(metadata)
  10075. builder->finish(metadata,&fileCrc);
  10076. else
  10077. builder->finish(&fileCrc);
  10078. }
  10079. }
  10080. virtual void stop(bool aborting)
  10081. {
  10082. if (writer)
  10083. {
  10084. if (!aborting)
  10085. updateWorkUnitResult();
  10086. writer->finish(!aborting, this);
  10087. writer.clear();
  10088. }
  10089. CRoxieServerActivity::stop(aborting);
  10090. }
  10091. virtual void reset()
  10092. {
  10093. CRoxieServerActivity::reset();
  10094. writer.clear();
  10095. }
  10096. //interface IRoxiePublishCallback
  10097. virtual void setFileProperties(IFileDescriptor *desc) const
  10098. {
  10099. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10100. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10101. // Now publish to name services
  10102. StringBuffer dir,base;
  10103. offset_t indexFileSize = writer->queryFile()->size();
  10104. if(clusterHandler)
  10105. clusterHandler->splitPhysicalFilename(dir, base);
  10106. else
  10107. splitFilename(filename.str(), &dir, &dir, &base, &base);
  10108. desc->setDefaultDir(dir.str());
  10109. //properties of the first file part.
  10110. Owned<IPropertyTree> attrs;
  10111. if(clusterHandler)
  10112. attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
  10113. else
  10114. {
  10115. // add cluster
  10116. StringBuffer mygroupname;
  10117. desc->setNumParts(1);
  10118. desc->setPartMask(base.str());
  10119. attrs.set(&desc->queryPart(0)->queryProperties());
  10120. }
  10121. attrs->setPropInt64("@size", indexFileSize);
  10122. CDateTime createTime, modifiedTime, accessedTime;
  10123. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  10124. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  10125. unsigned hour, min, sec, nanosec;
  10126. modifiedTime.getTime(hour, min, sec, nanosec);
  10127. modifiedTime.setTime(hour, min, sec, 0);
  10128. StringBuffer timestr;
  10129. modifiedTime.getString(timestr);
  10130. if(timestr.length())
  10131. attrs->setProp("@modified", timestr.str());
  10132. if(clusterHandler)
  10133. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  10134. // properties of the logical file
  10135. IPropertyTree & properties = desc->queryProperties();
  10136. properties.setProp("@kind", "key");
  10137. properties.setPropInt64("@size", indexFileSize);
  10138. properties.setPropInt64("@recordCount", reccount);
  10139. SCMStringBuffer info;
  10140. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  10141. if (workUnit)
  10142. {
  10143. properties.setProp("@owner", workUnit->getUser(info).str());
  10144. info.clear();
  10145. properties.setProp("@workunit", workUnit->getWuid(info).str());
  10146. info.clear();
  10147. properties.setProp("@job", workUnit->getJobName(info).str());
  10148. }
  10149. char const * rececl = helper.queryRecordECL();
  10150. if(rececl && *rececl)
  10151. properties.setProp("ECL", rececl);
  10152. if (helper.getFlags() & TIWexpires)
  10153. setExpiryTime(properties, helper.getExpiryDays());
  10154. if (helper.getFlags() & TIWupdate)
  10155. {
  10156. unsigned eclCRC;
  10157. unsigned __int64 totalCRC;
  10158. helper.getUpdateCRCs(eclCRC, totalCRC);
  10159. properties.setPropInt("@eclCRC", eclCRC);
  10160. properties.setPropInt64("@totalCRC", totalCRC);
  10161. }
  10162. properties.setPropInt("@fileCrc", fileCrc);
  10163. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  10164. void * layoutMetaBuff;
  10165. size32_t layoutMetaSize;
  10166. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  10167. {
  10168. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  10169. rtlFree(layoutMetaBuff);
  10170. }
  10171. }
  10172. IUserDescriptor *queryUserDescriptor() const
  10173. {
  10174. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10175. if (workUnit)
  10176. return workUnit->queryUserDescriptor();
  10177. else
  10178. return NULL;
  10179. }
  10180. };
  10181. //=================================================================================
  10182. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10183. {
  10184. public:
  10185. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10186. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10187. {
  10188. setNumOutputs(0);
  10189. }
  10190. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10191. {
  10192. return new CRoxieServerIndexWriteActivity(this, _probeManager);
  10193. }
  10194. virtual bool isSink() const
  10195. {
  10196. return true;
  10197. }
  10198. };
  10199. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  10200. {
  10201. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  10202. }
  10203. //=================================================================================
  10204. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  10205. {
  10206. if((flags & JFmatchAbortLimitSkips) != 0)
  10207. {
  10208. limitFail = false;
  10209. limitOnFail = false;
  10210. }
  10211. else
  10212. {
  10213. limitOnFail = ((flags & JFonfail) != 0);
  10214. limitFail = !limitOnFail;
  10215. }
  10216. }
  10217. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  10218. {
  10219. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  10220. IHThorJoinArg &helper;
  10221. ICompare * collate;
  10222. ICompare * collateupper;
  10223. ThorActivityKind activityKind;
  10224. bool leftOuterJoin;
  10225. bool rightOuterJoin;
  10226. bool exclude;
  10227. bool limitFail;
  10228. bool limitOnFail;
  10229. unsigned keepLimit;
  10230. unsigned joinLimit;
  10231. unsigned atmostLimit;
  10232. unsigned abortLimit;
  10233. unsigned atmostsTriggered;
  10234. bool betweenjoin;
  10235. OwnedRowArray right;
  10236. const void * left;
  10237. const void * pendingRight;
  10238. unsigned rightIndex;
  10239. BoolArray matchedRight;
  10240. bool matchedLeft;
  10241. Owned<IException> failingLimit;
  10242. ConstPointerArray filteredRight;
  10243. Owned<IRHLimitedCompareHelper> limitedhelper;
  10244. OwnedConstRoxieRow defaultLeft;
  10245. OwnedConstRoxieRow defaultRight;
  10246. Owned<IEngineRowAllocator> defaultLeftAllocator;
  10247. Owned<IEngineRowAllocator> defaultRightAllocator;
  10248. bool cloneLeft;
  10249. void createDefaultLeft()
  10250. {
  10251. if (!defaultLeft)
  10252. {
  10253. if (!defaultLeftAllocator)
  10254. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  10255. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  10256. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  10257. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  10258. }
  10259. }
  10260. void createDefaultRight()
  10261. {
  10262. if (!defaultRight)
  10263. {
  10264. if (!defaultRightAllocator)
  10265. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  10266. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  10267. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  10268. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  10269. }
  10270. }
  10271. public:
  10272. CRoxieServerJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10273. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  10274. {
  10275. // MORE - some of this should be done in factory
  10276. unsigned joinFlags = helper.getJoinFlags();
  10277. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  10278. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  10279. exclude = (joinFlags & JFexclude) != 0;
  10280. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  10281. getLimitType(joinFlags, limitFail, limitOnFail);
  10282. if (joinFlags & JFslidingmatch)
  10283. {
  10284. betweenjoin = true;
  10285. collate = helper.queryCompareLeftRightLower();
  10286. collateupper = helper.queryCompareLeftRightUpper();
  10287. }
  10288. else
  10289. {
  10290. betweenjoin = false;
  10291. collate = collateupper = helper.queryCompareLeftRight();
  10292. }
  10293. rightIndex = 0;
  10294. state = JSfill;
  10295. matchedLeft = false;
  10296. joinLimit = 0;
  10297. keepLimit = 0; // wait until ctx available
  10298. atmostLimit = 0; // wait until ctx available
  10299. abortLimit = 0; // wait until ctx available
  10300. atmostsTriggered = 0;
  10301. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  10302. left = NULL;
  10303. pendingRight = NULL;
  10304. activityKind = _factory->getKind();
  10305. }
  10306. virtual bool needsAllocator() const { return true; }
  10307. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10308. {
  10309. left = NULL;
  10310. rightIndex = 0;
  10311. state = JSfill;
  10312. matchedLeft = false;
  10313. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  10314. keepLimit = helper.getKeepLimit();
  10315. if (keepLimit == 0)
  10316. keepLimit = (unsigned)-1;
  10317. atmostsTriggered = 0;
  10318. atmostLimit = helper.getJoinLimit();
  10319. if(atmostLimit == 0)
  10320. atmostLimit = (unsigned)-1;
  10321. else
  10322. assertex(!rightOuterJoin && !betweenjoin);
  10323. abortLimit = helper.getMatchAbortLimit();
  10324. if (abortLimit == 0)
  10325. abortLimit = (unsigned)-1;
  10326. if (rightOuterJoin)
  10327. createDefaultLeft();
  10328. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  10329. createDefaultRight();
  10330. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  10331. { //limited match join (s[1..n])
  10332. limitedhelper.setown(createRHLimitedCompareHelper());
  10333. limitedhelper->init( helper.getJoinLimit(), input1, collate, helper.queryPrefixCompare() );
  10334. }
  10335. }
  10336. virtual void reset()
  10337. {
  10338. if (atmostsTriggered)
  10339. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  10340. right.clear();
  10341. ReleaseClearRoxieRow(left);
  10342. ReleaseClearRoxieRow(pendingRight);
  10343. defaultRight.clear();
  10344. defaultLeft.clear();
  10345. CRoxieServerTwoInputActivity::reset();
  10346. }
  10347. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10348. {
  10349. switch(idx)
  10350. {
  10351. case 0:
  10352. if ((helper.getJoinFlags() & JFparallel) != 0)
  10353. {
  10354. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  10355. puller->setInput(0, _in);
  10356. _in = puller;
  10357. }
  10358. input = _in;
  10359. break;
  10360. case 1:
  10361. input1 = _in;
  10362. break;
  10363. default:
  10364. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10365. }
  10366. }
  10367. virtual IRoxieInput *queryOutput(unsigned idx)
  10368. {
  10369. if (idx==(unsigned)-1)
  10370. idx = 0;
  10371. return idx ? NULL : this;
  10372. }
  10373. void fillLeft()
  10374. {
  10375. matchedLeft = false;
  10376. left = input->nextInGroup();
  10377. if (!left)
  10378. left = input->nextInGroup();
  10379. if(betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  10380. fillRight();
  10381. if (limitedhelper && 0==rightIndex)
  10382. {
  10383. rightIndex = 0;
  10384. right.clear();
  10385. matchedRight.kill();
  10386. if (left)
  10387. {
  10388. limitedhelper->getGroup(right,left);
  10389. ForEachItemIn(idx, right)
  10390. matchedRight.append(false);
  10391. }
  10392. }
  10393. }
  10394. void fillRight()
  10395. {
  10396. if (limitedhelper)
  10397. return;
  10398. failingLimit.clear();
  10399. if(betweenjoin && left)
  10400. {
  10401. aindex_t start = 0;
  10402. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  10403. start++;
  10404. if(start>0)
  10405. right.clearPart(0, start);
  10406. }
  10407. else
  10408. right.clear();
  10409. rightIndex = 0;
  10410. unsigned groupCount = 0;
  10411. const void * next;
  10412. while(true)
  10413. {
  10414. if(pendingRight)
  10415. {
  10416. next = pendingRight;
  10417. pendingRight = NULL;
  10418. }
  10419. else
  10420. {
  10421. next = input1->nextInGroup();
  10422. }
  10423. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  10424. {
  10425. while(next)
  10426. {
  10427. ReleaseClearRoxieRow(next);
  10428. next = input1->nextInGroup();
  10429. }
  10430. continue;
  10431. }
  10432. while(next)
  10433. {
  10434. if(groupCount==abortLimit)
  10435. {
  10436. if(limitFail)
  10437. failLimit();
  10438. if (ctx->queryDebugContext())
  10439. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  10440. if(limitOnFail)
  10441. {
  10442. assertex(!failingLimit);
  10443. try
  10444. {
  10445. failLimit();
  10446. }
  10447. catch(IException * except)
  10448. {
  10449. failingLimit.setown(except);
  10450. }
  10451. assertex(failingLimit != NULL);
  10452. }
  10453. right.append(next);
  10454. do
  10455. {
  10456. next = input1->nextInGroup();
  10457. ReleaseRoxieRow(next);
  10458. } while(next);
  10459. break;
  10460. }
  10461. else if(groupCount==atmostLimit)
  10462. {
  10463. atmostsTriggered++;
  10464. right.clear();
  10465. groupCount = 0;
  10466. while(next)
  10467. {
  10468. ReleaseRoxieRow(next);
  10469. next = input1->nextInGroup();
  10470. }
  10471. }
  10472. else
  10473. {
  10474. right.append(next);
  10475. groupCount++;
  10476. }
  10477. next = input1->nextInGroup();
  10478. }
  10479. // normally only want to read one right group, but if is between join and next right group is in window for left, need to continue
  10480. if(betweenjoin && left)
  10481. {
  10482. pendingRight = input1->nextInGroup();
  10483. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  10484. break;
  10485. }
  10486. else
  10487. break;
  10488. }
  10489. matchedRight.kill();
  10490. ForEachItemIn(idx, right)
  10491. matchedRight.append(false);
  10492. }
  10493. const void * joinRecords(const void * curLeft, const void * curRight)
  10494. {
  10495. if (cloneLeft)
  10496. {
  10497. LinkRoxieRow(curLeft);
  10498. return curLeft;
  10499. }
  10500. try
  10501. {
  10502. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10503. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight);
  10504. if (thisSize)
  10505. return rowBuilder.finalizeRowClear(thisSize);
  10506. else
  10507. return NULL;
  10508. }
  10509. catch (IException *E)
  10510. {
  10511. throw makeWrappedException(E);
  10512. }
  10513. }
  10514. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  10515. {
  10516. try
  10517. {
  10518. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10519. unsigned numRows = rows.ordinality();
  10520. const void * right = numRows ? rows.item(0) : defaultRight.get();
  10521. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
  10522. if (thisSize)
  10523. return rowBuilder.finalizeRowClear(thisSize);
  10524. else
  10525. return NULL;
  10526. }
  10527. catch (IException *E)
  10528. {
  10529. throw makeWrappedException(E);
  10530. }
  10531. }
  10532. const void * joinException(const void * curLeft, IException * except)
  10533. {
  10534. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10535. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
  10536. return rowBuilder.finalizeRowClear(thisSize);
  10537. }
  10538. void failLimit()
  10539. {
  10540. helper.onMatchAbortLimitExceeded();
  10541. CommonXmlWriter xmlwrite(0);
  10542. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  10543. {
  10544. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  10545. }
  10546. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  10547. }
  10548. virtual const void * nextInGroup()
  10549. {
  10550. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10551. loop
  10552. {
  10553. switch (state)
  10554. {
  10555. case JSfill:
  10556. fillLeft();
  10557. state = JSfillright;
  10558. break;
  10559. case JSfillright:
  10560. fillRight();
  10561. state = JScollate;
  10562. break;
  10563. case JSfillleft:
  10564. fillLeft();
  10565. state = JScollate;
  10566. break;
  10567. case JScollate:
  10568. if (right.ordinality() == 0)
  10569. {
  10570. if (left == NULL)
  10571. return NULL;
  10572. state = JSleftonly;
  10573. }
  10574. else
  10575. {
  10576. if (!left)
  10577. state = JSrightonly;
  10578. else
  10579. {
  10580. int diff;
  10581. if(betweenjoin)
  10582. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  10583. else
  10584. diff = collate->docompare(left, right.item(0));
  10585. bool limitExceeded = right.ordinality()>abortLimit;
  10586. if (diff == 0)
  10587. {
  10588. if (limitExceeded)
  10589. {
  10590. const void * ret = NULL;
  10591. if(failingLimit)
  10592. ret = joinException(left, failingLimit);
  10593. ReleaseRoxieRow(left);
  10594. left = NULL;
  10595. state = JSfillleft;
  10596. ForEachItemIn(idx, right)
  10597. matchedRight.replace(true, idx);
  10598. if(ret)
  10599. {
  10600. processed++;
  10601. return ret;
  10602. }
  10603. }
  10604. else
  10605. {
  10606. state = JScompare;
  10607. joinLimit = keepLimit;
  10608. }
  10609. }
  10610. else if (diff < 0)
  10611. state = JSleftonly;
  10612. else if (limitExceeded)
  10613. {
  10614. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  10615. state = JSfillright;
  10616. }
  10617. else
  10618. state = JSrightonly;
  10619. }
  10620. }
  10621. break;
  10622. case JSrightonly:
  10623. if (rightOuterJoin)
  10624. {
  10625. switch (activityKind)
  10626. {
  10627. case TAKjoin:
  10628. {
  10629. while (right.isItem(rightIndex))
  10630. {
  10631. if (!matchedRight.item(rightIndex))
  10632. {
  10633. const void * rhs = right.item(rightIndex++);
  10634. const void *ret = joinRecords(defaultLeft, rhs);
  10635. if (ret)
  10636. {
  10637. processed++;
  10638. return ret;
  10639. }
  10640. }
  10641. rightIndex++;
  10642. }
  10643. break;
  10644. }
  10645. //Probably excessive to implement the following, but possibly useful
  10646. case TAKdenormalize:
  10647. {
  10648. OwnedConstRoxieRow newLeft;
  10649. newLeft.set(defaultLeft);
  10650. unsigned rowSize = 0;
  10651. unsigned leftCount = 0;
  10652. while (right.isItem(rightIndex))
  10653. {
  10654. if (!matchedRight.item(rightIndex))
  10655. {
  10656. const void * rhs = right.item(rightIndex);
  10657. try
  10658. {
  10659. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10660. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10661. if (thisSize)
  10662. {
  10663. rowSize = thisSize;
  10664. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10665. }
  10666. }
  10667. catch (IException *E)
  10668. {
  10669. throw makeWrappedException(E);
  10670. }
  10671. }
  10672. rightIndex++;
  10673. }
  10674. state = JSfillright;
  10675. if (rowSize)
  10676. {
  10677. processed++;
  10678. return newLeft.getClear();
  10679. }
  10680. break;
  10681. }
  10682. case TAKdenormalizegroup:
  10683. {
  10684. filteredRight.kill();
  10685. while (right.isItem(rightIndex))
  10686. {
  10687. if (!matchedRight.item(rightIndex))
  10688. filteredRight.append(right.item(rightIndex));
  10689. rightIndex++;
  10690. }
  10691. state = JSfillright;
  10692. if (filteredRight.ordinality())
  10693. {
  10694. const void * ret = denormalizeRecords(defaultLeft, filteredRight);
  10695. filteredRight.kill();
  10696. if (ret)
  10697. {
  10698. processed++;
  10699. return ret;
  10700. }
  10701. }
  10702. break;
  10703. }
  10704. }
  10705. }
  10706. state = JSfillright;
  10707. break;
  10708. case JSleftonly:
  10709. {
  10710. const void * ret = NULL;
  10711. if (!matchedLeft && leftOuterJoin)
  10712. {
  10713. switch (activityKind)
  10714. {
  10715. case TAKjoin:
  10716. ret = joinRecords(left, defaultRight);
  10717. break;
  10718. case TAKdenormalize:
  10719. ret = left;
  10720. left = NULL;
  10721. break;
  10722. case TAKdenormalizegroup:
  10723. filteredRight.kill();
  10724. ret = denormalizeRecords(left, filteredRight);
  10725. break;
  10726. }
  10727. }
  10728. ReleaseRoxieRow(left);
  10729. left = NULL;
  10730. state = JSfillleft;
  10731. if (ret)
  10732. {
  10733. processed++;
  10734. return ret;
  10735. }
  10736. break;
  10737. }
  10738. case JScompare:
  10739. if (joinLimit != 0)
  10740. {
  10741. switch (activityKind)
  10742. {
  10743. case TAKjoin:
  10744. {
  10745. while (right.isItem(rightIndex))
  10746. {
  10747. const void * rhs = right.item(rightIndex++);
  10748. if (helper.match(left, rhs))
  10749. {
  10750. matchedRight.replace(true, rightIndex-1);
  10751. matchedLeft = true;
  10752. if (!exclude)
  10753. {
  10754. const void *ret = joinRecords(left, rhs);
  10755. if (ret)
  10756. {
  10757. processed++;
  10758. joinLimit--;
  10759. return ret;
  10760. }
  10761. }
  10762. }
  10763. }
  10764. break;
  10765. }
  10766. case TAKdenormalize:
  10767. {
  10768. OwnedConstRoxieRow newLeft;
  10769. newLeft.set(left);
  10770. unsigned rowSize = 0;
  10771. unsigned leftCount = 0;
  10772. while (right.isItem(rightIndex) && joinLimit)
  10773. {
  10774. try
  10775. {
  10776. const void * rhs = right.item(rightIndex++);
  10777. if (helper.match(left, rhs))
  10778. {
  10779. matchedRight.replace(true, rightIndex-1);
  10780. matchedLeft = true;
  10781. if (!exclude)
  10782. {
  10783. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10784. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
  10785. if (thisSize)
  10786. {
  10787. rowSize = thisSize;
  10788. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  10789. joinLimit--;
  10790. }
  10791. }
  10792. }
  10793. }
  10794. catch (IException *E)
  10795. {
  10796. throw makeWrappedException(E);
  10797. }
  10798. }
  10799. state = JSleftonly;
  10800. rightIndex = 0;
  10801. if (rowSize)
  10802. {
  10803. processed++;
  10804. return newLeft.getClear();
  10805. }
  10806. break;
  10807. }
  10808. case TAKdenormalizegroup:
  10809. {
  10810. filteredRight.kill();
  10811. while (right.isItem(rightIndex))
  10812. {
  10813. const void * rhs = right.item(rightIndex++);
  10814. if (helper.match(left, rhs))
  10815. {
  10816. matchedRight.replace(true, rightIndex-1);
  10817. filteredRight.append(rhs);
  10818. matchedLeft = true;
  10819. if (filteredRight.ordinality()==joinLimit)
  10820. break;
  10821. }
  10822. }
  10823. state = JSleftonly;
  10824. rightIndex = 0;
  10825. if (!exclude && filteredRight.ordinality())
  10826. {
  10827. const void * ret = denormalizeRecords(left, filteredRight);
  10828. filteredRight.kill();
  10829. if (ret)
  10830. {
  10831. processed++;
  10832. return ret;
  10833. }
  10834. }
  10835. break;
  10836. }
  10837. }
  10838. }
  10839. state = JSleftonly;
  10840. rightIndex = 0;
  10841. break;
  10842. }
  10843. }
  10844. }
  10845. };
  10846. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  10847. {
  10848. unsigned input2;
  10849. unsigned input2idx;
  10850. public:
  10851. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10852. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  10853. {
  10854. input2 = 0;
  10855. input2idx = 0;
  10856. }
  10857. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  10858. {
  10859. return new CRoxieServerJoinActivity(this, _probeManager);
  10860. }
  10861. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  10862. {
  10863. if (idx==1)
  10864. {
  10865. input2 = source;
  10866. input2idx = sourceidx;
  10867. }
  10868. else
  10869. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  10870. }
  10871. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  10872. {
  10873. switch (idx)
  10874. {
  10875. case 1:
  10876. sourceidx = input2idx;
  10877. return input2;
  10878. case 0:
  10879. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  10880. default:
  10881. return (unsigned) -1;
  10882. }
  10883. }
  10884. virtual unsigned numInputs() const { return 2; }
  10885. };
  10886. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  10887. {
  10888. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  10889. }
  10890. //=================================================================================
  10891. #define CONCAT_READAHEAD 1000
  10892. MAKEPointerArray(RecordPullerThread, RecordPullerArray);
  10893. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  10894. {
  10895. QueueOf<const void, true> buffer;
  10896. InterruptableSemaphore ready;
  10897. InterruptableSemaphore space;
  10898. CriticalSection crit;
  10899. unsigned eofs;
  10900. RecordPullerArray pullers;
  10901. unsigned numInputs;
  10902. public:
  10903. CRoxieServerThreadedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  10904. : CRoxieServerActivity(_factory, _probeManager)
  10905. {
  10906. eofs = 0;
  10907. numInputs = _numInputs;
  10908. for (unsigned i = 0; i < numInputs; i++)
  10909. pullers.append(*new RecordPullerThread(_grouped));
  10910. }
  10911. ~CRoxieServerThreadedConcatActivity()
  10912. {
  10913. ForEachItemIn(idx, pullers)
  10914. delete &pullers.item(idx);
  10915. }
  10916. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10917. {
  10918. space.reinit(CONCAT_READAHEAD);
  10919. ready.reinit();
  10920. eofs = 0;
  10921. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10922. ForEachItemIn(idx, pullers)
  10923. {
  10924. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx->concatPreload(), false, ctx);
  10925. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  10926. // in the part of the subgraph that the thread uses has been started.
  10927. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  10928. }
  10929. }
  10930. virtual void stop(bool aborting)
  10931. {
  10932. space.interrupt();
  10933. ready.interrupt();
  10934. ForEachItemIn(idx, pullers)
  10935. pullers.item(idx).stop(aborting);
  10936. CRoxieServerActivity::stop(aborting);
  10937. }
  10938. virtual unsigned __int64 queryLocalCycles() const
  10939. {
  10940. return 0;
  10941. }
  10942. virtual IRoxieInput *queryInput(unsigned idx) const
  10943. {
  10944. if (pullers.isItem(idx))
  10945. return pullers.item(idx).queryInput();
  10946. else
  10947. return NULL;
  10948. }
  10949. virtual void reset()
  10950. {
  10951. CRoxieServerActivity::reset();
  10952. ForEachItemIn(idx, pullers)
  10953. pullers.item(idx).reset();
  10954. ForEachItemIn(idx1, buffer)
  10955. ReleaseRoxieRow(buffer.item(idx1));
  10956. buffer.clear();
  10957. }
  10958. virtual void setInput(unsigned idx, IRoxieInput *_in)
  10959. {
  10960. if (pullers.isItem(idx))
  10961. pullers.item(idx).setInput(this, _in);
  10962. else
  10963. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  10964. }
  10965. virtual const void * nextInGroup()
  10966. {
  10967. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  10968. loop
  10969. {
  10970. {
  10971. CriticalBlock b(crit);
  10972. if (eofs==numInputs && !buffer.ordinality())
  10973. return NULL; // eof
  10974. }
  10975. ready.wait();
  10976. const void *ret;
  10977. {
  10978. CriticalBlock b(crit);
  10979. ret = buffer.dequeue();
  10980. }
  10981. if (ret)
  10982. processed++;
  10983. space.signal();
  10984. return ret;
  10985. }
  10986. }
  10987. virtual bool fireException(IException *e)
  10988. {
  10989. // called from puller thread on failure
  10990. ready.interrupt(LINK(e));
  10991. space.interrupt(e);
  10992. return true;
  10993. }
  10994. virtual void processRow(const void *row)
  10995. {
  10996. {
  10997. CriticalBlock b(crit);
  10998. buffer.enqueue(row);
  10999. }
  11000. ready.signal();
  11001. space.wait();
  11002. }
  11003. virtual void processGroup(const ConstPointerArray &rows)
  11004. {
  11005. // NOTE - a bit bizzare in that it waits for the space AFTER using it.
  11006. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  11007. // if group was larger than max(space)
  11008. {
  11009. CriticalBlock b(crit);
  11010. ForEachItemIn(idx, rows)
  11011. buffer.enqueue(rows.item(idx));
  11012. buffer.enqueue(NULL);
  11013. }
  11014. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  11015. {
  11016. ready.signal();
  11017. space.wait();
  11018. }
  11019. }
  11020. virtual void processEOG()
  11021. {
  11022. // Used when output is not grouped - just ignore
  11023. }
  11024. virtual void processDone()
  11025. {
  11026. CriticalBlock b(crit);
  11027. eofs++;
  11028. if (eofs == numInputs)
  11029. ready.signal();
  11030. }
  11031. };
  11032. class CRoxieServerOrderedConcatActivity : public CRoxieServerActivity
  11033. {
  11034. IRoxieInput *curInput;
  11035. bool eogSeen;
  11036. bool anyThisGroup;
  11037. bool grouped;
  11038. unsigned numInputs;
  11039. unsigned inputIdx;
  11040. IRoxieInput **inputArray;
  11041. public:
  11042. CRoxieServerOrderedConcatActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11043. : CRoxieServerActivity(_factory, _probeManager)
  11044. {
  11045. eogSeen = false;
  11046. anyThisGroup = false;
  11047. grouped = _grouped;
  11048. numInputs = _numInputs;
  11049. inputIdx = 0;
  11050. inputArray = new IRoxieInput*[numInputs];
  11051. for (unsigned i = 0; i < numInputs; i++)
  11052. inputArray[i] = NULL;
  11053. }
  11054. ~CRoxieServerOrderedConcatActivity()
  11055. {
  11056. delete [] inputArray;
  11057. }
  11058. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11059. {
  11060. inputIdx = 0;
  11061. curInput = inputArray[inputIdx];
  11062. eogSeen = false;
  11063. anyThisGroup = false;
  11064. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11065. for (unsigned i = 0; i < numInputs; i++)
  11066. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11067. }
  11068. virtual void stop(bool aborting)
  11069. {
  11070. for (unsigned i = 0; i < numInputs; i++)
  11071. inputArray[i]->stop(aborting);
  11072. CRoxieServerActivity::stop(aborting);
  11073. }
  11074. virtual unsigned __int64 queryLocalCycles() const
  11075. {
  11076. return 0;
  11077. }
  11078. virtual IRoxieInput *queryInput(unsigned idx) const
  11079. {
  11080. if (idx < numInputs)
  11081. return inputArray[idx];
  11082. else
  11083. return NULL;
  11084. }
  11085. virtual void reset()
  11086. {
  11087. CRoxieServerActivity::reset();
  11088. for (unsigned i = 0; i < numInputs; i++)
  11089. inputArray[i]->reset();
  11090. }
  11091. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11092. {
  11093. inputArray[idx] = _in;
  11094. }
  11095. virtual const void * nextInGroup()
  11096. {
  11097. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11098. if (!curInput)
  11099. return NULL; // eof
  11100. const void * next = curInput->nextInGroup();
  11101. if (next)
  11102. {
  11103. anyThisGroup = true;
  11104. eogSeen = false;
  11105. processed++;
  11106. return next;
  11107. }
  11108. else if (!eogSeen)
  11109. {
  11110. eogSeen = true;
  11111. if (grouped)
  11112. {
  11113. if (anyThisGroup)
  11114. {
  11115. anyThisGroup = false;
  11116. return NULL;
  11117. }
  11118. else
  11119. return nextInGroup();
  11120. }
  11121. else
  11122. return nextInGroup();
  11123. }
  11124. else if (inputIdx < numInputs-1)
  11125. {
  11126. inputIdx++;
  11127. curInput = inputArray[inputIdx];
  11128. eogSeen = false;
  11129. return nextInGroup();
  11130. }
  11131. else
  11132. {
  11133. curInput = NULL;
  11134. return NULL;
  11135. }
  11136. }
  11137. };
  11138. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  11139. {
  11140. bool ordered;
  11141. bool grouped;
  11142. public:
  11143. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11144. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11145. {
  11146. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  11147. ordered = helper->isOrdered();
  11148. grouped = helper->queryOutputMeta()->isGrouped();
  11149. }
  11150. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11151. {
  11152. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  11153. return new CRoxieServerOrderedConcatActivity(this, _probeManager, grouped, numInputs());
  11154. else
  11155. return new CRoxieServerThreadedConcatActivity(this, _probeManager, grouped, numInputs());
  11156. }
  11157. };
  11158. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11159. {
  11160. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11161. }
  11162. //=================================================================================
  11163. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  11164. {
  11165. IRoxieInput * selectedInput;
  11166. unsigned savedParentExtractSize;
  11167. const byte * savedParentExtract;
  11168. bool foundInput;
  11169. public:
  11170. CRoxieServerNonEmptyActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11171. : CRoxieServerMultiInputBaseActivity(_factory, _probeManager, _numInputs)
  11172. {
  11173. foundInput = false;
  11174. selectedInput = NULL;
  11175. savedParentExtractSize = 0;;
  11176. savedParentExtract = NULL;
  11177. }
  11178. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11179. {
  11180. //Don't start the inputs yet so we can short-circuit...
  11181. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  11182. savedParentExtractSize = parentExtractSize;
  11183. savedParentExtract = parentExtract;
  11184. }
  11185. virtual void stop(bool aborting)
  11186. {
  11187. if (foundInput)
  11188. {
  11189. if (selectedInput)
  11190. selectedInput->stop(aborting);
  11191. }
  11192. else
  11193. {
  11194. for (unsigned i = 0; i < numInputs; i++)
  11195. inputArray[i]->stop(aborting);
  11196. }
  11197. CRoxieServerMultiInputBaseActivity::stop(aborting);
  11198. }
  11199. virtual void reset()
  11200. {
  11201. CRoxieServerMultiInputBaseActivity::reset();
  11202. foundInput = false;
  11203. selectedInput = NULL;
  11204. }
  11205. virtual unsigned __int64 queryLocalCycles() const
  11206. {
  11207. return 0; // Can't easily calcuate anything reliable but local processing is negligible
  11208. }
  11209. virtual const void * nextInGroup()
  11210. {
  11211. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11212. if (!foundInput)
  11213. {
  11214. foundInput = true;
  11215. //If we get an exception in this loop then stop() will stop any started inputs
  11216. for (unsigned i=0; i < numInputs; i++)
  11217. {
  11218. selectedInput = inputArray[i];
  11219. selectedInput->start(savedParentExtractSize, savedParentExtract, false);
  11220. const void * next = selectedInput->nextInGroup();
  11221. if (next)
  11222. {
  11223. //Found a row so stop remaining
  11224. for (unsigned j=i+1; j < numInputs; j++)
  11225. inputArray[j]->stop(false);
  11226. processed++;
  11227. return next;
  11228. }
  11229. selectedInput->stop(false);
  11230. }
  11231. selectedInput = NULL;
  11232. return NULL;
  11233. }
  11234. if (!selectedInput)
  11235. return NULL;
  11236. const void * next = selectedInput->nextInGroup();
  11237. if (next)
  11238. processed++;
  11239. return next;
  11240. }
  11241. };
  11242. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  11243. {
  11244. public:
  11245. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11246. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11247. {
  11248. }
  11249. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11250. {
  11251. return new CRoxieServerNonEmptyActivity(this, _probeManager, numInputs());
  11252. }
  11253. };
  11254. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11255. {
  11256. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11257. }
  11258. //=================================================================================
  11259. class CRoxieServerMergeActivity : public CRoxieServerActivity
  11260. {
  11261. IHThorMergeArg &helper;
  11262. unsigned *mergeheap;
  11263. unsigned activeInputs;
  11264. unsigned numInputs;
  11265. IRoxieInput **inputArray;
  11266. const void **pending;
  11267. bool first;
  11268. ICompare *compare;
  11269. bool dedup;
  11270. void permute()
  11271. {
  11272. assertex(activeInputs == 0);
  11273. for(unsigned i = 0; i < numInputs; i++)
  11274. if(pullInput(i))
  11275. mergeheap[activeInputs++] = i;
  11276. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  11277. // the heap property: no element should be smaller than its parent
  11278. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  11279. // the method: establish this by starting with the parent of the bottom element and working up to the top element, sifting each down to its correct place
  11280. if (activeInputs >= 2)
  11281. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  11282. siftDown(p);
  11283. if(dedup)
  11284. siftDownDedupTop();
  11285. else
  11286. siftDown(0);
  11287. }
  11288. void readNext()
  11289. {
  11290. if(!pullInput(mergeheap[0]))
  11291. if(!promote(0))
  11292. return;
  11293. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  11294. if(dedup)
  11295. siftDownDedupTop();
  11296. else
  11297. siftDown(0);
  11298. }
  11299. bool pullInput(unsigned i)
  11300. {
  11301. const void *next = inputArray[i]->nextInGroup();
  11302. if (!next)
  11303. next = inputArray[i]->nextInGroup();
  11304. pending[i] = next;
  11305. return (next != NULL);
  11306. }
  11307. bool promote(unsigned p)
  11308. {
  11309. activeInputs--;
  11310. if(activeInputs == p)
  11311. return false;
  11312. mergeheap[p] = mergeheap[activeInputs];
  11313. return true;
  11314. }
  11315. bool siftDown(unsigned p)
  11316. {
  11317. // assumimg that all descendents of p form a heap, sift p down to its correct position, and so include it in the heap
  11318. bool nochange = true;
  11319. while(1)
  11320. {
  11321. unsigned c = p*2 + 1;
  11322. if(c >= activeInputs)
  11323. return nochange;
  11324. if(c+1 < activeInputs)
  11325. {
  11326. int childcmp = BuffCompare(c+1, c);
  11327. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  11328. ++c;
  11329. }
  11330. int cmp = BuffCompare(c, p);
  11331. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  11332. return nochange;
  11333. nochange = false;
  11334. unsigned r = mergeheap[c];
  11335. mergeheap[c] = mergeheap[p];
  11336. mergeheap[p] = r;
  11337. p = c;
  11338. }
  11339. }
  11340. void siftDownDedupTop()
  11341. {
  11342. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  11343. if(activeInputs < 2)
  11344. return;
  11345. unsigned c = 1;
  11346. int childcmp = 1;
  11347. if(activeInputs >= 3)
  11348. {
  11349. childcmp = BuffCompare(2, 1);
  11350. if(childcmp < 0)
  11351. c = 2;
  11352. }
  11353. int cmp = BuffCompare(c, 0);
  11354. if(cmp > 0)
  11355. return;
  11356. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  11357. while(cmp <= 0)
  11358. {
  11359. if(cmp == 0)
  11360. {
  11361. if(mergeheap[c] < mergeheap[0])
  11362. {
  11363. unsigned r = mergeheap[c];
  11364. mergeheap[c] = mergeheap[0];
  11365. mergeheap[0] = r;
  11366. }
  11367. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11368. if(!pullInput(mergeheap[c]))
  11369. if(!promote(c))
  11370. break;
  11371. siftDown(c);
  11372. }
  11373. else
  11374. {
  11375. unsigned r = mergeheap[c];
  11376. mergeheap[c] = mergeheap[0];
  11377. mergeheap[0] = r;
  11378. if(siftDown(c))
  11379. break;
  11380. }
  11381. cmp = BuffCompare(c, 0);
  11382. }
  11383. // the following loop ensures the uniqueness property holds on the other branch too
  11384. c = 3-c;
  11385. if(activeInputs <= c)
  11386. return;
  11387. while(childcmp == 0)
  11388. {
  11389. if(mergeheap[c] < mergeheap[0])
  11390. {
  11391. unsigned r = mergeheap[c];
  11392. mergeheap[c] = mergeheap[0];
  11393. mergeheap[0] = r;
  11394. }
  11395. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  11396. if(!pullInput(mergeheap[c]))
  11397. if(!promote(c))
  11398. break;
  11399. siftDown(c);
  11400. childcmp = BuffCompare(c, 0);
  11401. }
  11402. }
  11403. inline int BuffCompare(unsigned a, unsigned b)
  11404. {
  11405. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  11406. }
  11407. public:
  11408. CRoxieServerMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11409. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorMergeArg &)basehelper), numInputs(_numInputs)
  11410. {
  11411. activeInputs = 0;
  11412. first = true;
  11413. mergeheap = new unsigned[numInputs];
  11414. inputArray = new IRoxieInput*[numInputs];
  11415. pending = new const void *[numInputs];
  11416. compare = helper.queryCompare();
  11417. dedup = helper.dedup();
  11418. for (unsigned i = 0; i < numInputs; i++)
  11419. {
  11420. inputArray[i] = NULL;
  11421. pending[i] = NULL;
  11422. }
  11423. }
  11424. ~CRoxieServerMergeActivity()
  11425. {
  11426. delete [] mergeheap;
  11427. delete [] inputArray;
  11428. delete [] pending;
  11429. }
  11430. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11431. {
  11432. activeInputs = 0;
  11433. first = true;
  11434. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11435. for (unsigned i = 0; i < numInputs; i++)
  11436. {
  11437. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  11438. }
  11439. }
  11440. virtual void stop(bool aborting)
  11441. {
  11442. for (unsigned i = 0; i < numInputs; i++)
  11443. {
  11444. inputArray[i]->stop(aborting);
  11445. }
  11446. CRoxieServerActivity::stop(aborting);
  11447. }
  11448. virtual void reset()
  11449. {
  11450. for (unsigned i = 0; i < numInputs; i++)
  11451. {
  11452. ReleaseClearRoxieRow(pending[i]);
  11453. inputArray[i]->reset();
  11454. }
  11455. CRoxieServerActivity::reset();
  11456. }
  11457. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11458. {
  11459. inputArray[idx] = _in;
  11460. }
  11461. virtual const void * nextInGroup()
  11462. {
  11463. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11464. if (first)
  11465. {
  11466. permute();
  11467. first = false;
  11468. }
  11469. if (activeInputs)
  11470. {
  11471. const void *next = pending[mergeheap[0]];
  11472. readNext();
  11473. if (next)
  11474. processed++;
  11475. return next;
  11476. }
  11477. else
  11478. return NULL;
  11479. }
  11480. };
  11481. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  11482. {
  11483. public:
  11484. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11485. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11486. {
  11487. }
  11488. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11489. {
  11490. return new CRoxieServerMergeActivity(this, _probeManager, numInputs());
  11491. }
  11492. };
  11493. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11494. {
  11495. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11496. }
  11497. //=================================================================================
  11498. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  11499. {
  11500. IHThorRegroupArg &helper;
  11501. unsigned inputIndex;
  11502. bool eof;
  11503. unsigned __int64 numProcessedLastGroup;
  11504. public:
  11505. CRoxieServerRegroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11506. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
  11507. {
  11508. inputIndex = 0;
  11509. eof = false;
  11510. numProcessedLastGroup = 0;
  11511. }
  11512. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11513. {
  11514. inputIndex = 0;
  11515. eof = false;
  11516. numProcessedLastGroup = processed;
  11517. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11518. }
  11519. const void * nextFromInputs()
  11520. {
  11521. unsigned initialInput = inputIndex;
  11522. while (inputIndex < numInputs)
  11523. {
  11524. const void * next = inputArray[inputIndex]->nextInGroup();
  11525. if (next)
  11526. {
  11527. if ((inputIndex != initialInput) && (inputIndex != initialInput+1))
  11528. {
  11529. ReleaseRoxieRow(next);
  11530. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11531. }
  11532. return next;
  11533. }
  11534. inputIndex++;
  11535. }
  11536. if ((initialInput != 0) && (initialInput+1 != numInputs))
  11537. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  11538. inputIndex = 0;
  11539. return NULL;
  11540. }
  11541. virtual const void * nextInGroup()
  11542. {
  11543. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11544. if (eof)
  11545. return NULL;
  11546. const void * ret = nextFromInputs();
  11547. if (ret)
  11548. {
  11549. processed++;
  11550. return ret;
  11551. }
  11552. if (numProcessedLastGroup != processed)
  11553. {
  11554. numProcessedLastGroup = processed;
  11555. return NULL;
  11556. }
  11557. eof = true;
  11558. return NULL;
  11559. }
  11560. #if 0
  11561. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11562. {
  11563. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11564. if (idx)
  11565. {
  11566. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11567. puller->setInput(0, _in);
  11568. CRoxieServerMultiInputActivity::setInput(idx, puller);
  11569. }
  11570. else
  11571. CRoxieServerMultiInputActivity::setInput(idx, _in);
  11572. }
  11573. #endif
  11574. };
  11575. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  11576. {
  11577. public:
  11578. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11579. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11580. {
  11581. }
  11582. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11583. {
  11584. return new CRoxieServerRegroupActivity(this, _probeManager, numInputs());
  11585. }
  11586. };
  11587. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11588. {
  11589. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11590. }
  11591. //=================================================================================
  11592. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  11593. {
  11594. IHThorCombineArg &helper;
  11595. unsigned __int64 numProcessedLastGroup;
  11596. public:
  11597. CRoxieServerCombineActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  11598. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  11599. {
  11600. numProcessedLastGroup = 0;
  11601. }
  11602. ~CRoxieServerCombineActivity()
  11603. {
  11604. }
  11605. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11606. {
  11607. numProcessedLastGroup = processed;
  11608. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  11609. }
  11610. void nextInputs(ConstPointerArray & out)
  11611. {
  11612. for (unsigned i=0; i < numInputs; i++)
  11613. {
  11614. const void * next = inputArray[i]->nextInGroup();
  11615. if (next)
  11616. out.append(next);
  11617. }
  11618. }
  11619. virtual bool needsAllocator() const { return true; }
  11620. virtual const void * nextInGroup()
  11621. {
  11622. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11623. loop
  11624. {
  11625. ConstPointerArray group;
  11626. nextInputs(group);
  11627. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  11628. nextInputs(group);
  11629. if (group.ordinality() == 0)
  11630. {
  11631. numProcessedLastGroup = processed;
  11632. return NULL;
  11633. }
  11634. else if (group.ordinality() != numInputs)
  11635. {
  11636. ReleaseRoxieRowSet(group);
  11637. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  11638. }
  11639. try
  11640. {
  11641. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11642. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  11643. ReleaseRoxieRowSet(group);
  11644. if (outSize)
  11645. {
  11646. processed++;
  11647. return rowBuilder.finalizeRowClear(outSize);
  11648. }
  11649. }
  11650. catch (IException *E)
  11651. {
  11652. ReleaseRoxieRowSet(group);
  11653. throw makeWrappedException(E);
  11654. }
  11655. }
  11656. }
  11657. };
  11658. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  11659. {
  11660. public:
  11661. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11662. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11663. {
  11664. }
  11665. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11666. {
  11667. return new CRoxieServerCombineActivity(this, _probeManager, numInputs());
  11668. }
  11669. };
  11670. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11671. {
  11672. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11673. }
  11674. //=================================================================================
  11675. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  11676. {
  11677. IHThorCombineGroupArg &helper;
  11678. unsigned __int64 numProcessedLastGroup;
  11679. public:
  11680. CRoxieServerCombineGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11681. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  11682. {
  11683. numProcessedLastGroup = 0;
  11684. }
  11685. ~CRoxieServerCombineGroupActivity()
  11686. {
  11687. }
  11688. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11689. {
  11690. numProcessedLastGroup = processed;
  11691. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11692. }
  11693. virtual void setInput(unsigned idx, IRoxieInput *_in)
  11694. {
  11695. switch(idx)
  11696. {
  11697. case 0:
  11698. #if 0
  11699. //MORE: RKC: Do we want to do this i) always ii) conditionally iii) never
  11700. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  11701. puller->setInput(0, _in);
  11702. _in = puller;
  11703. #endif
  11704. input = _in;
  11705. break;
  11706. case 1:
  11707. input1 = _in;
  11708. break;
  11709. default:
  11710. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  11711. }
  11712. }
  11713. virtual IRoxieInput *queryOutput(unsigned idx)
  11714. {
  11715. if (idx==(unsigned)-1)
  11716. idx = 0;
  11717. return idx ? NULL : this;
  11718. }
  11719. virtual bool needsAllocator() const { return true; }
  11720. virtual const void * nextInGroup()
  11721. {
  11722. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11723. loop
  11724. {
  11725. const void * left = input->nextInGroup();
  11726. if (!left && (numProcessedLastGroup == processed))
  11727. left = input->nextInGroup();
  11728. if (!left)
  11729. {
  11730. if (numProcessedLastGroup == processed)
  11731. {
  11732. const void * nextRight = input1->nextInGroup();
  11733. if (nextRight)
  11734. {
  11735. ReleaseRoxieRow(nextRight);
  11736. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  11737. }
  11738. }
  11739. else
  11740. numProcessedLastGroup = processed;
  11741. return NULL;
  11742. }
  11743. ConstPointerArray group;
  11744. loop
  11745. {
  11746. const void * in = input1->nextInGroup();
  11747. if (!in)
  11748. break;
  11749. group.append(in);
  11750. }
  11751. if (group.ordinality() == 0)
  11752. {
  11753. ReleaseRoxieRow(left);
  11754. ReleaseRoxieRowSet(group);
  11755. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  11756. }
  11757. try
  11758. {
  11759. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11760. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  11761. ReleaseRoxieRow(left);
  11762. ReleaseRoxieRowSet(group);
  11763. if (outSize)
  11764. {
  11765. processed++;
  11766. return rowBuilder.finalizeRowClear(outSize);
  11767. }
  11768. }
  11769. catch (IException *E)
  11770. {
  11771. ReleaseRoxieRow(left);
  11772. ReleaseRoxieRowSet(group);
  11773. throw makeWrappedException(E);
  11774. }
  11775. }
  11776. }
  11777. };
  11778. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  11779. {
  11780. unsigned input2;
  11781. unsigned input2idx;
  11782. public:
  11783. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11784. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11785. {
  11786. input2 = 0;
  11787. input2idx = 0;
  11788. }
  11789. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11790. {
  11791. return new CRoxieServerCombineGroupActivity(this, _probeManager);
  11792. }
  11793. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11794. {
  11795. if (idx==1)
  11796. {
  11797. input2 = source;
  11798. input2idx = sourceidx;
  11799. }
  11800. else
  11801. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11802. }
  11803. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11804. {
  11805. switch (idx)
  11806. {
  11807. case 1:
  11808. sourceidx = input2idx;
  11809. return input2;
  11810. case 0:
  11811. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11812. default:
  11813. return (unsigned) -1;
  11814. }
  11815. }
  11816. virtual unsigned numInputs() const { return 2; }
  11817. };
  11818. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11819. {
  11820. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11821. }
  11822. //=================================================================================
  11823. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  11824. {
  11825. IHThorRollupGroupArg &helper;
  11826. bool eof;
  11827. public:
  11828. CRoxieServerRollupGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11829. : CRoxieServerActivity(_factory, _probeManager),
  11830. helper((IHThorRollupGroupArg &)basehelper)
  11831. {
  11832. eof = false;
  11833. }
  11834. ~CRoxieServerRollupGroupActivity()
  11835. {
  11836. }
  11837. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11838. {
  11839. eof = false;
  11840. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11841. }
  11842. virtual bool needsAllocator() const { return true; }
  11843. virtual const void * nextInGroup()
  11844. {
  11845. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11846. if (eof)
  11847. return NULL;
  11848. loop
  11849. {
  11850. ConstPointerArray group;
  11851. loop
  11852. {
  11853. const void * in = input->nextInGroup();
  11854. if (!in)
  11855. break;
  11856. group.append(in);
  11857. }
  11858. if (group.ordinality() == 0)
  11859. {
  11860. eof = true;
  11861. return NULL;
  11862. }
  11863. try
  11864. {
  11865. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11866. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  11867. ReleaseRoxieRowSet(group);
  11868. if (outSize)
  11869. {
  11870. processed++;
  11871. return rowBuilder.finalizeRowClear(outSize);
  11872. }
  11873. }
  11874. catch (IException * E)
  11875. {
  11876. ReleaseRoxieRowSet(group);
  11877. throw makeWrappedException(E);
  11878. }
  11879. }
  11880. }
  11881. };
  11882. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  11883. {
  11884. public:
  11885. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11886. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11887. {
  11888. }
  11889. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11890. {
  11891. return new CRoxieServerRollupGroupActivity(this, _probeManager);
  11892. }
  11893. };
  11894. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11895. {
  11896. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11897. }
  11898. //=================================================================================
  11899. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  11900. {
  11901. IHThorFilterProjectArg &helper;
  11902. unsigned numProcessedLastGroup;
  11903. unsigned __int64 recordCount;
  11904. public:
  11905. CRoxieServerFilterProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  11906. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  11907. {
  11908. numProcessedLastGroup = 0;
  11909. recordCount = 0;
  11910. }
  11911. ~CRoxieServerFilterProjectActivity()
  11912. {
  11913. }
  11914. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11915. {
  11916. numProcessedLastGroup = 0;
  11917. recordCount = 0;
  11918. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  11919. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  11920. }
  11921. virtual bool needsAllocator() const { return true; }
  11922. virtual const void * nextInGroup()
  11923. {
  11924. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  11925. if (eof)
  11926. return NULL;
  11927. loop
  11928. {
  11929. const void * in = input->nextInGroup();
  11930. if (!in)
  11931. {
  11932. recordCount = 0;
  11933. if (numProcessedLastGroup == processed)
  11934. in = input->nextInGroup();
  11935. if (!in)
  11936. {
  11937. numProcessedLastGroup = processed;
  11938. return NULL;
  11939. }
  11940. }
  11941. try
  11942. {
  11943. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11944. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  11945. ReleaseRoxieRow(in);
  11946. if (outSize)
  11947. {
  11948. processed++;
  11949. return rowBuilder.finalizeRowClear(outSize);
  11950. }
  11951. }
  11952. catch (IException *E)
  11953. {
  11954. throw makeWrappedException(E);
  11955. }
  11956. }
  11957. }
  11958. };
  11959. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  11960. {
  11961. public:
  11962. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11963. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  11964. {
  11965. }
  11966. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  11967. {
  11968. return new CRoxieServerFilterProjectActivity(this, _probeManager);
  11969. }
  11970. };
  11971. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  11972. {
  11973. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  11974. }
  11975. //=================================================================================
  11976. class CRoxieServerProjectActivity : public CRoxieServerActivity
  11977. {
  11978. unsigned numProcessedLastGroup;
  11979. bool count;
  11980. unsigned __int64 recordCount;
  11981. public:
  11982. CRoxieServerProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  11983. : CRoxieServerActivity(_factory, _probeManager),
  11984. count(_count)
  11985. {
  11986. numProcessedLastGroup = 0;
  11987. recordCount = 0;
  11988. }
  11989. ~CRoxieServerProjectActivity()
  11990. {
  11991. }
  11992. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11993. {
  11994. numProcessedLastGroup = 0;
  11995. recordCount = 0;
  11996. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  11997. }
  11998. virtual bool needsAllocator() const { return true; }
  11999. virtual const void * nextInGroup()
  12000. {
  12001. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12002. loop
  12003. {
  12004. OwnedConstRoxieRow in = input->nextInGroup();
  12005. if (!in)
  12006. {
  12007. recordCount = 0;
  12008. if (numProcessedLastGroup == processed)
  12009. in.setown(input->nextInGroup());
  12010. if (!in)
  12011. {
  12012. numProcessedLastGroup = processed;
  12013. return NULL;
  12014. }
  12015. }
  12016. try
  12017. {
  12018. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12019. size32_t outSize;
  12020. if (count)
  12021. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  12022. else
  12023. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  12024. if (outSize)
  12025. {
  12026. processed++;
  12027. return rowBuilder.finalizeRowClear(outSize);
  12028. }
  12029. }
  12030. catch (IException *E)
  12031. {
  12032. throw makeWrappedException(E);
  12033. }
  12034. }
  12035. }
  12036. };
  12037. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  12038. {
  12039. protected:
  12040. bool count;
  12041. public:
  12042. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12043. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12044. {
  12045. count = (_kind==TAKcountproject || _kind==TAKprefetchcountproject);
  12046. }
  12047. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12048. {
  12049. return new CRoxieServerProjectActivity(this, _probeManager, count);
  12050. }
  12051. };
  12052. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12053. {
  12054. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12055. }
  12056. //=================================================================================
  12057. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  12058. {
  12059. unsigned numProcessedLastGroup;
  12060. bool count;
  12061. bool eof;
  12062. bool allPulled;
  12063. bool isThreaded;
  12064. unsigned preload;
  12065. unsigned __int64 recordCount;
  12066. IHThorPrefetchProjectArg &helper;
  12067. RecordPullerThread puller;
  12068. InterruptableSemaphore ready;
  12069. InterruptableSemaphore space;
  12070. class PrefetchInfo : public CInterface
  12071. {
  12072. public:
  12073. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  12074. {
  12075. if (helper.preTransform(extract, _in, _recordCount))
  12076. {
  12077. in.setown(_in);
  12078. recordCount = _recordCount;
  12079. }
  12080. else
  12081. ReleaseRoxieRow(_in);
  12082. }
  12083. OwnedConstRoxieRow in;
  12084. unsigned __int64 recordCount;
  12085. rtlRowBuilder extract;
  12086. };
  12087. QueueOf<PrefetchInfo, true> pulled;
  12088. CriticalSection pulledCrit;
  12089. public:
  12090. CRoxieServerPrefetchProjectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  12091. : CRoxieServerActivity(_factory, _probeManager),
  12092. helper((IHThorPrefetchProjectArg &) basehelper),
  12093. puller(false),
  12094. count(_count)
  12095. {
  12096. numProcessedLastGroup = 0;
  12097. recordCount = 0;
  12098. eof = false;
  12099. allPulled = false;
  12100. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  12101. preload = 0;
  12102. }
  12103. ~CRoxieServerPrefetchProjectActivity()
  12104. {
  12105. while (pulled.ordinality())
  12106. ::Release(pulled.dequeue());
  12107. }
  12108. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12109. {
  12110. if (idx)
  12111. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12112. puller.setInput(this, _in);
  12113. }
  12114. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12115. {
  12116. numProcessedLastGroup = 0;
  12117. recordCount = 0;
  12118. eof = false;
  12119. allPulled = false;
  12120. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12121. preload = helper.getLookahead();
  12122. if (!preload)
  12123. preload = ctx->prefetchProjectPreload();
  12124. space.reinit(preload);
  12125. ready.reinit();
  12126. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  12127. }
  12128. virtual void stop(bool aborting)
  12129. {
  12130. space.interrupt();
  12131. ready.interrupt();
  12132. CRoxieServerActivity::stop(aborting);
  12133. puller.stop(aborting);
  12134. }
  12135. virtual void reset()
  12136. {
  12137. CRoxieServerActivity::reset();
  12138. puller.reset();
  12139. allPulled = false;
  12140. while (pulled.ordinality())
  12141. ::Release(pulled.dequeue());
  12142. }
  12143. virtual PrefetchInfo *readNextRecord()
  12144. {
  12145. if (!isThreaded)
  12146. {
  12147. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  12148. puller.pullRecords(1);
  12149. }
  12150. else
  12151. ready.wait();
  12152. CriticalBlock b(pulledCrit);
  12153. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  12154. space.signal();
  12155. return ret;
  12156. }
  12157. virtual bool needsAllocator() const { return true; }
  12158. virtual const void * nextInGroup()
  12159. {
  12160. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12161. if (eof)
  12162. return NULL;
  12163. loop
  12164. {
  12165. Owned<PrefetchInfo> in = readNextRecord();
  12166. if (!in)
  12167. {
  12168. recordCount = 0;
  12169. if (numProcessedLastGroup == processed)
  12170. in.setown(readNextRecord());
  12171. if (!in)
  12172. {
  12173. numProcessedLastGroup = processed;
  12174. eof = true;
  12175. return NULL;
  12176. }
  12177. }
  12178. try
  12179. {
  12180. if (in->in)
  12181. {
  12182. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12183. size32_t outSize;
  12184. IThorChildGraph *child = helper.queryChild();
  12185. Owned<IEclGraphResults> results;
  12186. if (child)
  12187. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  12188. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  12189. if (outSize)
  12190. {
  12191. processed++;
  12192. return rowBuilder.finalizeRowClear(outSize);
  12193. }
  12194. }
  12195. }
  12196. catch (IException *E)
  12197. {
  12198. throw makeWrappedException(E);
  12199. }
  12200. }
  12201. }
  12202. // interface IExceptionHandler
  12203. virtual bool fireException(IException *e)
  12204. {
  12205. // called from puller thread on failure
  12206. ready.interrupt(LINK(e));
  12207. space.interrupt(e);
  12208. return true;
  12209. }
  12210. // interface IRecordPullerCallback
  12211. virtual void processRow(const void *row)
  12212. {
  12213. {
  12214. CriticalBlock b(pulledCrit);
  12215. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  12216. }
  12217. if (isThreaded)
  12218. {
  12219. ready.signal();
  12220. space.wait();
  12221. }
  12222. }
  12223. virtual void processEOG()
  12224. {
  12225. {
  12226. CriticalBlock b(pulledCrit);
  12227. pulled.enqueue(NULL);
  12228. }
  12229. if (isThreaded)
  12230. {
  12231. ready.signal();
  12232. space.wait();
  12233. }
  12234. }
  12235. virtual void processGroup(const ConstPointerArray &rows)
  12236. {
  12237. throwUnexpected();
  12238. }
  12239. virtual void processDone()
  12240. {
  12241. CriticalBlock b(pulledCrit);
  12242. allPulled = true;
  12243. if (isThreaded)
  12244. ready.signal();
  12245. }
  12246. };
  12247. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  12248. {
  12249. public:
  12250. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12251. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  12252. {
  12253. }
  12254. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12255. {
  12256. return new CRoxieServerPrefetchProjectActivity(this, _probeManager, count);
  12257. }
  12258. };
  12259. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  12260. {
  12261. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  12262. }
  12263. //=================================================================================
  12264. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  12265. {
  12266. public:
  12267. CPointerArrayRoxieInput()
  12268. {
  12269. rowset = NULL;
  12270. rowcount = 0;
  12271. curRow = 0;
  12272. }
  12273. void init(size32_t _rowcount, byte **_rowset)
  12274. {
  12275. rowset = _rowset;
  12276. rowcount = _rowcount;
  12277. curRow = 0;
  12278. }
  12279. virtual const void * nextInGroup()
  12280. {
  12281. if (curRow < rowcount)
  12282. {
  12283. const void * ret = rowset[curRow];
  12284. if (ret)
  12285. LinkRoxieRow(ret);
  12286. curRow++;
  12287. return ret;
  12288. }
  12289. return NULL;
  12290. }
  12291. protected:
  12292. byte **rowset;
  12293. size32_t rowcount;
  12294. size32_t curRow;
  12295. };
  12296. class CRoxieServerLoopActivity : public CRoxieServerActivity
  12297. {
  12298. protected:
  12299. IHThorLoopArg &helper;
  12300. ThorActivityKind activityKind;
  12301. unsigned maxIterations;
  12302. bool finishedLooping;
  12303. unsigned flags;
  12304. bool eof;
  12305. rtlRowBuilder loopExtractBuilder;
  12306. unsigned loopGraphId;
  12307. Linked<IOutputMetaData> counterMeta;
  12308. public:
  12309. CRoxieServerLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12310. : CRoxieServerActivity(_factory, _probeManager),
  12311. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  12312. {
  12313. eof = false;
  12314. finishedLooping = false;
  12315. activityKind = factory->getKind();
  12316. flags = helper.getFlags();
  12317. maxIterations = 0;
  12318. }
  12319. virtual bool needsAllocator() const { return true; }
  12320. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12321. {
  12322. eof = false;
  12323. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12324. int iterations = (int) helper.numIterations();
  12325. maxIterations = (iterations >= 0) ? iterations : 0;
  12326. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  12327. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  12328. finishedLooping = true;
  12329. loopExtractBuilder.clear();
  12330. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  12331. }
  12332. virtual void stop(bool aborting)
  12333. {
  12334. CRoxieServerActivity::stop(aborting);
  12335. loopExtractBuilder.clear();
  12336. }
  12337. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12338. {
  12339. if (flags & IHThorLoopArg::LFcounter)
  12340. {
  12341. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12342. *((thor_loop_counter_t *)counterRow) = counter;
  12343. RtlLinkedDatasetBuilder builder(rowAllocator);
  12344. builder.appendOwn(counterRow);
  12345. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12346. graph->setInputResult(2, counterResult);
  12347. }
  12348. }
  12349. };
  12350. //=================================================================================
  12351. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  12352. {
  12353. Owned<IActivityGraph> loopQuery;
  12354. Owned<IRoxieServerChildGraph> loopGraph;
  12355. IRoxieInput * curInput;
  12356. RtlLinkedDatasetBuilder *loopInputBuilder;
  12357. CPointerArrayRoxieInput arrayInput;
  12358. Linked<IRoxieInput> resultInput;
  12359. unsigned loopCounter;
  12360. public:
  12361. CRoxieServerSequentialLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12362. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta)
  12363. {
  12364. curInput = NULL;
  12365. loopCounter = 0;
  12366. loopInputBuilder = NULL;
  12367. }
  12368. virtual bool needsAllocator() const { return true; }
  12369. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12370. {
  12371. CRoxieServerLoopActivity::onCreate(_ctx, _colocalParent);
  12372. loopQuery.set(_ctx->queryChildGraph(loopGraphId));
  12373. }
  12374. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12375. {
  12376. curInput = input;
  12377. loopCounter = 1;
  12378. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12379. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  12380. loopGraph.set(loopQuery->queryLoopGraph());
  12381. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  12382. }
  12383. virtual void stop(bool aborting)
  12384. {
  12385. delete loopInputBuilder;
  12386. loopInputBuilder = NULL;
  12387. CRoxieServerLoopActivity::stop(aborting);
  12388. }
  12389. virtual const void * nextInGroup()
  12390. {
  12391. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12392. if (eof)
  12393. return NULL;
  12394. unsigned emptyIterations = 0;
  12395. loop
  12396. {
  12397. loop
  12398. {
  12399. const void * ret = curInput->nextInGroup();
  12400. if (!ret)
  12401. {
  12402. ret = curInput->nextInGroup(); // more cope with groups somehow....
  12403. if (!ret)
  12404. {
  12405. if (finishedLooping)
  12406. {
  12407. eof = true;
  12408. return NULL;
  12409. }
  12410. break;
  12411. }
  12412. }
  12413. if (finishedLooping ||
  12414. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  12415. {
  12416. processed++;
  12417. return ret;
  12418. }
  12419. loopInputBuilder->appendOwn(ret);
  12420. }
  12421. switch (activityKind)
  12422. {
  12423. case TAKloopdataset:
  12424. {
  12425. if (!(flags & IHThorLoopArg::LFnewloopagain))
  12426. {
  12427. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  12428. {
  12429. if (loopInputBuilder->getcount() == 0)
  12430. {
  12431. eof = true;
  12432. return NULL;
  12433. }
  12434. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12435. // MORE - should builder be cleared here?
  12436. curInput = &arrayInput;
  12437. finishedLooping = true;
  12438. continue; // back to the input loop again
  12439. }
  12440. }
  12441. break;
  12442. }
  12443. case TAKlooprow:
  12444. if (!loopInputBuilder->getcount())
  12445. {
  12446. finishedLooping = true;
  12447. eof = true;
  12448. return NULL;
  12449. }
  12450. break;
  12451. }
  12452. if (loopInputBuilder->getcount())
  12453. emptyIterations = 0;
  12454. else
  12455. {
  12456. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  12457. emptyIterations++;
  12458. if (emptyIterations > maxEmptyLoopIterations)
  12459. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  12460. if (emptyIterations % 32 == 0)
  12461. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  12462. }
  12463. checkAbort();
  12464. try
  12465. {
  12466. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  12467. resultInput.setown(results->createIterator(0));
  12468. if (flags & IHThorLoopArg::LFnewloopagain)
  12469. {
  12470. Owned<IRoxieInput> againResult = results->createIterator(helper.loopAgainResult());
  12471. OwnedConstRoxieRow row = againResult->nextInGroup();
  12472. assertex(row);
  12473. //Result is a row which contains a single boolean field.
  12474. if (!((const bool *)row.get())[0])
  12475. finishedLooping = true;
  12476. }
  12477. }
  12478. catch (IException *E)
  12479. {
  12480. throw makeWrappedException(E);
  12481. }
  12482. curInput = resultInput.get();
  12483. loopCounter++;
  12484. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  12485. finishedLooping = true;
  12486. }
  12487. }
  12488. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  12489. {
  12490. try
  12491. {
  12492. loopGraph->beforeExecute();
  12493. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  12494. loopInputBuilder->clear();
  12495. loopGraph->setInputResult(1, inputRowsResult);
  12496. createCounterResult(loopGraph, counter);
  12497. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  12498. loopGraph->afterExecute();
  12499. return ret.getClear();
  12500. }
  12501. catch (...)
  12502. {
  12503. CTXLOG("Exception thrown in loop body - cleaning up");
  12504. loopGraph->afterExecute();
  12505. throw;
  12506. }
  12507. }
  12508. };
  12509. //=================================================================================
  12510. typedef SafeQueueOf<const void, true> SafeRowQueue;
  12511. class CRowQueuePseudoInput : public CPseudoRoxieInput
  12512. {
  12513. public:
  12514. CRowQueuePseudoInput(SafeRowQueue & _input) :
  12515. input(_input)
  12516. {
  12517. eof = false;
  12518. }
  12519. virtual const void * nextInGroup()
  12520. {
  12521. if (eof)
  12522. return NULL;
  12523. const void * ret = input.dequeue();
  12524. if (!ret)
  12525. eof = true;
  12526. return ret;
  12527. }
  12528. protected:
  12529. SafeRowQueue & input;
  12530. bool eof;
  12531. };
  12532. class CRoxieServerParallelLoopActivity;
  12533. class LoopFilterPseudoInput : public CIndirectRoxieInput
  12534. {
  12535. public:
  12536. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput * _input, unsigned _counter) :
  12537. CIndirectRoxieInput(_input), activity(_activity), counter(_counter)
  12538. {
  12539. }
  12540. virtual const void * nextInGroup();
  12541. protected:
  12542. CRoxieServerParallelLoopActivity * activity;
  12543. unsigned counter;
  12544. };
  12545. class LoopExecutorThread : public RestartableThread
  12546. {
  12547. protected:
  12548. Owned<IRoxieInput> safeInput;
  12549. CRoxieServerParallelLoopActivity * activity;
  12550. bool eof;
  12551. CriticalSection crit;
  12552. unsigned flags;
  12553. SafeRowQueue tempResults[2];
  12554. unsigned savedParentExtractSize;
  12555. const byte * savedParentExtract;
  12556. IArrayOf<IActivityGraph> cachedGraphs;
  12557. IRoxieSlaveContext *ctx;
  12558. public:
  12559. LoopExecutorThread()
  12560. : RestartableThread("LoopExecutorThread")
  12561. {
  12562. activity = NULL;
  12563. eof = false;
  12564. flags = 0;
  12565. ctx = NULL;
  12566. savedParentExtract = NULL;
  12567. savedParentExtractSize = 0;
  12568. }
  12569. virtual IRoxieInput *queryInput(unsigned idx) const
  12570. {
  12571. return safeInput->queryInput(idx);
  12572. }
  12573. void setInput(CRoxieServerParallelLoopActivity * _activity, IRoxieInput *_input, unsigned _flags)
  12574. {
  12575. activity = _activity;
  12576. flags = _flags;
  12577. // stop is called on our consumer's thread. We need to take care calling stop for our input to make sure it is not in mid-nextInGroup etc etc.
  12578. safeInput.setown(new CSafeRoxieInput(_input));
  12579. }
  12580. IRoxieInput *queryInput() const
  12581. {
  12582. return safeInput;
  12583. }
  12584. void onCreate(IRoxieSlaveContext * _ctx);
  12585. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  12586. void stop(bool aborting);
  12587. void reset();
  12588. virtual int run();
  12589. protected:
  12590. void executeLoop();
  12591. void executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput);
  12592. IRoxieInput * createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter);
  12593. };
  12594. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  12595. {
  12596. friend class LoopFilterPseudoInput;
  12597. friend class LoopExecutorThread;
  12598. QueueOf<const void, true> ready;
  12599. CriticalSection helperCS;
  12600. CriticalSection cs;
  12601. size32_t sizeNumParallel;
  12602. rtlDataAttr listNumParallel;
  12603. unsigned defaultNumParallel;
  12604. LoopExecutorThread executor;
  12605. IProbeManager* probeManager;
  12606. CriticalSection canAccess;
  12607. CriticalSection scrit;
  12608. InterruptableSemaphore readySpace;
  12609. InterruptableSemaphore recordsReady;
  12610. protected:
  12611. bool includeInLoop(unsigned counter, const void * row)
  12612. {
  12613. CriticalBlock b(helperCS);
  12614. return helper.sendToLoop(counter, row);
  12615. }
  12616. public:
  12617. CRoxieServerParallelLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  12618. : CRoxieServerLoopActivity(_factory, _probeManager, _loopGraphId, _counterMeta),
  12619. readySpace(parallelLoopFlowLimit)
  12620. {
  12621. probeManager = _probeManager;
  12622. defaultNumParallel = 0;
  12623. }
  12624. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  12625. {
  12626. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  12627. executor.onCreate(_ctx);
  12628. }
  12629. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12630. {
  12631. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12632. readySpace.reinit(parallelLoopFlowLimit);
  12633. recordsReady.reinit();
  12634. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  12635. defaultNumParallel = helper.defaultParallelIterations();
  12636. if (!defaultNumParallel)
  12637. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  12638. helper.numParallelIterations(sizeNumParallel, listNumParallel.refdata());
  12639. //MORE: If numIterations <= number of parallel iterations[1],
  12640. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  12641. //being transferred via a queue
  12642. executor.start(parentExtractSize, parentExtract, paused);
  12643. }
  12644. virtual void setInput(unsigned idx, IRoxieInput *_in)
  12645. {
  12646. if (idx)
  12647. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  12648. executor.setInput(this, _in, flags);
  12649. }
  12650. virtual void stop(bool aborting)
  12651. {
  12652. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  12653. readySpace.interrupt();
  12654. recordsReady.interrupt();
  12655. executor.join(); // MORE - may not be needed given stop/reset split
  12656. CRoxieServerLoopActivity::stop(aborting);
  12657. }
  12658. virtual void reset()
  12659. {
  12660. while (ready.ordinality())
  12661. ReleaseRoxieRow(ready.dequeue());
  12662. executor.reset();
  12663. CRoxieServerActivity::reset();
  12664. }
  12665. virtual const void * nextInGroup()
  12666. {
  12667. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  12668. loop
  12669. {
  12670. if (eof)
  12671. return NULL;
  12672. recordsReady.wait();
  12673. CriticalBlock procedure(canAccess);
  12674. if (ready.ordinality())
  12675. {
  12676. const void *result = ready.dequeue();
  12677. readySpace.signal();
  12678. if (result)
  12679. processed++;
  12680. return result;
  12681. }
  12682. else
  12683. eof = true;
  12684. }
  12685. }
  12686. unsigned getNumParallel(unsigned iter)
  12687. {
  12688. if (iter * sizeof(unsigned) >= sizeNumParallel)
  12689. return defaultNumParallel;
  12690. return ((unsigned *)listNumParallel.getdata())[iter];
  12691. }
  12692. inline void enqueueResult(const void * row)
  12693. {
  12694. try
  12695. {
  12696. while(!readySpace.wait(1000))
  12697. {
  12698. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  12699. }
  12700. }
  12701. catch (...)
  12702. {
  12703. ReleaseRoxieRow(row);
  12704. throw;
  12705. }
  12706. CriticalBlock b2(canAccess);
  12707. ready.enqueue(row);
  12708. recordsReady.signal();
  12709. }
  12710. inline void finishResults()
  12711. {
  12712. recordsReady.signal();
  12713. }
  12714. virtual bool fireException(IException *e)
  12715. {
  12716. readySpace.interrupt(LINK(e));
  12717. recordsReady.interrupt(e);
  12718. return true;
  12719. }
  12720. IActivityGraph * createChildGraphInstance()
  12721. {
  12722. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  12723. }
  12724. IActivityGraph * queryChildGraph()
  12725. {
  12726. return ctx->queryChildGraph(loopGraphId);
  12727. }
  12728. };
  12729. //=================================================================================
  12730. const void * LoopFilterPseudoInput::nextInGroup()
  12731. {
  12732. loop
  12733. {
  12734. const void * next = input->nextInGroup();
  12735. if (!next || activity->includeInLoop(counter, next))
  12736. return next;
  12737. activity->enqueueResult(next);
  12738. }
  12739. }
  12740. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  12741. {
  12742. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  12743. ctx = _ctx;
  12744. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  12745. }
  12746. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12747. {
  12748. savedParentExtractSize = parentExtractSize;
  12749. savedParentExtract = parentExtract;
  12750. eof = false;
  12751. StringBuffer logPrefix("[");
  12752. ctx->getLogPrefix(logPrefix).append("] ");
  12753. RestartableThread::start(logPrefix);
  12754. }
  12755. int LoopExecutorThread::run()
  12756. {
  12757. try
  12758. {
  12759. executeLoop();
  12760. }
  12761. catch (IException *e)
  12762. {
  12763. activity->fireException(e);
  12764. }
  12765. catch (...)
  12766. {
  12767. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  12768. }
  12769. return 0;
  12770. }
  12771. void LoopExecutorThread::stop(bool aborting)
  12772. {
  12773. safeInput->stop(aborting);
  12774. RestartableThread::join();
  12775. }
  12776. void LoopExecutorThread::reset()
  12777. {
  12778. safeInput->reset();
  12779. }
  12780. void LoopExecutorThread::executeLoop()
  12781. {
  12782. unsigned iterations = 0;
  12783. unsigned counter = 0;
  12784. unsigned outputIndex = 0;
  12785. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  12786. loop
  12787. {
  12788. if (activity->activityKind == TAKloopcount)
  12789. {
  12790. if (counter == activity->maxIterations)
  12791. break;
  12792. }
  12793. else
  12794. {
  12795. //This condition isn't quite right because it needs to be whether the filtered
  12796. //input is empty. May be ok if we include that in the semantics,
  12797. if (tempResults[1-outputIndex].ordinality() == 0)
  12798. break;
  12799. }
  12800. unsigned numParallel = activity->getNumParallel(iterations);
  12801. Linked<IRoxieInput> curInput;
  12802. if (iterations == 0)
  12803. curInput.set(safeInput);
  12804. else
  12805. {
  12806. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12807. inputQueue.enqueue(NULL);
  12808. curInput.setown(new CRowQueuePseudoInput(inputQueue));
  12809. }
  12810. SafeRowQueue * curOutput = NULL;
  12811. if (counter+numParallel > activity->maxIterations)
  12812. numParallel = activity->maxIterations - counter;
  12813. else if (counter+numParallel < activity->maxIterations)
  12814. curOutput = &tempResults[outputIndex];
  12815. executeLoopInstance(counter, numParallel, curInput, curOutput);
  12816. outputIndex = 1-outputIndex;
  12817. counter += numParallel;
  12818. iterations++;
  12819. }
  12820. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  12821. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  12822. while (inputQueue.ordinality())
  12823. {
  12824. const void * next = inputQueue.dequeue();
  12825. activity->enqueueResult(next);
  12826. }
  12827. activity->finishResults();
  12828. }
  12829. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, IRoxieInput * input, SafeRowQueue * spillOutput)
  12830. {
  12831. IArrayOf<IRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  12832. Linked<IRoxieInput> curInput = input;
  12833. unsigned i;
  12834. for (i= 0; i != numIterations; i++)
  12835. {
  12836. unsigned thisCounter = counter+i+1;
  12837. IRoxieInput * filtered = curInput;
  12838. if (flags & IHThorLoopArg::LFfiltered)
  12839. {
  12840. filtered = new LoopFilterPseudoInput(activity, curInput, thisCounter);
  12841. savedInputs.append(*filtered);
  12842. }
  12843. //graph is kept, so new curInput will be guaranteed to exist
  12844. curInput.setown(createLoopIterationGraph(i, filtered, thisCounter));
  12845. }
  12846. try
  12847. {
  12848. curInput->start(savedParentExtractSize, savedParentExtract, false);
  12849. if (spillOutput)
  12850. {
  12851. loop
  12852. {
  12853. const void * next = curInput->nextInGroup();
  12854. if (!next)
  12855. break;
  12856. spillOutput->enqueue(next);
  12857. }
  12858. }
  12859. else
  12860. {
  12861. loop
  12862. {
  12863. const void * next = curInput->nextInGroup();
  12864. if (!next)
  12865. break;
  12866. activity->enqueueResult(next);
  12867. }
  12868. }
  12869. }
  12870. catch (IException *E)
  12871. {
  12872. ctx->notifyAbort(E);
  12873. for (i= 0; i != numIterations; i++)
  12874. {
  12875. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12876. }
  12877. curInput->stop(true);
  12878. curInput->reset();
  12879. throw;
  12880. }
  12881. for (i= 0; i != numIterations; i++)
  12882. {
  12883. cachedGraphs.item(i).queryLoopGraph()->afterExecute();
  12884. }
  12885. curInput->stop(false);
  12886. curInput->reset();
  12887. }
  12888. IRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, IRoxieInput * input, unsigned counter)
  12889. {
  12890. if (!cachedGraphs.isItem(i))
  12891. cachedGraphs.append(*activity->createChildGraphInstance());
  12892. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  12893. loopGraph->beforeExecute();
  12894. if (!loopGraph->querySetInputResult(1, input))
  12895. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  12896. activity->createCounterResult(loopGraph, counter);
  12897. return loopGraph->selectOutput(0);
  12898. }
  12899. //=================================================================================
  12900. class CCounterRowMetaData : public CInterface, implements IOutputMetaData
  12901. {
  12902. public:
  12903. IMPLEMENT_IINTERFACE
  12904. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  12905. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  12906. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  12907. virtual void toXML(const byte * self, IXmlWriter & out) { }
  12908. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  12909. virtual unsigned getMetaFlags() { return 0; }
  12910. virtual void destruct(byte * self) {}
  12911. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12912. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12913. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12914. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  12915. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12916. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  12917. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  12918. };
  12919. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  12920. {
  12921. unsigned loopGraphId;
  12922. unsigned flags;
  12923. Linked<IOutputMetaData> counterMeta;
  12924. public:
  12925. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12926. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  12927. {
  12928. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  12929. flags = helper->getFlags();
  12930. counterMeta.setown(new CCounterRowMetaData);
  12931. }
  12932. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  12933. {
  12934. if (flags & IHThorLoopArg::LFparallel)
  12935. return new CRoxieServerParallelLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12936. else
  12937. return new CRoxieServerSequentialLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  12938. }
  12939. };
  12940. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  12941. {
  12942. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  12943. }
  12944. //=================================================================================
  12945. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  12946. {
  12947. protected:
  12948. IHThorGraphLoopArg &helper;
  12949. unsigned maxIterations;
  12950. unsigned flags;
  12951. rtlRowBuilder GraphExtractBuilder;
  12952. unsigned loopGraphId;
  12953. Linked<IOutputMetaData> counterMeta;
  12954. public:
  12955. CRoxieServerGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  12956. : CRoxieServerActivity(_factory, _probeManager),
  12957. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  12958. {
  12959. flags = helper.getFlags();
  12960. maxIterations = 0;
  12961. }
  12962. virtual bool needsAllocator() const { return true; }
  12963. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12964. {
  12965. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12966. int iterations = (int) helper.numIterations();
  12967. maxIterations = (iterations >= 0) ? iterations : 0;
  12968. if (maxIterations > maxGraphLoopIterations)
  12969. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  12970. if (maxIterations != 0)
  12971. {
  12972. GraphExtractBuilder.clear();
  12973. helper.createParentExtract(GraphExtractBuilder);
  12974. }
  12975. }
  12976. virtual void stop(bool aborting)
  12977. {
  12978. CRoxieServerActivity::stop(aborting);
  12979. GraphExtractBuilder.clear();
  12980. }
  12981. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  12982. {
  12983. if (flags & IHThorGraphLoopArg::GLFcounter)
  12984. {
  12985. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  12986. *((thor_loop_counter_t *)counterRow) = counter;
  12987. RtlLinkedDatasetBuilder builder(rowAllocator);
  12988. builder.appendOwn(counterRow);
  12989. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  12990. graph->setInputResult(0, counterResult);
  12991. }
  12992. }
  12993. };
  12994. //=================================================================================
  12995. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  12996. {
  12997. Owned<IActivityGraph> GraphQuery;
  12998. Owned<IRoxieServerChildGraph> loopGraph;
  12999. Linked<IRoxieInput> resultInput;
  13000. bool evaluated;
  13001. public:
  13002. CRoxieServerSequentialGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13003. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta)
  13004. {
  13005. evaluated = false;
  13006. }
  13007. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13008. {
  13009. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13010. GraphQuery.set(_ctx->queryChildGraph(loopGraphId));
  13011. }
  13012. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13013. {
  13014. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  13015. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13016. loopGraph.set(GraphQuery->queryLoopGraph());
  13017. evaluated = false;
  13018. }
  13019. virtual void stop(bool aborting)
  13020. {
  13021. if (loopGraph)
  13022. loopGraph->clearGraphLoopResults();
  13023. CRoxieServerGraphLoopActivity::stop(aborting);
  13024. }
  13025. virtual const void * nextInGroup()
  13026. {
  13027. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13028. if (!evaluated)
  13029. {
  13030. executeEntireGraph();
  13031. evaluated = true;
  13032. }
  13033. const void * ret = resultInput->nextInGroup();
  13034. if (ret)
  13035. processed++;
  13036. return ret;
  13037. }
  13038. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13039. {
  13040. try
  13041. {
  13042. loopGraph->beforeExecute();
  13043. createCounterResult(loopGraph, counter);
  13044. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  13045. loopGraph->afterExecute();
  13046. }
  13047. catch (...)
  13048. {
  13049. CTXLOG("Exception thrown in graph body - cleaning up");
  13050. loopGraph->afterExecute();
  13051. throw;
  13052. }
  13053. }
  13054. void createInitialGraphInput()
  13055. {
  13056. loopGraph->clearGraphLoopResults();
  13057. RtlLinkedDatasetBuilder builder(rowAllocator);
  13058. input->readAll(builder);
  13059. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  13060. loopGraph->setGraphLoopResult(0, result);
  13061. }
  13062. void executeEntireGraph()
  13063. {
  13064. createInitialGraphInput();
  13065. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  13066. {
  13067. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  13068. }
  13069. resultInput.setown(loopGraph->getGraphLoopResult(maxIterations));
  13070. }
  13071. };
  13072. //=================================================================================
  13073. struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
  13074. {
  13075. public:
  13076. virtual unsigned numBranches()
  13077. {
  13078. return 0;
  13079. }
  13080. virtual IOutputMetaData * queryOutputMeta()
  13081. {
  13082. return NULL;// get it from the parent..
  13083. }
  13084. };
  13085. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  13086. class CGraphIterationInfo : public CInterface
  13087. {
  13088. private:
  13089. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  13090. unsigned sourceIdx;
  13091. Linked<IRoxieServerActivity> sourceAct;
  13092. Linked<IRoxieInput> sourceInput;
  13093. unsigned numUses;
  13094. unsigned iteration;
  13095. public:
  13096. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  13097. : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
  13098. {
  13099. numUses = 0;
  13100. }
  13101. inline void noteUsed()
  13102. {
  13103. numUses++;
  13104. }
  13105. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager)
  13106. {
  13107. if (numUses > 1)
  13108. {
  13109. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses));
  13110. IRoxieServerActivity *splitter = factory->createActivity(NULL);
  13111. splitter->onCreate(ctx, NULL);
  13112. IRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  13113. if (probeManager)
  13114. {
  13115. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  13116. input = static_cast<IRoxieInput*>(inputBase);
  13117. // MORE - shouldn't this be added to probes?
  13118. }
  13119. sourceAct.setown(splitter);
  13120. sourceAct->setInput(0, input);
  13121. sourceIdx = 0;
  13122. sourceInput.clear();
  13123. }
  13124. }
  13125. IRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13126. {
  13127. // MORE - not really necessary to create splitters in separate pass, is it?
  13128. if (factory) // we created a splitter....
  13129. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  13130. IRoxieInput *ret = sourceInput;
  13131. if (probeManager)
  13132. {
  13133. IInputBase *inputBase = probeManager->createProbe(ret, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  13134. ret = static_cast<IRoxieInput *>(inputBase);
  13135. probes.append(*LINK(ret));
  13136. }
  13137. if (factory) // we created a splitter....
  13138. sourceIdx++;
  13139. return ret;
  13140. }
  13141. };
  13142. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  13143. {
  13144. Owned<IActivityGraph> childGraph;
  13145. IRoxieInput * resultInput;
  13146. CIArrayOf<CGraphIterationInfo> outputs;
  13147. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  13148. Owned<CExtractMapperInput> inputExtractMapper;
  13149. IProbeManager *probeManager;
  13150. unsigned createLoopCounter;
  13151. IArrayOf<IRoxieInput> probes;
  13152. public:
  13153. CRoxieServerParallelGraphLoopActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  13154. : CRoxieServerGraphLoopActivity(_factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  13155. {
  13156. inputExtractMapper.setown(new CExtractMapperInput);
  13157. resultInput = NULL;
  13158. createLoopCounter = 0;
  13159. }
  13160. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13161. {
  13162. CRoxieServerGraphLoopActivity::onCreate(_ctx, _colocalParent);
  13163. childGraph.set(_ctx->queryChildGraph(loopGraphId));
  13164. }
  13165. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13166. {
  13167. //Input needs to be handled very carefully.....
  13168. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  13169. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  13170. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  13171. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  13172. assertex(idx == 0);
  13173. inputExtractMapper->setInput(_in);
  13174. }
  13175. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13176. {
  13177. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  13178. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  13179. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  13180. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  13181. }
  13182. virtual void stop(bool aborting)
  13183. {
  13184. if (resultInput)
  13185. resultInput->stop(aborting);
  13186. CRoxieServerGraphLoopActivity::stop(aborting);
  13187. }
  13188. virtual void reset()
  13189. {
  13190. if (resultInput)
  13191. resultInput->reset();
  13192. resultInput = NULL;
  13193. iterationGraphs.kill();
  13194. outputs.kill();
  13195. if (probeManager)
  13196. {
  13197. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  13198. probes.kill();
  13199. }
  13200. CRoxieServerGraphLoopActivity::reset();
  13201. }
  13202. virtual const void * nextInGroup()
  13203. {
  13204. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13205. const void * ret = resultInput->nextInGroup();
  13206. if (ret)
  13207. processed++;
  13208. return ret;
  13209. }
  13210. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  13211. {
  13212. //result(0) is the input to the graph.
  13213. resultInput = inputExtractMapper;
  13214. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  13215. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  13216. {
  13217. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(createLoopCounter, parentExtractSize, parentExtract, *this);
  13218. graph->beforeExecute();
  13219. iterationGraphs.append(*graph);
  13220. graph->gatherIterationUsage(*this);
  13221. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  13222. outputs.append(*iteration);
  13223. }
  13224. createLoopCounter = 0;
  13225. createSplitters(probeManager);
  13226. ForEachItemIn(i2, iterationGraphs)
  13227. iterationGraphs.item(i2).associateIterationOutputs(*this);
  13228. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  13229. }
  13230. void createSplitters(IProbeManager *probeManager)
  13231. {
  13232. ForEachItemIn(i, outputs)
  13233. {
  13234. CGraphIterationInfo & next = outputs.item(i);
  13235. next.createSplitter(ctx, probeManager);
  13236. }
  13237. }
  13238. //IRoxieServerLoopResultProcessor
  13239. virtual void noteUseIteration(unsigned _whichIteration)
  13240. {
  13241. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  13242. if (whichIteration >= 0)
  13243. {
  13244. if (!outputs.isItem(whichIteration))
  13245. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  13246. outputs.item(whichIteration).noteUsed();
  13247. }
  13248. }
  13249. virtual IRoxieInput * connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  13250. {
  13251. if (outputs.isItem(whichIteration))
  13252. {
  13253. CGraphIterationInfo & next = outputs.item(whichIteration);
  13254. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  13255. }
  13256. return NULL;
  13257. }
  13258. };
  13259. //=================================================================================
  13260. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  13261. {
  13262. unsigned loopGraphId;
  13263. unsigned flags;
  13264. Linked<IOutputMetaData> counterMeta;
  13265. public:
  13266. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13267. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), loopGraphId(_loopGraphId)
  13268. {
  13269. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  13270. flags = helper->getFlags();
  13271. counterMeta.setown(new CCounterRowMetaData);
  13272. }
  13273. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13274. {
  13275. if (kind == TAKparallelgraphloop)
  13276. return new CRoxieServerParallelGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13277. else
  13278. return new CRoxieServerSequentialGraphLoopActivity(this, _probeManager, loopGraphId, counterMeta);
  13279. }
  13280. };
  13281. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _loopGraphId)
  13282. {
  13283. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _loopGraphId);
  13284. }
  13285. //=====================================================================================================
  13286. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  13287. {
  13288. class OutputAdaptor : public CExtractMapperInput
  13289. {
  13290. bool stopped;
  13291. public:
  13292. CRoxieServerLibraryCallActivity *parent;
  13293. unsigned oid;
  13294. unsigned processed;
  13295. public:
  13296. IMPLEMENT_IINTERFACE;
  13297. OutputAdaptor() : CExtractMapperInput(NULL)
  13298. {
  13299. parent = NULL;
  13300. oid = 0;
  13301. init();
  13302. }
  13303. void init()
  13304. {
  13305. processed = 0;
  13306. stopped = false;
  13307. }
  13308. virtual unsigned queryId() const
  13309. {
  13310. return parent->queryId();
  13311. }
  13312. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13313. {
  13314. parent->start(oid, parentExtractSize, parentExtract, paused);
  13315. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  13316. }
  13317. virtual void stop(bool aborting)
  13318. {
  13319. if (!stopped)
  13320. {
  13321. stopped = true;
  13322. parent->stop(oid, aborting); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  13323. CExtractMapperInput::stop(aborting);
  13324. }
  13325. };
  13326. virtual void reset()
  13327. {
  13328. parent->reset(oid, processed);
  13329. CExtractMapperInput::reset();
  13330. init();
  13331. };
  13332. virtual void checkAbort()
  13333. {
  13334. parent->checkAbort();
  13335. }
  13336. };
  13337. IHThorLibraryCallArg &helper;
  13338. unsigned numInputs;
  13339. unsigned numOutputs;
  13340. unsigned numActiveOutputs;
  13341. bool started;
  13342. OutputAdaptor* outputAdaptors;
  13343. CExtractMapperInput * * inputAdaptors;
  13344. bool * inputUsed;
  13345. bool * outputUsed;
  13346. Owned<IException> error;
  13347. CriticalSection crit;
  13348. rtlRowBuilder libraryExtractBuilder;
  13349. Owned<IActivityGraph> libraryGraph;
  13350. const LibraryCallFactoryExtra & extra;
  13351. public:
  13352. CRoxieServerLibraryCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  13353. : CRoxieServerActivity(_factory, _probeManager),
  13354. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  13355. {
  13356. numInputs = _numInputs;
  13357. numOutputs = _numOutputs;
  13358. numActiveOutputs = numOutputs;
  13359. inputAdaptors = new CExtractMapperInput*[numInputs];
  13360. inputUsed = new bool[numInputs];
  13361. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13362. {
  13363. inputAdaptors[i1] = new CExtractMapperInput;
  13364. inputUsed[i1] = false;
  13365. }
  13366. outputAdaptors = new OutputAdaptor[numOutputs];
  13367. outputUsed = new bool[numOutputs];
  13368. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13369. {
  13370. outputAdaptors[i2].parent = this;
  13371. outputAdaptors[i2].oid = i2;
  13372. outputUsed[i2] = false;
  13373. }
  13374. started = false;
  13375. }
  13376. ~CRoxieServerLibraryCallActivity()
  13377. {
  13378. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13379. ::Release(inputAdaptors[i1]);
  13380. delete [] inputAdaptors;
  13381. delete [] inputUsed;
  13382. delete [] outputAdaptors;
  13383. delete [] outputUsed;
  13384. }
  13385. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  13386. {
  13387. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  13388. libraryGraph.setown(_ctx->getLibraryGraph(extra, this));
  13389. libraryGraph->onCreate(_ctx, _colocalParent);
  13390. //Now map the inputs and outputs to the adapters
  13391. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13392. for (unsigned i1=0; i1<numInputs; i1++)
  13393. inputUsed[i1] = graph->querySetInputResult(i1, inputAdaptors[i1]);
  13394. for (unsigned i2=0; i2<numOutputs; i2++)
  13395. {
  13396. unsigned outputIndex = extra.outputs.item(i2);
  13397. Owned<IRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  13398. outputAdaptors[i2].setInput(output);
  13399. }
  13400. }
  13401. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13402. {
  13403. CriticalBlock b(crit);
  13404. if (error)
  13405. throw error.getLink();
  13406. if (factory)
  13407. factory->noteStarted(oid);
  13408. if (!started)
  13409. {
  13410. // even though it is not complete, we don't want to run this again if it fails.
  13411. started = true;
  13412. //see notes on splitter above
  13413. try
  13414. {
  13415. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13416. }
  13417. catch (IException *E)
  13418. {
  13419. #ifdef TRACE_SPLIT
  13420. CTXLOG("spill %d caught exception in start", activityId);
  13421. #endif
  13422. error.set(E);
  13423. throw;
  13424. }
  13425. catch (...)
  13426. {
  13427. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  13428. error.set(E);
  13429. throw E;
  13430. }
  13431. //recreate the parent extract, and use it to reinitialize the graphs...
  13432. libraryExtractBuilder.clear();
  13433. helper.createParentExtract(libraryExtractBuilder);
  13434. // NOTE - do NOT set activeOutputs = numOutputs here - we must rely on the value set in reset and constructor. This is because we can see stop on
  13435. // some inputs before we see start on others.
  13436. for (unsigned i1 = 0; i1 < numInputs; i1++)
  13437. {
  13438. if (inputUsed[i1])
  13439. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  13440. else
  13441. inputAdaptors[i1]->stop(false);
  13442. }
  13443. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  13444. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  13445. //call stop on all the unused inputs.
  13446. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13447. graph->beforeExecute();
  13448. ForEachItemIn(i3, extra.unusedOutputs)
  13449. {
  13450. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13451. output->stop(false);
  13452. }
  13453. }
  13454. }
  13455. virtual void stop(unsigned oid, bool aborting)
  13456. {
  13457. CriticalBlock b(crit);
  13458. if (--numActiveOutputs == 0)
  13459. {
  13460. //call stop on all the unused inputs.
  13461. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13462. graph->beforeExecute();
  13463. ForEachItemIn(i3, extra.unusedOutputs)
  13464. {
  13465. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13466. output->stop(false);
  13467. }
  13468. CRoxieServerActivity::stop(aborting);
  13469. }
  13470. }
  13471. void reset(unsigned oid, unsigned _processed)
  13472. {
  13473. noteProcessed(oid, _processed, 0, 0);
  13474. started = false;
  13475. error.clear();
  13476. numActiveOutputs = numOutputs;
  13477. if (state != STATEreset) // make sure input is only reset once
  13478. {
  13479. CRoxieServerActivity::reset();
  13480. libraryGraph->reset();
  13481. //Call reset on all unused outputs from the graph - no one else will.
  13482. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  13483. ForEachItemIn(i3, extra.unusedOutputs)
  13484. {
  13485. Owned<IRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  13486. output->reset();
  13487. }
  13488. }
  13489. };
  13490. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13491. {
  13492. inputAdaptors[idx]->setInput(_in);
  13493. }
  13494. public:
  13495. virtual const void *nextInGroup()
  13496. {
  13497. throwUnexpected(); // Internal logic error - we are not anybody's input
  13498. }
  13499. virtual IOutputMetaData * queryOutputMeta() const
  13500. {
  13501. throwUnexpected(); // should be called on outputs instead
  13502. }
  13503. virtual IRoxieInput *queryOutput(unsigned idx)
  13504. {
  13505. assertex(idx!=(unsigned)-1);
  13506. assertex(!outputUsed[idx]);
  13507. outputUsed[idx] = true;
  13508. return &outputAdaptors[idx];
  13509. }
  13510. };
  13511. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  13512. {
  13513. ForEachItemIn(i1, _other.outputs)
  13514. outputs.append(_other.outputs.item(i1));
  13515. ForEachItemIn(i2, _other.unusedOutputs)
  13516. unusedOutputs.append(_other.unusedOutputs.item(i2));
  13517. maxOutputs = _other.maxOutputs;
  13518. graphid = _other.graphid;
  13519. libraryName.set(_other.libraryName);
  13520. interfaceHash = _other.interfaceHash;
  13521. embedded = _other.embedded;
  13522. }
  13523. void LibraryCallFactoryExtra::calcUnused()
  13524. {
  13525. for (unsigned i=0; i < maxOutputs; i++)
  13526. if (!outputs.contains(i))
  13527. unusedOutputs.append(i);
  13528. }
  13529. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  13530. {
  13531. private:
  13532. CRoxieServerMultiInputInfo inputs;
  13533. LibraryCallFactoryExtra extra;
  13534. public:
  13535. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13536. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13537. {
  13538. extra.set(_extra);
  13539. extra.calcUnused();
  13540. setNumOutputs(extra.outputs.ordinality());
  13541. }
  13542. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13543. {
  13544. return new CRoxieServerLibraryCallActivity(this, _probeManager, numInputs(), numOutputs, extra);
  13545. }
  13546. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13547. {
  13548. inputs.set(idx, source, sourceidx);
  13549. }
  13550. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  13551. {
  13552. return inputs.get(idx, sourceidx);
  13553. }
  13554. virtual unsigned numInputs() const { return inputs.ordinality(); }
  13555. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  13556. {
  13557. addXrefLibraryInfo(reply, extra.libraryName);
  13558. }
  13559. };
  13560. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, LibraryCallFactoryExtra & _extra)
  13561. {
  13562. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _extra);
  13563. }
  13564. //=====================================================================================================
  13565. class CRoxieServerNWayInputActivity : public CRoxieServerActivity
  13566. {
  13567. IHThorNWayInputArg & helper;
  13568. IRoxieInput ** inputs;
  13569. PointerArrayOf<IRoxieInput> selectedInputs;
  13570. unsigned numInputs;
  13571. public:
  13572. CRoxieServerNWayInputActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13573. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayInputArg &)basehelper), numInputs(_numInputs)
  13574. {
  13575. inputs = new IRoxieInput*[numInputs];
  13576. for (unsigned i = 0; i < numInputs; i++)
  13577. inputs[i] = NULL;
  13578. }
  13579. ~CRoxieServerNWayInputActivity()
  13580. {
  13581. delete [] inputs;
  13582. }
  13583. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13584. {
  13585. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13586. bool selectionIsAll;
  13587. size32_t selectionLen;
  13588. rtlDataAttr selection;
  13589. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13590. selectedInputs.kill();
  13591. if (selectionIsAll)
  13592. {
  13593. for (unsigned i=0; i < numInputs; i++)
  13594. selectedInputs.append(inputs[i]);
  13595. }
  13596. else
  13597. {
  13598. const size32_t * selections = (const size32_t *)selection.getdata();
  13599. unsigned max = selectionLen/sizeof(size32_t);
  13600. for (unsigned i = 0; i < max; i++)
  13601. {
  13602. unsigned nextIndex = selections[i];
  13603. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  13604. for (unsigned j=i+1; j < max; j++)
  13605. {
  13606. if (nextIndex == selections[j])
  13607. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  13608. }
  13609. if (nextIndex > numInputs)
  13610. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  13611. selectedInputs.append(inputs[nextIndex-1]);
  13612. }
  13613. }
  13614. ForEachItemIn(i2, selectedInputs)
  13615. selectedInputs.item(i2)->start(parentExtractSize, parentExtract, paused);
  13616. }
  13617. virtual void stop(bool aborting)
  13618. {
  13619. ForEachItemIn(i2, selectedInputs)
  13620. selectedInputs.item(i2)->stop(aborting);
  13621. CRoxieServerActivity::stop(aborting);
  13622. }
  13623. virtual unsigned __int64 queryLocalCycles() const
  13624. {
  13625. __int64 localCycles = totalCycles;
  13626. ForEachItemIn(i, selectedInputs)
  13627. {
  13628. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  13629. }
  13630. if (localCycles < 0)
  13631. localCycles = 0;
  13632. return localCycles;
  13633. }
  13634. virtual IRoxieInput *queryInput(unsigned idx) const
  13635. {
  13636. if (selectedInputs.isItem(idx))
  13637. return selectedInputs.item(idx);
  13638. else
  13639. return NULL;
  13640. }
  13641. virtual void reset()
  13642. {
  13643. ForEachItemIn(i, selectedInputs)
  13644. selectedInputs.item(i)->reset();
  13645. selectedInputs.kill();
  13646. CRoxieServerActivity::reset();
  13647. }
  13648. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13649. {
  13650. assertex(idx < numInputs);
  13651. inputs[idx] = _in;
  13652. }
  13653. virtual const void * nextInGroup()
  13654. {
  13655. throwUnexpected();
  13656. }
  13657. virtual unsigned numConcreteOutputs() const
  13658. {
  13659. return selectedInputs.ordinality();
  13660. }
  13661. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13662. {
  13663. if (selectedInputs.isItem(idx))
  13664. return selectedInputs.item(idx);
  13665. return NULL;
  13666. }
  13667. };
  13668. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  13669. {
  13670. // bool ordered;
  13671. public:
  13672. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13673. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  13674. {
  13675. }
  13676. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13677. {
  13678. return new CRoxieServerNWayInputActivity(this, _probeManager, numInputs());
  13679. }
  13680. };
  13681. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  13682. {
  13683. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  13684. }
  13685. //=====================================================================================================
  13686. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerActivity
  13687. {
  13688. IHThorNWayGraphLoopResultReadArg & helper;
  13689. CIArrayOf<CRoxieServerActivity> resultReaders;
  13690. PointerArrayOf<IRoxieInput> inputs;
  13691. unsigned graphId;
  13692. bool grouped;
  13693. bool selectionIsAll;
  13694. size32_t selectionLen;
  13695. rtlDataAttr selection;
  13696. public:
  13697. CRoxieServerNWayGraphLoopResultReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  13698. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  13699. {
  13700. grouped = helper.isGrouped();
  13701. graphId = _graphId;
  13702. selectionIsAll = false;
  13703. }
  13704. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13705. {
  13706. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13707. if (inputs.ordinality() == 0)
  13708. {
  13709. initInputSelection();
  13710. unsigned max = selectionLen / sizeof(size32_t);
  13711. const size32_t * selections = (const size32_t *)selection.getdata();
  13712. IProbeManager * probeManager = NULL; // MORE!!
  13713. for (unsigned i = 0; i < max; i++)
  13714. {
  13715. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(factory, probeManager, graphId, selections[i]);
  13716. resultReaders.append(*resultInput);
  13717. inputs.append(resultInput->queryOutput(0));
  13718. resultInput->onCreate(ctx, colocalParent);
  13719. resultInput->start(parentExtractSize, parentExtract, paused);
  13720. }
  13721. }
  13722. else
  13723. {
  13724. ForEachItemIn(i, inputs)
  13725. inputs.item(i)->start(parentExtractSize, parentExtract, paused);
  13726. }
  13727. }
  13728. virtual void stop(bool aborting)
  13729. {
  13730. ForEachItemIn(i, inputs)
  13731. inputs.item(i)->stop(aborting);
  13732. CRoxieServerActivity::stop(aborting);
  13733. }
  13734. virtual void reset()
  13735. {
  13736. ForEachItemIn(i, inputs)
  13737. inputs.item(i)->reset();
  13738. inputs.kill();
  13739. resultReaders.kill();
  13740. CRoxieServerActivity::reset();
  13741. }
  13742. virtual void setInput(unsigned idx, IRoxieInput *_in)
  13743. {
  13744. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for nway graph result read");
  13745. }
  13746. virtual const void * nextInGroup()
  13747. {
  13748. throwUnexpected();
  13749. }
  13750. virtual unsigned numConcreteOutputs() const
  13751. {
  13752. return inputs.ordinality();
  13753. }
  13754. virtual IRoxieInput * queryConcreteInput(unsigned idx)
  13755. {
  13756. if (inputs.isItem(idx))
  13757. return inputs.item(idx);
  13758. return NULL;
  13759. }
  13760. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  13761. {
  13762. ensureCreated();
  13763. basehelper.onStart(parentExtract, NULL);
  13764. initInputSelection();
  13765. unsigned max = selectionLen / sizeof(size32_t);
  13766. const size32_t * selections = (const size32_t *)selection.getdata();
  13767. for (unsigned i = 0; i < max; i++)
  13768. processor.noteUseIteration(selections[i]);
  13769. }
  13770. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieInput> &probes)
  13771. {
  13772. //selection etc. already initialised from the gratherIterationUsage() call.
  13773. unsigned max = selectionLen / sizeof(size32_t);
  13774. const size32_t * selections = (const size32_t *)selection.getdata();
  13775. for (unsigned i = 0; i < max; i++)
  13776. inputs.append(processor.connectIterationOutput(selections[i], probeManager, probes, this, i));
  13777. }
  13778. protected:
  13779. void initInputSelection()
  13780. {
  13781. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  13782. if (selectionIsAll)
  13783. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  13784. }
  13785. };
  13786. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  13787. {
  13788. unsigned graphId;
  13789. public:
  13790. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _graphId)
  13791. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), graphId(_graphId)
  13792. {
  13793. }
  13794. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  13795. {
  13796. return new CRoxieServerNWayGraphLoopResultReadActivity(this, _probeManager, graphId);
  13797. }
  13798. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  13799. {
  13800. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  13801. }
  13802. };
  13803. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned graphId)
  13804. {
  13805. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, graphId);
  13806. }
  13807. //=================================================================================
  13808. class RoxieSteppedInput : public CInterface, implements ISteppedInput
  13809. {
  13810. public:
  13811. RoxieSteppedInput(IRoxieInput * _input) { input = _input; }
  13812. IMPLEMENT_IINTERFACE
  13813. protected:
  13814. virtual const void * nextInputRow()
  13815. {
  13816. #ifdef TRACE_SEEK_REQUESTS
  13817. IRoxieContextLogger * logger = input->queryActivity();
  13818. const void * ret = doNextInputRow();
  13819. {
  13820. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13821. if (!ret)
  13822. xmlwrite.outputBool(true,"eof");
  13823. else if (input->queryOutputMeta()->hasXML())
  13824. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13825. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  13826. }
  13827. return ret;
  13828. #else
  13829. return doNextInputRow();
  13830. #endif
  13831. }
  13832. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13833. {
  13834. #ifdef TRACE_SEEK_REQUESTS
  13835. IRoxieContextLogger * logger = input->queryActivity();
  13836. {
  13837. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13838. if (input->queryOutputMeta()->hasXML())
  13839. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  13840. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  13841. numFields,
  13842. stepExtra.readAheadManyResults() ? "readahead " : "",
  13843. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13844. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13845. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13846. xmlwrite.str());
  13847. }
  13848. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13849. {
  13850. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  13851. if (!ret)
  13852. xmlwrite.outputBool(true,"eof");
  13853. else if (input->queryOutputMeta()->hasXML())
  13854. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  13855. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  13856. numFields,
  13857. stepExtra.readAheadManyResults() ? "readahead " : "",
  13858. stepExtra.returnMismatches() ? "mismatch" : "exact",
  13859. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  13860. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  13861. xmlwrite.str());
  13862. }
  13863. return ret;
  13864. #else
  13865. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13866. #endif
  13867. }
  13868. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  13869. {
  13870. return input->gatherConjunctions(collector);
  13871. }
  13872. virtual void resetEOF()
  13873. {
  13874. input->resetEOF();
  13875. }
  13876. virtual IInputSteppingMeta * queryInputSteppingMeta()
  13877. {
  13878. return input->querySteppingMeta();
  13879. }
  13880. inline const void * doNextInputRow()
  13881. {
  13882. const void * ret = input->nextInGroup();
  13883. if (!ret)
  13884. ret = input->nextInGroup();
  13885. return ret;
  13886. }
  13887. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13888. {
  13889. assertex(wasCompleteMatch);
  13890. return input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  13891. }
  13892. protected:
  13893. IRoxieInput * input;
  13894. };
  13895. //=================================================================================
  13896. class CRoxieServerNaryActivity : public CRoxieServerMultiInputActivity
  13897. {
  13898. public:
  13899. CRoxieServerNaryActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13900. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs)
  13901. {
  13902. }
  13903. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13904. {
  13905. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  13906. for (unsigned i=0; i < numInputs; i++)
  13907. {
  13908. IRoxieInput * cur = inputArray[i];
  13909. unsigned numRealInputs = cur->numConcreteOutputs();
  13910. for (unsigned j = 0; j < numRealInputs; j++)
  13911. {
  13912. IRoxieInput * curReal = cur->queryConcreteInput(j);
  13913. expandedInputs.append(curReal);
  13914. }
  13915. }
  13916. }
  13917. virtual void reset()
  13918. {
  13919. expandedInputs.kill();
  13920. CRoxieServerMultiInputActivity::reset();
  13921. }
  13922. protected:
  13923. PointerArrayOf<IRoxieInput> expandedInputs;
  13924. };
  13925. //=================================================================================
  13926. class CRoxieStreamMerger : public CStreamMerger
  13927. {
  13928. public:
  13929. CRoxieStreamMerger() : CStreamMerger(true) {}
  13930. void initInputs(unsigned _numInputs, IRoxieInput ** _inputArray)
  13931. {
  13932. CStreamMerger::initInputs(_numInputs);
  13933. inputArray = _inputArray;
  13934. }
  13935. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  13936. {
  13937. const void * next;
  13938. bool matches = true;
  13939. if (seek)
  13940. next = inputArray[i]->nextSteppedGE(seek, numFields, matches, *stepExtra);
  13941. else
  13942. next = nextUngrouped(inputArray[i]);
  13943. pending[i] = next;
  13944. pendingMatches[i] = matches;
  13945. return (next != NULL);
  13946. }
  13947. virtual void releaseRow(const void * row)
  13948. {
  13949. ReleaseRoxieRow(row);
  13950. }
  13951. protected:
  13952. IRoxieInput **inputArray;
  13953. };
  13954. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  13955. {
  13956. public:
  13957. CRoxieServerNWayMergeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  13958. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),
  13959. helper((IHThorNWayMergeArg &)basehelper)
  13960. {
  13961. initializedMeta = false;
  13962. }
  13963. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13964. {
  13965. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  13966. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  13967. merger.initInputs(expandedInputs.length(), expandedInputs.getArray());
  13968. }
  13969. virtual void stop(bool aborting)
  13970. {
  13971. merger.done();
  13972. CRoxieServerNaryActivity::stop(aborting);
  13973. }
  13974. virtual void reset()
  13975. {
  13976. merger.cleanup();
  13977. CRoxieServerNaryActivity::reset();
  13978. initializedMeta = false;
  13979. }
  13980. virtual const void * nextInGroup()
  13981. {
  13982. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13983. const void * next = merger.nextRow();
  13984. if (next)
  13985. processed++;
  13986. return next;
  13987. }
  13988. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  13989. {
  13990. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  13991. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  13992. if (next)
  13993. processed++;
  13994. return next;
  13995. }
  13996. virtual IInputSteppingMeta * querySteppingMeta()
  13997. {
  13998. if (expandedInputs.ordinality() == 0)
  13999. return NULL;
  14000. if (!initializedMeta)
  14001. {
  14002. meta.init(helper.querySteppingMeta(), false);
  14003. ForEachItemIn(i, expandedInputs)
  14004. {
  14005. if (meta.getNumFields() == 0)
  14006. break;
  14007. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  14008. meta.intersect(inputMeta);
  14009. }
  14010. initializedMeta = true;
  14011. }
  14012. if (meta.getNumFields() == 0)
  14013. return NULL;
  14014. return &meta;
  14015. }
  14016. protected:
  14017. IHThorNWayMergeArg &helper;
  14018. CRoxieStreamMerger merger;
  14019. CSteppingMeta meta;
  14020. bool initializedMeta;
  14021. };
  14022. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  14023. {
  14024. public:
  14025. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14026. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14027. {
  14028. }
  14029. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14030. {
  14031. return new CRoxieServerNWayMergeActivity(this, _probeManager, numInputs());
  14032. }
  14033. };
  14034. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14035. {
  14036. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14037. }
  14038. //=================================================================================
  14039. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  14040. {
  14041. public:
  14042. CRoxieServerNWayMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  14043. : CRoxieServerNaryActivity(_factory, _probeManager, _numInputs),processor(_processor),
  14044. helper((IHThorNWayMergeJoinArg &)basehelper)
  14045. {
  14046. }
  14047. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14048. {
  14049. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  14050. ForEachItemIn(i1, expandedInputs)
  14051. {
  14052. IRoxieInput * cur = expandedInputs.item(i1);
  14053. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(cur);
  14054. processor.addInput(stepInput);
  14055. }
  14056. ICodeContext * codectx = ctx->queryCodeContext();
  14057. Owned<IEngineRowAllocator> inputAllocator = codectx->getRowAllocator(helper.queryInputMeta(), activityId);
  14058. Owned<IEngineRowAllocator> outputAllocator = codectx->getRowAllocator(helper.queryOutputMeta(), activityId);
  14059. processor.beforeProcessing(inputAllocator, outputAllocator);
  14060. }
  14061. virtual void stop(bool aborting)
  14062. {
  14063. processor.afterProcessing();
  14064. CRoxieServerNaryActivity::stop(aborting);
  14065. }
  14066. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14067. {
  14068. return processor.gatherConjunctions(collector);
  14069. }
  14070. virtual void resetEOF()
  14071. {
  14072. processor.queryResetEOF();
  14073. }
  14074. virtual const void * nextInGroup()
  14075. {
  14076. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14077. const void * next = processor.nextInGroup();
  14078. if (next)
  14079. processed++;
  14080. return next;
  14081. }
  14082. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14083. {
  14084. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14085. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  14086. if (next)
  14087. processed++;
  14088. return next;
  14089. }
  14090. virtual IInputSteppingMeta * querySteppingMeta()
  14091. {
  14092. return processor.queryInputSteppingMeta();
  14093. }
  14094. protected:
  14095. IHThorNWayMergeJoinArg & helper;
  14096. CMergeJoinProcessor & processor;
  14097. };
  14098. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14099. {
  14100. public:
  14101. CRoxieServerAndMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14102. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  14103. {
  14104. }
  14105. protected:
  14106. CAndMergeJoinProcessor andProcessor;
  14107. };
  14108. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14109. {
  14110. public:
  14111. CRoxieServerAndLeftMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14112. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  14113. {
  14114. }
  14115. protected:
  14116. CAndLeftMergeJoinProcessor andLeftProcessor;
  14117. };
  14118. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14119. {
  14120. public:
  14121. CRoxieServerMofNMergeJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14122. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  14123. {
  14124. }
  14125. protected:
  14126. CMofNMergeJoinProcessor mofnProcessor;
  14127. };
  14128. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  14129. {
  14130. public:
  14131. CRoxieServerProximityJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14132. : CRoxieServerNWayMergeJoinActivity(_factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  14133. {
  14134. }
  14135. protected:
  14136. CProximityJoinProcessor proximityProcessor;
  14137. };
  14138. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  14139. {
  14140. unsigned flags;
  14141. public:
  14142. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14143. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14144. {
  14145. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  14146. flags = helper->getJoinFlags();
  14147. }
  14148. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14149. {
  14150. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  14151. return new CRoxieServerProximityJoinActivity(this, _probeManager, numInputs());
  14152. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  14153. {
  14154. case IHThorNWayMergeJoinArg::MJFinner:
  14155. return new CRoxieServerAndMergeJoinActivity(this, _probeManager, numInputs());
  14156. case IHThorNWayMergeJoinArg::MJFleftonly:
  14157. case IHThorNWayMergeJoinArg::MJFleftouter:
  14158. return new CRoxieServerAndLeftMergeJoinActivity(this, _probeManager, numInputs());
  14159. case IHThorNWayMergeJoinArg::MJFmofn:
  14160. return new CRoxieServerMofNMergeJoinActivity(this, _probeManager, numInputs());
  14161. default:
  14162. throwUnexpected();
  14163. }
  14164. }
  14165. };
  14166. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14167. {
  14168. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14169. }
  14170. //=================================================================================
  14171. class CRoxieServerNWaySelectActivity : public CRoxieServerMultiInputActivity
  14172. {
  14173. IHThorNWaySelectArg &helper;
  14174. public:
  14175. CRoxieServerNWaySelectActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14176. : CRoxieServerMultiInputActivity(_factory, _probeManager, _numInputs),
  14177. helper((IHThorNWaySelectArg &)basehelper)
  14178. {
  14179. }
  14180. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14181. {
  14182. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  14183. unsigned whichInput = helper.getInputIndex();
  14184. selectedInput = NULL;
  14185. if (whichInput--)
  14186. {
  14187. for (unsigned i=0; i < numInputs; i++)
  14188. {
  14189. IRoxieInput * cur = inputArray[i];
  14190. unsigned numRealInputs = cur->numConcreteOutputs();
  14191. if (whichInput < numRealInputs)
  14192. {
  14193. selectedInput = cur->queryConcreteInput(whichInput);
  14194. break;
  14195. }
  14196. whichInput -= numRealInputs;
  14197. }
  14198. }
  14199. }
  14200. virtual void reset()
  14201. {
  14202. selectedInput = NULL;
  14203. CRoxieServerMultiInputActivity::reset();
  14204. }
  14205. const void * nextInGroup()
  14206. {
  14207. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14208. if (!selectedInput)
  14209. return NULL;
  14210. return selectedInput->nextInGroup();
  14211. }
  14212. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  14213. {
  14214. if (!selectedInput)
  14215. return false;
  14216. return selectedInput->gatherConjunctions(collector);
  14217. }
  14218. virtual void resetEOF()
  14219. {
  14220. if (selectedInput)
  14221. selectedInput->resetEOF();
  14222. }
  14223. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  14224. {
  14225. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14226. if (!selectedInput)
  14227. return NULL;
  14228. return selectedInput->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  14229. }
  14230. IInputSteppingMeta * querySteppingMeta()
  14231. {
  14232. if (selectedInput)
  14233. return selectedInput->querySteppingMeta();
  14234. return NULL;
  14235. }
  14236. protected:
  14237. IRoxieInput * selectedInput;
  14238. };
  14239. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  14240. {
  14241. public:
  14242. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14243. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14244. {
  14245. }
  14246. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14247. {
  14248. return new CRoxieServerNWaySelectActivity(this, _probeManager, numInputs());
  14249. }
  14250. };
  14251. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14252. {
  14253. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14254. }
  14255. //=================================================================================
  14256. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  14257. {
  14258. protected:
  14259. IHThorRemoteArg &helper;
  14260. CRemoteResultAdaptor remote;
  14261. public:
  14262. CRoxieServerRemoteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  14263. : CRoxieServerActivity(_factory, _probeManager),
  14264. helper((IHThorRemoteArg &)basehelper),
  14265. remote(_remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  14266. {
  14267. }
  14268. virtual const IResolvedFile *queryVarFileInfo() const
  14269. {
  14270. return NULL;
  14271. }
  14272. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14273. {
  14274. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14275. remote.onCreate(this, this, _ctx, _colocalParent);
  14276. }
  14277. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14278. {
  14279. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14280. remote.onStart(parentExtractSize, parentExtract);
  14281. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  14282. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  14283. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  14284. remote.flush();
  14285. remote.senddone();
  14286. }
  14287. virtual void setInput(unsigned idx, IRoxieInput *_in)
  14288. {
  14289. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  14290. }
  14291. virtual IRoxieInput *queryOutput(unsigned idx)
  14292. {
  14293. if (idx==(unsigned)-1)
  14294. idx = 0;
  14295. return idx ? NULL: &remote;
  14296. }
  14297. virtual void reset()
  14298. {
  14299. processed = remote.processed;
  14300. remote.processed = 0;
  14301. CRoxieServerActivity::reset();
  14302. }
  14303. virtual void onLimitExceeded(bool isKeyed)
  14304. {
  14305. if (traceLevel > 4)
  14306. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  14307. helper.onLimitExceeded();
  14308. }
  14309. virtual const void *createLimitFailRow(bool isKeyed)
  14310. {
  14311. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  14312. }
  14313. virtual const void *nextInGroup()
  14314. {
  14315. throwUnexpected(); // I am nobody's input
  14316. }
  14317. };
  14318. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  14319. {
  14320. public:
  14321. RemoteActivityId remoteId;
  14322. bool isRoot;
  14323. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14324. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId), isRoot(_isRoot)
  14325. {
  14326. }
  14327. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14328. {
  14329. return new CRoxieServerRemoteActivity(this, _probeManager, remoteId);
  14330. }
  14331. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14332. {
  14333. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  14334. }
  14335. virtual bool isSink() const
  14336. {
  14337. //I don't think the action version of this is implemented - but this would be the code
  14338. return isRoot && !meta.queryOriginal();
  14339. }
  14340. };
  14341. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, bool _isRoot)
  14342. {
  14343. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _isRoot);
  14344. }
  14345. //=================================================================================
  14346. class CRoxieServerIterateActivity : public CRoxieServerActivity
  14347. {
  14348. IHThorIterateArg &helper;
  14349. OwnedConstRoxieRow defaultRecord;
  14350. OwnedConstRoxieRow left;
  14351. OwnedConstRoxieRow right;
  14352. unsigned counter;
  14353. public:
  14354. CRoxieServerIterateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14355. : CRoxieServerActivity(_factory, _probeManager),
  14356. helper((IHThorIterateArg &)basehelper)
  14357. {
  14358. counter = 0;
  14359. }
  14360. virtual bool needsAllocator() const { return true; }
  14361. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14362. {
  14363. counter = 0;
  14364. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14365. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14366. size32_t thisSize = helper.createDefault(rowBuilder);
  14367. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  14368. }
  14369. virtual void reset()
  14370. {
  14371. defaultRecord.clear();
  14372. right.clear();
  14373. left.clear();
  14374. CRoxieServerActivity::reset();
  14375. }
  14376. virtual const void * nextInGroup()
  14377. {
  14378. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14379. loop
  14380. {
  14381. right.setown(input->nextInGroup());
  14382. if (!right)
  14383. {
  14384. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  14385. left.clear();
  14386. counter = 0;
  14387. if (skippedGroup) continue;
  14388. return NULL;
  14389. }
  14390. try
  14391. {
  14392. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14393. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  14394. if (outSize)
  14395. {
  14396. left.setown(rowBuilder.finalizeRowClear(outSize));
  14397. processed++;
  14398. return left.getLink();
  14399. }
  14400. }
  14401. catch (IException *E)
  14402. {
  14403. throw makeWrappedException(E);
  14404. }
  14405. }
  14406. }
  14407. };
  14408. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  14409. {
  14410. public:
  14411. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14412. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14413. {
  14414. }
  14415. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14416. {
  14417. return new CRoxieServerIterateActivity(this, _probeManager);
  14418. }
  14419. };
  14420. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14421. {
  14422. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14423. }
  14424. //=================================================================================
  14425. class CRoxieServerProcessActivity : public CRoxieServerActivity
  14426. {
  14427. IHThorProcessArg &helper;
  14428. OwnedConstRoxieRow curRight;
  14429. OwnedConstRoxieRow initialRight;
  14430. unsigned counter;
  14431. Owned<IEngineRowAllocator> rightRowAllocator;
  14432. public:
  14433. CRoxieServerProcessActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14434. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  14435. {
  14436. counter = 0;
  14437. }
  14438. virtual bool needsAllocator() const { return true; }
  14439. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  14440. {
  14441. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  14442. rightRowAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryRightRecordSize(), IOutputMetaData), activityId));
  14443. }
  14444. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14445. {
  14446. counter = 0;
  14447. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14448. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  14449. size32_t thisSize = helper.createInitialRight(rowBuilder);
  14450. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14451. curRight.set(initialRight);
  14452. }
  14453. virtual const void * nextInGroup()
  14454. {
  14455. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14456. try
  14457. {
  14458. loop
  14459. {
  14460. const void * in = input->nextInGroup();
  14461. if (!in)
  14462. {
  14463. bool eog = (curRight != initialRight); // processed any records?
  14464. counter = 0;
  14465. curRight.set(initialRight);
  14466. if (eog)
  14467. return NULL;
  14468. in = input->nextInGroup();
  14469. if (!in)
  14470. return NULL;
  14471. }
  14472. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14473. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  14474. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  14475. ReleaseRoxieRow(in);
  14476. if (outSize)
  14477. {
  14478. //MORE: This should be returned...
  14479. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  14480. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  14481. processed++;
  14482. return rowBuilder.finalizeRowClear(outSize);
  14483. }
  14484. }
  14485. }
  14486. catch (IException *E)
  14487. {
  14488. throw makeWrappedException(E);
  14489. }
  14490. }
  14491. };
  14492. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  14493. {
  14494. public:
  14495. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14496. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14497. {
  14498. }
  14499. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14500. {
  14501. return new CRoxieServerProcessActivity(this, _probeManager);
  14502. }
  14503. };
  14504. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14505. {
  14506. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14507. }
  14508. //=================================================================================
  14509. class CRoxieServerGroupActivity : public CRoxieServerActivity
  14510. {
  14511. IHThorGroupArg &helper;
  14512. bool endPending;
  14513. bool eof;
  14514. bool first;
  14515. const void *next;
  14516. public:
  14517. CRoxieServerGroupActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14518. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  14519. {
  14520. next = NULL;
  14521. endPending = false;
  14522. eof = false;
  14523. first = true;
  14524. }
  14525. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14526. {
  14527. endPending = false;
  14528. eof = false;
  14529. first = true;
  14530. assertex(next == NULL);
  14531. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14532. }
  14533. virtual void reset()
  14534. {
  14535. ReleaseClearRoxieRow(next);
  14536. CRoxieServerActivity::reset();
  14537. }
  14538. virtual const void * nextInGroup()
  14539. {
  14540. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14541. if (first)
  14542. {
  14543. next = input->nextInGroup();
  14544. first = false;
  14545. }
  14546. if (eof || endPending)
  14547. {
  14548. endPending = false;
  14549. return NULL;
  14550. }
  14551. const void * prev = next;
  14552. next = input->nextInGroup();
  14553. if (!next)
  14554. next = input->nextInGroup();
  14555. if (next)
  14556. {
  14557. assertex(prev);
  14558. if (!helper.isSameGroup(prev, next))
  14559. endPending = true;
  14560. }
  14561. else
  14562. eof = true;
  14563. if (prev)
  14564. processed++;
  14565. return prev;
  14566. }
  14567. };
  14568. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  14569. {
  14570. public:
  14571. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14572. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14573. {
  14574. }
  14575. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14576. {
  14577. return new CRoxieServerGroupActivity(this, _probeManager);
  14578. }
  14579. };
  14580. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14581. {
  14582. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14583. }
  14584. //=================================================================================
  14585. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  14586. {
  14587. unsigned __int64 limit;
  14588. unsigned __int64 skip;
  14589. unsigned doneThisGroup;
  14590. IHThorFirstNArg &helper;
  14591. public:
  14592. CRoxieServerFirstNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14593. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  14594. {
  14595. doneThisGroup = 0;
  14596. limit = 0;
  14597. skip = 0;
  14598. }
  14599. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14600. {
  14601. doneThisGroup = 0;
  14602. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  14603. limit = helper.getLimit();
  14604. skip = helper.numToSkip();
  14605. lateStart(parentExtractSize, parentExtract, limit > 0);
  14606. if (limit + skip >= limit)
  14607. limit += skip;
  14608. }
  14609. const void * nextInGroup()
  14610. {
  14611. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14612. if (eof)
  14613. return NULL;
  14614. const void *ret;
  14615. loop
  14616. {
  14617. ret = input->nextInGroup();
  14618. if (!ret)
  14619. {
  14620. if (meta.isGrouped())
  14621. {
  14622. if (doneThisGroup > skip)
  14623. {
  14624. doneThisGroup = 0;
  14625. return NULL;
  14626. }
  14627. doneThisGroup = 0;
  14628. }
  14629. ret = input->nextInGroup();
  14630. if (!ret)
  14631. {
  14632. eof = true;
  14633. return NULL;
  14634. }
  14635. }
  14636. doneThisGroup++;
  14637. if (doneThisGroup > skip)
  14638. break;
  14639. ReleaseRoxieRow(ret);
  14640. }
  14641. if (doneThisGroup <= limit)
  14642. {
  14643. processed++;
  14644. return ret;
  14645. }
  14646. ReleaseRoxieRow(ret);
  14647. if (meta.isGrouped())
  14648. {
  14649. while ((ret = input->nextInGroup()) != NULL)
  14650. ReleaseRoxieRow(ret);
  14651. doneThisGroup = 0;
  14652. }
  14653. else
  14654. eof = true;
  14655. return NULL;
  14656. }
  14657. };
  14658. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  14659. {
  14660. public:
  14661. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14662. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14663. {
  14664. }
  14665. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14666. {
  14667. return new CRoxieServerFirstNActivity(this, _probeManager);
  14668. }
  14669. };
  14670. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14671. {
  14672. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14673. }
  14674. //=================================================================================
  14675. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  14676. {
  14677. bool done;
  14678. IHThorSelectNArg &helper;
  14679. public:
  14680. CRoxieServerSelectNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14681. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  14682. {
  14683. done = false;
  14684. }
  14685. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14686. {
  14687. done = false;
  14688. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14689. }
  14690. const void *defaultRow()
  14691. {
  14692. if (!rowAllocator)
  14693. createRowAllocator(); // We delay as often not needed...
  14694. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14695. size32_t thisSize = helper.createDefault(rowBuilder);
  14696. return rowBuilder.finalizeRowClear(thisSize);
  14697. }
  14698. virtual const void * nextInGroup()
  14699. {
  14700. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14701. if (done)
  14702. return NULL;
  14703. done = true;
  14704. processed++; // always going to return a row!
  14705. unsigned __int64 index = helper.getRowToSelect();
  14706. while (--index)
  14707. {
  14708. const void * next = input->nextInGroup();
  14709. if (!next)
  14710. next = input->nextInGroup();
  14711. if (!next)
  14712. return defaultRow();
  14713. ReleaseRoxieRow(next);
  14714. }
  14715. const void * next = input->nextInGroup();
  14716. if (!next)
  14717. next = input->nextInGroup();
  14718. if (!next)
  14719. next = defaultRow();
  14720. return next;
  14721. }
  14722. };
  14723. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  14724. {
  14725. public:
  14726. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14727. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  14728. {
  14729. }
  14730. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  14731. {
  14732. return new CRoxieServerSelectNActivity(this, _probeManager);
  14733. }
  14734. };
  14735. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  14736. {
  14737. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  14738. }
  14739. //=================================================================================
  14740. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  14741. {
  14742. IHThorJoinArg &helper;
  14743. ICompare *collate;
  14744. OwnedRowArray group;
  14745. bool matchedLeft;
  14746. BoolArray matchedRight;
  14747. bool eof;
  14748. bool first;
  14749. unsigned leftIndex;
  14750. unsigned rightIndex;
  14751. unsigned rightOuterIndex;
  14752. unsigned joinLimit;
  14753. unsigned atmostLimit;
  14754. unsigned atmostsTriggered;
  14755. unsigned abortLimit;
  14756. unsigned keepLimit;
  14757. bool leftOuterJoin;
  14758. bool rightOuterJoin;
  14759. bool exclude;
  14760. bool limitFail;
  14761. bool limitOnFail;
  14762. bool cloneLeft;
  14763. OwnedConstRoxieRow defaultLeft;
  14764. OwnedConstRoxieRow defaultRight;
  14765. OwnedConstRoxieRow lhs;
  14766. Owned<IException> failingLimit;
  14767. bool failingOuterAtmost;
  14768. Owned<IEngineRowAllocator> defaultAllocator;
  14769. Owned<IRHLimitedCompareHelper> limitedhelper;
  14770. Owned<CRHDualCache> dualcache;
  14771. IInputBase *dualCacheInput;
  14772. bool fillGroup()
  14773. {
  14774. group.clear();
  14775. matchedLeft = false;
  14776. matchedRight.kill();
  14777. failingOuterAtmost = false;
  14778. const void * next;
  14779. unsigned groupCount = 0;
  14780. while((next = input->nextInGroup()) != NULL)
  14781. {
  14782. if(groupCount==abortLimit)
  14783. {
  14784. if(limitFail)
  14785. failLimit(next);
  14786. if (ctx->queryDebugContext())
  14787. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  14788. if(limitOnFail)
  14789. {
  14790. assertex(!failingLimit);
  14791. try
  14792. {
  14793. failLimit(next);
  14794. }
  14795. catch(IException * except)
  14796. {
  14797. failingLimit.setown(except);
  14798. }
  14799. assertex(failingLimit != NULL);
  14800. group.append(next);
  14801. groupCount++;
  14802. break;
  14803. }
  14804. group.clear();
  14805. groupCount = 0;
  14806. while(next)
  14807. {
  14808. ReleaseRoxieRow(next);
  14809. next = input->nextInGroup();
  14810. }
  14811. }
  14812. else if(groupCount==atmostLimit)
  14813. {
  14814. atmostsTriggered++;
  14815. if(leftOuterJoin)
  14816. {
  14817. group.append(next);
  14818. groupCount++;
  14819. failingOuterAtmost = true;
  14820. break;
  14821. }
  14822. else
  14823. {
  14824. group.clear();
  14825. groupCount = 0;
  14826. while (next)
  14827. {
  14828. ReleaseRoxieRow(next);
  14829. next = input->nextInGroup();
  14830. }
  14831. }
  14832. }
  14833. else
  14834. {
  14835. group.append(next);
  14836. groupCount++;
  14837. }
  14838. }
  14839. if(group.ordinality()==0)
  14840. {
  14841. eof = true;
  14842. return false;
  14843. }
  14844. leftIndex = 0;
  14845. rightIndex = 0;
  14846. rightOuterIndex = 0;
  14847. joinLimit = keepLimit;
  14848. ForEachItemIn(idx, group)
  14849. matchedRight.append(false);
  14850. return true;
  14851. }
  14852. void failLimit(const void * next)
  14853. {
  14854. helper.onMatchAbortLimitExceeded();
  14855. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  14856. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  14857. {
  14858. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  14859. }
  14860. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  14861. }
  14862. virtual bool needsAllocator() const { return true; }
  14863. const void *joinRecords(const void * curLeft, const void * curRight, IException * except = NULL)
  14864. {
  14865. try
  14866. {
  14867. if (cloneLeft && !except)
  14868. {
  14869. LinkRoxieRow(curLeft);
  14870. return curLeft;
  14871. }
  14872. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  14873. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight);
  14874. if (outsize)
  14875. return rowBuilder.finalizeRowClear(outsize);
  14876. else
  14877. return NULL;
  14878. }
  14879. catch (IException *E)
  14880. {
  14881. throw makeWrappedException(E);
  14882. }
  14883. }
  14884. void createDefaultLeft()
  14885. {
  14886. if (!defaultLeft)
  14887. {
  14888. if (!defaultAllocator)
  14889. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14890. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14891. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  14892. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  14893. }
  14894. }
  14895. void createDefaultRight()
  14896. {
  14897. if (!defaultRight)
  14898. {
  14899. if (!defaultAllocator)
  14900. defaultAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  14901. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  14902. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  14903. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  14904. }
  14905. }
  14906. public:
  14907. CRoxieServerSelfJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  14908. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorJoinArg &)basehelper)
  14909. {
  14910. collate = helper.queryCompareLeftRight();
  14911. eof = false;
  14912. first = true;
  14913. keepLimit = 0;
  14914. atmostLimit = 0;
  14915. atmostsTriggered = 0;
  14916. unsigned joinFlags = helper.getJoinFlags();
  14917. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  14918. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  14919. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  14920. exclude = (joinFlags & JFexclude) != 0;
  14921. abortLimit = 0;
  14922. joinLimit = 0;
  14923. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  14924. getLimitType(joinFlags, limitFail, limitOnFail);
  14925. if((joinFlags & JFslidingmatch) != 0)
  14926. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  14927. failingOuterAtmost = false;
  14928. matchedLeft = false;
  14929. leftIndex = 0;
  14930. rightIndex = 0;
  14931. rightOuterIndex = 0;
  14932. dualCacheInput = NULL;
  14933. }
  14934. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14935. {
  14936. eof = false;
  14937. first = true;
  14938. failingLimit.clear();
  14939. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14940. keepLimit = helper.getKeepLimit();
  14941. if(keepLimit == 0)
  14942. keepLimit = (unsigned)-1;
  14943. atmostsTriggered = 0;
  14944. atmostLimit = helper.getJoinLimit();
  14945. if(atmostLimit == 0)
  14946. atmostLimit = (unsigned)-1;
  14947. else
  14948. assertex(!rightOuterJoin);
  14949. abortLimit = helper.getMatchAbortLimit();
  14950. if (abortLimit == 0)
  14951. abortLimit = (unsigned)-1;
  14952. if (rightOuterJoin)
  14953. createDefaultLeft();
  14954. if (leftOuterJoin || limitOnFail)
  14955. createDefaultRight();
  14956. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  14957. { //limited match join (s[1..n])
  14958. dualcache.setown(new CRHDualCache());
  14959. dualcache->init(CRoxieServerActivity::input);
  14960. dualCacheInput = dualcache->queryOut1();
  14961. failingOuterAtmost = false;
  14962. matchedLeft = false;
  14963. leftIndex = 0;
  14964. rightOuterIndex = 0;
  14965. limitedhelper.setown(createRHLimitedCompareHelper());
  14966. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  14967. }
  14968. }
  14969. virtual void reset()
  14970. {
  14971. if (atmostsTriggered)
  14972. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  14973. group.clear();
  14974. CRoxieServerActivity::reset();
  14975. defaultLeft.clear();
  14976. defaultRight.clear();
  14977. }
  14978. virtual const void * nextInGroup()
  14979. {
  14980. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  14981. if (limitedhelper)
  14982. {
  14983. while(!eof) //limited match join
  14984. {
  14985. if (!group.isItem(rightIndex))
  14986. {
  14987. lhs.setown(dualCacheInput->nextInGroup());
  14988. if (lhs)
  14989. {
  14990. rightIndex = 0;
  14991. group.clear();
  14992. limitedhelper->getGroup(group,lhs);
  14993. }
  14994. else
  14995. {
  14996. eof = true;
  14997. }
  14998. }
  14999. if (group.isItem(rightIndex))
  15000. {
  15001. const void * rhs = group.item(rightIndex++);
  15002. if(helper.match(lhs, rhs))
  15003. {
  15004. const void * ret = joinRecords(lhs, rhs);
  15005. return ret;
  15006. }
  15007. }
  15008. }
  15009. return NULL;
  15010. }
  15011. else
  15012. {
  15013. if (first)
  15014. {
  15015. first = false;
  15016. fillGroup();
  15017. }
  15018. while(!eof)
  15019. {
  15020. if(failingOuterAtmost)
  15021. while(group.isItem(leftIndex))
  15022. {
  15023. const void * ret = joinRecords(group.item(leftIndex++), defaultRight);
  15024. if(ret)
  15025. {
  15026. processed++;
  15027. return ret;
  15028. }
  15029. }
  15030. if((joinLimit == 0) || !group.isItem(rightIndex))
  15031. {
  15032. if(leftOuterJoin && !matchedLeft && !failingLimit)
  15033. {
  15034. const void * ret = joinRecords(group.item(leftIndex), defaultRight);
  15035. if(ret)
  15036. {
  15037. matchedLeft = true;
  15038. processed++;
  15039. return ret;
  15040. }
  15041. }
  15042. leftIndex++;
  15043. matchedLeft = false;
  15044. rightIndex = 0;
  15045. joinLimit = keepLimit;
  15046. }
  15047. if(!group.isItem(leftIndex))
  15048. {
  15049. if(failingLimit || failingOuterAtmost)
  15050. {
  15051. const void * lhs;
  15052. while((lhs = input->nextInGroup()) != NULL) // dualCache never active here
  15053. {
  15054. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15055. ReleaseRoxieRow(lhs);
  15056. if(ret)
  15057. {
  15058. processed++;
  15059. return ret;
  15060. }
  15061. }
  15062. failingLimit.clear();
  15063. }
  15064. if(rightOuterJoin && !failingLimit)
  15065. while(group.isItem(rightOuterIndex))
  15066. if(!matchedRight.item(rightOuterIndex++))
  15067. {
  15068. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1));
  15069. if(ret)
  15070. {
  15071. processed++;
  15072. return ret;
  15073. }
  15074. }
  15075. if(!fillGroup())
  15076. return NULL;
  15077. continue;
  15078. }
  15079. const void * lhs = group.item(leftIndex);
  15080. if(failingLimit)
  15081. {
  15082. leftIndex++;
  15083. const void * ret = joinRecords(lhs, defaultRight, failingLimit);
  15084. if(ret)
  15085. {
  15086. processed++;
  15087. return ret;
  15088. }
  15089. }
  15090. else
  15091. {
  15092. const void * rhs = group.item(rightIndex++);
  15093. if(helper.match(lhs, rhs))
  15094. {
  15095. matchedLeft = true;
  15096. matchedRight.replace(true, rightIndex-1);
  15097. if(!exclude)
  15098. {
  15099. const void * ret = joinRecords(lhs, rhs);
  15100. if(ret)
  15101. {
  15102. processed++;
  15103. joinLimit--;
  15104. return ret;
  15105. }
  15106. }
  15107. }
  15108. }
  15109. }
  15110. return NULL;
  15111. }
  15112. }
  15113. };
  15114. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  15115. {
  15116. public:
  15117. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15118. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15119. {
  15120. }
  15121. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15122. {
  15123. return new CRoxieServerSelfJoinActivity(this, _probeManager);
  15124. }
  15125. };
  15126. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15127. {
  15128. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15129. }
  15130. //=====================================================================================================
  15131. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  15132. {
  15133. private:
  15134. class LookupTable : public CInterface
  15135. {
  15136. public:
  15137. LookupTable(unsigned _size, ICompare * _leftRightCompare, ICompare * _rightCompare, IHash * _leftHash, IHash * _rightHash, bool _dedupOnAdd)
  15138. : leftRightCompare(_leftRightCompare), rightCompare(_rightCompare), leftHash(_leftHash), rightHash(_rightHash), dedupOnAdd(_dedupOnAdd)
  15139. {
  15140. unsigned minsize = (4*_size)/3;
  15141. size = 2;
  15142. while((minsize >>= 1) > 0)
  15143. size <<= 1;
  15144. mask = size - 1;
  15145. table = (const void * *)calloc(size, sizeof(void *));
  15146. findex = BadIndex;
  15147. }
  15148. ~LookupTable()
  15149. {
  15150. unsigned i;
  15151. for(i=0; i<size; i++)
  15152. ReleaseRoxieRow(table[i]);
  15153. free(table);
  15154. }
  15155. void add(const void * right)
  15156. {
  15157. findex = BadIndex;
  15158. unsigned start = rightHash->hash(right) & mask;
  15159. unsigned index = start;
  15160. while(table[index])
  15161. {
  15162. if(dedupOnAdd && (rightCompare->docompare(table[index], right) == 0))
  15163. {
  15164. ReleaseRoxieRow(right);
  15165. return;
  15166. }
  15167. index++;
  15168. if(index==size)
  15169. index = 0;
  15170. if(index==start)
  15171. throwUnexpected(); //table is full, should never happen
  15172. }
  15173. table[index] = right;
  15174. }
  15175. const void *find(const void * left) const
  15176. {
  15177. fstart = leftHash->hash(left) & mask;
  15178. findex = fstart;
  15179. return doFind(left);
  15180. }
  15181. const void *findNext(const void * left) const
  15182. {
  15183. if(findex == BadIndex)
  15184. return NULL;
  15185. advance();
  15186. return doFind(left);
  15187. }
  15188. void advance() const
  15189. {
  15190. findex++;
  15191. if(findex==size)
  15192. findex = 0;
  15193. if(findex==fstart)
  15194. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error hthor lookup join activity (hash table full on lookup)");
  15195. }
  15196. const void *doFind(const void * left) const
  15197. {
  15198. while(table[findex])
  15199. {
  15200. if(leftRightCompare->docompare(left, table[findex]) == 0)
  15201. return table[findex];
  15202. advance();
  15203. }
  15204. findex = BadIndex;
  15205. return NULL;
  15206. }
  15207. private:
  15208. ICompare * leftRightCompare;
  15209. ICompare * rightCompare;
  15210. IHash * leftHash;
  15211. IHash * rightHash;
  15212. unsigned size;
  15213. unsigned mask;
  15214. const void * * table;
  15215. bool dedupOnAdd;
  15216. unsigned mutable fstart;
  15217. unsigned mutable findex;
  15218. static unsigned const BadIndex;
  15219. };
  15220. IHThorHashJoinArg &helper;
  15221. bool leftOuterJoin;
  15222. bool exclude;
  15223. bool eog;
  15224. bool many;
  15225. bool dedupRHS;
  15226. bool matchedGroup;
  15227. const void *left;
  15228. OwnedConstRoxieRow defaultRight;
  15229. Owned<LookupTable> table;
  15230. unsigned keepLimit;
  15231. unsigned atmostLimit;
  15232. unsigned atmostsTriggered;
  15233. unsigned limitLimit;
  15234. bool limitFail;
  15235. bool limitOnFail;
  15236. bool hasGroupLimit;
  15237. bool isSmartJoin;
  15238. unsigned keepCount;
  15239. bool gotMatch;
  15240. bool cloneLeft;
  15241. ConstPointerArray rightGroup;
  15242. aindex_t rightGroupIndex;
  15243. Owned<IException> failingLimit;
  15244. ConstPointerArray filteredRight;
  15245. ThorActivityKind activityKind;
  15246. Owned<IEngineRowAllocator> defaultRightAllocator;
  15247. void createDefaultRight()
  15248. {
  15249. if (!defaultRight)
  15250. {
  15251. if (!defaultRightAllocator)
  15252. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15253. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15254. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15255. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15256. }
  15257. }
  15258. public:
  15259. CRoxieServerLookupJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15260. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorHashJoinArg &)basehelper)
  15261. {
  15262. unsigned joinFlags = helper.getJoinFlags();
  15263. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15264. assertex((joinFlags & JFrightouter) == 0);
  15265. exclude = (joinFlags & JFexclude) != 0;
  15266. many = (joinFlags & JFmanylookup) != 0;
  15267. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15268. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  15269. left = NULL;
  15270. activityKind = factory->getKind();
  15271. eog = false;
  15272. matchedGroup = false;
  15273. gotMatch = false;
  15274. keepLimit = 0;
  15275. keepCount = 0;
  15276. atmostLimit = 0;
  15277. atmostsTriggered = 0;
  15278. limitLimit = 0;
  15279. hasGroupLimit = false;
  15280. isSmartJoin = (joinFlags & JFsmart) != 0;
  15281. getLimitType(joinFlags, limitFail, limitOnFail);
  15282. }
  15283. void loadRight()
  15284. {
  15285. ConstPointerArray rightset;
  15286. unsigned i = 0;
  15287. try
  15288. {
  15289. const void * next;
  15290. while(true)
  15291. {
  15292. next = input1->nextInGroup();
  15293. if(!next)
  15294. next = input1->nextInGroup();
  15295. if(!next)
  15296. break;
  15297. rightset.append(next);
  15298. }
  15299. unsigned rightord = rightset.ordinality();
  15300. table.setown(new LookupTable(rightord, helper.queryCompareLeftRight(), helper.queryCompareRight(), helper.queryHashLeft(), helper.queryHashRight(), dedupRHS));
  15301. for(i=0; i<rightord; i++)
  15302. table->add(rightset.item(i));
  15303. }
  15304. catch (...)
  15305. {
  15306. unsigned rightord = rightset.ordinality();
  15307. for ( ; i<rightord; i++)
  15308. ReleaseRoxieRow(rightset.item(i));
  15309. throw;
  15310. }
  15311. };
  15312. virtual void reset()
  15313. {
  15314. if (atmostsTriggered)
  15315. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  15316. CRoxieServerTwoInputActivity::reset();
  15317. ReleaseClearRoxieRow(left);
  15318. defaultRight.clear();
  15319. table.clear();
  15320. }
  15321. virtual bool needsAllocator() const { return true; }
  15322. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15323. {
  15324. eog = false;
  15325. matchedGroup = false;
  15326. left = NULL;
  15327. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15328. keepLimit = helper.getKeepLimit();
  15329. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  15330. atmostsTriggered = 0;
  15331. atmostLimit = helper.getJoinLimit();
  15332. limitLimit = helper.getMatchAbortLimit();
  15333. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  15334. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  15335. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  15336. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  15337. switch (activityKind)
  15338. {
  15339. case TAKlookupjoin:
  15340. case TAKlookupdenormalizegroup:
  15341. case TAKsmartjoin:
  15342. case TAKsmartdenormalizegroup:
  15343. if (leftOuterJoin)
  15344. createDefaultRight();
  15345. break;
  15346. }
  15347. if (limitOnFail)
  15348. createDefaultRight();
  15349. }
  15350. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15351. {
  15352. if (idx==1)
  15353. input1 = _in;
  15354. else
  15355. {
  15356. if ((helper.getJoinFlags() & JFparallel) != 0)
  15357. {
  15358. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15359. puller->setInput(0, _in);
  15360. _in = puller;
  15361. }
  15362. CRoxieServerActivity::setInput(idx, _in);
  15363. }
  15364. }
  15365. virtual const void * nextInGroup()
  15366. {
  15367. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15368. if(!table)
  15369. loadRight();
  15370. switch (activityKind)
  15371. {
  15372. case TAKlookupjoin:
  15373. case TAKsmartjoin:
  15374. return nextInGroupJoin();
  15375. case TAKlookupdenormalize:
  15376. case TAKlookupdenormalizegroup:
  15377. case TAKsmartdenormalize:
  15378. case TAKsmartdenormalizegroup:
  15379. return nextInGroupDenormalize();
  15380. }
  15381. throwUnexpected();
  15382. }
  15383. private:
  15384. const void * nextInGroupJoin()
  15385. {
  15386. if(!table)
  15387. loadRight();
  15388. while(true)
  15389. {
  15390. const void * right = NULL;
  15391. if(!left)
  15392. {
  15393. left = input->nextInGroup();
  15394. keepCount = keepLimit;
  15395. if(!left)
  15396. {
  15397. if (isSmartJoin)
  15398. left = input->nextInGroup();
  15399. if (!left)
  15400. {
  15401. if(matchedGroup || eog)
  15402. {
  15403. matchedGroup = false;
  15404. eog = true;
  15405. return NULL;
  15406. }
  15407. eog = true;
  15408. continue;
  15409. }
  15410. }
  15411. eog = false;
  15412. gotMatch = false;
  15413. right = getRightFirst();
  15414. }
  15415. else
  15416. right = getRightNext();
  15417. const void * ret = NULL;
  15418. if(failingLimit)
  15419. {
  15420. ret = joinException(left, failingLimit);
  15421. }
  15422. else
  15423. {
  15424. while(right)
  15425. {
  15426. if(helper.match(left, right))
  15427. {
  15428. gotMatch = true;
  15429. if(exclude)
  15430. break;
  15431. ret = joinRecords(left, right);
  15432. if(ret)
  15433. break;
  15434. }
  15435. right = getRightNext();
  15436. ret = NULL;
  15437. }
  15438. if(leftOuterJoin && !gotMatch)
  15439. {
  15440. ret = joinRecords(left, defaultRight);
  15441. gotMatch = true;
  15442. }
  15443. }
  15444. if(ret)
  15445. {
  15446. matchedGroup = true;
  15447. processed++;
  15448. if(!many || (--keepCount == 0) || failingLimit)
  15449. {
  15450. ReleaseClearRoxieRow(left);
  15451. failingLimit.clear();
  15452. }
  15453. return ret;
  15454. }
  15455. ReleaseClearRoxieRow(left);
  15456. }
  15457. }
  15458. const void * nextInGroupDenormalize()
  15459. {
  15460. while(true)
  15461. {
  15462. left = input->nextInGroup();
  15463. if(!left)
  15464. {
  15465. if (!matchedGroup || isSmartJoin)
  15466. left = input->nextInGroup();
  15467. if (!left)
  15468. {
  15469. matchedGroup = false;
  15470. return NULL;
  15471. }
  15472. }
  15473. gotMatch = false;
  15474. const void * right = getRightFirst();
  15475. const void * ret = NULL;
  15476. if (failingLimit)
  15477. ret = joinException(left, failingLimit);
  15478. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  15479. {
  15480. OwnedConstRoxieRow newLeft;
  15481. newLeft.set(left);
  15482. unsigned rowSize = 0;
  15483. unsigned leftCount = 0;
  15484. keepCount = keepLimit;
  15485. while (right)
  15486. {
  15487. try
  15488. {
  15489. if (helper.match(left, right))
  15490. {
  15491. gotMatch = true;
  15492. if (exclude)
  15493. break;
  15494. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15495. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15496. if (thisSize)
  15497. {
  15498. rowSize = thisSize;
  15499. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15500. }
  15501. if(!many || (--keepCount == 0))
  15502. break;
  15503. }
  15504. right = getRightNext();
  15505. }
  15506. catch (IException *E)
  15507. {
  15508. throw makeWrappedException(E);
  15509. }
  15510. }
  15511. if (rowSize)
  15512. ret = newLeft.getClear();
  15513. else if (leftOuterJoin && !gotMatch)
  15514. {
  15515. ret = left;
  15516. left = NULL;
  15517. }
  15518. }
  15519. else
  15520. {
  15521. filteredRight.kill();
  15522. keepCount = keepLimit;
  15523. while (right)
  15524. {
  15525. if (helper.match(left, right))
  15526. {
  15527. gotMatch = true;
  15528. if(exclude)
  15529. break;
  15530. filteredRight.append(right);
  15531. if(!many || (--keepCount == 0))
  15532. break;
  15533. }
  15534. right = getRightNext();
  15535. }
  15536. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  15537. ret = denormalizeRecords(left, filteredRight);
  15538. filteredRight.kill();
  15539. }
  15540. ReleaseRoxieRow(left);
  15541. left = NULL;
  15542. failingLimit.clear();
  15543. if(ret)
  15544. {
  15545. matchedGroup = true;
  15546. processed++;
  15547. return ret;
  15548. }
  15549. }
  15550. }
  15551. const void * joinRecords(const void * left, const void * right)
  15552. {
  15553. if (cloneLeft)
  15554. {
  15555. LinkRoxieRow(left);
  15556. return left;
  15557. }
  15558. try
  15559. {
  15560. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15561. unsigned outSize = helper.transform(rowBuilder, left, right);
  15562. if (outSize)
  15563. return rowBuilder.finalizeRowClear(outSize);
  15564. else
  15565. return NULL;
  15566. }
  15567. catch (IException *E)
  15568. {
  15569. throw makeWrappedException(E);
  15570. }
  15571. }
  15572. const void * joinException(const void * left, IException * except)
  15573. {
  15574. try
  15575. {
  15576. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15577. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
  15578. if (outSize)
  15579. return rowBuilder.finalizeRowClear(outSize);
  15580. else
  15581. return NULL;
  15582. }
  15583. catch (IException *E)
  15584. {
  15585. throw makeWrappedException(E);
  15586. }
  15587. }
  15588. const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
  15589. {
  15590. try
  15591. {
  15592. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15593. unsigned numRows = rows.ordinality();
  15594. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15595. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
  15596. if (outSize)
  15597. return rowBuilder.finalizeRowClear(outSize);
  15598. else
  15599. return NULL;
  15600. }
  15601. catch (IException *E)
  15602. {
  15603. throw makeWrappedException(E);
  15604. }
  15605. }
  15606. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  15607. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  15608. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  15609. const void *fillRightGroup()
  15610. {
  15611. rightGroup.kill();
  15612. for(const void * right = table->find(left); right; right = table->findNext(left))
  15613. {
  15614. rightGroup.append(right);
  15615. if(rightGroup.ordinality() > limitLimit)
  15616. {
  15617. if(limitFail)
  15618. failLimit();
  15619. gotMatch = true;
  15620. if (ctx->queryDebugContext())
  15621. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  15622. if(limitOnFail)
  15623. {
  15624. assertex(!failingLimit);
  15625. try
  15626. {
  15627. failLimit();
  15628. }
  15629. catch(IException * e)
  15630. {
  15631. failingLimit.setown(e);
  15632. }
  15633. assertex(failingLimit != NULL);
  15634. }
  15635. else
  15636. {
  15637. rightGroup.kill();
  15638. }
  15639. break;
  15640. }
  15641. if(rightGroup.ordinality() > atmostLimit)
  15642. {
  15643. atmostsTriggered++;
  15644. rightGroup.kill();
  15645. break;
  15646. }
  15647. }
  15648. rightGroupIndex = 0;
  15649. return readRightGroup();
  15650. }
  15651. void failLimit()
  15652. {
  15653. helper.onMatchAbortLimitExceeded();
  15654. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  15655. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  15656. {
  15657. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  15658. }
  15659. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  15660. }
  15661. };
  15662. unsigned const CRoxieServerLookupJoinActivity::LookupTable::BadIndex(static_cast<unsigned>(-1));
  15663. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  15664. {
  15665. public:
  15666. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15667. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  15668. {
  15669. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  15670. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  15671. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  15672. }
  15673. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  15674. {
  15675. return new CRoxieServerLookupJoinActivity(this, _probeManager);
  15676. }
  15677. };
  15678. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  15679. {
  15680. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  15681. }
  15682. //=====================================================================================================
  15683. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  15684. {
  15685. private:
  15686. IHThorAllJoinArg &helper;
  15687. bool leftOuterJoin;
  15688. bool rightOuterJoin;
  15689. bool exclude;
  15690. OwnedConstRoxieRow defaultRight;
  15691. OwnedConstRoxieRow defaultLeft;
  15692. Owned<IEngineRowAllocator> defaultRightAllocator;
  15693. Owned<IEngineRowAllocator> defaultLeftAllocator;
  15694. const void *left;
  15695. unsigned countForLeft;
  15696. ConstPointerArray rightset;
  15697. BoolArray matchedRight; // MORE - could use a bitset...
  15698. unsigned keepLimit;
  15699. bool started;
  15700. bool eog;
  15701. bool eos;
  15702. bool matchedLeft;
  15703. bool matchedGroup;
  15704. bool leftIsGrouped;
  15705. bool cloneLeft;
  15706. unsigned rightIndex;
  15707. unsigned rightOrdinality;
  15708. ThorActivityKind activityKind;
  15709. ConstPointerArray filteredRight;
  15710. void createDefaultLeft()
  15711. {
  15712. if (!defaultLeft)
  15713. {
  15714. if (!defaultLeftAllocator)
  15715. defaultLeftAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input->queryOutputMeta(), activityId));
  15716. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  15717. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  15718. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  15719. }
  15720. }
  15721. void createDefaultRight()
  15722. {
  15723. if (!defaultRight)
  15724. {
  15725. if (!defaultRightAllocator)
  15726. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(input1->queryOutputMeta(), activityId));
  15727. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  15728. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  15729. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15730. }
  15731. }
  15732. public:
  15733. CRoxieServerAllJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15734. : CRoxieServerTwoInputActivity(_factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  15735. {
  15736. unsigned joinFlags = helper.getJoinFlags();
  15737. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  15738. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  15739. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  15740. keepLimit = (unsigned) -1;
  15741. exclude = (joinFlags & JFexclude) != 0;
  15742. left = NULL;
  15743. started = true;
  15744. eog = false;
  15745. eos = false;
  15746. matchedLeft = false;
  15747. matchedGroup = false;
  15748. activityKind = factory->getKind();
  15749. rightIndex = 0;
  15750. rightOrdinality = 0;
  15751. leftIsGrouped = false;
  15752. countForLeft = 0;
  15753. }
  15754. virtual void reset()
  15755. {
  15756. defaultRight.clear();
  15757. defaultLeft.clear();
  15758. ReleaseRoxieRowSet(rightset);
  15759. matchedRight.kill();
  15760. CRoxieServerTwoInputActivity::reset();
  15761. }
  15762. virtual bool needsAllocator() const { return true; }
  15763. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15764. {
  15765. eog = false;
  15766. eos = false;
  15767. matchedLeft = false;
  15768. matchedGroup = false;
  15769. started = false;
  15770. left = NULL;
  15771. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  15772. keepLimit = helper.getKeepLimit();
  15773. if(keepLimit==0)
  15774. keepLimit = (unsigned) -1;
  15775. countForLeft = keepLimit;
  15776. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  15777. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  15778. createDefaultRight();
  15779. if(rightOuterJoin)
  15780. createDefaultLeft();
  15781. }
  15782. void loadRight()
  15783. {
  15784. const void * next;
  15785. while(true)
  15786. {
  15787. next = input1->nextInGroup();
  15788. if(!next)
  15789. next = input1->nextInGroup();
  15790. if(!next)
  15791. break;
  15792. rightset.append(next);
  15793. matchedRight.append(false);
  15794. }
  15795. rightIndex = 0;
  15796. rightOrdinality = rightset.ordinality();
  15797. }
  15798. virtual void setInput(unsigned idx, IRoxieInput *_in)
  15799. {
  15800. if (idx==1)
  15801. input1 = _in;
  15802. else
  15803. {
  15804. if ((helper.getJoinFlags() & JFparallel) != 0)
  15805. {
  15806. puller.setown(new CRoxieServerReadAheadInput(0)); // MORE - cant ask context for parallelJoinPreload as context is not yet set up.
  15807. puller->setInput(0, _in);
  15808. _in = puller;
  15809. }
  15810. CRoxieServerActivity::setInput(idx, _in);
  15811. }
  15812. }
  15813. const void * joinRecords(const void * left, const void * right)
  15814. {
  15815. // MORE - could share some code with lookup join
  15816. if (cloneLeft)
  15817. {
  15818. LinkRoxieRow(left);
  15819. return left;
  15820. }
  15821. try
  15822. {
  15823. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15824. unsigned outSize = helper.transform(rowBuilder, left, right);
  15825. if (outSize)
  15826. return rowBuilder.finalizeRowClear(outSize);
  15827. else
  15828. return NULL;
  15829. }
  15830. catch (IException *E)
  15831. {
  15832. throw makeWrappedException(E);
  15833. }
  15834. }
  15835. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
  15836. {
  15837. try
  15838. {
  15839. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15840. unsigned numRows = rows.ordinality();
  15841. const void * right = numRows ? rows.item(0) : defaultRight.get();
  15842. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
  15843. if (outSize)
  15844. return rowBuilder.finalizeRowClear(outSize);
  15845. else
  15846. return NULL;
  15847. }
  15848. catch (IException *E)
  15849. {
  15850. throw makeWrappedException(E);
  15851. }
  15852. }
  15853. virtual const void *nextInGroup()
  15854. {
  15855. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  15856. if(!started)
  15857. {
  15858. started = true;
  15859. left = input->nextInGroup();
  15860. matchedLeft = false;
  15861. countForLeft = keepLimit;
  15862. if(left == NULL)
  15863. {
  15864. eos = true;
  15865. return NULL;
  15866. }
  15867. loadRight();
  15868. }
  15869. const void * ret;
  15870. const void * right;
  15871. if(eos)
  15872. return NULL;
  15873. while(true)
  15874. {
  15875. ret = NULL;
  15876. if((rightIndex == rightOrdinality) || (countForLeft==0))
  15877. {
  15878. if(leftOuterJoin && left && !matchedLeft)
  15879. {
  15880. switch(activityKind)
  15881. {
  15882. case TAKalljoin:
  15883. ret = joinRecords(left, defaultRight);
  15884. break;
  15885. case TAKalldenormalize:
  15886. ret = left;
  15887. left = NULL;
  15888. break;
  15889. case TAKalldenormalizegroup:
  15890. filteredRight.kill();
  15891. ret = denormalizeRecords(left, filteredRight);
  15892. break;
  15893. default:
  15894. throwUnexpected();
  15895. }
  15896. }
  15897. rightIndex = 0;
  15898. ReleaseRoxieRow(left);
  15899. left = NULL;
  15900. if(ret)
  15901. {
  15902. matchedGroup = true;
  15903. processed++;
  15904. return ret;
  15905. }
  15906. }
  15907. if(!left)
  15908. {
  15909. left = input->nextInGroup();
  15910. matchedLeft = false;
  15911. countForLeft = keepLimit;
  15912. }
  15913. if(!left)
  15914. {
  15915. if(eog)
  15916. {
  15917. eos = true;
  15918. matchedGroup = false;
  15919. return NULL;
  15920. }
  15921. eog = true;
  15922. if (matchedGroup && leftIsGrouped)
  15923. {
  15924. matchedGroup = false;
  15925. return NULL;
  15926. }
  15927. matchedGroup = false;
  15928. continue;
  15929. }
  15930. eog = false;
  15931. switch(activityKind)
  15932. {
  15933. case TAKalljoin:
  15934. while(rightIndex < rightOrdinality)
  15935. {
  15936. right = rightset.item(rightIndex);
  15937. if(helper.match(left, right))
  15938. {
  15939. matchedLeft = true;
  15940. matchedRight.replace(true, rightIndex);
  15941. if(!exclude)
  15942. ret = joinRecords(left, right);
  15943. }
  15944. rightIndex++;
  15945. if(ret)
  15946. {
  15947. countForLeft--;
  15948. matchedGroup = true;
  15949. processed++;
  15950. return ret;
  15951. }
  15952. }
  15953. break;
  15954. case TAKalldenormalize:
  15955. {
  15956. OwnedConstRoxieRow newLeft;
  15957. newLeft.set(left);
  15958. unsigned rowSize = 0;
  15959. unsigned leftCount = 0;
  15960. while((rightIndex < rightOrdinality) && countForLeft)
  15961. {
  15962. right = rightset.item(rightIndex);
  15963. if(helper.match(left, right))
  15964. {
  15965. matchedLeft = true;
  15966. matchedRight.replace(true, rightIndex);
  15967. if(!exclude)
  15968. {
  15969. try
  15970. {
  15971. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15972. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
  15973. if(thisSize)
  15974. {
  15975. rowSize = thisSize;
  15976. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  15977. --countForLeft;
  15978. }
  15979. }
  15980. catch (IException *e)
  15981. {
  15982. throw makeWrappedException(e);
  15983. }
  15984. }
  15985. }
  15986. rightIndex++;
  15987. }
  15988. if(rowSize)
  15989. {
  15990. processed++;
  15991. return newLeft.getClear();
  15992. }
  15993. }
  15994. break;
  15995. case TAKalldenormalizegroup:
  15996. filteredRight.kill();
  15997. while((rightIndex < rightOrdinality) && countForLeft)
  15998. {
  15999. right = rightset.item(rightIndex);
  16000. if(helper.match(left, right))
  16001. {
  16002. matchedLeft = true;
  16003. matchedRight.replace(true, rightIndex);
  16004. filteredRight.append(right);
  16005. --countForLeft;
  16006. }
  16007. ++rightIndex;
  16008. }
  16009. if(!exclude && filteredRight.ordinality())
  16010. {
  16011. ret = denormalizeRecords(left, filteredRight);
  16012. filteredRight.kill();
  16013. if(ret)
  16014. {
  16015. processed++;
  16016. return ret;
  16017. }
  16018. }
  16019. break;
  16020. default:
  16021. throwUnexpected();
  16022. }
  16023. }
  16024. }
  16025. };
  16026. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  16027. {
  16028. public:
  16029. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16030. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16031. {
  16032. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  16033. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  16034. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  16035. }
  16036. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16037. {
  16038. return new CRoxieServerAllJoinActivity(this, _probeManager);
  16039. }
  16040. };
  16041. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16042. {
  16043. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16044. }
  16045. //=====================================================================================================
  16046. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  16047. {
  16048. unsigned limit;
  16049. bool hasBest;
  16050. bool eoi;
  16051. const void **sorted;
  16052. unsigned sortedCount;
  16053. unsigned curIndex;
  16054. IHThorTopNArg &helper;
  16055. ICompare &compare;
  16056. public:
  16057. CRoxieServerTopNActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16058. : CRoxieServerLateStartActivity(_factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  16059. {
  16060. sorted = NULL;
  16061. sortedCount = 0;
  16062. curIndex = 0;
  16063. limit = 0;
  16064. eoi = false;
  16065. hasBest = false;
  16066. }
  16067. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16068. {
  16069. assertex(sorted == NULL);
  16070. sortedCount = 0;
  16071. curIndex = 0;
  16072. eoi = false;
  16073. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  16074. limit = (unsigned) helper.getLimit();
  16075. hasBest = helper.hasBest();
  16076. lateStart(parentExtractSize, parentExtract, limit > 0);
  16077. // MORE - should we use an expanding array instead?
  16078. if (limit > 0)
  16079. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  16080. }
  16081. virtual void reset()
  16082. {
  16083. if (sorted)
  16084. {
  16085. while(curIndex < sortedCount)
  16086. ReleaseRoxieRow(sorted[curIndex++]);
  16087. ReleaseRoxieRow(sorted);
  16088. }
  16089. sorted = NULL;
  16090. CRoxieServerLateStartActivity::reset();
  16091. }
  16092. bool abortEarly()
  16093. {
  16094. if (hasBest && (sortedCount == limit))
  16095. {
  16096. int compare = helper.compareBest(sorted[sortedCount-1]);
  16097. if (compare == 0)
  16098. {
  16099. if (meta.isGrouped())
  16100. {
  16101. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  16102. const void * next;
  16103. while ((next = input->nextInGroup()) != NULL)
  16104. ReleaseRoxieRow(next);
  16105. }
  16106. else
  16107. eoi = true;
  16108. return true;
  16109. }
  16110. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  16111. if (compare < 0)
  16112. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  16113. }
  16114. return false;
  16115. }
  16116. void getSorted()
  16117. {
  16118. curIndex = 0;
  16119. sortedCount = 0;
  16120. if(eoi)
  16121. return;
  16122. const void * next;
  16123. while ((next = input->nextInGroup()) != NULL)
  16124. {
  16125. if (sortedCount < limit)
  16126. {
  16127. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  16128. sortedCount++;
  16129. if(abortEarly())
  16130. return;
  16131. }
  16132. else
  16133. {
  16134. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  16135. {
  16136. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  16137. ReleaseRoxieRow(sorted[sortedCount]);
  16138. if(abortEarly())
  16139. return;
  16140. }
  16141. else
  16142. {
  16143. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  16144. }
  16145. }
  16146. }
  16147. }
  16148. virtual const void * nextInGroup()
  16149. {
  16150. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16151. if (eof)
  16152. return NULL;
  16153. if (curIndex >= sortedCount)
  16154. {
  16155. bool eog = sortedCount != 0;
  16156. getSorted();
  16157. if(sortedCount == 0)
  16158. {
  16159. eof = true;
  16160. return NULL;
  16161. }
  16162. if (eog)
  16163. return NULL;
  16164. }
  16165. processed++;
  16166. return sorted[curIndex++];
  16167. }
  16168. };
  16169. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  16170. {
  16171. public:
  16172. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16173. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16174. {
  16175. }
  16176. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16177. {
  16178. return new CRoxieServerTopNActivity(this, _probeManager);
  16179. }
  16180. };
  16181. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16182. {
  16183. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16184. }
  16185. //=================================================================================
  16186. class CRoxieServerLimitActivity : public CRoxieServerActivity
  16187. {
  16188. protected:
  16189. unsigned __int64 rowLimit;
  16190. IHThorLimitArg &helper;
  16191. public:
  16192. CRoxieServerLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16193. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  16194. {
  16195. rowLimit = 0;
  16196. }
  16197. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16198. {
  16199. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16200. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  16201. }
  16202. virtual const void *nextInGroup()
  16203. {
  16204. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16205. const void * ret = input->nextInGroup();
  16206. if (ret)
  16207. {
  16208. processed++;
  16209. if (processed > rowLimit)
  16210. {
  16211. ReleaseRoxieRow(ret);
  16212. if (traceLevel > 4)
  16213. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16214. helper.onLimitExceeded();
  16215. }
  16216. }
  16217. return ret;
  16218. }
  16219. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16220. {
  16221. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16222. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16223. if (ret)
  16224. {
  16225. if (wasCompleteMatch)
  16226. processed++;
  16227. if (processed > rowLimit)
  16228. {
  16229. ReleaseRoxieRow(ret);
  16230. if (traceLevel > 4)
  16231. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  16232. helper.onLimitExceeded();
  16233. }
  16234. }
  16235. return ret;
  16236. }
  16237. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16238. {
  16239. return input->gatherConjunctions(collector);
  16240. }
  16241. virtual void resetEOF()
  16242. {
  16243. //Do not reset the rowLimit
  16244. input->resetEOF();
  16245. }
  16246. IInputSteppingMeta * querySteppingMeta()
  16247. {
  16248. return input->querySteppingMeta();
  16249. }
  16250. };
  16251. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  16252. {
  16253. public:
  16254. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16255. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16256. {
  16257. }
  16258. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16259. {
  16260. return new CRoxieServerLimitActivity(this, _probeManager);
  16261. }
  16262. };
  16263. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16264. {
  16265. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16266. }
  16267. //=====================================================================================================
  16268. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  16269. {
  16270. ConstPointerArray buff;
  16271. bool started;
  16272. unsigned index;
  16273. IHThorLimitTransformExtra * transformExtra;
  16274. public:
  16275. CRoxieServerSkipLimitActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  16276. : CRoxieServerLimitActivity(_factory, _probeManager)
  16277. {
  16278. transformExtra = NULL;
  16279. started = false;
  16280. index = 0;
  16281. if (_onFail)
  16282. transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
  16283. }
  16284. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16285. {
  16286. started = false;
  16287. index = 0;
  16288. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  16289. }
  16290. virtual void reset()
  16291. {
  16292. while (buff.isItem(index))
  16293. ReleaseRoxieRow(buff.item(index++));
  16294. buff.kill();
  16295. started = false;
  16296. CRoxieServerLimitActivity::reset();
  16297. }
  16298. virtual const void *nextInGroup()
  16299. {
  16300. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16301. if (!started)
  16302. pullInput();
  16303. if (buff.isItem(index))
  16304. {
  16305. const void * next = buff.item(index++);
  16306. if(next)
  16307. processed++;
  16308. return next;
  16309. }
  16310. return NULL;
  16311. }
  16312. protected:
  16313. void pullInput()
  16314. {
  16315. unsigned count = 0;
  16316. loop
  16317. {
  16318. const void * next = input->nextInGroup();
  16319. if (next == NULL)
  16320. {
  16321. next = input->nextInGroup();
  16322. if(next == NULL)
  16323. break;
  16324. buff.append(NULL);
  16325. }
  16326. count++;
  16327. if (count > rowLimit)
  16328. {
  16329. ReleaseRoxieRow(next);
  16330. ReleaseRoxieRowSet(buff);
  16331. if (ctx->queryDebugContext())
  16332. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16333. if (transformExtra)
  16334. {
  16335. createRowAllocator();
  16336. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16337. size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
  16338. if (outSize)
  16339. buff.append(rowBuilder.finalizeRowClear(outSize));
  16340. }
  16341. break;
  16342. }
  16343. buff.append(next);
  16344. }
  16345. started = true;
  16346. }
  16347. };
  16348. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  16349. {
  16350. public:
  16351. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16352. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16353. {
  16354. }
  16355. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16356. {
  16357. return new CRoxieServerSkipLimitActivity(this, _probeManager, kind==TAKcreaterowlimit);
  16358. }
  16359. };
  16360. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16361. {
  16362. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16363. }
  16364. //=================================================================================
  16365. class CRoxieServerCatchActivity : public CRoxieServerActivity
  16366. {
  16367. IHThorCatchArg &helper;
  16368. public:
  16369. CRoxieServerCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16370. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  16371. {
  16372. }
  16373. virtual const void *nextInGroup()
  16374. {
  16375. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16376. try
  16377. {
  16378. const void *ret = input->nextInGroup();
  16379. if (ret)
  16380. processed++;
  16381. return ret;
  16382. }
  16383. catch (IException *E)
  16384. {
  16385. E->Release();
  16386. helper.onExceptionCaught();
  16387. }
  16388. catch (...)
  16389. {
  16390. helper.onExceptionCaught();
  16391. }
  16392. throwUnexpected(); // onExceptionCaught should have thrown something
  16393. }
  16394. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  16395. {
  16396. try
  16397. {
  16398. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16399. const void * ret = input->nextSteppedGE(seek, numFields, wasCompleteMatch, stepExtra);
  16400. if (ret && wasCompleteMatch)
  16401. processed++;
  16402. return ret;
  16403. }
  16404. catch (IException *E)
  16405. {
  16406. E->Release();
  16407. helper.onExceptionCaught();
  16408. }
  16409. catch (...)
  16410. {
  16411. helper.onExceptionCaught();
  16412. }
  16413. throwUnexpected(); // onExceptionCaught should have thrown something
  16414. }
  16415. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  16416. {
  16417. return input->gatherConjunctions(collector);
  16418. }
  16419. virtual void resetEOF()
  16420. {
  16421. input->resetEOF(); // MORE - why not in base class?
  16422. }
  16423. IInputSteppingMeta * querySteppingMeta()
  16424. {
  16425. return input->querySteppingMeta();
  16426. }
  16427. };
  16428. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  16429. {
  16430. ConstPointerArray buff;
  16431. bool started;
  16432. unsigned index;
  16433. IHThorCatchArg &helper;
  16434. bool createRow;
  16435. public:
  16436. CRoxieServerSkipCatchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  16437. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  16438. {
  16439. started = false;
  16440. index = 0;
  16441. }
  16442. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16443. {
  16444. started = false;
  16445. index = 0;
  16446. try
  16447. {
  16448. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16449. }
  16450. catch (IException *E)
  16451. {
  16452. onException(E);
  16453. started = true;
  16454. }
  16455. catch (...)
  16456. {
  16457. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16458. started = true;
  16459. }
  16460. }
  16461. virtual void reset()
  16462. {
  16463. while (buff.isItem(index))
  16464. ReleaseRoxieRow(buff.item(index++));
  16465. buff.kill();
  16466. started = false;
  16467. CRoxieServerActivity::reset();
  16468. }
  16469. virtual const void *nextInGroup()
  16470. {
  16471. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16472. if (!started)
  16473. pullInput();
  16474. if (buff.isItem(index))
  16475. {
  16476. const void * next = buff.item(index++);
  16477. if(next)
  16478. processed++;
  16479. return next;
  16480. }
  16481. return NULL;
  16482. }
  16483. protected:
  16484. void onException(IException *E)
  16485. {
  16486. input->stop(true);
  16487. ReleaseRoxieRowSet(buff);
  16488. if (createRow)
  16489. {
  16490. createRowAllocator();
  16491. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16492. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  16493. if (outSize)
  16494. buff.append(rowBuilder.finalizeRowClear(outSize));
  16495. }
  16496. E->Release();
  16497. }
  16498. void pullInput()
  16499. {
  16500. try
  16501. {
  16502. bool EOGseen = false;
  16503. loop
  16504. {
  16505. const void * next = input->nextInGroup();
  16506. buff.append(next);
  16507. if (next == NULL)
  16508. {
  16509. if (EOGseen)
  16510. break;
  16511. EOGseen = true;
  16512. }
  16513. else
  16514. EOGseen = false;
  16515. }
  16516. }
  16517. catch (IException *E)
  16518. {
  16519. onException(E);
  16520. }
  16521. catch (...)
  16522. {
  16523. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  16524. }
  16525. started = true;
  16526. }
  16527. };
  16528. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  16529. {
  16530. public:
  16531. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16532. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16533. {
  16534. }
  16535. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16536. {
  16537. switch (kind)
  16538. {
  16539. case TAKcatch:
  16540. return new CRoxieServerCatchActivity(this, _probeManager);
  16541. case TAKskipcatch:
  16542. return new CRoxieServerSkipCatchActivity(this, _probeManager, false);
  16543. case TAKcreaterowcatch:
  16544. return new CRoxieServerSkipCatchActivity(this, _probeManager, true);
  16545. default:
  16546. throwUnexpected();
  16547. }
  16548. }
  16549. };
  16550. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  16551. {
  16552. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  16553. }
  16554. //=================================================================================
  16555. class CRoxieServerCaseActivity : public CRoxieServerActivity
  16556. {
  16557. IHThorCaseArg &helper;
  16558. IRoxieInput **inputs;
  16559. unsigned cond;
  16560. bool unusedStopped;
  16561. IRoxieInput *in;
  16562. unsigned numInputs;
  16563. public:
  16564. CRoxieServerCaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  16565. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorCaseArg &)basehelper), numInputs(_numInputs)
  16566. {
  16567. unusedStopped = false;
  16568. cond = 0;
  16569. inputs = new IRoxieInput*[numInputs];
  16570. for (unsigned i = 0; i < numInputs; i++)
  16571. inputs[i] = NULL;
  16572. in = NULL;
  16573. }
  16574. ~CRoxieServerCaseActivity()
  16575. {
  16576. delete [] inputs;
  16577. }
  16578. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16579. {
  16580. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16581. cond = helper.getBranch();
  16582. //CHOOSE defaults to the last argument if out of range.
  16583. if (cond >= numInputs)
  16584. cond = numInputs - 1;
  16585. inputs[cond]->start(parentExtractSize, parentExtract, paused);
  16586. for (unsigned idx = 0; idx < numInputs; idx++)
  16587. {
  16588. if (idx!=cond)
  16589. inputs[idx]->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16590. }
  16591. in = inputs[cond];
  16592. unusedStopped = true;
  16593. }
  16594. virtual void stop(bool aborting)
  16595. {
  16596. for (unsigned idx = 0; idx < numInputs; idx++)
  16597. {
  16598. if (idx==cond || !unusedStopped)
  16599. inputs[idx]->stop(aborting);
  16600. }
  16601. CRoxieServerActivity::stop(aborting);
  16602. }
  16603. virtual void reset()
  16604. {
  16605. for (unsigned idx = 0; idx < numInputs; idx++)
  16606. {
  16607. inputs[idx]->reset();
  16608. }
  16609. unusedStopped = false;
  16610. in = NULL;
  16611. CRoxieServerActivity::reset();
  16612. }
  16613. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16614. {
  16615. assertex(idx < numInputs);
  16616. inputs[idx] = _in;
  16617. }
  16618. virtual const void *nextInGroup()
  16619. {
  16620. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16621. if (in)
  16622. {
  16623. const void *ret = in->nextInGroup();
  16624. if (ret)
  16625. processed++;
  16626. return ret;
  16627. }
  16628. return NULL;
  16629. }
  16630. };
  16631. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  16632. {
  16633. bool graphInvariant;
  16634. public:
  16635. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16636. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16637. {
  16638. graphInvariant = _graphInvariant;
  16639. }
  16640. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16641. {
  16642. return new CRoxieServerCaseActivity(this, _probeManager, numInputs());
  16643. }
  16644. virtual bool isGraphInvariant() const
  16645. {
  16646. return graphInvariant;
  16647. }
  16648. };
  16649. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16650. {
  16651. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16652. }
  16653. //=================================================================================
  16654. class CRoxieServerIfActivity : public CRoxieServerActivity
  16655. {
  16656. IHThorIfArg &helper;
  16657. IRoxieInput *inputTrue;
  16658. IRoxieInput *inputFalse;
  16659. bool cond;
  16660. bool unusedStopped;
  16661. public:
  16662. CRoxieServerIfActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16663. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16664. {
  16665. inputFalse = NULL;
  16666. inputTrue = NULL;
  16667. unusedStopped = false;
  16668. cond = false;
  16669. }
  16670. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16671. {
  16672. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16673. cond = helper.getCondition();
  16674. if (cond)
  16675. {
  16676. inputTrue->start(parentExtractSize, parentExtract, paused);
  16677. if (inputFalse)
  16678. inputFalse->stop(false); // Note: stopping unused branches early helps us avoid buffering splits too long.
  16679. }
  16680. else
  16681. {
  16682. if (inputFalse)
  16683. inputFalse->start(parentExtractSize, parentExtract, paused);
  16684. inputTrue->stop(false);
  16685. }
  16686. unusedStopped = true;
  16687. }
  16688. virtual void stop(bool aborting)
  16689. {
  16690. if (!unusedStopped || cond)
  16691. inputTrue->stop(aborting);
  16692. if (inputFalse && (!unusedStopped || !cond))
  16693. inputFalse->stop(aborting);
  16694. CRoxieServerActivity::stop(aborting);
  16695. }
  16696. virtual unsigned __int64 queryLocalCycles() const
  16697. {
  16698. __int64 localCycles = totalCycles;
  16699. localCycles -= inputTrue->queryTotalCycles();
  16700. if (inputFalse)
  16701. localCycles -= inputFalse->queryTotalCycles();
  16702. if (localCycles < 0)
  16703. localCycles = 0;
  16704. return localCycles;
  16705. }
  16706. virtual IRoxieInput *queryInput(unsigned idx) const
  16707. {
  16708. switch (idx)
  16709. {
  16710. case 0:
  16711. return inputTrue;
  16712. case 1:
  16713. return inputFalse;
  16714. default:
  16715. return NULL;
  16716. }
  16717. }
  16718. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  16719. {
  16720. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16721. if (in)
  16722. return in->queryIndexReadActivity();
  16723. return NULL;
  16724. }
  16725. virtual void reset()
  16726. {
  16727. CRoxieServerActivity::reset();
  16728. inputTrue->reset();
  16729. if (inputFalse)
  16730. inputFalse->reset();
  16731. unusedStopped = false;
  16732. }
  16733. virtual void setInput(unsigned idx, IRoxieInput *_in)
  16734. {
  16735. if (idx==1)
  16736. inputFalse = _in;
  16737. else
  16738. {
  16739. assertex(!idx);
  16740. inputTrue = _in;
  16741. }
  16742. }
  16743. virtual const void *nextInGroup()
  16744. {
  16745. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16746. IRoxieInput *in = cond ? inputTrue : inputFalse;
  16747. if (in)
  16748. {
  16749. const void * ret;
  16750. if ((ret = in->nextInGroup()) != NULL)
  16751. processed++;
  16752. return ret;
  16753. }
  16754. return NULL;
  16755. }
  16756. };
  16757. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  16758. {
  16759. unsigned input2;
  16760. unsigned input2idx;
  16761. bool graphInvariant;
  16762. public:
  16763. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16764. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  16765. {
  16766. graphInvariant = _graphInvariant;
  16767. input2 = (unsigned)-1;
  16768. input2idx = (unsigned)-1;
  16769. }
  16770. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16771. {
  16772. return new CRoxieServerIfActivity(this, _probeManager);
  16773. }
  16774. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  16775. {
  16776. if (idx==1)
  16777. {
  16778. input2 = source;
  16779. input2idx = sourceidx;
  16780. }
  16781. else
  16782. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  16783. }
  16784. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  16785. {
  16786. switch (idx)
  16787. {
  16788. case 1:
  16789. sourceidx = input2idx;
  16790. return input2;
  16791. case 0:
  16792. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  16793. default:
  16794. return (unsigned) -1;
  16795. }
  16796. }
  16797. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  16798. virtual bool isGraphInvariant() const
  16799. {
  16800. return graphInvariant;
  16801. }
  16802. };
  16803. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _graphInvariant)
  16804. {
  16805. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphInvariant);
  16806. }
  16807. //=================================================================================
  16808. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  16809. {
  16810. CriticalSection ecrit;
  16811. Owned<IException> exception;
  16812. bool executed;
  16813. public:
  16814. CRoxieServerActionBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16815. : CRoxieServerActivity(_factory, _probeManager)
  16816. {
  16817. executed = false;
  16818. }
  16819. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  16820. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  16821. {
  16822. CriticalBlock b(ecrit);
  16823. if (exception)
  16824. throw(exception.getLink());
  16825. if (!executed)
  16826. {
  16827. try
  16828. {
  16829. executed = true;
  16830. start(parentExtractSize, parentExtract, false);
  16831. doExecuteAction(parentExtractSize, parentExtract);
  16832. stop(false);
  16833. }
  16834. catch (IException * E)
  16835. {
  16836. ctx->notifyAbort(E);
  16837. stop(true);
  16838. exception.set(E);
  16839. throw;
  16840. }
  16841. }
  16842. }
  16843. virtual void reset()
  16844. {
  16845. executed = false;
  16846. exception.clear();
  16847. CRoxieServerActivity::reset();
  16848. }
  16849. virtual unsigned __int64 queryLocalCycles() const
  16850. {
  16851. return totalCycles;
  16852. }
  16853. virtual const void *nextInGroup()
  16854. {
  16855. throwUnexpected(); // I am nobody's input
  16856. }
  16857. virtual IRoxieInput *queryInput(unsigned idx) const
  16858. {
  16859. throwUnexpected(); // I am nobody's input
  16860. }
  16861. };
  16862. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  16863. {
  16864. IHThorIfArg &helper;
  16865. public:
  16866. CRoxieServerIfActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16867. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorIfArg &)basehelper)
  16868. {
  16869. }
  16870. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16871. {
  16872. bool cond;
  16873. {
  16874. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  16875. cond = helper.getCondition();
  16876. }
  16877. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  16878. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  16879. }
  16880. };
  16881. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  16882. {
  16883. bool isRoot;
  16884. public:
  16885. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16886. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16887. {
  16888. }
  16889. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16890. {
  16891. return new CRoxieServerIfActionActivity(this, _probeManager);
  16892. }
  16893. virtual bool isSink() const
  16894. {
  16895. return isRoot;
  16896. }
  16897. };
  16898. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16899. {
  16900. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16901. }
  16902. //=================================================================================
  16903. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  16904. {
  16905. public:
  16906. CRoxieServerParallelActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16907. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  16908. {
  16909. }
  16910. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16911. {
  16912. #ifdef PARALLEL_EXECUTE
  16913. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  16914. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  16915. #else
  16916. ForEachItemIn(idx, dependencies)
  16917. {
  16918. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  16919. }
  16920. #endif
  16921. }
  16922. };
  16923. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  16924. {
  16925. bool isRoot;
  16926. public:
  16927. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16928. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16929. {
  16930. assertex(!isRoot); // non-internal should be expanded out..
  16931. }
  16932. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16933. {
  16934. return new CRoxieServerParallelActionActivity(this, _probeManager);
  16935. }
  16936. virtual bool isSink() const
  16937. {
  16938. return isRoot;
  16939. }
  16940. };
  16941. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16942. {
  16943. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16944. }
  16945. //=================================================================================
  16946. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  16947. {
  16948. IHThorSequentialArg &helper;
  16949. public:
  16950. CRoxieServerSequentialActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16951. : CRoxieServerActionBaseActivity(_factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  16952. {
  16953. }
  16954. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  16955. {
  16956. unsigned numBranches = helper.numBranches();
  16957. for (unsigned branch=1; branch <= numBranches; branch++)
  16958. executeDependencies(parentExtractSize, parentExtract, branch);
  16959. }
  16960. };
  16961. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  16962. {
  16963. bool isRoot;
  16964. public:
  16965. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16966. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  16967. {
  16968. }
  16969. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  16970. {
  16971. return new CRoxieServerSequentialActionActivity(this, _probeManager);
  16972. }
  16973. virtual bool isSink() const
  16974. {
  16975. return isRoot;
  16976. }
  16977. };
  16978. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  16979. {
  16980. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  16981. }
  16982. //=================================================================================
  16983. class CRoxieServerWhenActivity : public CRoxieServerActivity
  16984. {
  16985. public:
  16986. CRoxieServerWhenActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16987. : CRoxieServerActivity(_factory, _probeManager)
  16988. {
  16989. savedExtractSize = 0;
  16990. savedExtract = NULL;
  16991. }
  16992. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16993. {
  16994. savedExtractSize = parentExtractSize;
  16995. savedExtract = parentExtract;
  16996. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16997. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  16998. }
  16999. virtual void stop(bool aborting)
  17000. {
  17001. if (state != STATEstopped)
  17002. {
  17003. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  17004. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId); // These ones do
  17005. }
  17006. CRoxieServerActivity::stop(aborting);
  17007. }
  17008. virtual const void *nextInGroup()
  17009. {
  17010. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext()); // bit of a waste of time....
  17011. return input->nextInGroup();
  17012. }
  17013. protected:
  17014. unsigned savedExtractSize;
  17015. const byte *savedExtract;
  17016. };
  17017. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  17018. {
  17019. public:
  17020. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17021. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17022. {
  17023. }
  17024. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17025. {
  17026. return new CRoxieServerWhenActivity(this, _probeManager);
  17027. }
  17028. };
  17029. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17030. {
  17031. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17032. }
  17033. //=================================================================================
  17034. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  17035. {
  17036. public:
  17037. CRoxieServerWhenActionActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17038. : CRoxieServerActionBaseActivity(_factory, _probeManager)
  17039. {
  17040. savedExtractSize = 0;
  17041. savedExtract = NULL;
  17042. }
  17043. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17044. {
  17045. savedExtractSize = parentExtractSize;
  17046. savedExtract = parentExtract;
  17047. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  17048. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  17049. }
  17050. virtual void stop(bool aborting)
  17051. {
  17052. if (state != STATEstopped)
  17053. {
  17054. stopDependencies(savedExtractSize, savedExtract, aborting ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  17055. executeDependencies(savedExtractSize, savedExtract, aborting ? WhenFailureId : WhenSuccessId);
  17056. }
  17057. CRoxieServerActionBaseActivity::stop(aborting);
  17058. }
  17059. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  17060. {
  17061. executeDependencies(parentExtractSize, parentExtract, 1);
  17062. }
  17063. protected:
  17064. unsigned savedExtractSize;
  17065. const byte *savedExtract;
  17066. };
  17067. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  17068. {
  17069. public:
  17070. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17071. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  17072. {
  17073. }
  17074. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17075. {
  17076. return new CRoxieServerWhenActionActivity(this, _probeManager);
  17077. }
  17078. virtual bool isSink() const
  17079. {
  17080. return isRoot;
  17081. }
  17082. private:
  17083. bool isRoot;
  17084. };
  17085. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  17086. {
  17087. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  17088. }
  17089. //=================================================================================
  17090. class CRoxieServerParseActivity : public CRoxieServerActivity, implements IMatchedAction
  17091. {
  17092. IHThorParseArg &helper;
  17093. INlpParser * parser;
  17094. INlpResultIterator * rowIter;
  17095. const void * in;
  17096. char * curSearchText;
  17097. INlpParseAlgorithm * algorithm;
  17098. size32_t curSearchTextLen;
  17099. bool anyThisGroup;
  17100. bool processRecord(const void * inRec)
  17101. {
  17102. if (helper.searchTextNeedsFree())
  17103. rtlFree(curSearchText);
  17104. curSearchTextLen = 0;
  17105. curSearchText = NULL;
  17106. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  17107. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  17108. }
  17109. public:
  17110. CRoxieServerParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm)
  17111. : CRoxieServerActivity(_factory, _probeManager),
  17112. helper((IHThorParseArg &)basehelper), algorithm(_algorithm)
  17113. {
  17114. parser = NULL;
  17115. rowIter = NULL;
  17116. in = NULL;
  17117. curSearchText = NULL;
  17118. anyThisGroup = false;
  17119. curSearchTextLen = 0;
  17120. }
  17121. ~CRoxieServerParseActivity()
  17122. {
  17123. ::Release(parser);
  17124. }
  17125. virtual bool needsAllocator() const { return true; }
  17126. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17127. {
  17128. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17129. parser = algorithm->createParser(_ctx->queryCodeContext(), activityId, helper.queryHelper(), &helper);
  17130. rowIter = parser->queryResultIter();
  17131. }
  17132. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17133. {
  17134. anyThisGroup = false;
  17135. curSearchTextLen = 0;
  17136. curSearchText = NULL;
  17137. in = NULL;
  17138. parser->reset();
  17139. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17140. }
  17141. virtual void reset()
  17142. {
  17143. if (helper.searchTextNeedsFree())
  17144. rtlFree(curSearchText);
  17145. curSearchText = NULL;
  17146. ReleaseClearRoxieRow(in);
  17147. CRoxieServerActivity::reset();
  17148. }
  17149. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  17150. {
  17151. try
  17152. {
  17153. return helper.transform(self, curRecord, results, walker);
  17154. }
  17155. catch (IException *E)
  17156. {
  17157. throw makeWrappedException(E);
  17158. }
  17159. }
  17160. virtual const void * nextInGroup()
  17161. {
  17162. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17163. loop
  17164. {
  17165. if (rowIter->isValid())
  17166. {
  17167. anyThisGroup = true;
  17168. OwnedConstRoxieRow out = rowIter->getRow();
  17169. rowIter->next();
  17170. processed++;
  17171. return out.getClear();
  17172. }
  17173. ReleaseClearRoxieRow(in);
  17174. in = input->nextInGroup();
  17175. if (!in)
  17176. {
  17177. if (anyThisGroup)
  17178. {
  17179. anyThisGroup = false;
  17180. return NULL;
  17181. }
  17182. in = input->nextInGroup();
  17183. if (!in)
  17184. return NULL;
  17185. }
  17186. processRecord(in);
  17187. rowIter->first();
  17188. }
  17189. }
  17190. };
  17191. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  17192. {
  17193. Owned<INlpParseAlgorithm> algorithm;
  17194. Owned<IHThorParseArg> helper;
  17195. public:
  17196. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17197. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17198. {
  17199. helper.setown((IHThorParseArg *) helperFactory());
  17200. algorithm.setown(createThorParser(rc, *helper));
  17201. }
  17202. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17203. {
  17204. return new CRoxieServerParseActivity(this, _probeManager, algorithm);
  17205. }
  17206. };
  17207. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IResourceContext *rc)
  17208. {
  17209. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, rc);
  17210. }
  17211. //=====================================================================================================
  17212. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  17213. {
  17214. IHThorWorkUnitWriteArg &helper;
  17215. bool isReread;
  17216. bool grouped;
  17217. IRoxieServerContext *serverContext;
  17218. public:
  17219. CRoxieServerWorkUnitWriteActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread)
  17220. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  17221. {
  17222. grouped = (helper.getFlags() & POFgrouped) != 0;
  17223. serverContext = NULL;
  17224. }
  17225. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17226. {
  17227. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17228. serverContext = ctx->queryServerContext();
  17229. if (!serverContext)
  17230. {
  17231. throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
  17232. }
  17233. }
  17234. virtual bool needsAllocator() const { return true; }
  17235. virtual void onExecute()
  17236. {
  17237. int sequence = helper.getSequence();
  17238. const char *storedName = helper.queryName();
  17239. if (!storedName)
  17240. storedName = "Dataset";
  17241. MemoryBuffer result;
  17242. FlushingStringBuffer *response = NULL;
  17243. bool saveInContext = (int) sequence < 0 || isReread;
  17244. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  17245. meta.set(input->queryOutputMeta());
  17246. Owned<IOutputRowSerializer> rowSerializer;
  17247. Owned<IXmlWriter> writer;
  17248. if ((int) sequence >= 0)
  17249. {
  17250. response = serverContext->queryResult(sequence);
  17251. if (response)
  17252. {
  17253. response->startDataset("Dataset", helper.queryName(), sequence, (helper.getFlags() & POFextend) != 0);
  17254. if (response->mlFmt==MarkupFmt_XML || response->mlFmt==MarkupFmt_JSON)
  17255. {
  17256. unsigned int writeFlags = serverContext->getXmlFlags();
  17257. if (response->mlFmt==MarkupFmt_JSON)
  17258. writeFlags |= XWFnoindent;
  17259. writer.setown(createIXmlWriter(writeFlags, 1, response, (response->mlFmt==MarkupFmt_JSON) ? WTJSON : WTStandard));
  17260. writer->outputBeginArray("Row");
  17261. }
  17262. }
  17263. }
  17264. if (serverContext->outputResultsToWorkUnit()||(response && response->isRaw))
  17265. {
  17266. createRowAllocator();
  17267. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  17268. }
  17269. __int64 initialProcessed = processed;
  17270. RtlLinkedDatasetBuilder builder(rowAllocator);
  17271. loop
  17272. {
  17273. const void *row = input->nextInGroup();
  17274. if (saveInContext)
  17275. {
  17276. if (row || grouped)
  17277. builder.append(row);
  17278. }
  17279. if (grouped && (processed != initialProcessed))
  17280. {
  17281. if (serverContext->outputResultsToWorkUnit())
  17282. result.append(row == NULL);
  17283. if (response)
  17284. {
  17285. if (response->isRaw)
  17286. response->append(row == NULL);
  17287. else
  17288. {
  17289. response->append("<Row __GroupBreak__=\"1\"/>"); // sensible, but need to handle on input
  17290. }
  17291. }
  17292. }
  17293. if (!row)
  17294. {
  17295. row = input->nextInGroup();
  17296. if (!row)
  17297. break;
  17298. if (saveInContext)
  17299. builder.append(row);
  17300. }
  17301. processed++;
  17302. if (serverContext->outputResultsToWorkUnit())
  17303. {
  17304. CThorDemoRowSerializer serializerTarget(result);
  17305. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17306. }
  17307. if (response)
  17308. {
  17309. if (response->isRaw)
  17310. {
  17311. // MORE - should be able to serialize straight to the response...
  17312. MemoryBuffer rowbuff;
  17313. CThorDemoRowSerializer serializerTarget(rowbuff);
  17314. rowSerializer->serialize(serializerTarget, (const byte *) row);
  17315. response->append(rowbuff.length(), rowbuff.toByteArray());
  17316. }
  17317. else if (writer)
  17318. {
  17319. writer->outputBeginNested("Row", false);
  17320. helper.serializeXml((byte *) row, *writer);
  17321. writer->outputEndNested("Row");
  17322. }
  17323. else
  17324. {
  17325. SimpleOutputWriter x;
  17326. helper.serializeXml((byte *) row, x);
  17327. x.newline();
  17328. response->append(x.str());
  17329. }
  17330. response->incrementRowCount();
  17331. response->flush(false);
  17332. }
  17333. ReleaseRoxieRow(row);
  17334. }
  17335. if (writer)
  17336. writer->outputEndArray("Row");
  17337. if (saveInContext)
  17338. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17339. if (serverContext->outputResultsToWorkUnit())
  17340. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  17341. }
  17342. };
  17343. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  17344. {
  17345. bool isReread;
  17346. public:
  17347. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17348. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17349. {
  17350. isReread = usageCount > 0;
  17351. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  17352. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17353. }
  17354. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17355. {
  17356. return new CRoxieServerWorkUnitWriteActivity(this, _probeManager, isReread);
  17357. }
  17358. };
  17359. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17360. {
  17361. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17362. }
  17363. //=====================================================================================================
  17364. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  17365. {
  17366. IHThorDictionaryWorkUnitWriteArg &helper;
  17367. IRoxieServerContext *serverContext;
  17368. public:
  17369. CRoxieServerWorkUnitWriteDictActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17370. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  17371. {
  17372. serverContext = NULL;
  17373. }
  17374. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17375. {
  17376. CRoxieServerInternalSinkActivity::onCreate(_ctx, _colocalParent);
  17377. serverContext = ctx->queryServerContext();
  17378. if (!serverContext)
  17379. {
  17380. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  17381. }
  17382. }
  17383. virtual bool needsAllocator() const { return true; }
  17384. virtual void onExecute()
  17385. {
  17386. int sequence = helper.getSequence();
  17387. const char *storedName = helper.queryName();
  17388. assertex(storedName && *storedName);
  17389. assertex(sequence < 0);
  17390. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  17391. loop
  17392. {
  17393. const void *row = input->nextInGroup();
  17394. if (!row)
  17395. {
  17396. row = input->nextInGroup();
  17397. if (!row)
  17398. break;
  17399. }
  17400. builder.appendOwn(row);
  17401. processed++;
  17402. }
  17403. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  17404. }
  17405. };
  17406. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  17407. {
  17408. public:
  17409. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17410. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17411. {
  17412. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  17413. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17414. }
  17415. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17416. {
  17417. return new CRoxieServerWorkUnitWriteDictActivity(this, _probeManager);
  17418. }
  17419. };
  17420. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17421. {
  17422. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17423. }
  17424. //=================================================================================
  17425. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  17426. {
  17427. IHThorRemoteResultArg &helper;
  17428. public:
  17429. CRoxieServerRemoteResultActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17430. : CRoxieServerInternalSinkActivity(_factory, _probeManager), helper((IHThorRemoteResultArg &)basehelper)
  17431. {
  17432. }
  17433. virtual void onExecute()
  17434. {
  17435. OwnedConstRoxieRow row = input->nextInGroup();
  17436. helper.sendResult(row); // should be only one row or something has gone wrong!
  17437. }
  17438. };
  17439. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  17440. {
  17441. public:
  17442. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17443. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot)
  17444. {
  17445. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  17446. isInternal = (helper->getSequence()==ResultSequenceInternal);
  17447. }
  17448. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17449. {
  17450. return new CRoxieServerRemoteResultActivity(this, _probeManager);
  17451. }
  17452. };
  17453. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, unsigned _usageCount, bool _isRoot)
  17454. {
  17455. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _usageCount, _isRoot);
  17456. }
  17457. //=================================================================================
  17458. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  17459. {
  17460. IHThorXmlParseArg &helper;
  17461. Owned<IXMLParse> xmlParser;
  17462. const void * in;
  17463. char * srchStr;
  17464. unsigned numProcessedLastGroup;
  17465. bool srchStrNeedsFree;
  17466. Owned<IColumnProvider> lastMatch;
  17467. public:
  17468. IMPLEMENT_IINTERFACE;
  17469. CRoxieServerXmlParseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17470. : CRoxieServerActivity(_factory, _probeManager),
  17471. helper((IHThorXmlParseArg &)basehelper)
  17472. {
  17473. srchStrNeedsFree = helper.searchTextNeedsFree();
  17474. numProcessedLastGroup = 0;
  17475. srchStr = NULL;
  17476. in = NULL;
  17477. }
  17478. ~CRoxieServerXmlParseActivity()
  17479. {
  17480. }
  17481. virtual bool needsAllocator() const { return true; }
  17482. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17483. {
  17484. numProcessedLastGroup = 0;
  17485. srchStr = NULL;
  17486. in = NULL;
  17487. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17488. }
  17489. virtual void reset()
  17490. {
  17491. if (helper.searchTextNeedsFree())
  17492. rtlFree(srchStr);
  17493. srchStr = NULL;
  17494. ReleaseClearRoxieRow(in);
  17495. xmlParser.clear();
  17496. CRoxieServerActivity::reset();
  17497. }
  17498. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17499. {
  17500. lastMatch.set(&entry);
  17501. }
  17502. virtual const void *nextInGroup()
  17503. {
  17504. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  17505. loop
  17506. {
  17507. if(xmlParser)
  17508. {
  17509. loop
  17510. {
  17511. if(!xmlParser->next())
  17512. {
  17513. if (srchStrNeedsFree)
  17514. {
  17515. rtlFree(srchStr);
  17516. srchStr = NULL;
  17517. }
  17518. xmlParser.clear();
  17519. break;
  17520. }
  17521. if(lastMatch)
  17522. {
  17523. try
  17524. {
  17525. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17526. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  17527. lastMatch.clear();
  17528. if (outSize)
  17529. {
  17530. processed++;
  17531. return rowBuilder.finalizeRowClear(outSize);
  17532. }
  17533. }
  17534. catch (IException *E)
  17535. {
  17536. throw makeWrappedException(E);
  17537. }
  17538. }
  17539. }
  17540. }
  17541. ReleaseClearRoxieRow(in);
  17542. in = input->nextInGroup();
  17543. if(!in)
  17544. {
  17545. if(numProcessedLastGroup == processed)
  17546. in = input->nextInGroup();
  17547. if(!in)
  17548. {
  17549. numProcessedLastGroup = processed;
  17550. return NULL;
  17551. }
  17552. }
  17553. size32_t srchLen;
  17554. helper.getSearchText(srchLen, srchStr, in);
  17555. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  17556. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  17557. }
  17558. }
  17559. };
  17560. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  17561. {
  17562. public:
  17563. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17564. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  17565. {
  17566. }
  17567. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  17568. {
  17569. return new CRoxieServerXmlParseActivity(this, _probeManager);
  17570. }
  17571. };
  17572. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  17573. {
  17574. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  17575. }
  17576. //=====================================================================================================
  17577. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  17578. {
  17579. protected:
  17580. IHThorDiskReadBaseArg &helper;
  17581. IHThorCompoundExtra * compoundHelper;
  17582. RemoteActivityId remoteId; // Note we copy it rather than reference
  17583. Owned<CSkippableRemoteResultAdaptor> remote;
  17584. unsigned numParts;
  17585. unsigned __int64 rowLimit;
  17586. unsigned __int64 stopAfter;
  17587. Linked<IInMemoryIndexManager> manager;
  17588. Owned<IInMemoryIndexCursor> cursor;
  17589. Owned<IDirectReader> reader;
  17590. CThorContiguousRowBuffer deserializeSource;
  17591. Owned<ISourceRowPrefetcher> prefetcher;
  17592. bool eof;
  17593. bool isKeyed;
  17594. bool variableFileName;
  17595. bool isOpt;
  17596. bool sorted;
  17597. bool maySkip;
  17598. bool isLocal;
  17599. CachedOutputMetaData diskSize;
  17600. Owned<const IResolvedFile> varFileInfo;
  17601. Owned<IFileIOArray> varFiles;
  17602. inline bool useRemote()
  17603. {
  17604. return remote != NULL && numParts > 1;
  17605. }
  17606. public:
  17607. IMPLEMENT_IINTERFACE;
  17608. CRoxieServerDiskReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17609. : CRoxieServerActivity(_factory, _probeManager),
  17610. helper((IHThorDiskReadBaseArg &)basehelper),
  17611. numParts(_numParts),
  17612. remoteId(_remoteId),
  17613. manager(_manager),
  17614. isLocal(_isLocal),
  17615. sorted(_sorted),
  17616. maySkip(_maySkip),
  17617. deserializeSource(NULL)
  17618. {
  17619. if (numParts != 1 && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  17620. remote.setown(new CSkippableRemoteResultAdaptor(remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  17621. compoundHelper = NULL;
  17622. eof = false;
  17623. rowLimit = (unsigned __int64) -1;
  17624. isKeyed = false;
  17625. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  17626. diskSize.set(helper.queryDiskRecordSize());
  17627. variableFileName = allFilesDynamic || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  17628. isOpt = (helper.getFlags() & TDRoptional) != 0;
  17629. }
  17630. virtual const IResolvedFile *queryVarFileInfo() const
  17631. {
  17632. return varFileInfo;
  17633. }
  17634. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  17635. {
  17636. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  17637. if (remote)
  17638. remote->onCreate(this, this, _ctx, _colocalParent);
  17639. }
  17640. virtual bool needsAllocator() const { return true; }
  17641. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17642. {
  17643. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17644. if (compoundHelper)
  17645. {
  17646. rowLimit = compoundHelper->getRowLimit();
  17647. stopAfter = compoundHelper->getChooseNLimit();
  17648. }
  17649. if (!helper.canMatchAny())
  17650. eof = true;
  17651. else
  17652. {
  17653. if (variableFileName)
  17654. {
  17655. OwnedRoxieString fileName(helper.getFileName());
  17656. varFileInfo.setown(resolveLFN(fileName, isOpt));
  17657. numParts = 0;
  17658. if (varFileInfo)
  17659. {
  17660. Owned<IFilePartMap> map = varFileInfo->getFileMap();
  17661. if (map)
  17662. numParts = map->getNumParts();
  17663. }
  17664. }
  17665. if (!numParts)
  17666. {
  17667. eof = true;
  17668. }
  17669. else if (useRemote())
  17670. {
  17671. remote->onStart(parentExtractSize, parentExtract);
  17672. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  17673. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  17674. // Translation into a message per channel done elsewhere....
  17675. remote->getMem(0, fileNo, 0);
  17676. remote->flush();
  17677. remote->senddone();
  17678. }
  17679. else
  17680. {
  17681. if (variableFileName)
  17682. {
  17683. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  17684. varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
  17685. manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
  17686. }
  17687. assertex(manager != NULL);
  17688. helper.createSegmentMonitors(this);
  17689. if (cursor)
  17690. {
  17691. isKeyed = cursor->selectKey();
  17692. cursor->reset();
  17693. }
  17694. if (!isKeyed)
  17695. {
  17696. reader.setown(manager->createReader(0, 0, 1));
  17697. deserializeSource.setStream(reader);
  17698. prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
  17699. }
  17700. helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
  17701. }
  17702. }
  17703. }
  17704. virtual void append(IKeySegmentMonitor *segment)
  17705. {
  17706. if (!segment->isWild())
  17707. {
  17708. if (!cursor)
  17709. cursor.setown(manager->createCursor());
  17710. cursor->append(segment);
  17711. }
  17712. }
  17713. virtual unsigned ordinality() const
  17714. {
  17715. return cursor ? cursor->ordinality() : 0;
  17716. }
  17717. virtual IKeySegmentMonitor *item(unsigned idx) const
  17718. {
  17719. return cursor ? cursor->item(idx) : 0;
  17720. }
  17721. virtual void setMergeBarrier(unsigned barrierOffset)
  17722. {
  17723. // no merging so no issue...
  17724. }
  17725. virtual void stop(bool aborting)
  17726. {
  17727. if (useRemote())
  17728. remote->onStop(aborting);
  17729. CRoxieServerActivity::stop(aborting);
  17730. }
  17731. virtual void reset()
  17732. {
  17733. if (useRemote())
  17734. {
  17735. processed = remote->processed;
  17736. remote->processed = 0;
  17737. remote->onReset();
  17738. }
  17739. varFileInfo.clear();
  17740. eof = false;
  17741. if (cursor)
  17742. cursor->reset();
  17743. deserializeSource.clearStream();
  17744. CRoxieServerActivity::reset();
  17745. }
  17746. virtual void setInput(unsigned idx, IRoxieInput *_in)
  17747. {
  17748. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  17749. }
  17750. virtual void onLimitExceeded(bool isKeyed)
  17751. {
  17752. if (traceLevel > 4)
  17753. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17754. assertex(compoundHelper);
  17755. if (isKeyed) // MORE does this exist for diskread? should it?
  17756. {
  17757. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  17758. {
  17759. if (ctx->queryDebugContext())
  17760. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17761. throw makeLimitSkipException(true);
  17762. }
  17763. else
  17764. {
  17765. UNIMPLEMENTED;
  17766. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  17767. }
  17768. }
  17769. else
  17770. {
  17771. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  17772. {
  17773. if (ctx->queryDebugContext())
  17774. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17775. throw makeLimitSkipException(false);
  17776. }
  17777. else
  17778. compoundHelper->onLimitExceeded();
  17779. }
  17780. }
  17781. virtual const void * createLimitFailRow(bool isKeyed)
  17782. {
  17783. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17784. IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
  17785. assertex(limitTransformExtra);
  17786. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  17787. if (outSize)
  17788. return rowBuilder.finalizeRowClear(outSize);
  17789. return NULL;
  17790. }
  17791. };
  17792. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  17793. {
  17794. IHThorCompoundReadExtra * readHelper;
  17795. ConstPointerArray readrows;
  17796. bool readAheadDone;
  17797. unsigned readIndex;
  17798. public:
  17799. CRoxieServerDiskReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17800. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17801. {
  17802. compoundHelper = (IHThorDiskReadArg *)&helper;
  17803. readHelper = (IHThorDiskReadArg *)&helper;
  17804. readAheadDone = false;
  17805. readIndex = 0;
  17806. }
  17807. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17808. {
  17809. rowLimit = compoundHelper->getRowLimit();
  17810. stopAfter = compoundHelper->getChooseNLimit();
  17811. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17812. readAheadDone = false;
  17813. readIndex = 0;
  17814. }
  17815. virtual void reset()
  17816. {
  17817. while (readrows.isItem(readIndex))
  17818. ReleaseRoxieRow(readrows.item(readIndex++));
  17819. readrows.kill();
  17820. readAheadDone = false;
  17821. readIndex = 0;
  17822. CRoxieServerDiskReadBaseActivity::reset();
  17823. }
  17824. virtual const void *nextInGroup()
  17825. {
  17826. if (eof)
  17827. return NULL;
  17828. else if (useRemote())
  17829. return remote->nextInGroup();
  17830. else if (maySkip)
  17831. {
  17832. if (!readAheadDone)
  17833. {
  17834. unsigned preprocessed = 0;
  17835. while (!eof)
  17836. {
  17837. const void *row = _nextInGroup();
  17838. if (row)
  17839. preprocessed++;
  17840. if (preprocessed > rowLimit)
  17841. {
  17842. ReleaseRoxieRow(row);
  17843. while (readrows.isItem(readIndex))
  17844. ReleaseRoxieRow(readrows.item(readIndex++));
  17845. readrows.kill();
  17846. eof = true;
  17847. if (ctx->queryDebugContext())
  17848. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17849. if (helper.getFlags() & TDRlimitskips)
  17850. return NULL;
  17851. else if (helper.getFlags() & TDRlimitcreates)
  17852. return createLimitFailRow(false);
  17853. else
  17854. throwUnexpected();
  17855. }
  17856. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  17857. {
  17858. eof = true;
  17859. ReleaseRoxieRow(row);
  17860. break;
  17861. }
  17862. readrows.append(row);
  17863. }
  17864. readAheadDone = true;
  17865. }
  17866. if (readrows.isItem(readIndex))
  17867. {
  17868. const void *ret = readrows.item(readIndex++);
  17869. if (ret)
  17870. processed++;
  17871. return ret;
  17872. }
  17873. else
  17874. {
  17875. eof = true;
  17876. return NULL;
  17877. }
  17878. }
  17879. else
  17880. {
  17881. const void *ret = _nextInGroup();
  17882. if (ret)
  17883. {
  17884. processed++;
  17885. if (processed > rowLimit)
  17886. {
  17887. if (traceLevel > 4)
  17888. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  17889. ReleaseRoxieRow(ret);
  17890. compoundHelper->onLimitExceeded();
  17891. throwUnexpected(); // onLimitExceeded is not supposed to return
  17892. }
  17893. if (processed > stopAfter) // MORE - bit of a strange place to check
  17894. {
  17895. eof = true;
  17896. ReleaseRoxieRow(ret);
  17897. return NULL;
  17898. }
  17899. }
  17900. return ret;
  17901. }
  17902. }
  17903. const void *_nextInGroup()
  17904. {
  17905. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17906. unsigned transformedSize = 0;
  17907. if (isKeyed)
  17908. {
  17909. loop
  17910. {
  17911. const void *nextCandidate = cursor->nextMatch();
  17912. if (!nextCandidate)
  17913. {
  17914. eof = true;
  17915. return NULL;
  17916. }
  17917. transformedSize = readHelper->transform(rowBuilder, nextCandidate);
  17918. if (transformedSize)
  17919. break;
  17920. }
  17921. }
  17922. else // use reader...
  17923. {
  17924. assertex(reader != NULL);
  17925. loop
  17926. {
  17927. if (deserializeSource.eos())
  17928. {
  17929. eof = true;
  17930. return NULL;
  17931. }
  17932. prefetcher->readAhead(deserializeSource);
  17933. const byte *nextRec = deserializeSource.queryRow();
  17934. if (cursor && cursor->isFiltered(nextRec))
  17935. transformedSize = 0;
  17936. else
  17937. transformedSize = readHelper->transform(rowBuilder, nextRec);
  17938. deserializeSource.finishedRow();
  17939. if (transformedSize)
  17940. break;
  17941. }
  17942. }
  17943. return rowBuilder.finalizeRowClear(transformedSize);
  17944. }
  17945. };
  17946. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect
  17947. {
  17948. IHThorXmlReadArg * readHelper;
  17949. Owned<IXmlToRowTransformer> rowTransformer;
  17950. Owned<IXMLParse> xmlParser;
  17951. Owned<IColumnProvider> lastMatch;
  17952. unsigned __int64 localOffset;
  17953. public:
  17954. IMPLEMENT_IINTERFACE;
  17955. CRoxieServerXmlReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
  17956. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
  17957. {
  17958. compoundHelper = NULL;
  17959. readHelper = (IHThorXmlReadArg *)&helper;
  17960. localOffset = 0;
  17961. }
  17962. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17963. {
  17964. rowLimit = readHelper->getRowLimit();
  17965. stopAfter = readHelper->getChooseNLimit();
  17966. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  17967. if (!useRemote())
  17968. {
  17969. rowTransformer.set(readHelper->queryTransformer());
  17970. assertex(reader != NULL);
  17971. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  17972. xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  17973. }
  17974. }
  17975. virtual void reset()
  17976. {
  17977. CRoxieServerDiskReadBaseActivity::reset();
  17978. rowTransformer.clear();
  17979. xmlParser.clear();
  17980. }
  17981. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  17982. {
  17983. localOffset = startOffset;
  17984. lastMatch.set(&entry);
  17985. }
  17986. virtual const void *nextInGroup()
  17987. {
  17988. if (eof)
  17989. return NULL;
  17990. else if (useRemote())
  17991. return remote->nextInGroup();
  17992. assertex(xmlParser != NULL);
  17993. try
  17994. {
  17995. while (!eof)
  17996. {
  17997. //call to next() will callback on the IXmlSelect interface
  17998. bool gotNext = false;
  17999. gotNext = xmlParser->next();
  18000. if(!gotNext)
  18001. eof = true;
  18002. else if (lastMatch)
  18003. {
  18004. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18005. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, reader->queryThorDiskCallback());
  18006. lastMatch.clear();
  18007. localOffset = 0;
  18008. if (sizeGot)
  18009. {
  18010. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  18011. if (processed > rowLimit)
  18012. {
  18013. if (traceLevel > 4)
  18014. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18015. readHelper->onLimitExceeded();
  18016. throwUnexpected(); // onLimitExceeded is not supposed to return
  18017. }
  18018. processed++;
  18019. if (processed > stopAfter) // MORE - bit of a strange place to check
  18020. {
  18021. eof = true;
  18022. return NULL;
  18023. }
  18024. return ret.getClear();
  18025. }
  18026. }
  18027. }
  18028. return NULL;
  18029. }
  18030. catch(IException *E)
  18031. {
  18032. throw makeWrappedException(E);
  18033. }
  18034. }
  18035. };
  18036. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  18037. {
  18038. IHThorCsvReadArg *readHelper;
  18039. ICsvParameters * csvInfo;
  18040. unsigned headerLines;
  18041. unsigned maxDiskSize;
  18042. CSVSplitter csvSplitter;
  18043. unsigned __int64 localOffset;
  18044. const char *quotes;
  18045. const char *separators;
  18046. const char *terminators;
  18047. const char *escapes;
  18048. public:
  18049. CRoxieServerCsvReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18050. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
  18051. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes)
  18052. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
  18053. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes)
  18054. {
  18055. compoundHelper = NULL;
  18056. readHelper = (IHThorCsvReadArg *)&helper;
  18057. rowLimit = readHelper->getRowLimit();
  18058. stopAfter = readHelper->getChooseNLimit();
  18059. csvInfo = readHelper->queryCsvParameters();
  18060. maxDiskSize = csvInfo->queryMaxSize();
  18061. localOffset = 0;
  18062. headerLines = 0;
  18063. }
  18064. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18065. {
  18066. rowLimit = readHelper->getRowLimit();
  18067. stopAfter = readHelper->getChooseNLimit();
  18068. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18069. if (!useRemote())
  18070. {
  18071. headerLines = csvInfo->queryHeaderLen();
  18072. if (headerLines && isLocal && reader->queryFilePart() != 1)
  18073. headerLines = 0; // MORE - you could argue that if SINGLE not specified, should skip from all parts. But it would be painful since we have already concatenated and no-one else does...
  18074. if (!eof)
  18075. {
  18076. if (varFileInfo)
  18077. {
  18078. const IPropertyTree *options = varFileInfo->queryProperties();
  18079. if (options)
  18080. {
  18081. quotes = options->queryProp("@csvQuote");
  18082. separators = options->queryProp("@csvSeparate");
  18083. terminators = options->queryProp("@csvTerminate");
  18084. escapes = options->queryProp("@csvEscape");
  18085. }
  18086. }
  18087. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  18088. }
  18089. }
  18090. }
  18091. virtual const void *nextInGroup()
  18092. {
  18093. if (eof)
  18094. return NULL;
  18095. else if (useRemote())
  18096. return remote->nextInGroup();
  18097. try
  18098. {
  18099. while (!eof)
  18100. {
  18101. if (reader->eos())
  18102. {
  18103. eof = true;
  18104. break;
  18105. }
  18106. // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
  18107. size32_t rowSize = 4096; // MORE - make configurable
  18108. size32_t maxRowSize = 10*1024*1024; // MORE - make configurable
  18109. size32_t thisLineLength;
  18110. loop
  18111. {
  18112. size32_t avail;
  18113. const void *peek = reader->peek(rowSize, avail);
  18114. thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
  18115. if (thisLineLength < rowSize || avail < rowSize)
  18116. break;
  18117. if (rowSize == maxRowSize)
  18118. throw MakeStringException(0, "Row too big");
  18119. if (rowSize >= maxRowSize/2)
  18120. rowSize = maxRowSize;
  18121. else
  18122. rowSize += rowSize;
  18123. }
  18124. if (headerLines)
  18125. {
  18126. headerLines--;
  18127. reader->skip(thisLineLength);
  18128. }
  18129. else
  18130. {
  18131. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18132. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  18133. reader->skip(thisLineLength);
  18134. if (transformedSize)
  18135. {
  18136. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  18137. if (processed > rowLimit)
  18138. {
  18139. readHelper->onLimitExceeded();
  18140. throwUnexpected(); // onLimitExceeded is not supposed to return
  18141. }
  18142. processed++;
  18143. if (processed > stopAfter) // MORE - bit of a strange place to check
  18144. {
  18145. eof = true;
  18146. return NULL;
  18147. }
  18148. return ret.getClear();
  18149. }
  18150. }
  18151. }
  18152. return NULL;
  18153. }
  18154. catch(IException *E)
  18155. {
  18156. throw makeWrappedException(E);
  18157. }
  18158. }
  18159. virtual void reset()
  18160. {
  18161. CRoxieServerDiskReadBaseActivity::reset();
  18162. csvSplitter.reset();
  18163. localOffset = 0;
  18164. }
  18165. virtual unsigned __int64 getFilePosition(const void * row)
  18166. {
  18167. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  18168. }
  18169. virtual unsigned __int64 getLocalFilePosition(const void * row)
  18170. {
  18171. UNIMPLEMENTED;
  18172. }
  18173. };
  18174. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  18175. {
  18176. IHThorDiskNormalizeArg *normalizeHelper;
  18177. bool firstPending;
  18178. public:
  18179. CRoxieServerDiskNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
  18180. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
  18181. {
  18182. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  18183. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  18184. firstPending = true;
  18185. }
  18186. virtual void reset()
  18187. {
  18188. firstPending = true;
  18189. CRoxieServerDiskReadBaseActivity::reset();
  18190. }
  18191. virtual const void *nextInGroup()
  18192. {
  18193. if (eof)
  18194. return NULL;
  18195. else if (useRemote())
  18196. return remote->nextInGroup();
  18197. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18198. unsigned transformedSize = 0;
  18199. if (isKeyed)
  18200. {
  18201. loop
  18202. {
  18203. while (firstPending)
  18204. {
  18205. const void *nextCandidate = cursor->nextMatch();
  18206. if (!nextCandidate)
  18207. {
  18208. eof = true;
  18209. return NULL;
  18210. }
  18211. if (normalizeHelper->first(nextCandidate))
  18212. {
  18213. firstPending = false;
  18214. break;
  18215. }
  18216. }
  18217. transformedSize = normalizeHelper->transform(rowBuilder);
  18218. firstPending = !normalizeHelper->next();
  18219. if (transformedSize)
  18220. break;
  18221. }
  18222. }
  18223. else
  18224. {
  18225. assertex(reader != NULL);
  18226. loop
  18227. {
  18228. while (firstPending)
  18229. {
  18230. if (deserializeSource.eos())
  18231. {
  18232. eof = true;
  18233. return NULL;
  18234. }
  18235. prefetcher->readAhead(deserializeSource);
  18236. const byte *nextRec = deserializeSource.queryRow();
  18237. if (!cursor || !cursor->isFiltered(nextRec))
  18238. {
  18239. if (normalizeHelper->first(nextRec))
  18240. firstPending = false;
  18241. }
  18242. deserializeSource.finishedRow();
  18243. }
  18244. transformedSize = normalizeHelper->transform(rowBuilder);
  18245. firstPending = !normalizeHelper->next();
  18246. if (transformedSize)
  18247. break;
  18248. }
  18249. }
  18250. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  18251. processed++;
  18252. if (processed > rowLimit)
  18253. {
  18254. compoundHelper->onLimitExceeded();
  18255. throwUnexpected(); // onLimitExceeded is not supposed to return
  18256. }
  18257. if (processed > stopAfter) // MORE - bit of a strange place to check
  18258. {
  18259. eof = true;
  18260. return NULL;
  18261. }
  18262. return recBuffer.getClear();
  18263. }
  18264. };
  18265. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  18266. {
  18267. protected:
  18268. bool done;
  18269. public:
  18270. CRoxieServerDiskAggregateBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18271. : CRoxieServerDiskReadBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
  18272. done(false)
  18273. {
  18274. }
  18275. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18276. {
  18277. done = false;
  18278. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18279. }
  18280. virtual IRoxieInput *queryOutput(unsigned idx)
  18281. {
  18282. if (idx==(unsigned)-1)
  18283. idx = 0;
  18284. return idx ? NULL: this;
  18285. }
  18286. };
  18287. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  18288. {
  18289. IHThorDiskCountArg & countHelper;
  18290. unsigned __int64 choosenLimit;
  18291. IHThorSourceCountLimit *limitHelper;
  18292. unsigned __int64 getSkippedCount()
  18293. {
  18294. unsigned flags = countHelper.getFlags();
  18295. if (flags & TDRlimitskips)
  18296. return 0;
  18297. else if (flags & TDRlimitcreates)
  18298. return 1;
  18299. else
  18300. {
  18301. assertex(limitHelper);
  18302. if (traceLevel > 4)
  18303. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  18304. limitHelper->onLimitExceeded();
  18305. throwUnexpected(); // onLimitExceeded should always throw exception
  18306. }
  18307. }
  18308. public:
  18309. CRoxieServerDiskCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18310. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18311. countHelper((IHThorDiskCountArg &)basehelper)
  18312. {
  18313. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  18314. choosenLimit = 0;
  18315. }
  18316. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18317. {
  18318. choosenLimit = countHelper.getChooseNLimit();
  18319. if (limitHelper)
  18320. {
  18321. rowLimit = limitHelper->getRowLimit();
  18322. // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
  18323. }
  18324. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18325. }
  18326. virtual const void *nextInGroup()
  18327. {
  18328. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18329. if (done) return NULL;
  18330. done = true;
  18331. unsigned __int64 totalCount = 0;
  18332. if (helper.canMatchAny() && !eof)
  18333. {
  18334. if (useRemote())
  18335. {
  18336. loop
  18337. {
  18338. const void * next = remote->nextInGroup();
  18339. if (!next)
  18340. break;
  18341. if (meta.getFixedSize() == 1)
  18342. totalCount += *(byte *)next;
  18343. else
  18344. totalCount += *(unsigned __int64 *)next;
  18345. ReleaseRoxieRow(next);
  18346. if (totalCount > rowLimit)
  18347. {
  18348. totalCount = getSkippedCount();
  18349. break;
  18350. }
  18351. else if (totalCount >= choosenLimit)
  18352. {
  18353. totalCount = choosenLimit;
  18354. break;
  18355. }
  18356. }
  18357. }
  18358. else
  18359. {
  18360. if (isKeyed)
  18361. {
  18362. loop
  18363. {
  18364. const void *nextCandidate = cursor->nextMatch();
  18365. if (!nextCandidate)
  18366. break;
  18367. totalCount += countHelper.numValid(nextCandidate);
  18368. if (totalCount > rowLimit)
  18369. {
  18370. totalCount = getSkippedCount();
  18371. break;
  18372. }
  18373. else if (totalCount >= choosenLimit)
  18374. {
  18375. totalCount = choosenLimit;
  18376. break;
  18377. }
  18378. }
  18379. }
  18380. else
  18381. {
  18382. assertex(reader != NULL);
  18383. while (!deserializeSource.eos())
  18384. {
  18385. prefetcher->readAhead(deserializeSource);
  18386. const byte *nextRec = deserializeSource.queryRow();
  18387. if (!cursor || !cursor->isFiltered(nextRec))
  18388. {
  18389. totalCount += countHelper.numValid(nextRec);
  18390. }
  18391. deserializeSource.finishedRow();
  18392. if (totalCount > rowLimit)
  18393. {
  18394. totalCount = getSkippedCount();
  18395. break;
  18396. }
  18397. else if (totalCount >= choosenLimit)
  18398. {
  18399. totalCount = choosenLimit;
  18400. break;
  18401. }
  18402. }
  18403. }
  18404. }
  18405. }
  18406. size32_t rowSize = meta.getFixedSize();
  18407. void * result = rowAllocator->createRow();
  18408. if (rowSize == 1)
  18409. *(byte *)result = (byte)totalCount;
  18410. else
  18411. {
  18412. assertex(rowSize == sizeof(unsigned __int64));
  18413. *(unsigned __int64 *)result = totalCount;
  18414. }
  18415. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  18416. }
  18417. };
  18418. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18419. {
  18420. IHThorCompoundAggregateExtra & aggregateHelper;
  18421. public:
  18422. CRoxieServerDiskAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18423. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18424. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18425. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  18426. {
  18427. }
  18428. const void * gatherMerged()
  18429. {
  18430. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  18431. size32_t finalSize = 0;
  18432. if (useRemote())
  18433. {
  18434. const void * firstRow = remote->nextInGroup();
  18435. if (!firstRow)
  18436. {
  18437. rowBuilder.ensureRow();
  18438. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  18439. }
  18440. else
  18441. {
  18442. // NOTE need to clone this because going to modify below, could special case 1 row only
  18443. finalSize = cloneRow(rowBuilder, firstRow, meta);
  18444. ReleaseRoxieRow(firstRow);
  18445. }
  18446. loop
  18447. {
  18448. const void * next = remote->nextInGroup();
  18449. if (!next)
  18450. break;
  18451. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  18452. ReleaseRoxieRow(next);
  18453. }
  18454. }
  18455. else
  18456. {
  18457. aggregateHelper.clearAggregate(rowBuilder);
  18458. if (helper.canMatchAny() && !eof)
  18459. {
  18460. if (isKeyed)
  18461. {
  18462. loop
  18463. {
  18464. const void *next = cursor->nextMatch();
  18465. if (!next)
  18466. break;
  18467. aggregateHelper.processRow(rowBuilder, next);
  18468. }
  18469. }
  18470. else
  18471. {
  18472. assertex(reader != NULL);
  18473. while (!deserializeSource.eos())
  18474. {
  18475. prefetcher->readAhead(deserializeSource);
  18476. const byte *nextRec = deserializeSource.queryRow();
  18477. if (!cursor || !cursor->isFiltered(nextRec))
  18478. {
  18479. aggregateHelper.processRow(rowBuilder, nextRec);
  18480. }
  18481. deserializeSource.finishedRow();
  18482. }
  18483. }
  18484. }
  18485. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  18486. }
  18487. return rowBuilder.finalizeRowClear(finalSize);
  18488. }
  18489. virtual const void *nextInGroup()
  18490. {
  18491. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18492. if (done) return NULL;
  18493. const void * ret = gatherMerged();
  18494. done = true;
  18495. return ret;
  18496. }
  18497. };
  18498. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  18499. {
  18500. IHThorDiskGroupAggregateArg & aggregateHelper;
  18501. RowAggregator resultAggregator;
  18502. bool gathered;
  18503. public:
  18504. IMPLEMENT_IINTERFACE;
  18505. CRoxieServerDiskGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
  18506. : CRoxieServerDiskAggregateBaseActivity(_factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
  18507. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  18508. resultAggregator(aggregateHelper, aggregateHelper),
  18509. gathered(false)
  18510. {
  18511. }
  18512. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18513. {
  18514. gathered= false;
  18515. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  18516. resultAggregator.start(rowAllocator);
  18517. }
  18518. virtual void reset()
  18519. {
  18520. resultAggregator.reset();
  18521. CRoxieServerDiskAggregateBaseActivity::reset();
  18522. }
  18523. void gatherMerged()
  18524. {
  18525. if (useRemote())
  18526. {
  18527. loop
  18528. {
  18529. const void * next = remote->nextInGroup();
  18530. if (!next)
  18531. break;
  18532. resultAggregator.mergeElement(next);
  18533. ReleaseRoxieRow(next);
  18534. }
  18535. }
  18536. else
  18537. {
  18538. if (helper.canMatchAny() && !eof)
  18539. {
  18540. Owned<IInMemoryFileProcessor> processor = isKeyed ?
  18541. createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
  18542. createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
  18543. ctx->queryCodeContext(), activityId);
  18544. processor->doQuery(NULL, 0, 0, 0);
  18545. }
  18546. }
  18547. gathered = true;
  18548. }
  18549. virtual const void *nextInGroup()
  18550. {
  18551. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18552. if (done)
  18553. return NULL;
  18554. if (!gathered)
  18555. gatherMerged();
  18556. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  18557. if (next)
  18558. {
  18559. processed++;
  18560. return next->finalizeRowClear();
  18561. }
  18562. done = true;
  18563. return NULL;
  18564. }
  18565. };
  18566. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  18567. {
  18568. public:
  18569. RemoteActivityId remoteId;
  18570. bool isLocal;
  18571. bool sorted;
  18572. bool maySkip;
  18573. bool variableFileName;
  18574. Owned<IFilePartMap> map;
  18575. Owned<IFileIOArray> files;
  18576. Owned<IInMemoryIndexManager> manager;
  18577. Owned<const IResolvedFile> datafile;
  18578. const char *quotes;
  18579. const char *separators;
  18580. const char *terminators;
  18581. const char *escapes;
  18582. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18583. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  18584. {
  18585. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  18586. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  18587. sorted = (helper->getFlags() & TDRunsorted) == 0;
  18588. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  18589. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  18590. quotes = separators = terminators = escapes = NULL;
  18591. if (!variableFileName)
  18592. {
  18593. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  18594. OwnedRoxieString fileName(helper->getFileName());
  18595. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit()));
  18596. if (datafile)
  18597. map.setown(datafile->getFileMap());
  18598. bool isSimple = (map && map->getNumParts()==1 && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false));
  18599. if (isLocal || isSimple)
  18600. {
  18601. if (datafile)
  18602. {
  18603. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  18604. files.setown(datafile->getIFileIOArray(isOpt, channel));
  18605. manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
  18606. const IPropertyTree *options = datafile->queryProperties();
  18607. if (options)
  18608. {
  18609. quotes = options->queryProp("@csvQuote");
  18610. separators = options->queryProp("@csvSeparate");
  18611. terminators = options->queryProp("@csvTerminate");
  18612. escapes = options->queryProp("@csvEscape");
  18613. }
  18614. }
  18615. else
  18616. manager.setown(getEmptyIndexManager());
  18617. }
  18618. }
  18619. }
  18620. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  18621. {
  18622. unsigned numParts = map ? map->getNumParts() : 0;
  18623. switch (kind)
  18624. {
  18625. case TAKcsvread:
  18626. return new CRoxieServerCsvReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
  18627. quotes, separators, terminators, escapes);
  18628. case TAKxmlread:
  18629. return new CRoxieServerXmlReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18630. case TAKdiskread:
  18631. return new CRoxieServerDiskReadActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
  18632. case TAKdisknormalize:
  18633. return new CRoxieServerDiskNormalizeActivity(this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
  18634. case TAKdiskcount:
  18635. return new CRoxieServerDiskCountActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18636. case TAKdiskaggregate:
  18637. return new CRoxieServerDiskAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18638. case TAKdiskgroupaggregate:
  18639. return new CRoxieServerDiskGroupAggregateActivity(this, _probeManager, remoteId, numParts, isLocal, manager);
  18640. }
  18641. throwUnexpected();
  18642. }
  18643. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18644. {
  18645. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  18646. }
  18647. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  18648. {
  18649. if (datafile)
  18650. addXrefFileInfo(reply, datafile);
  18651. }
  18652. };
  18653. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  18654. {
  18655. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  18656. }
  18657. //=================================================================================
  18658. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  18659. {
  18660. protected:
  18661. IHThorIndexReadBaseArg &indexHelper;
  18662. IHThorSteppedSourceExtra * steppedExtra;
  18663. Linked<IKeyArray> keySet;
  18664. Linked<TranslatorArray> translators;
  18665. CSkippableRemoteResultAdaptor remote;
  18666. CIndexTransformCallback callback;
  18667. bool sorted;
  18668. bool variableFileName;
  18669. bool variableInfoPending;
  18670. bool isOpt;
  18671. bool isLocal;
  18672. unsigned __int64 rowLimit;
  18673. unsigned __int64 keyedLimit;
  18674. unsigned __int64 choosenLimit;
  18675. unsigned accepted;
  18676. unsigned rejected;
  18677. unsigned seekGEOffset;
  18678. Owned<IKeyManager> tlk;
  18679. Owned<const IResolvedFile> varFileInfo;
  18680. const RemoteActivityId &remoteId;
  18681. void setVariableFileInfo()
  18682. {
  18683. OwnedRoxieString indexName(indexHelper.getFileName());
  18684. varFileInfo.setown(resolveLFN(indexName, isOpt));
  18685. if (varFileInfo)
  18686. {
  18687. translators.setown(new TranslatorArray) ;
  18688. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  18689. }
  18690. variableInfoPending = false;
  18691. }
  18692. public:
  18693. CRoxieServerIndexActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18694. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18695. : CRoxieServerActivity(_factory, _probeManager),
  18696. keySet(_keySet),
  18697. translators(_translators),
  18698. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  18699. remote(_remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  18700. remoteId(_remoteId),
  18701. sorted(_sorted),
  18702. isLocal(_isLocal)
  18703. {
  18704. indexHelper.setCallback(&callback);
  18705. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  18706. variableFileName = allFilesDynamic || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  18707. variableInfoPending = false;
  18708. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  18709. seekGEOffset = 0;
  18710. // started = false;
  18711. rejected = accepted = 0;
  18712. rowLimit = choosenLimit = keyedLimit = 0;
  18713. }
  18714. virtual const IResolvedFile *queryVarFileInfo() const
  18715. {
  18716. return varFileInfo;
  18717. }
  18718. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  18719. {
  18720. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  18721. remote.onCreate(this, this, _ctx, _colocalParent);
  18722. }
  18723. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18724. {
  18725. accepted = 0;
  18726. rejected = 0;
  18727. rowLimit = (unsigned __int64) -1;
  18728. keyedLimit = (unsigned __int64 ) -1;
  18729. choosenLimit = I64C(0x7fffffffffffffff);
  18730. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18731. remote.onStart(parentExtractSize, parentExtract);
  18732. variableInfoPending = variableFileName;
  18733. }
  18734. void processAllKeys()
  18735. {
  18736. try
  18737. {
  18738. if (indexHelper.canMatchAny())
  18739. {
  18740. if (variableInfoPending)
  18741. setVariableFileInfo();
  18742. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  18743. if (keySet)
  18744. {
  18745. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  18746. // With soft layout support may need to recreate per fileno too (i.e. different keys in a superkey have different layout) but never per partno
  18747. // However order is probably better to iterate fileno's inside partnos
  18748. // MORE - also not properly supporting STEPPED I fear.
  18749. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  18750. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  18751. {
  18752. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  18753. if (thisBase)
  18754. {
  18755. unsigned fileNo = 0;
  18756. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  18757. if (!thisKey->isTopLevelKey())
  18758. {
  18759. if (keyedLimit != (unsigned __int64) -1)
  18760. {
  18761. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  18762. {
  18763. Owned<IKeyManager> countKey;
  18764. countKey.setown(createKeyManager(thisKey, 0, this));
  18765. countKey->setLayoutTranslator(translators->item(fileNo));
  18766. createSegmentMonitors(countKey);
  18767. unsigned __int64 count = countKey->checkCount(keyedLimit);
  18768. if (count > keyedLimit)
  18769. {
  18770. if (traceLevel > 4)
  18771. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  18772. onLimitExceeded(true);
  18773. }
  18774. }
  18775. }
  18776. }
  18777. if (seekGEOffset && !thisKey->isTopLevelKey())
  18778. {
  18779. tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
  18780. }
  18781. else
  18782. {
  18783. tlk.setown(createKeyManager(thisKey, 0, this));
  18784. tlk->setLayoutTranslator(translators->item(fileNo));
  18785. }
  18786. createSegmentMonitors(tlk);
  18787. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  18788. {
  18789. StringBuffer out;
  18790. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  18791. CTXLOG("Using filter %s", out.str());
  18792. if (ctx->queryProbeManager())
  18793. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  18794. }
  18795. tlk->reset();
  18796. loop // for each file part
  18797. {
  18798. //block for TransformCallbackAssociation
  18799. {
  18800. TransformCallbackAssociation associate(callback, tlk);
  18801. if (thisKey->isTopLevelKey())
  18802. {
  18803. if (thisKey->isFullySorted())
  18804. {
  18805. while (tlk->lookup(false))
  18806. {
  18807. unsigned slavePart = (unsigned) tlk->queryFpos();
  18808. if (slavePart)
  18809. {
  18810. accepted++;
  18811. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  18812. if (sorted && numChannels>1)
  18813. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  18814. }
  18815. }
  18816. }
  18817. else
  18818. {
  18819. // MORE - we could check whether there are any matching parts if we wanted.
  18820. // If people are in the habit of sending null values that would be worthwhile
  18821. remote.getMem(0, fileNo, 0);
  18822. }
  18823. }
  18824. else
  18825. {
  18826. if (processSingleKey(thisKey, translators->item(fileNo)))
  18827. break;
  18828. }
  18829. }
  18830. if (++fileNo < thisBase->numParts())
  18831. {
  18832. thisKey = thisBase->queryPart(fileNo);
  18833. tlk->setKey(thisKey);
  18834. tlk->setLayoutTranslator(translators->item(fileNo));
  18835. tlk->reset();
  18836. }
  18837. else
  18838. break;
  18839. }
  18840. tlk->releaseSegmentMonitors();
  18841. tlk->setKey(NULL);
  18842. }
  18843. }
  18844. }
  18845. }
  18846. remote.flush();
  18847. remote.senddone();
  18848. }
  18849. catch (IException *E)
  18850. {
  18851. remote.setException(E);
  18852. }
  18853. }
  18854. virtual void createSegmentMonitors(IKeyManager *key)
  18855. {
  18856. indexHelper.createSegmentMonitors(key);
  18857. key->finishSegmentMonitors();
  18858. }
  18859. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
  18860. virtual void reset()
  18861. {
  18862. if (accepted)
  18863. noteStatistic(STATS_ACCEPTED, accepted, 1);
  18864. if (rejected)
  18865. noteStatistic(STATS_REJECTED, rejected, 1);
  18866. remote.onReset();
  18867. CRoxieServerActivity::reset();
  18868. if (varFileInfo)
  18869. {
  18870. keySet.clear();
  18871. varFileInfo.clear();
  18872. }
  18873. variableInfoPending = false;
  18874. }
  18875. virtual void stop(bool aborting)
  18876. {
  18877. remote.onStop(aborting);
  18878. CRoxieServerActivity::stop(aborting);
  18879. }
  18880. virtual void setInput(unsigned idx, IRoxieInput *_in)
  18881. {
  18882. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  18883. }
  18884. };
  18885. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  18886. {
  18887. IHThorSourceLimitTransformExtra * limitTransformExtra;
  18888. public:
  18889. CRoxieServerIndexReadBaseActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18890. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
  18891. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
  18892. {
  18893. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  18894. }
  18895. virtual void reset()
  18896. {
  18897. remote.onReset();
  18898. CRoxieServerIndexActivity::reset();
  18899. }
  18900. virtual const void *nextInGroup()
  18901. {
  18902. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  18903. try
  18904. {
  18905. const void *ret = remote.nextInGroup();
  18906. if (ret)
  18907. processed++;
  18908. return ret;
  18909. }
  18910. catch (IException *E)
  18911. {
  18912. throw makeWrappedException(E);
  18913. }
  18914. }
  18915. protected:
  18916. virtual const void * createLimitFailRow(bool isKeyed)
  18917. {
  18918. createRowAllocator();
  18919. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18920. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  18921. if (outSize)
  18922. return rowBuilder.finalizeRowClear(outSize);
  18923. return NULL;
  18924. }
  18925. };
  18926. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  18927. {
  18928. protected:
  18929. IHThorCompoundReadExtra & readHelper;
  18930. ISteppingMeta *rawMeta;
  18931. CSteppingMeta steppingMeta;
  18932. unsigned * seekSizes;
  18933. bool optimizeSteppedPostFilter;
  18934. ISteppingMeta * projectedMeta;
  18935. unsigned maxSeekLookahead;
  18936. public:
  18937. CRoxieServerIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  18938. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  18939. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
  18940. readHelper((IHThorIndexReadArg &)basehelper)
  18941. {
  18942. rawMeta = readHelper.queryRawSteppingMeta();
  18943. unsigned flags = indexHelper.getFlags();
  18944. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  18945. seekSizes = NULL;
  18946. maxSeekLookahead = _maxSeekLookahead;
  18947. if (rawMeta)
  18948. {
  18949. const CFieldOffsetSize * fields = rawMeta->queryFields();
  18950. unsigned maxFields = rawMeta->getNumFields();
  18951. seekGEOffset = fields[0].offset;
  18952. seekSizes = new unsigned[maxFields];
  18953. seekSizes[0] = fields[0].size;
  18954. for (unsigned i=1; i < maxFields; i++)
  18955. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  18956. projectedMeta = readHelper.queryProjectedSteppingMeta();
  18957. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  18958. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  18959. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  18960. steppingMeta.init(useMeta, hasPostFilter);
  18961. }
  18962. }
  18963. ~CRoxieServerIndexReadActivity()
  18964. {
  18965. delete [] seekSizes;
  18966. }
  18967. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18968. {
  18969. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  18970. steppingMeta.setDistributed();
  18971. if (steppedExtra)
  18972. steppingMeta.setExtra(steppedExtra);
  18973. rowLimit = readHelper.getRowLimit();
  18974. keyedLimit = readHelper.getKeyedLimit();
  18975. choosenLimit = readHelper.getChooseNLimit();
  18976. if (!paused)
  18977. processAllKeys();
  18978. }
  18979. class LazyLocalKeyReader : public CInterface, implements IMessageResult, implements IMessageUnpackCursor
  18980. {
  18981. public:
  18982. IMPLEMENT_IINTERFACE;
  18983. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  18984. {
  18985. Link();
  18986. return const_cast<LazyLocalKeyReader*> (this);
  18987. }
  18988. virtual const void *getMessageHeader(unsigned &length) const
  18989. {
  18990. length = 0;
  18991. return NULL;
  18992. }
  18993. virtual const void *getMessageMetadata(unsigned &length) const
  18994. {
  18995. length = 0;
  18996. return NULL;
  18997. }
  18998. virtual void discard() const
  18999. {
  19000. // nothing to do.
  19001. }
  19002. unsigned keyedCount;
  19003. unsigned matched;
  19004. bool EOFseen;
  19005. Owned<IKeyIndexSet> keySet;
  19006. Owned<IKeyManager> tlk;
  19007. CRoxieServerIndexReadActivity &owner;
  19008. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
  19009. : owner(_owner)
  19010. {
  19011. keyedCount = 0;
  19012. matched = 0;
  19013. EOFseen = false;
  19014. keySet.setown(createKeyIndexSet());
  19015. keySet->addIndex(LINK(key));
  19016. if (owner.seekGEOffset)
  19017. tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
  19018. else
  19019. tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
  19020. tlk->setLayoutTranslator(trans);
  19021. owner.indexHelper.createSegmentMonitors(tlk);
  19022. tlk->finishSegmentMonitors();
  19023. tlk->reset();
  19024. }
  19025. virtual const void *getNext(int length)
  19026. {
  19027. TransformCallbackAssociation associate(owner.callback, tlk);
  19028. while (tlk->lookup(true))
  19029. {
  19030. keyedCount++;
  19031. if (keyedCount > owner.keyedLimit)
  19032. {
  19033. owner.onLimitExceeded(true); // Should throw exception
  19034. throwUnexpected();
  19035. }
  19036. size32_t transformedSize;
  19037. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  19038. byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
  19039. try
  19040. {
  19041. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  19042. owner.callback.finishedRow();
  19043. }
  19044. catch (IException *E)
  19045. {
  19046. throw owner.makeWrappedException(E);
  19047. }
  19048. if (transformedSize)
  19049. {
  19050. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  19051. matched++;
  19052. if (matched > owner.rowLimit)
  19053. {
  19054. owner.onLimitExceeded(false); // Should throw exception
  19055. throwUnexpected();
  19056. }
  19057. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  19058. {
  19059. break;
  19060. }
  19061. owner.accepted++;
  19062. return result.getClear();
  19063. }
  19064. else
  19065. owner.rejected++;
  19066. }
  19067. EOFseen = true;
  19068. return NULL;
  19069. }
  19070. virtual bool atEOF() const
  19071. {
  19072. return EOFseen;
  19073. }
  19074. virtual bool isSerialized() const
  19075. {
  19076. return false;
  19077. }
  19078. };
  19079. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19080. {
  19081. createRowAllocator();
  19082. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  19083. return false;
  19084. }
  19085. virtual void onLimitExceeded(bool isKeyed)
  19086. {
  19087. if (traceLevel > 4)
  19088. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19089. if (isKeyed)
  19090. {
  19091. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19092. {
  19093. if (ctx->queryDebugContext())
  19094. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19095. throw makeLimitSkipException(true);
  19096. }
  19097. else
  19098. readHelper.onKeyedLimitExceeded();
  19099. }
  19100. else
  19101. {
  19102. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19103. {
  19104. if (ctx->queryDebugContext())
  19105. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19106. throw makeLimitSkipException(false);
  19107. }
  19108. else
  19109. readHelper.onLimitExceeded();
  19110. }
  19111. }
  19112. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  19113. {
  19114. out.append((unsigned short) numFields);
  19115. out.append((unsigned short) seekLen);
  19116. out.append((unsigned short) stepExtra.queryFlags());
  19117. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  19118. if (seeks)
  19119. {
  19120. unsigned lookahead = 40000/seekLen;
  19121. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  19122. lookahead = maxSeekLookahead;
  19123. seeks->ensureFilled(seek, numFields, lookahead);
  19124. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  19125. unsigned serialized = 1; // rawseek is always serialized...
  19126. unsigned patchLength = out.length();
  19127. out.append(serialized); // NOTE - we come back and patch with the actual value...
  19128. out.append(seekLen, rawSeek);
  19129. if (seeks->ordinality())
  19130. {
  19131. const void *lastSeek = rawSeek;
  19132. byte *nextSeek = NULL;
  19133. if (projectedMeta)
  19134. nextSeek = (byte *) alloca(seekLen);
  19135. for (unsigned i = 0; i < seeks->ordinality(); i++)
  19136. {
  19137. if (projectedMeta)
  19138. {
  19139. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  19140. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19141. }
  19142. else
  19143. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  19144. int diff = memcmp(nextSeek, lastSeek, seekLen);
  19145. if (diff > 0)
  19146. {
  19147. serialized++;
  19148. out.append(seekLen, nextSeek);
  19149. lastSeek = (const byte *) out.reserve(0) - seekLen;
  19150. }
  19151. }
  19152. unsigned length = out.length();
  19153. out.setWritePos(patchLength);
  19154. out.append(serialized);
  19155. out.setWritePos(length);
  19156. }
  19157. }
  19158. else
  19159. {
  19160. out.append(false);
  19161. out.append(1);
  19162. out.append(seekLen, rawSeek);
  19163. }
  19164. }
  19165. virtual const void * nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19166. {
  19167. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19168. try
  19169. {
  19170. unsigned seeklen = 0;
  19171. const void *rawSeek = NULL;
  19172. if (seek && numFields)
  19173. {
  19174. seeklen = seekSizes[numFields-1];
  19175. rawSeek = (const byte *)seek + seekGEOffset;
  19176. if (projectedMeta)
  19177. {
  19178. byte * temp = (byte *) alloca(seeklen);
  19179. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  19180. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19181. rawSeek = (byte *)temp;
  19182. }
  19183. }
  19184. const void *ret = remote.nextSteppedGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  19185. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  19186. processed++;
  19187. return ret;
  19188. }
  19189. catch (IException *E)
  19190. {
  19191. throw makeWrappedException(E);
  19192. }
  19193. }
  19194. virtual IInputSteppingMeta * querySteppingMeta()
  19195. {
  19196. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19197. return &steppingMeta;
  19198. return NULL;
  19199. }
  19200. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19201. {
  19202. if (variableInfoPending)
  19203. setVariableFileInfo();
  19204. return this;
  19205. }
  19206. virtual IKeyArray *getKeySet() const
  19207. {
  19208. return keySet.getLink();
  19209. }
  19210. virtual const IResolvedFile *getVarFileInfo() const
  19211. {
  19212. return varFileInfo.getLink();
  19213. }
  19214. virtual TranslatorArray *getTranslators() const
  19215. {
  19216. return translators.getLink();
  19217. }
  19218. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19219. {
  19220. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19221. }
  19222. virtual IRoxieServerActivity *queryActivity() { return this; }
  19223. virtual const RemoteActivityId& queryRemoteId() const
  19224. {
  19225. return remoteId;
  19226. }
  19227. };
  19228. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  19229. {
  19230. IHThorCompoundReadExtra & readHelper;
  19231. IHThorIndexReadBaseArg & indexHelper;
  19232. IHThorSourceLimitTransformExtra * limitTransformExtra;
  19233. IHThorSteppedSourceExtra * steppedExtra;
  19234. bool eof;
  19235. Linked<IKeyArray>keySet;
  19236. Owned<IKeyIndexSet>keyIndexSet;
  19237. Owned<IKeyManager> tlk;
  19238. Linked<TranslatorArray> translators;
  19239. CIndexTransformCallback callback;
  19240. unsigned __int64 keyedLimit;
  19241. unsigned rowLimit;
  19242. unsigned chooseNLimit;
  19243. unsigned accepted;
  19244. unsigned rejected;
  19245. unsigned keyedCount;
  19246. ISteppingMeta * rawMeta;
  19247. ISteppingMeta * projectedMeta;
  19248. size32_t seekGEOffset;
  19249. unsigned * seekSizes;
  19250. CSteppingMeta steppingMeta;
  19251. Owned<const IResolvedFile> varFileInfo;
  19252. const RemoteActivityId &remoteId;
  19253. bool firstRead;
  19254. bool variableFileName;
  19255. bool variableInfoPending;
  19256. bool isOpt;
  19257. bool isLocal;
  19258. bool optimizeSteppedPostFilter;
  19259. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  19260. void initKeySet()
  19261. {
  19262. if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
  19263. {
  19264. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  19265. }
  19266. keyIndexSet.setown(createKeyIndexSet());
  19267. for (unsigned part = 0; part < keySet->length(); part++)
  19268. {
  19269. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  19270. if (kib)
  19271. {
  19272. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  19273. {
  19274. IKeyIndex *k = kib->queryPart(subpart);
  19275. if (k)
  19276. {
  19277. assertex(!k->isTopLevelKey());
  19278. keyIndexSet->addIndex(LINK(k));
  19279. }
  19280. }
  19281. }
  19282. }
  19283. }
  19284. void setVariableFileInfo()
  19285. {
  19286. OwnedRoxieString indexName(indexHelper.getFileName());
  19287. varFileInfo.setown(resolveLFN(indexName, isOpt));
  19288. translators.setown(new TranslatorArray) ;
  19289. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  19290. initKeySet();
  19291. variableInfoPending = false;
  19292. }
  19293. void onEOF()
  19294. {
  19295. callback.setManager(NULL);
  19296. eof = true;
  19297. tlk.clear();
  19298. }
  19299. public:
  19300. CRoxieServerSimpleIndexReadActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19301. IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
  19302. : CRoxieServerActivity(_factory, _probeManager),
  19303. readHelper((IHThorIndexReadArg &)basehelper),
  19304. indexHelper((IHThorIndexReadArg &)basehelper),
  19305. translators(_translatorArray),
  19306. keySet(_keyArray),
  19307. isLocal(_isLocal),
  19308. remoteId(_remoteId)
  19309. {
  19310. rowLimit = 0;
  19311. keyedLimit = 0;
  19312. chooseNLimit = 0;
  19313. indexHelper.setCallback(&callback);
  19314. steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
  19315. limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
  19316. unsigned flags = indexHelper.getFlags();
  19317. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19318. variableInfoPending = false;
  19319. isOpt = (flags & TIRoptional) != 0;
  19320. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  19321. firstRead = true;
  19322. accepted = 0;
  19323. rejected = 0;
  19324. keyedCount = 0;
  19325. eof = false;
  19326. rawMeta = readHelper.queryRawSteppingMeta();
  19327. projectedMeta = readHelper.queryProjectedSteppingMeta();
  19328. seekGEOffset = 0;
  19329. seekSizes = NULL;
  19330. if (rawMeta)
  19331. {
  19332. // MORE - should check all keys in maxFields list can actually be keyed.
  19333. const CFieldOffsetSize * fields = rawMeta->queryFields();
  19334. unsigned maxFields = rawMeta->getNumFields();
  19335. seekGEOffset = fields[0].offset;
  19336. seekSizes = new unsigned[maxFields];
  19337. seekSizes[0] = fields[0].size;
  19338. for (unsigned i=1; i < maxFields; i++)
  19339. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  19340. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  19341. if (projectedMeta)
  19342. steppingMeta.init(projectedMeta, hasPostFilter);
  19343. else
  19344. steppingMeta.init(rawMeta, hasPostFilter);
  19345. }
  19346. }
  19347. virtual const IResolvedFile *queryVarFileInfo() const
  19348. {
  19349. return varFileInfo;
  19350. }
  19351. ~CRoxieServerSimpleIndexReadActivity()
  19352. {
  19353. delete [] seekSizes;
  19354. }
  19355. virtual bool needsAllocator() const { return true; }
  19356. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19357. {
  19358. firstRead = true;
  19359. accepted = 0;
  19360. rejected = 0;
  19361. keyedCount = 0;
  19362. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19363. if (steppedExtra)
  19364. steppingMeta.setExtra(steppedExtra);
  19365. eof = !indexHelper.canMatchAny();
  19366. if (variableFileName)
  19367. variableInfoPending = true;
  19368. else
  19369. {
  19370. variableInfoPending = false;
  19371. if (!keyIndexSet)
  19372. initKeySet();
  19373. }
  19374. }
  19375. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  19376. {
  19377. if (variableInfoPending)
  19378. setVariableFileInfo();
  19379. return this;
  19380. }
  19381. virtual IKeyArray *getKeySet() const
  19382. {
  19383. return keySet.getLink();
  19384. }
  19385. virtual const IResolvedFile *getVarFileInfo() const
  19386. {
  19387. return varFileInfo.getLink();
  19388. }
  19389. virtual TranslatorArray *getTranslators() const
  19390. {
  19391. return translators.getLink();
  19392. }
  19393. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  19394. {
  19395. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  19396. }
  19397. virtual IRoxieServerActivity *queryActivity() { return this; }
  19398. virtual const RemoteActivityId& queryRemoteId() const
  19399. {
  19400. return remoteId;
  19401. }
  19402. const void *nextInGroup()
  19403. {
  19404. bool matched = true;
  19405. return nextSteppedGE(NULL, 0, matched, dummySmartStepExtra);
  19406. }
  19407. unsigned __int64 checkCount(unsigned __int64 limit)
  19408. {
  19409. unsigned numParts = keyIndexSet->numParts();
  19410. unsigned __int64 result = 0;
  19411. for (unsigned i = 0; i < numParts; i++)
  19412. {
  19413. Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
  19414. countTlk->setLayoutTranslator(translators->item(i));
  19415. indexHelper.createSegmentMonitors(countTlk);
  19416. countTlk->finishSegmentMonitors();
  19417. result += countTlk->checkCount(limit-result);
  19418. if (result > limit)
  19419. break;
  19420. }
  19421. return result;
  19422. }
  19423. virtual const void *nextSteppedGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  19424. {
  19425. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19426. if (eof)
  19427. return NULL;
  19428. if (firstRead)
  19429. {
  19430. if (variableInfoPending)
  19431. setVariableFileInfo();
  19432. rowLimit = (unsigned) readHelper.getRowLimit();
  19433. chooseNLimit = (unsigned) readHelper.getChooseNLimit();
  19434. unsigned numParts = keyIndexSet->numParts();
  19435. if (!numParts)
  19436. {
  19437. onEOF();
  19438. return NULL;
  19439. }
  19440. if (numParts > 1 || seekGEOffset)
  19441. {
  19442. tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
  19443. // note that we don't set up translator because we don't support it. If that ever changes...
  19444. }
  19445. else
  19446. {
  19447. tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
  19448. tlk->setLayoutTranslator(translators->item(0));
  19449. }
  19450. indexHelper.createSegmentMonitors(tlk);
  19451. tlk->finishSegmentMonitors();
  19452. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  19453. {
  19454. StringBuffer out;
  19455. printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
  19456. CTXLOG("Using filter %s", out.str());
  19457. if (ctx->queryProbeManager())
  19458. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  19459. }
  19460. tlk->reset();
  19461. callback.setManager(tlk);
  19462. keyedLimit = readHelper.getKeyedLimit();
  19463. if (keyedLimit != (unsigned __int64) -1)
  19464. {
  19465. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  19466. {
  19467. unsigned __int64 count = checkCount(keyedLimit);
  19468. if (count > keyedLimit)
  19469. {
  19470. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  19471. readHelper.onKeyedLimitExceeded();
  19472. const void * ret = NULL;
  19473. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  19474. ret = createKeyedLimitOnFailRow();
  19475. onEOF();
  19476. return ret;
  19477. }
  19478. keyedLimit = (unsigned __int64) -1;
  19479. }
  19480. }
  19481. firstRead = false;
  19482. }
  19483. if (accepted == chooseNLimit)
  19484. {
  19485. onEOF();
  19486. return NULL;
  19487. }
  19488. const byte * rawSeek = NULL;
  19489. unsigned seekSize = 0;
  19490. if (seek)
  19491. {
  19492. seekSize = seekSizes[numFields-1];
  19493. rawSeek = (const byte *)seek + seekGEOffset;
  19494. if (projectedMeta)
  19495. {
  19496. byte *temp = (byte *) alloca(seekSize);
  19497. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  19498. readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  19499. rawSeek = (byte *)temp;
  19500. }
  19501. #ifdef _DEBUG
  19502. // StringBuffer seekStr;
  19503. // for (unsigned i = 0; i < seekSize; i++)
  19504. // {
  19505. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  19506. // }
  19507. // DBGLOG("nextSteppedGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  19508. #endif
  19509. }
  19510. const byte * originalRawSeek = rawSeek;
  19511. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  19512. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  19513. {
  19514. checkAbort();
  19515. keyedCount++;
  19516. if (keyedCount > keyedLimit)
  19517. {
  19518. readHelper.onKeyedLimitExceeded();
  19519. break;
  19520. }
  19521. byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
  19522. #ifdef _DEBUG
  19523. // StringBuffer recstr;
  19524. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  19525. // for (unsigned i = 0; i < size; i++)
  19526. // {
  19527. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  19528. // }
  19529. // DBGLOG("nextSteppedGE Got %s", recstr.str());
  19530. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  19531. assertex(!"smart seek failure");
  19532. #endif
  19533. size32_t transformedSize;
  19534. rowBuilder.ensureRow();
  19535. try
  19536. {
  19537. transformedSize = readHelper.transform(rowBuilder, keyRow);
  19538. //if the post filter causes a mismatch, and the stepping condition no longer matches
  19539. //then return a mismatch record - so the join code can start seeking on the other input.
  19540. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  19541. {
  19542. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  19543. {
  19544. transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
  19545. if (transformedSize != 0)
  19546. wasCompleteMatch = false;
  19547. }
  19548. }
  19549. callback.finishedRow();
  19550. }
  19551. catch (IException *E)
  19552. {
  19553. throw makeWrappedException(E);
  19554. }
  19555. if (transformedSize)
  19556. {
  19557. accepted++;
  19558. if (accepted > rowLimit)
  19559. {
  19560. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  19561. {
  19562. throwUnexpected(); // should not have used simple variant if maySkip set...
  19563. }
  19564. if (traceLevel > 4)
  19565. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19566. readHelper.onLimitExceeded();
  19567. break;
  19568. }
  19569. processed++;
  19570. #ifdef _DEBUG
  19571. // const byte *ret = (const byte *) out.get();
  19572. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  19573. // queryOutputMeta()->toXML(ret, xmlwrite);
  19574. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  19575. #endif
  19576. return rowBuilder.finalizeRowClear(transformedSize);
  19577. }
  19578. else
  19579. rejected++;
  19580. rawSeek = NULL;
  19581. }
  19582. onEOF();
  19583. return NULL;
  19584. }
  19585. virtual void reset()
  19586. {
  19587. onEOF();
  19588. if (accepted)
  19589. noteStatistic(STATS_ACCEPTED, accepted, 1);
  19590. if (rejected)
  19591. noteStatistic(STATS_REJECTED, rejected, 1);
  19592. if (variableFileName)
  19593. {
  19594. varFileInfo.clear();
  19595. translators.clear();
  19596. }
  19597. variableInfoPending = false;
  19598. CRoxieServerActivity::reset();
  19599. }
  19600. virtual void setInput(unsigned idx, IRoxieInput *_in)
  19601. {
  19602. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19603. }
  19604. virtual IInputSteppingMeta * querySteppingMeta()
  19605. {
  19606. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  19607. return &steppingMeta;
  19608. return NULL;
  19609. }
  19610. protected:
  19611. const void * createKeyedLimitOnFailRow()
  19612. {
  19613. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19614. size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
  19615. if (outSize)
  19616. return rowBuilder.finalizeRowClear(outSize);
  19617. return NULL;
  19618. }
  19619. };
  19620. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  19621. {
  19622. public:
  19623. Owned<IKeyArray> keySet;
  19624. Owned<TranslatorArray> translatorArray;
  19625. Owned<IDefRecordMeta> activityMeta;
  19626. RemoteActivityId remoteId;
  19627. bool isSimple;
  19628. bool isLocal;
  19629. bool maySkip;
  19630. bool sorted;
  19631. bool variableFileName;
  19632. bool enableFieldTranslation;
  19633. unsigned maxSeekLookahead;
  19634. Owned<const IResolvedFile> indexfile;
  19635. CRoxieServerSideCache *cache;
  19636. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19637. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  19638. {
  19639. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  19640. unsigned flags = indexHelper->getFlags();
  19641. sorted = (flags & TIRunordered) == 0;
  19642. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  19643. rtlDataAttr indexLayoutMeta;
  19644. size32_t indexLayoutSize;
  19645. if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  19646. assertex(indexLayoutSize==0);
  19647. MemoryBuffer m;
  19648. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  19649. activityMeta.setown(deserializeRecordMeta(m, true));
  19650. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  19651. translatorArray.setown(new TranslatorArray);
  19652. variableFileName = allFilesDynamic || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  19653. if (!variableFileName)
  19654. {
  19655. bool isOpt = (flags & TIRoptional) != 0;
  19656. OwnedRoxieString indexName(indexHelper->getFileName());
  19657. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  19658. if (indexfile)
  19659. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  19660. }
  19661. isSimple = isLocal;
  19662. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  19663. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  19664. {
  19665. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  19666. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  19667. isSimple = true;
  19668. }
  19669. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  19670. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  19671. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  19672. }
  19673. ~CRoxieServerBaseIndexActivityFactory()
  19674. {
  19675. delete cache;
  19676. }
  19677. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  19678. {
  19679. if (indexfile)
  19680. addXrefFileInfo(reply, indexfile);
  19681. }
  19682. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  19683. {
  19684. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  19685. }
  19686. virtual IRoxieServerSideCache *queryServerSideCache() const
  19687. {
  19688. return cache;
  19689. }
  19690. virtual bool getEnableFieldTranslation() const
  19691. {
  19692. return enableFieldTranslation;
  19693. }
  19694. virtual IDefRecordMeta *queryActivityMeta() const
  19695. {
  19696. return activityMeta;
  19697. }
  19698. };
  19699. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19700. {
  19701. public:
  19702. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19703. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19704. {
  19705. }
  19706. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19707. {
  19708. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19709. return new CRoxieServerNullActivity(this, _probeManager);
  19710. else if (isSimple && !maySkip)
  19711. return new CRoxieServerSimpleIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19712. else
  19713. return new CRoxieServerIndexReadActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
  19714. }
  19715. };
  19716. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19717. {
  19718. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19719. }
  19720. //--------------------------------------------------------------------------------------------------------------------------
  19721. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  19722. {
  19723. bool done;
  19724. public:
  19725. CRoxieServerNullCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19726. : CRoxieServerActivity(_factory, _probeManager)
  19727. {
  19728. done = false;
  19729. }
  19730. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19731. {
  19732. done = false;
  19733. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19734. }
  19735. virtual bool needsAllocator() const { return true; }
  19736. virtual const void *nextInGroup()
  19737. {
  19738. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19739. if (done) return NULL;
  19740. done = true;
  19741. size32_t rowSize = meta.getFixedSize();
  19742. void * nullRow = rowAllocator->createRow();
  19743. if (rowSize == 1)
  19744. *(byte *)nullRow = 0;
  19745. else
  19746. {
  19747. assertex(rowSize == sizeof(unsigned __int64));
  19748. *(unsigned __int64 *)nullRow = 0;
  19749. }
  19750. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  19751. }
  19752. };
  19753. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  19754. {
  19755. IHThorCompoundCountExtra & countHelper;
  19756. IHThorSourceCountLimit * limitHelper;
  19757. bool done;
  19758. public:
  19759. CRoxieServerIndexCountActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19760. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19761. countHelper((IHThorIndexCountArg &)basehelper),
  19762. done(false)
  19763. {
  19764. limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
  19765. }
  19766. virtual bool needsAllocator() const { return true; }
  19767. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19768. {
  19769. done = false;
  19770. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19771. choosenLimit = countHelper.getChooseNLimit();
  19772. if (limitHelper)
  19773. {
  19774. rowLimit = limitHelper->getRowLimit();
  19775. keyedLimit = limitHelper->getKeyedLimit();
  19776. }
  19777. if (!paused)
  19778. processAllKeys();
  19779. }
  19780. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  19781. {
  19782. unsigned __int64 count = 0;
  19783. if (countHelper.hasFilter())
  19784. {
  19785. while (tlk->lookup(true))
  19786. {
  19787. try
  19788. {
  19789. count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
  19790. callback.finishedRow();
  19791. }
  19792. catch (IException *E)
  19793. {
  19794. throw makeWrappedException(E);
  19795. }
  19796. accepted++;
  19797. if (count >= choosenLimit) // MORE - what about limit?
  19798. break;
  19799. }
  19800. }
  19801. else
  19802. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  19803. if (count)
  19804. {
  19805. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
  19806. if (count > choosenLimit)
  19807. count = choosenLimit;
  19808. void * recBuffer = rowAllocator->createRow();
  19809. if (meta.getFixedSize() == 1)
  19810. *(byte *)recBuffer = (byte)count;
  19811. else
  19812. {
  19813. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19814. *(unsigned __int64 *)recBuffer = count;
  19815. }
  19816. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  19817. result->append(recBuffer);
  19818. remote.injectResult(result.getClear());
  19819. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  19820. if (count >= choosenLimit)
  19821. return true;
  19822. }
  19823. return false;
  19824. }
  19825. virtual void onLimitExceeded(bool isKeyed)
  19826. {
  19827. if (traceLevel > 4)
  19828. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19829. if (isKeyed)
  19830. {
  19831. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  19832. {
  19833. if (ctx->queryDebugContext())
  19834. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19835. throw makeLimitSkipException(true);
  19836. }
  19837. else
  19838. {
  19839. assertex(limitHelper); // Should not be able to generate exception if there was not one...
  19840. limitHelper->onKeyedLimitExceeded();
  19841. }
  19842. }
  19843. else
  19844. {
  19845. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  19846. {
  19847. if (ctx->queryDebugContext())
  19848. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19849. throw makeLimitSkipException(false);
  19850. }
  19851. else
  19852. {
  19853. assertex(limitHelper);
  19854. limitHelper->onLimitExceeded();
  19855. }
  19856. }
  19857. }
  19858. virtual const void *createLimitFailRow(bool isKeyed)
  19859. {
  19860. throwUnexpected();
  19861. }
  19862. virtual const void *nextInGroup()
  19863. {
  19864. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19865. if (done) return NULL;
  19866. done = true;
  19867. unsigned __int64 totalCount = 0;
  19868. bool hasLimit = rowLimit != (unsigned __int64) -1;
  19869. try
  19870. {
  19871. loop
  19872. {
  19873. const void * next = remote.nextInGroup();
  19874. if (!next)
  19875. break;
  19876. if (meta.getFixedSize() == 1)
  19877. totalCount += *(byte *)next;
  19878. else
  19879. totalCount += *(unsigned __int64 *) next;
  19880. ReleaseRoxieRow(next);
  19881. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  19882. break;
  19883. }
  19884. if (totalCount > rowLimit)
  19885. {
  19886. unsigned flags = indexHelper.getFlags();
  19887. if (flags & TIRlimitskips)
  19888. totalCount = 0;
  19889. else if (flags & TIRlimitcreates)
  19890. totalCount = 1;
  19891. else
  19892. {
  19893. assertex(limitHelper);
  19894. limitHelper->onLimitExceeded();
  19895. }
  19896. }
  19897. else if (totalCount > choosenLimit)
  19898. totalCount = choosenLimit;
  19899. }
  19900. catch (IException *E)
  19901. {
  19902. if (QUERYINTERFACE(E, LimitSkipException))
  19903. {
  19904. totalCount = 0;
  19905. unsigned flags = indexHelper.getFlags();
  19906. if (E->errorCode() == KeyedLimitSkipErrorCode)
  19907. {
  19908. if (flags & TIRkeyedlimitcreates)
  19909. totalCount++;
  19910. }
  19911. else
  19912. {
  19913. if (flags & TIRlimitcreates)
  19914. totalCount++;
  19915. }
  19916. if (totalCount > choosenLimit)
  19917. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  19918. E->Release();
  19919. }
  19920. else
  19921. throw ;
  19922. }
  19923. void * result = rowAllocator->createRow();
  19924. if (meta.getFixedSize() == 1)
  19925. *(byte *)result = (byte)totalCount;
  19926. else
  19927. {
  19928. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  19929. *(unsigned __int64 *)result = totalCount;
  19930. }
  19931. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  19932. }
  19933. };
  19934. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  19935. {
  19936. public:
  19937. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19938. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  19939. {
  19940. }
  19941. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  19942. {
  19943. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  19944. return new CRoxieServerNullCountActivity(this, _probeManager);
  19945. // else if (isSimple)
  19946. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  19947. else
  19948. return new CRoxieServerIndexCountActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  19949. }
  19950. };
  19951. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  19952. {
  19953. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  19954. }
  19955. //--------------------------------------------------------------------------------------------------------------------------
  19956. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  19957. {
  19958. IHThorIndexAggregateArg &aggregateHelper;
  19959. bool done;
  19960. public:
  19961. CRoxieServerNullIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19962. : CRoxieServerActivity(_factory, _probeManager),
  19963. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  19964. {
  19965. done = false;
  19966. }
  19967. virtual bool needsAllocator() const { return true; }
  19968. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19969. {
  19970. done = false;
  19971. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19972. }
  19973. virtual const void *nextInGroup()
  19974. {
  19975. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  19976. if (done) return NULL;
  19977. done = true;
  19978. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19979. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  19980. return rowBuilder.finalizeRowClear(thisSize);
  19981. }
  19982. };
  19983. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  19984. {
  19985. IHThorCompoundAggregateExtra & aggregateHelper;
  19986. bool done;
  19987. public:
  19988. CRoxieServerIndexAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19989. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  19990. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  19991. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  19992. done(false)
  19993. {
  19994. }
  19995. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19996. {
  19997. done = false;
  19998. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  19999. if (!paused)
  20000. processAllKeys();
  20001. }
  20002. virtual bool needsAllocator() const { return true; }
  20003. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20004. {
  20005. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20006. while (tlk->lookup(true))
  20007. {
  20008. if (!rowBuilder.exists())
  20009. {
  20010. rowBuilder.ensureRow();
  20011. aggregateHelper.clearAggregate(rowBuilder);
  20012. }
  20013. try
  20014. {
  20015. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
  20016. callback.finishedRow();
  20017. }
  20018. catch (IException *E)
  20019. {
  20020. throw makeWrappedException(E);
  20021. }
  20022. accepted++;
  20023. }
  20024. if (aggregateHelper.processedAnyRows())
  20025. {
  20026. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  20027. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  20028. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20029. result->append(recBuffer);
  20030. remote.injectResult(result.getClear());
  20031. }
  20032. return false;
  20033. }
  20034. virtual void onLimitExceeded(bool isKeyed)
  20035. {
  20036. if (traceLevel > 4)
  20037. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20038. throwUnexpected();
  20039. }
  20040. virtual const void *createLimitFailRow(bool isKeyed)
  20041. {
  20042. throwUnexpected();
  20043. }
  20044. const void * gatherMerged()
  20045. {
  20046. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20047. const void * firstRow = remote.nextInGroup();
  20048. size32_t finalSize = 0;
  20049. if (!firstRow)
  20050. {
  20051. rowBuilder.ensureRow();
  20052. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20053. }
  20054. else
  20055. {
  20056. // NOTE need to clone this because going to modify below, could special case 1 row only
  20057. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20058. ReleaseRoxieRow(firstRow);
  20059. }
  20060. loop
  20061. {
  20062. const void * next = remote.nextInGroup();
  20063. if (!next)
  20064. break;
  20065. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20066. ReleaseRoxieRow(next);
  20067. }
  20068. return rowBuilder.finalizeRowClear(finalSize);
  20069. }
  20070. virtual const void *nextInGroup()
  20071. {
  20072. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20073. if (done) return NULL;
  20074. const void * ret = gatherMerged();
  20075. done = true;
  20076. return ret;
  20077. }
  20078. };
  20079. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20080. {
  20081. public:
  20082. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20083. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20084. {
  20085. }
  20086. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20087. {
  20088. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20089. return new CRoxieServerNullIndexAggregateActivity(this, _probeManager);
  20090. // else if (isSimple)
  20091. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20092. else
  20093. return new CRoxieServerIndexAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20094. }
  20095. };
  20096. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20097. {
  20098. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20099. }
  20100. //--------------------------------------------------------------------------------------------------------------------------
  20101. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  20102. {
  20103. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  20104. RowAggregator singleAggregator;
  20105. RowAggregator resultAggregator;
  20106. unsigned groupSegCount;
  20107. bool gathered;
  20108. bool eof;
  20109. public:
  20110. CRoxieServerIndexGroupAggregateActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20111. IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
  20112. : CRoxieServerIndexActivity(_factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
  20113. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  20114. singleAggregator(aggregateHelper, aggregateHelper),
  20115. resultAggregator(aggregateHelper, aggregateHelper),
  20116. gathered(false), eof(true)
  20117. {
  20118. groupSegCount = 0;
  20119. }
  20120. IMPLEMENT_IINTERFACE
  20121. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20122. {
  20123. eof = false;
  20124. gathered= false;
  20125. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  20126. groupSegCount = 0;
  20127. if (!paused)
  20128. processAllKeys();
  20129. resultAggregator.start(rowAllocator);
  20130. }
  20131. virtual bool needsAllocator() const { return true; }
  20132. virtual void reset()
  20133. {
  20134. resultAggregator.reset();
  20135. CRoxieServerIndexActivity::reset();
  20136. }
  20137. virtual void processRow(const void * next)
  20138. {
  20139. singleAggregator.addRow(next);
  20140. }
  20141. virtual void createSegmentMonitors(IKeyManager *key)
  20142. {
  20143. unsigned groupSegSize;
  20144. ThorActivityKind kind = factory->getKind();
  20145. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  20146. groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
  20147. else
  20148. groupSegSize = 0;
  20149. if (groupSegSize)
  20150. {
  20151. key->setMergeBarrier(groupSegSize);
  20152. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20153. unsigned numSegs = tlk->ordinality();
  20154. for (unsigned segNo = 0; segNo < numSegs; segNo++)
  20155. {
  20156. IKeySegmentMonitor *seg = tlk->item(segNo);
  20157. if (seg->getOffset()+seg->getSize()==groupSegSize)
  20158. {
  20159. groupSegCount = segNo+1;
  20160. break;
  20161. }
  20162. }
  20163. assertex(groupSegCount);
  20164. }
  20165. else
  20166. CRoxieServerIndexActivity::createSegmentMonitors(key);
  20167. }
  20168. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20169. {
  20170. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20171. singleAggregator.start(rowAllocator);
  20172. ThorActivityKind kind = factory->getKind();
  20173. while (tlk->lookup(true))
  20174. {
  20175. try
  20176. {
  20177. if (groupSegCount && !trans)
  20178. {
  20179. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
  20180. callback.finishedRow();
  20181. if (kind==TAKindexgroupcount)
  20182. {
  20183. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  20184. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  20185. }
  20186. if (!tlk->nextRange(groupSegCount))
  20187. break;
  20188. }
  20189. else
  20190. {
  20191. aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
  20192. callback.finishedRow();
  20193. }
  20194. }
  20195. catch (IException *E)
  20196. {
  20197. throw makeWrappedException(E);
  20198. }
  20199. accepted++;
  20200. }
  20201. loop
  20202. {
  20203. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  20204. if (!next)
  20205. break;
  20206. size32_t size = next->querySize();
  20207. result->append(next->finalizeRowClear());
  20208. }
  20209. remote.injectResult(result.getClear());
  20210. singleAggregator.reset();
  20211. return false;
  20212. }
  20213. virtual void onLimitExceeded(bool isKeyed)
  20214. {
  20215. if (traceLevel > 4)
  20216. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);DBGLOG("%d activityid = %d", __LINE__, activityId);
  20217. throwUnexpected();
  20218. }
  20219. virtual const void *createLimitFailRow(bool isKeyed)
  20220. {
  20221. throwUnexpected();
  20222. }
  20223. void gatherMerged()
  20224. {
  20225. gathered = true;
  20226. loop
  20227. {
  20228. const void * next = remote.nextInGroup();
  20229. if (!next)
  20230. break;
  20231. resultAggregator.mergeElement(next);
  20232. ReleaseRoxieRow(next);
  20233. }
  20234. }
  20235. virtual const void *nextInGroup()
  20236. {
  20237. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  20238. if (eof)
  20239. return NULL;
  20240. if (!gathered)
  20241. gatherMerged();
  20242. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20243. if (next)
  20244. {
  20245. processed++;
  20246. return next->finalizeRowClear();
  20247. }
  20248. eof = true;
  20249. return NULL;
  20250. }
  20251. };
  20252. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20253. {
  20254. public:
  20255. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20256. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20257. {
  20258. }
  20259. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20260. {
  20261. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20262. return new CRoxieServerNullActivity(this, _probeManager);
  20263. // else if (isSimple)
  20264. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  20265. else
  20266. return new CRoxieServerIndexGroupAggregateActivity(this, _probeManager, remoteId, keySet, translatorArray, isLocal);
  20267. }
  20268. };
  20269. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20270. {
  20271. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20272. }
  20273. //--------------------------------------------------------------------------------------------------------------------------
  20274. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  20275. {
  20276. IHThorCompoundNormalizeExtra & readHelper;
  20277. public:
  20278. CRoxieServerIndexNormalizeActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20279. IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
  20280. : CRoxieServerIndexReadBaseActivity(_factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
  20281. readHelper((IHThorIndexNormalizeArg &)basehelper)
  20282. {
  20283. }
  20284. virtual bool needsAllocator() const { return true; }
  20285. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20286. {
  20287. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20288. rowLimit = readHelper.getRowLimit();
  20289. keyedLimit = readHelper.getKeyedLimit();
  20290. if (!paused)
  20291. processAllKeys();
  20292. }
  20293. virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
  20294. {
  20295. unsigned keyedCount = 0;
  20296. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20297. while (tlk->lookup(true))
  20298. {
  20299. keyedCount++;
  20300. if (keyedCount > keyedLimit)
  20301. {
  20302. if (traceLevel > 4)
  20303. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20304. onLimitExceeded(true);
  20305. break;
  20306. }
  20307. size32_t transformedSize;
  20308. if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
  20309. {
  20310. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
  20311. do
  20312. {
  20313. rowBuilder.ensureRow();
  20314. try
  20315. {
  20316. transformedSize = readHelper.transform(rowBuilder);
  20317. }
  20318. catch (IException *E)
  20319. {
  20320. throw makeWrappedException(E);
  20321. }
  20322. if (transformedSize)
  20323. {
  20324. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  20325. result->append(rowBuilder.finalizeRowClear(transformedSize));
  20326. accepted++;
  20327. }
  20328. else
  20329. rejected++;
  20330. } while (readHelper.next());
  20331. remote.injectResult(result.getClear());
  20332. callback.finishedRow();
  20333. }
  20334. }
  20335. return false;
  20336. }
  20337. virtual void onLimitExceeded(bool isKeyed)
  20338. {
  20339. if (traceLevel > 4)
  20340. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20341. if (isKeyed)
  20342. {
  20343. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  20344. {
  20345. if (ctx->queryDebugContext())
  20346. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20347. throw makeLimitSkipException(true);
  20348. }
  20349. else
  20350. readHelper.onKeyedLimitExceeded();
  20351. }
  20352. else
  20353. {
  20354. if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
  20355. {
  20356. if (ctx->queryDebugContext())
  20357. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  20358. throw makeLimitSkipException(false);
  20359. }
  20360. else
  20361. readHelper.onLimitExceeded();
  20362. }
  20363. }
  20364. virtual const void *createLimitFailRow(bool isKeyed)
  20365. {
  20366. UNIMPLEMENTED;
  20367. }
  20368. };
  20369. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  20370. {
  20371. public:
  20372. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20373. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode)
  20374. {
  20375. }
  20376. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20377. {
  20378. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  20379. return new CRoxieServerNullActivity(this, _probeManager);
  20380. else
  20381. return new CRoxieServerIndexNormalizeActivity(this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
  20382. }
  20383. };
  20384. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20385. {
  20386. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20387. }
  20388. //=================================================================================
  20389. class CRoxieServerCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20390. {
  20391. unsigned __int64 answer;
  20392. public:
  20393. CRoxieServerCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned __int64 _answer)
  20394. : CRoxieServerActivity(_factory, _probeManager),
  20395. answer(_answer)
  20396. {
  20397. }
  20398. virtual const void *nextInGroup()
  20399. {
  20400. throwUnexpected();
  20401. }
  20402. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20403. {
  20404. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20405. }
  20406. virtual __int64 evaluate()
  20407. {
  20408. return answer;
  20409. }
  20410. virtual void onLimitExceeded(bool isKeyed)
  20411. {
  20412. if (traceLevel > 4)
  20413. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20414. throwUnexpected();
  20415. }
  20416. virtual const void *createLimitFailRow(bool isKeyed)
  20417. {
  20418. throwUnexpected();
  20419. }
  20420. };
  20421. class CRoxieServerVariableCountDiskActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20422. {
  20423. public:
  20424. CRoxieServerVariableCountDiskActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  20425. : CRoxieServerActivity(_factory, _probeManager)
  20426. {
  20427. }
  20428. virtual const void *nextInGroup()
  20429. {
  20430. throwUnexpected();
  20431. }
  20432. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20433. {
  20434. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20435. }
  20436. virtual __int64 evaluate()
  20437. {
  20438. IHThorCountFileArg &helper = (IHThorCountFileArg &) basehelper;
  20439. bool isOpt = (helper.getFlags() & TDRoptional) != 0;
  20440. unsigned recsize = helper.queryRecordSize()->getFixedSize();
  20441. assertex(recsize);
  20442. OwnedRoxieString fname(helper.getFileName());
  20443. Owned<const IResolvedFile> varFileInfo = resolveLFN(fname, isOpt);
  20444. return varFileInfo->getFileSize() / recsize;
  20445. }
  20446. virtual void onLimitExceeded(bool isKeyed)
  20447. {
  20448. if (traceLevel > 4)
  20449. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20450. throwUnexpected();
  20451. }
  20452. virtual const void *createLimitFailRow(bool isKeyed)
  20453. {
  20454. throwUnexpected();
  20455. }
  20456. };
  20457. class CRoxieServerCountDiskActivityFactory : public CRoxieServerActivityFactory
  20458. {
  20459. public:
  20460. unsigned __int64 answer;
  20461. bool variableFileName;
  20462. Owned<const IResolvedFile> datafile;
  20463. CRoxieServerCountDiskActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20464. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20465. {
  20466. Owned<IHThorCountFileArg> helper = (IHThorCountFileArg *) helperFactory();
  20467. variableFileName = allFilesDynamic || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20468. assertex(helper->queryRecordSize()->isFixedSize());
  20469. if (!variableFileName)
  20470. {
  20471. unsigned recsize = helper->queryRecordSize()->getFixedSize();
  20472. assertex(recsize);
  20473. OwnedRoxieString fileName(helper->getFileName());
  20474. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20475. datafile.setown(queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20476. offset_t filesize = datafile ? datafile->getFileSize() : 0;
  20477. if (filesize % recsize != 0)
  20478. throw MakeStringException(ROXIE_MISMATCH, "Record size mismatch for file %s - %"I64F"d is not a multiple of fixed record size %d", fileName.get(), filesize, recsize);
  20479. answer = filesize / recsize;
  20480. }
  20481. else
  20482. answer = 0;
  20483. }
  20484. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20485. {
  20486. if (datafile)
  20487. addXrefFileInfo(reply, datafile);
  20488. }
  20489. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  20490. {
  20491. arg.Release();
  20492. if (variableFileName)
  20493. return new CRoxieServerVariableCountDiskActivity(this, _probeManager);
  20494. else
  20495. return new CRoxieServerCountDiskActivity(this, _probeManager, answer);
  20496. }
  20497. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20498. {
  20499. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for CountDisk activity");
  20500. }
  20501. virtual bool isFunction() const
  20502. {
  20503. return true;
  20504. }
  20505. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20506. {
  20507. return NULL;
  20508. }
  20509. };
  20510. IRoxieServerActivityFactory *createRoxieServerDiskCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  20511. {
  20512. return new CRoxieServerCountDiskActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  20513. }
  20514. //=================================================================================
  20515. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  20516. {
  20517. IHThorFetchBaseArg &helper;
  20518. IHThorFetchContext * fetchContext;
  20519. Linked<IFilePartMap> map;
  20520. CRemoteResultAdaptor remote;
  20521. RecordPullerThread puller;
  20522. bool needsRHS;
  20523. bool variableFileName;
  20524. bool isOpt;
  20525. Owned<const IResolvedFile> varFileInfo;
  20526. public:
  20527. CRoxieServerFetchActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  20528. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  20529. {
  20530. fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
  20531. needsRHS = helper.transformNeedsRhs();
  20532. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20533. isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
  20534. }
  20535. virtual const IResolvedFile *queryVarFileInfo() const
  20536. {
  20537. return varFileInfo;
  20538. }
  20539. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  20540. {
  20541. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  20542. remote.onCreate(this, this, _ctx, _colocalParent);
  20543. }
  20544. virtual void setInput(unsigned idx, IRoxieInput *_in)
  20545. {
  20546. if (idx)
  20547. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  20548. puller.setInput(this, _in);
  20549. }
  20550. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20551. {
  20552. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20553. remote.onStart(parentExtractSize, parentExtract);
  20554. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  20555. if (variableFileName)
  20556. {
  20557. OwnedRoxieString fname(fetchContext->getFileName());
  20558. varFileInfo.setown(resolveLFN(fname, isOpt));
  20559. if (varFileInfo)
  20560. map.setown(varFileInfo->getFileMap());
  20561. }
  20562. puller.start(parentExtractSize, parentExtract, paused, ctx->fetchPreload(), false, ctx);
  20563. }
  20564. virtual void stop(bool aborting)
  20565. {
  20566. // Called from remote, so no need to call back to it....
  20567. puller.stop(aborting);
  20568. CRoxieServerActivity::stop(aborting);
  20569. }
  20570. virtual void reset()
  20571. {
  20572. processed = remote.processed;
  20573. remote.processed = 0;
  20574. puller.reset();
  20575. if (variableFileName)
  20576. {
  20577. varFileInfo.clear();
  20578. map.clear();
  20579. }
  20580. CRoxieServerActivity::reset();
  20581. }
  20582. virtual IRoxieInput *queryOutput(unsigned idx)
  20583. {
  20584. if (idx==(unsigned)-1)
  20585. idx = 0;
  20586. return idx ? NULL : &remote;
  20587. }
  20588. virtual void processRow(const void *row)
  20589. {
  20590. // called from puller thread
  20591. offset_t rp = fetchContext->extractPosition(row);
  20592. unsigned partNo;
  20593. if (isLocalFpos(rp))
  20594. partNo = getLocalFposPart(rp) + 1;
  20595. else
  20596. partNo = map->mapOffset(rp);
  20597. if (needsRHS)
  20598. {
  20599. Owned<IEngineRowAllocator> extractAllocator = ctx->queryCodeContext()->getRowAllocator(helper.queryExtractedSize(), activityId);
  20600. RtlDynamicRowBuilder rb(extractAllocator, true);
  20601. unsigned rhsSize = helper.extractJoinFields(rb, row);
  20602. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  20603. *(offset_t *) block = rp;
  20604. block += sizeof(rp);
  20605. *(unsigned *) block = rhsSize;
  20606. block += sizeof(rhsSize);
  20607. memcpy(block, rb.row(), rhsSize);
  20608. }
  20609. else
  20610. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  20611. ReleaseRoxieRow(row);
  20612. }
  20613. void processEOG()
  20614. {
  20615. #ifdef FETCH_PRESERVES_GROUPING
  20616. UNIMPLEMENTED;
  20617. #endif
  20618. // else discard is correct
  20619. }
  20620. void processGroup(const ConstPointerArray &)
  20621. {
  20622. throwUnexpected();
  20623. }
  20624. void processDone()
  20625. {
  20626. // called from puller thread
  20627. remote.flush();
  20628. remote.senddone();
  20629. }
  20630. virtual bool fireException(IException *e)
  20631. {
  20632. return remote.fireException(e);
  20633. }
  20634. virtual void onLimitExceeded(bool isKeyed)
  20635. {
  20636. if (traceLevel > 4)
  20637. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  20638. if (isKeyed)
  20639. throwUnexpected();
  20640. helper.onLimitExceeded();
  20641. }
  20642. virtual const void *createLimitFailRow(bool isKeyed)
  20643. {
  20644. UNIMPLEMENTED;
  20645. }
  20646. virtual const void *nextInGroup()
  20647. {
  20648. throwUnexpected(); // I am nobody's input
  20649. }
  20650. };
  20651. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  20652. {
  20653. RemoteActivityId remoteId;
  20654. Owned<IFilePartMap> map;
  20655. bool variableFileName;
  20656. Owned<const IResolvedFile> datafile;
  20657. public:
  20658. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20659. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), remoteId(_remoteId)
  20660. {
  20661. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  20662. IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
  20663. variableFileName = allFilesDynamic || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  20664. if (!variableFileName)
  20665. {
  20666. OwnedRoxieString fname(fetchContext->getFileName());
  20667. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  20668. (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
  20669. true, true,
  20670. _queryFactory.queryWorkUnit()));
  20671. if (datafile)
  20672. map.setown(datafile->getFileMap());
  20673. }
  20674. }
  20675. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  20676. {
  20677. return new CRoxieServerFetchActivity(this, _probeManager, remoteId, map);
  20678. }
  20679. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20680. {
  20681. if (datafile)
  20682. addXrefFileInfo(reply, datafile);
  20683. }
  20684. };
  20685. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, IPropertyTree &_graphNode)
  20686. {
  20687. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _graphNode);
  20688. }
  20689. // MORE - is there any point keeping this now?
  20690. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  20691. {
  20692. public:
  20693. Owned<const IResolvedFile> indexfile;
  20694. Owned<const IResolvedFile> datafile;
  20695. Owned<IKeyArray> keySet;
  20696. Owned<IFileIOArray> files;
  20697. Owned<IFilePartMap> map;
  20698. TranslatorArray layoutTranslators;
  20699. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20700. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  20701. {
  20702. try // does not want any missing file errors to be fatal, or throw traps - just log it
  20703. {
  20704. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  20705. return; // ignore 'spills'
  20706. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20707. bool isOpt = _graphNode.getPropBool("att[@name='_isOpt']/@value") || pretendAllOpt;
  20708. const char *fileName = queryNodeFileName(_graphNode);
  20709. const char *indexName = queryNodeIndexName(_graphNode);
  20710. if (indexName && (!fileName || !streq(indexName, fileName)))
  20711. {
  20712. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20713. if (indexfile)
  20714. keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
  20715. }
  20716. if (fileName)
  20717. {
  20718. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  20719. if (datafile)
  20720. {
  20721. if (isLocal)
  20722. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  20723. else
  20724. map.setown(datafile->getFileMap());
  20725. }
  20726. }
  20727. }
  20728. catch(IException *E)
  20729. {
  20730. StringBuffer errors;
  20731. E->errorMessage(errors);
  20732. DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  20733. E->Release();
  20734. }
  20735. }
  20736. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const { throw MakeStringException(ROXIE_INTERNAL_ERROR, "%s query %s is suspended and cannot be executed - error occurred at %s(%d)", (queryFactory.isQueryLibrary()) ? "Library" : " ", queryFactory.queryQueryName(), __FILE__, __LINE__); }
  20737. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20738. {
  20739. if (datafile)
  20740. addXrefFileInfo(reply, datafile);
  20741. if (indexfile)
  20742. addXrefFileInfo(reply, indexfile);
  20743. }
  20744. };
  20745. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  20746. {
  20747. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  20748. }
  20749. //=====================================================================================================
  20750. // Keyed joins...
  20751. //
  20752. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  20753. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  20754. // A separate thread (the caller's thread) is waiting on slave replies, and once it has all replies for a given LHS record or group of records, calls
  20755. // the transform and returns rows that are created.
  20756. // For a full-keyed join, there is a third thread that is pulling replies from index part and passing them to fetch part (check this is true)
  20757. //
  20758. //=====================================================================================================
  20759. class CJoinGroup;
  20760. interface IJoinProcessor
  20761. {
  20762. virtual void processEOG() = 0;
  20763. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  20764. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  20765. virtual bool fireException(IException *E) = 0;
  20766. virtual void processCompletedGroups() = 0;
  20767. };
  20768. //------------------------------------------------------------------------------------------------------
  20769. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  20770. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  20771. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  20772. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  20773. // per-query limits etc (Note that the pointer array block is not though).
  20774. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  20775. //
  20776. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  20777. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  20778. // initial count when created.
  20779. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  20780. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  20781. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  20782. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  20783. // remaining reference and the JoinGroup will be processed and destroyed.
  20784. //
  20785. //------------------------------------------------------------------------------------------------------
  20786. class CJoinGroup : public CInterface, implements IInterface
  20787. {
  20788. protected:
  20789. const void *left; // LHS row
  20790. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  20791. atomic_t endMarkersPending; // How many slave responses still waiting for
  20792. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  20793. unsigned lastPartNo;
  20794. unsigned pos;
  20795. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  20796. public:
  20797. #undef new
  20798. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  20799. {
  20800. return a->allocate(size, activityId);
  20801. }
  20802. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  20803. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  20804. #endif
  20805. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  20806. {
  20807. ReleaseRoxieRow(ptr);
  20808. }
  20809. void operator delete(void *ptr)
  20810. {
  20811. ReleaseRoxieRow(ptr);
  20812. }
  20813. public:
  20814. IMPLEMENT_IINTERFACE;
  20815. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  20816. {
  20817. #ifdef TRACE_JOINGROUPS
  20818. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  20819. #endif
  20820. candidates = 0;
  20821. lastPartNo = 0;
  20822. pos = 0;
  20823. left = _left;
  20824. groupStart = _groupStart;
  20825. if (_groupStart)
  20826. {
  20827. atomic_inc(&_groupStart->endMarkersPending);
  20828. }
  20829. atomic_set(&endMarkersPending, 1);
  20830. }
  20831. ~CJoinGroup()
  20832. {
  20833. #ifdef TRACE_JOINGROUPS
  20834. DBGLOG("Destroying joinGroup %p", this);
  20835. #endif
  20836. if (left)
  20837. {
  20838. ReleaseRoxieRow(left);
  20839. ForEachItemIn(idx, rows)
  20840. ReleaseRoxieRow(rows.item(idx));
  20841. rows.kill();
  20842. }
  20843. }
  20844. inline bool isHeadRecord() const
  20845. {
  20846. return left==NULL;
  20847. }
  20848. inline bool complete() const
  20849. {
  20850. return atomic_read(&endMarkersPending) == 0;
  20851. }
  20852. #ifdef TRACE_JOINGROUPS
  20853. inline void notePending(unsigned lineNo)
  20854. #else
  20855. inline void notePending()
  20856. #endif
  20857. {
  20858. assert(!complete());
  20859. atomic_inc(&endMarkersPending);
  20860. #ifdef TRACE_JOINGROUPS
  20861. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  20862. #endif
  20863. }
  20864. inline bool inGroup(CJoinGroup *leader) const
  20865. {
  20866. return groupStart==leader;
  20867. }
  20868. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  20869. {
  20870. // Single threaded by now
  20871. assert(complete());
  20872. return rows.item(idx);
  20873. }
  20874. #ifdef TRACE_JOINGROUPS
  20875. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  20876. #else
  20877. bool noteEndReceived(unsigned candidateCount)
  20878. #endif
  20879. {
  20880. assert(!complete());
  20881. if (candidateCount)
  20882. {
  20883. candidates += candidateCount;
  20884. }
  20885. #ifdef TRACE_JOINGROUPS
  20886. DBGLOG("CJoinGroup::noteEndReceived %p from %d, candidates %d + %d, my count was %d, group count was %d", this, lineNo, candidates, candidateCount, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  20887. #endif
  20888. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  20889. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  20890. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  20891. CJoinGroup *localGroupStart = groupStart;
  20892. if (atomic_dec_and_test(&endMarkersPending))
  20893. {
  20894. if (localGroupStart)
  20895. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  20896. else
  20897. return true;
  20898. }
  20899. else
  20900. return false;
  20901. }
  20902. inline const void *queryLeft() const
  20903. {
  20904. return left;
  20905. }
  20906. void addRightMatch(KeyedJoinHeader *right)
  20907. {
  20908. assert(!complete());
  20909. unsigned short partNo = right->partNo;
  20910. if (partNo != lastPartNo)
  20911. {
  20912. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  20913. if (partNo > lastPartNo)
  20914. pos = rows.length();
  20915. while (pos>0)
  20916. {
  20917. if (rows.item(pos-1)->partNo <= partNo)
  20918. break;
  20919. pos--;
  20920. }
  20921. lastPartNo = partNo;
  20922. }
  20923. rows.add(right, pos);
  20924. pos++;
  20925. }
  20926. inline unsigned rowsSeen() const
  20927. {
  20928. assert(complete());
  20929. return rows.length();
  20930. }
  20931. inline unsigned candidateCount() const
  20932. {
  20933. assert(complete());
  20934. return candidates;
  20935. }
  20936. };
  20937. #ifdef TRACE_JOINGROUPS
  20938. #define notePending() notePending(__LINE__)
  20939. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  20940. #endif
  20941. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  20942. {
  20943. private:
  20944. SafeQueueOf<const void, true> ready;
  20945. public:
  20946. IHThorKeyedJoinArg &helper;
  20947. unsigned joinProcessed;
  20948. bool isFullKey;
  20949. bool eof;
  20950. bool isSimple;
  20951. bool allPulled;
  20952. unsigned __int64 totalCycles;
  20953. unsigned activityId;
  20954. RecordPullerThread &puller;
  20955. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  20956. Owned<IEngineRowAllocator> ccdRecordAllocator;
  20957. IJoinProcessor &processor;
  20958. KeyedJoinRemoteAdaptor(const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper, IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  20959. RecordPullerThread &_puller, IJoinProcessor &_processor)
  20960. : helper(_helper),
  20961. CRemoteResultAdaptor(_remoteId, 0, _helper, _activity, true, true),
  20962. isFullKey(_isFullKey),
  20963. isSimple(_isSimple),
  20964. puller(_puller),
  20965. processor(_processor),
  20966. activityId(_activity.queryId())
  20967. {
  20968. joinProcessed = 0;
  20969. totalCycles = 0;
  20970. allPulled = false;
  20971. eof = false;
  20972. }
  20973. virtual void onCreate(IRoxieInput *_owner, IRoxieServerErrorHandler *_errorHandler, IRoxieSlaveContext *_ctx, IHThorArg *_colocalArg)
  20974. {
  20975. CRemoteResultAdaptor::onCreate(_owner, _errorHandler, _ctx, _colocalArg);
  20976. ccdRecordAllocator.setown(ctx->queryCodeContext()->getRowAllocator(QUERYINTERFACE(helper.queryJoinFieldsRecordSize(), IOutputMetaData), activityId));
  20977. }
  20978. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20979. {
  20980. eof = false;
  20981. joinProcessed = 0;
  20982. totalCycles = 0;
  20983. allPulled = false;
  20984. assertex(ready.ordinality()==0);
  20985. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  20986. }
  20987. virtual void reset()
  20988. {
  20989. CRemoteResultAdaptor::reset();
  20990. while (ready.ordinality())
  20991. {
  20992. const void *goer = ready.dequeue();
  20993. if (goer)
  20994. ReleaseRoxieRow(goer);
  20995. }
  20996. while (injected.ordinality())
  20997. {
  20998. const void *goer = injected.dequeue();
  20999. if (goer)
  21000. ReleaseRoxieRow(goer);
  21001. }
  21002. }
  21003. inline void addResult(const void *row)
  21004. {
  21005. ready.enqueue(row);
  21006. }
  21007. virtual unsigned __int64 queryTotalCycles() const
  21008. {
  21009. return totalCycles;
  21010. }
  21011. virtual IOutputMetaData * queryOutputMeta() const
  21012. {
  21013. return owner->queryOutputMeta();
  21014. }
  21015. virtual const void *nextInGroup()
  21016. {
  21017. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  21018. loop
  21019. {
  21020. if (eof)
  21021. return NULL;
  21022. processSlaveResults();
  21023. if (ready.ordinality())
  21024. {
  21025. const void *result = ready.dequeue();
  21026. if (result)
  21027. joinProcessed++;
  21028. return result;
  21029. }
  21030. else
  21031. eof = true;
  21032. }
  21033. }
  21034. private:
  21035. void processSlaveResults()
  21036. {
  21037. while (!ready.ordinality())
  21038. {
  21039. KeyedJoinHeader *fetchedData;
  21040. if (isSimple)
  21041. {
  21042. while (!allPulled && !injected.ordinality())
  21043. {
  21044. if (!puller.pullRecords(1))
  21045. {
  21046. puller.done();
  21047. allPulled = true;
  21048. }
  21049. }
  21050. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  21051. }
  21052. else
  21053. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextInGroup();
  21054. if (fetchedData)
  21055. {
  21056. CJoinGroup *thisGroup = fetchedData->thisGroup;
  21057. if (fetchedData->partNo == (unsigned short) -1)
  21058. {
  21059. #ifdef TRACE_JOINGROUPS
  21060. CTXLOG("Got end for group %p", thisGroup);
  21061. #endif
  21062. unsigned candidateCount = (unsigned) fetchedData->fpos;
  21063. ReleaseRoxieRow(fetchedData);
  21064. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  21065. }
  21066. else
  21067. {
  21068. #ifdef TRACE_JOINGROUPS
  21069. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  21070. #endif
  21071. thisGroup->addRightMatch(fetchedData);
  21072. if (isFullKey)
  21073. {
  21074. #ifdef TRACE_JOINGROUPS
  21075. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  21076. #endif
  21077. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  21078. }
  21079. }
  21080. }
  21081. else
  21082. break;
  21083. }
  21084. }
  21085. };
  21086. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  21087. {
  21088. IHThorKeyedJoinArg &helper;
  21089. Owned<IKeyManager> tlk;
  21090. Linked<IKeyArray> keySet;
  21091. Linked<TranslatorArray> translators;
  21092. CRemoteResultAdaptor remote;
  21093. RecordPullerThread puller;
  21094. IOutputMetaData *indexReadMeta;
  21095. IJoinProcessor *joinHandler;
  21096. bool variableIndexFileName;
  21097. bool indexReadInputRecordVariable;
  21098. bool isLocal;
  21099. Owned<IEngineRowAllocator> indexReadAllocator;
  21100. Owned<const IResolvedFile> varFileInfo;
  21101. IRoxieInput *indexReadInput;
  21102. IIndexReadActivityInfo *rootIndex;
  21103. public:
  21104. CRoxieServerFullKeyedJoinHead(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  21105. : CRoxieServerActivity(_factory, _probeManager),
  21106. helper((IHThorKeyedJoinArg &)basehelper),
  21107. tlk(createKeyManager(NULL, 0, this)),
  21108. translators(_translators),
  21109. keySet(_keySet),
  21110. remote(_remoteId, 0, helper, *this, true, true),
  21111. indexReadMeta(_indexReadMeta),
  21112. joinHandler(_joinHandler),
  21113. puller(false),
  21114. isLocal(_isLocal)
  21115. {
  21116. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21117. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21118. indexReadInput = NULL;
  21119. rootIndex = NULL;
  21120. }
  21121. virtual const IResolvedFile *queryVarFileInfo() const
  21122. {
  21123. return varFileInfo;
  21124. }
  21125. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21126. {
  21127. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21128. remote.onCreate(this, this, _ctx, _colocalParent);
  21129. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21130. }
  21131. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21132. {
  21133. if (!idx)
  21134. puller.setInput(this, _in);
  21135. else if (idx==1)
  21136. indexReadInput = _in;
  21137. else
  21138. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21139. }
  21140. virtual void serializeExtra(MemoryBuffer &out)
  21141. {
  21142. if (helper.getJoinFlags() & JFindexfromactivity)
  21143. {
  21144. assertex(rootIndex);
  21145. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21146. indexId.serialize(out);
  21147. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21148. MemoryBuffer tmp;
  21149. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21150. if (rootIndex->queryActivity()->queryVarFileInfo())
  21151. {
  21152. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21153. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21154. }
  21155. unsigned ctxlen = tmp.length();
  21156. out.append(ctxlen).append(tmp);
  21157. }
  21158. }
  21159. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21160. {
  21161. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21162. if (indexReadInput)
  21163. {
  21164. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21165. rootIndex = indexReadInput->queryIndexReadActivity();
  21166. if (!rootIndex)
  21167. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21168. }
  21169. remote.onStart(parentExtractSize, parentExtract);
  21170. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21171. if (rootIndex)
  21172. {
  21173. varFileInfo.setown(rootIndex->getVarFileInfo());
  21174. translators.setown(rootIndex->getTranslators());
  21175. keySet.setown(rootIndex->getKeySet());
  21176. }
  21177. else if (variableIndexFileName)
  21178. {
  21179. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21180. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21181. if (varFileInfo)
  21182. {
  21183. translators.setown(new TranslatorArray);
  21184. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation())); // MORE - isLocal?
  21185. }
  21186. }
  21187. puller.start(parentExtractSize, parentExtract, paused, ctx->fullKeyedJoinPreload(), false, ctx);
  21188. }
  21189. virtual void stop(bool aborting)
  21190. {
  21191. puller.stop(aborting);
  21192. CRoxieServerActivity::stop(aborting);
  21193. }
  21194. virtual void reset()
  21195. {
  21196. CRoxieServerActivity::reset();
  21197. puller.reset();
  21198. if (varFileInfo)
  21199. {
  21200. keySet.clear();
  21201. varFileInfo.clear();
  21202. }
  21203. }
  21204. virtual IRoxieInput *queryOutput(unsigned idx)
  21205. {
  21206. if (idx==(unsigned)-1)
  21207. idx = 0;
  21208. return idx ? NULL : &remote;
  21209. }
  21210. virtual void processRow(const void *row)
  21211. {
  21212. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  21213. // called from front puller thread
  21214. // buffer up an IndexRead request
  21215. if (helper.leftCanMatch(row))
  21216. {
  21217. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  21218. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  21219. OwnedConstRoxieRow extracted;
  21220. if (indexReadSize)
  21221. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  21222. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  21223. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21224. {
  21225. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21226. if (thisBase)
  21227. {
  21228. unsigned fileNo = 0;
  21229. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21230. try
  21231. {
  21232. tlk->setKey(thisKey);
  21233. tlk->setLayoutTranslator(translators->item(fileNo));
  21234. helper.createSegmentMonitors(tlk, extracted);
  21235. if (rootIndex)
  21236. rootIndex->mergeSegmentMonitors(tlk);
  21237. tlk->finishSegmentMonitors();
  21238. tlk->reset();
  21239. loop
  21240. {
  21241. typedef const void * cvp;
  21242. if (thisKey->isTopLevelKey())
  21243. {
  21244. bool locallySorted = !thisKey->isFullySorted();
  21245. while (locallySorted || tlk->lookup(false))
  21246. {
  21247. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21248. if (locallySorted || slavePart)
  21249. {
  21250. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21251. *outputBuffer++ = jg;
  21252. if (indexReadInputRecordVariable)
  21253. {
  21254. *(unsigned *) outputBuffer = indexReadSize;
  21255. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  21256. }
  21257. jg->notePending();
  21258. memcpy(outputBuffer, extracted, indexReadSize);
  21259. if (locallySorted)
  21260. {
  21261. for (unsigned i = 1; i < numChannels; i++)
  21262. jg->notePending();
  21263. break;
  21264. }
  21265. }
  21266. }
  21267. }
  21268. else
  21269. {
  21270. // MORE - this code seems to be duplicated in half keyed
  21271. unsigned accepted = 0;
  21272. unsigned rejected = 0;
  21273. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
  21274. jg->notePending();
  21275. unsigned candidateCount = 0;
  21276. while (tlk->lookup(true))
  21277. {
  21278. candidateCount++;
  21279. atomic_inc(&indexRecordsRead);
  21280. KLBlobProviderAdapter adapter(tlk);
  21281. offset_t recptr;
  21282. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  21283. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  21284. {
  21285. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21286. rhs->fpos = recptr;
  21287. rhs->thisGroup = jg;
  21288. rhs->partNo = partNo;
  21289. result->append(rhs);
  21290. }
  21291. else
  21292. {
  21293. rejected++;
  21294. atomic_inc(&postFiltered);
  21295. }
  21296. }
  21297. // output an end marker for the matches to this group
  21298. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  21299. endMarker->fpos = (offset_t) candidateCount;
  21300. endMarker->thisGroup = jg;
  21301. endMarker->partNo = (unsigned short) -1;
  21302. result->append(endMarker);
  21303. remote.injectResult(result.getClear());
  21304. if (accepted)
  21305. noteStatistic(STATS_ACCEPTED, accepted, 1);
  21306. if (rejected)
  21307. noteStatistic(STATS_REJECTED, rejected, 1);
  21308. }
  21309. if (++fileNo < thisBase->numParts())
  21310. {
  21311. thisKey = thisBase->queryPart(fileNo);
  21312. tlk->setKey(thisKey);
  21313. tlk->setLayoutTranslator(translators->item(fileNo));
  21314. tlk->reset();
  21315. }
  21316. else
  21317. break;
  21318. }
  21319. tlk->releaseSegmentMonitors();
  21320. tlk->setKey(NULL);
  21321. }
  21322. catch (...)
  21323. {
  21324. tlk->releaseSegmentMonitors();
  21325. tlk->setKey(NULL);
  21326. throw;
  21327. }
  21328. }
  21329. }
  21330. joinHandler->noteEndReceived(jg, 0);
  21331. }
  21332. else
  21333. {
  21334. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  21335. }
  21336. }
  21337. void processGroup(const ConstPointerArray &)
  21338. {
  21339. throwUnexpected();
  21340. }
  21341. virtual void processEOG()
  21342. {
  21343. joinHandler->processEOG();
  21344. }
  21345. virtual void processDone()
  21346. {
  21347. // called from puller thread
  21348. remote.flush();
  21349. remote.senddone();
  21350. }
  21351. virtual void onLimitExceeded(bool isKeyed)
  21352. {
  21353. if (traceLevel > 4)
  21354. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21355. if (isKeyed)
  21356. throwUnexpected();
  21357. helper.onLimitExceeded();
  21358. }
  21359. virtual const void *createLimitFailRow(bool isKeyed)
  21360. {
  21361. throwUnexpected();
  21362. }
  21363. virtual bool fireException(IException *e)
  21364. {
  21365. // called from puller thread on failure
  21366. remote.fireException(LINK(e));
  21367. return joinHandler->fireException(e);
  21368. }
  21369. virtual const void *nextInGroup()
  21370. {
  21371. throwUnexpected(); // I am nobody's input
  21372. }
  21373. };
  21374. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  21375. {
  21376. protected:
  21377. IHThorKeyedJoinArg &helper;
  21378. KeyedJoinRemoteAdaptor remote;
  21379. RecordPullerThread puller;
  21380. OwnedConstRoxieRow defaultRight;
  21381. Owned<IEngineRowAllocator> defaultRightAllocator;
  21382. unsigned joinFlags;
  21383. unsigned atMost;
  21384. unsigned atmostsTriggered;
  21385. unsigned abortLimit;
  21386. unsigned keepLimit;
  21387. bool limitFail;
  21388. bool limitOnFail;
  21389. bool preserveGroups;
  21390. bool cloneLeft;
  21391. bool isSimple;
  21392. bool isLocal;
  21393. ThorActivityKind activityKind;
  21394. CJoinGroup *groupStart;
  21395. CriticalSection groupsCrit;
  21396. QueueOf<CJoinGroup, false> groups;
  21397. IRoxieInput *indexReadInput;
  21398. IIndexReadActivityInfo *rootIndex;
  21399. void createDefaultRight()
  21400. {
  21401. if (!defaultRight)
  21402. {
  21403. if (!defaultRightAllocator)
  21404. defaultRightAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryJoinFieldsRecordSize(), activityId));
  21405. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  21406. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  21407. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  21408. }
  21409. }
  21410. public:
  21411. CRoxieServerKeyedJoinBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  21412. , bool isFull, bool _isSimple, bool _isLocal)
  21413. : CRoxieServerActivity(_factory, _probeManager),
  21414. helper((IHThorKeyedJoinArg &)basehelper),
  21415. remote(_remoteId, helper, *this, isFull, _isSimple, puller, *this),
  21416. joinFlags(_joinFlags),
  21417. preserveGroups(meta.isGrouped()),
  21418. puller(false),
  21419. isSimple(_isSimple),
  21420. isLocal(_isLocal),
  21421. abortLimit(0),
  21422. keepLimit(0),
  21423. atMost(0),
  21424. limitFail(false),
  21425. limitOnFail(false),
  21426. cloneLeft(false)
  21427. {
  21428. groupStart = NULL;
  21429. activityKind = _factory->getKind();
  21430. indexReadInput = NULL;
  21431. rootIndex = NULL;
  21432. atmostsTriggered = 0;
  21433. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  21434. }
  21435. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21436. {
  21437. CRoxieServerActivity::onCreate(_ctx, _colocalParent);
  21438. remote.onCreate(this, this, _ctx, _colocalParent);
  21439. }
  21440. virtual void setInput(unsigned idx, IRoxieInput *_in)
  21441. {
  21442. if (!idx)
  21443. puller.setInput(this, _in);
  21444. else if (idx==1)
  21445. indexReadInput = _in;
  21446. else
  21447. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", __FILE__, __LINE__);
  21448. }
  21449. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21450. {
  21451. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21452. if (indexReadInput)
  21453. {
  21454. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  21455. rootIndex = indexReadInput->queryIndexReadActivity();
  21456. if (!rootIndex)
  21457. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  21458. }
  21459. remote.onStart(parentExtractSize, parentExtract);
  21460. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  21461. atmostsTriggered = 0;
  21462. atMost = helper.getJoinLimit();
  21463. if (atMost == 0) atMost = (unsigned)-1;
  21464. abortLimit = helper.getMatchAbortLimit();
  21465. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  21466. keepLimit = helper.getKeepLimit();
  21467. if (keepLimit == 0) keepLimit = (unsigned)-1;
  21468. getLimitType(joinFlags, limitFail, limitOnFail);
  21469. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  21470. if (joinFlags & JFleftouter)
  21471. createDefaultRight();
  21472. }
  21473. virtual void stop(bool aborting)
  21474. {
  21475. puller.stop(aborting);
  21476. if (indexReadInput)
  21477. indexReadInput->stop(aborting);
  21478. CRoxieServerActivity::stop(aborting);
  21479. }
  21480. virtual unsigned __int64 queryLocalCycles() const
  21481. {
  21482. __int64 localCycles = remote.totalCycles;
  21483. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  21484. if (localCycles < 0)
  21485. localCycles = 0;
  21486. return localCycles;
  21487. }
  21488. virtual IRoxieInput *queryInput(unsigned idx)
  21489. {
  21490. if (idx==0)
  21491. return puller.queryInput();
  21492. else if (idx==1)
  21493. return indexReadInput;
  21494. else
  21495. return NULL;
  21496. }
  21497. virtual void reset()
  21498. {
  21499. totalCycles = remote.totalCycles;
  21500. remote.totalCycles = 0;
  21501. processed = remote.joinProcessed;
  21502. remote.joinProcessed = 0;
  21503. defaultRight.clear();
  21504. if (indexReadInput)
  21505. indexReadInput->reset();
  21506. if (atmostsTriggered)
  21507. noteStatistic(STATS_ATMOST, atmostsTriggered, 1);
  21508. CRoxieServerActivity::reset();
  21509. puller.reset();
  21510. while (groups.ordinality())
  21511. {
  21512. ::Release(groups.dequeue());
  21513. }
  21514. }
  21515. virtual IRoxieInput *queryOutput(unsigned idx)
  21516. {
  21517. if (idx==(unsigned)-1)
  21518. idx = 0;
  21519. return idx ? NULL : &remote;
  21520. }
  21521. #undef new
  21522. virtual CJoinGroup *createJoinGroup(const void *row)
  21523. {
  21524. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  21525. CriticalBlock c(groupsCrit);
  21526. if (preserveGroups && !groupStart)
  21527. {
  21528. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  21529. groups.enqueue(groupStart);
  21530. }
  21531. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  21532. groups.enqueue(jg);
  21533. return jg;
  21534. }
  21535. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  21536. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  21537. #endif
  21538. void endGroup()
  21539. {
  21540. CriticalBlock c(groupsCrit);
  21541. if (groupStart)
  21542. noteEndReceived(groupStart, 0);
  21543. groupStart = NULL;
  21544. }
  21545. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  21546. {
  21547. if (jg->noteEndReceived(candidateCount))
  21548. processCompletedGroups();
  21549. }
  21550. void processCompletedGroups()
  21551. {
  21552. loop
  21553. {
  21554. CriticalBlock c(groupsCrit);
  21555. if (!groups.head()->complete())
  21556. break;
  21557. Owned<CJoinGroup> head = groups.dequeue();
  21558. if (preserveGroups)
  21559. {
  21560. assert(head->isHeadRecord());
  21561. assert(groups.head()->inGroup(head));
  21562. unsigned joinGroupSize = 0;
  21563. while (groups.ordinality() && groups.head()->inGroup(head))
  21564. {
  21565. Owned<CJoinGroup> finger = groups.dequeue();
  21566. joinGroupSize += doJoinGroup(finger);
  21567. }
  21568. if (joinGroupSize)
  21569. remote.addResult(NULL);
  21570. }
  21571. else
  21572. doJoinGroup(head);
  21573. if (!groups.ordinality())
  21574. break;
  21575. }
  21576. }
  21577. void failLimit(const void * left)
  21578. {
  21579. helper.onMatchAbortLimitExceeded();
  21580. CommonXmlWriter xmlwrite(0);
  21581. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  21582. {
  21583. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  21584. }
  21585. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  21586. }
  21587. virtual bool needsAllocator() const { return true; }
  21588. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group)
  21589. {
  21590. if (cloneLeft && !except)
  21591. {
  21592. LinkRoxieRow(left);
  21593. remote.addResult((void *) left);
  21594. return 1;
  21595. }
  21596. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21597. unsigned outSize;
  21598. try
  21599. {
  21600. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  21601. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
  21602. helper.transform(rowBuilder, left, right, fpos_or_count);
  21603. }
  21604. catch (IException *E)
  21605. {
  21606. throw makeWrappedException(E);
  21607. }
  21608. if (outSize)
  21609. {
  21610. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  21611. remote.addResult(shrunk);
  21612. return 1;
  21613. }
  21614. else
  21615. return 0;
  21616. }
  21617. unsigned doJoinGroup(CJoinGroup *jg)
  21618. {
  21619. unsigned matched = jg->rowsSeen();
  21620. unsigned added = 0;
  21621. const void *left = jg->queryLeft();
  21622. if (jg->candidateCount() > abortLimit)
  21623. {
  21624. if (limitFail)
  21625. failLimit(left);
  21626. if (ctx->queryDebugContext())
  21627. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21628. if (limitOnFail)
  21629. {
  21630. Owned<IException> except;
  21631. try
  21632. {
  21633. failLimit(left);
  21634. }
  21635. catch(IException * e)
  21636. {
  21637. except.setown(e);
  21638. }
  21639. added = doTransform(left, defaultRight, 0, except, NULL);
  21640. }
  21641. }
  21642. else if (!matched || jg->candidateCount() > atMost)
  21643. {
  21644. if (jg->candidateCount() > atMost)
  21645. atmostsTriggered++;
  21646. switch (joinFlags & JFtypemask)
  21647. {
  21648. case JFleftouter:
  21649. case JFleftonly:
  21650. switch (activityKind)
  21651. {
  21652. case TAKkeyedjoin:
  21653. case TAKkeyeddenormalizegroup:
  21654. added = doTransform(left, defaultRight, 0, NULL, NULL);
  21655. break;
  21656. case TAKkeyeddenormalize:
  21657. LinkRoxieRow(left);
  21658. remote.addResult((void *) left);
  21659. added++;
  21660. break;
  21661. }
  21662. break;
  21663. }
  21664. }
  21665. else if (!(joinFlags & JFexclude))
  21666. {
  21667. unsigned idx = 0;
  21668. switch (activityKind)
  21669. {
  21670. case TAKkeyedjoin:
  21671. while (idx < matched)
  21672. {
  21673. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21674. added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL);
  21675. if (added==keepLimit)
  21676. break;
  21677. idx++;
  21678. }
  21679. break;
  21680. case TAKkeyeddenormalize:
  21681. {
  21682. OwnedConstRoxieRow newLeft;
  21683. newLeft.set(left);
  21684. unsigned rowSize = 0;
  21685. unsigned rightAdded = 0;
  21686. while (idx < matched)
  21687. {
  21688. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21689. try
  21690. {
  21691. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21692. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  21693. if (transformedSize)
  21694. {
  21695. rowSize = transformedSize;
  21696. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  21697. rightAdded++;
  21698. if (rightAdded==keepLimit)
  21699. break;
  21700. }
  21701. idx++;
  21702. }
  21703. catch (IException *E)
  21704. {
  21705. throw makeWrappedException(E);
  21706. }
  21707. }
  21708. if (rowSize)
  21709. {
  21710. remote.addResult(newLeft.getClear());
  21711. added++;
  21712. }
  21713. }
  21714. break;
  21715. case TAKkeyeddenormalizegroup:
  21716. {
  21717. ConstPointerArray extractedRows;
  21718. while (idx < matched && idx < keepLimit)
  21719. {
  21720. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  21721. extractedRows.append((void *) &rhs->rhsdata);
  21722. idx++;
  21723. }
  21724. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray());
  21725. }
  21726. break;
  21727. }
  21728. }
  21729. return added;
  21730. }
  21731. virtual void processDone()
  21732. {
  21733. // called from puller thread
  21734. remote.flush();
  21735. remote.senddone();
  21736. }
  21737. virtual void onLimitExceeded(bool isKeyed)
  21738. {
  21739. if (traceLevel > 4)
  21740. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21741. if (isKeyed)
  21742. throwUnexpected();
  21743. helper.onLimitExceeded();
  21744. }
  21745. virtual const void *createLimitFailRow(bool isKeyed)
  21746. {
  21747. throwUnexpected();
  21748. }
  21749. virtual bool fireException(IException *e)
  21750. {
  21751. // called from puller thread on failure
  21752. return remote.fireException(e);
  21753. }
  21754. virtual const void *nextInGroup()
  21755. {
  21756. throwUnexpected(); // I am nobody's input
  21757. }
  21758. };
  21759. #ifdef _MSC_VER
  21760. #pragma warning ( push )
  21761. #pragma warning ( disable: 4355 )
  21762. #endif
  21763. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21764. {
  21765. CRoxieServerFullKeyedJoinHead head;
  21766. Owned<IEngineRowAllocator> fetchInputAllocator;
  21767. Linked<IFilePartMap> map;
  21768. bool variableFetchFileName;
  21769. Owned<const IResolvedFile> varFetchFileInfo;
  21770. CachedOutputMetaData fetchInputFields;
  21771. public:
  21772. CRoxieServerKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
  21773. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  21774. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  21775. head(_factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
  21776. map(_map)
  21777. {
  21778. CRoxieServerKeyedJoinBase::setInput(0, head.queryOutput(0));
  21779. variableFetchFileName = allFilesDynamic || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  21780. }
  21781. virtual const IResolvedFile *queryVarFileInfo() const
  21782. {
  21783. return varFetchFileInfo;
  21784. }
  21785. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21786. {
  21787. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21788. head.onCreate(_ctx, _colocalParent);
  21789. fetchInputFields.set(helper.queryFetchInputRecordSize());
  21790. fetchInputAllocator.setown(ctx->queryCodeContext()->getRowAllocator(helper.queryFetchInputRecordSize(), activityId));
  21791. }
  21792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21793. {
  21794. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21795. if (variableFetchFileName)
  21796. {
  21797. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  21798. OwnedRoxieString fname(helper.getFileName());
  21799. varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
  21800. if (varFetchFileInfo)
  21801. map.setown(varFetchFileInfo->getFileMap());
  21802. }
  21803. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), false, ctx);
  21804. }
  21805. virtual void setInput(unsigned idx, IRoxieInput *in)
  21806. {
  21807. head.setInput(idx, in);
  21808. }
  21809. virtual void processRow(const void *_rhs)
  21810. {
  21811. // called from puller thread
  21812. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  21813. CJoinGroup *jg = rhs->thisGroup;
  21814. if (rhs->partNo != (unsigned short) -1)
  21815. {
  21816. unsigned partNo = map->mapOffset(rhs->fpos);
  21817. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  21818. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  21819. if (fetchInputFields.isVariableSize())
  21820. {
  21821. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  21822. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21823. ReleaseRoxieRow(rhs);
  21824. jg->notePending();
  21825. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  21826. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  21827. }
  21828. else
  21829. {
  21830. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  21831. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  21832. ReleaseRoxieRow(rhs);
  21833. jg->notePending();
  21834. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  21835. }
  21836. }
  21837. else
  21838. {
  21839. unsigned candidateCount = (unsigned) rhs->fpos;
  21840. // CTXLOG("Full keyed join - all results back from index");
  21841. ReleaseRoxieRow(rhs);
  21842. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  21843. }
  21844. }
  21845. virtual void processEOG()
  21846. {
  21847. // called from front puller thread
  21848. if (preserveGroups)
  21849. endGroup();
  21850. }
  21851. void processGroup(const ConstPointerArray &)
  21852. {
  21853. throwUnexpected();
  21854. }
  21855. };
  21856. #ifdef _MSC_VER
  21857. #pragma warning ( pop )
  21858. #endif
  21859. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  21860. {
  21861. IOutputMetaData *indexReadMeta;
  21862. Owned<IEngineRowAllocator> indexReadAllocator;
  21863. Owned<IKeyManager> tlk;
  21864. bool variableIndexFileName;
  21865. bool indexReadInputRecordVariable;
  21866. Owned<const IResolvedFile> varFileInfo;
  21867. Linked<TranslatorArray> translators;
  21868. Linked<IKeyArray> keySet;
  21869. Owned<IOutputMetaData> joinPrefixedMeta;
  21870. Owned<IEngineRowAllocator> joinFieldsAllocator;
  21871. public:
  21872. CRoxieServerHalfKeyedJoinActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
  21873. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  21874. : CRoxieServerKeyedJoinBase(_factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  21875. indexReadMeta(_indexReadMeta),
  21876. tlk(createKeyManager(NULL, 0, this)),
  21877. keySet(_keySet),
  21878. translators(_translators)
  21879. {
  21880. variableIndexFileName = allFilesDynamic || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  21881. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  21882. }
  21883. virtual void serializeExtra(MemoryBuffer &out)
  21884. {
  21885. if (helper.getJoinFlags() & JFindexfromactivity)
  21886. {
  21887. assertex(rootIndex);
  21888. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  21889. indexId.serialize(out);
  21890. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  21891. MemoryBuffer tmp;
  21892. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  21893. if (rootIndex->queryActivity()->queryVarFileInfo())
  21894. {
  21895. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  21896. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  21897. }
  21898. unsigned ctxlen = tmp.length();
  21899. out.append(ctxlen).append(tmp);
  21900. }
  21901. }
  21902. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  21903. {
  21904. CRoxieServerKeyedJoinBase::onCreate(_ctx, _colocalParent);
  21905. indexReadAllocator.setown(ctx->queryCodeContext()->getRowAllocator(indexReadMeta, activityId));
  21906. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  21907. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  21908. joinFieldsAllocator.setown(ctx->queryCodeContext()->getRowAllocator(joinPrefixedMeta, activityId));
  21909. }
  21910. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21911. {
  21912. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  21913. if (rootIndex)
  21914. {
  21915. varFileInfo.setown(rootIndex->getVarFileInfo());
  21916. translators.setown(rootIndex->getTranslators());
  21917. keySet.setown(rootIndex->getKeySet());
  21918. }
  21919. else if (variableIndexFileName)
  21920. {
  21921. OwnedRoxieString indexFileName(helper.getIndexFileName());
  21922. varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  21923. if (varFileInfo)
  21924. {
  21925. translators.setown(new TranslatorArray);
  21926. keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().getEnableFieldTranslation()));
  21927. }
  21928. }
  21929. puller.start(parentExtractSize, parentExtract, paused, ctx->keyedJoinPreload(), isSimple, ctx);
  21930. }
  21931. virtual const IResolvedFile *queryVarFileInfo() const
  21932. {
  21933. return varFileInfo;
  21934. }
  21935. virtual void reset()
  21936. {
  21937. CRoxieServerKeyedJoinBase::reset();
  21938. if (varFileInfo)
  21939. {
  21940. keySet.clear();
  21941. varFileInfo.clear();
  21942. }
  21943. }
  21944. virtual void processRow(const void *row)
  21945. {
  21946. // called from front puller thread
  21947. // buffer up an IndexRead request
  21948. if (helper.leftCanMatch(row) && keySet)
  21949. {
  21950. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  21951. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  21952. OwnedConstRoxieRow extracted;
  21953. if (indexReadRecordSize)
  21954. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  21955. CJoinGroup *jg = createJoinGroup(row);
  21956. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  21957. {
  21958. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  21959. if (thisBase)
  21960. {
  21961. unsigned fileNo = 0;
  21962. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  21963. tlk->setKey(thisKey);
  21964. tlk->setLayoutTranslator(translators->item(fileNo));
  21965. helper.createSegmentMonitors(tlk, extracted);
  21966. if (rootIndex)
  21967. rootIndex->mergeSegmentMonitors(tlk);
  21968. tlk->finishSegmentMonitors();
  21969. try
  21970. {
  21971. tlk->reset();
  21972. loop
  21973. {
  21974. typedef const void * cvp;
  21975. if (thisKey && thisKey->isTopLevelKey())
  21976. {
  21977. bool locallySorted = (!thisKey->isFullySorted());
  21978. while (locallySorted || tlk->lookup(false))
  21979. {
  21980. unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
  21981. if (locallySorted || slavePart)
  21982. {
  21983. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  21984. *outputBuffer++ = jg;
  21985. if (indexReadInputRecordVariable)
  21986. {
  21987. *(unsigned *) outputBuffer = indexReadRecordSize;
  21988. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  21989. }
  21990. jg->notePending();
  21991. memcpy(outputBuffer, extracted, indexReadRecordSize);
  21992. if (locallySorted)
  21993. {
  21994. for (unsigned i = 1; i < numChannels; i++)
  21995. jg->notePending();
  21996. break;
  21997. }
  21998. }
  21999. }
  22000. }
  22001. else
  22002. {
  22003. unsigned accepted = 0;
  22004. unsigned rejected = 0;
  22005. Owned<CRowArrayMessageResult> result;
  22006. if (!isSimple)
  22007. result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
  22008. // MORE - This code seems to be duplicated in keyedJoinHead
  22009. jg->notePending();
  22010. unsigned candidateCount = 0;
  22011. while (tlk->lookup(true))
  22012. {
  22013. candidateCount++;
  22014. atomic_inc(&indexRecordsRead);
  22015. KLBlobProviderAdapter adapter(tlk);
  22016. offset_t recptr;
  22017. const byte *indexRow = tlk->queryKeyBuffer(recptr);
  22018. if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
  22019. {
  22020. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  22021. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  22022. accepted++;
  22023. KLBlobProviderAdapter adapter(tlk);
  22024. size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
  22025. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  22026. rec->fpos = recptr;
  22027. rec->thisGroup = jg;
  22028. rec->partNo = partNo;
  22029. if (isSimple)
  22030. remote.injected.enqueue(rec);
  22031. else
  22032. result->append(rec);
  22033. }
  22034. else
  22035. {
  22036. rejected++;
  22037. atomic_inc(&postFiltered);
  22038. }
  22039. }
  22040. // output an end marker for the matches to this group
  22041. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  22042. rec->fpos = (offset_t) candidateCount;
  22043. rec->thisGroup = jg;
  22044. rec->partNo = (unsigned short) -1;
  22045. if (isSimple)
  22046. remote.injected.enqueue(rec);
  22047. else
  22048. {
  22049. result->append(rec);
  22050. remote.injectResult(result.getClear());
  22051. }
  22052. if (accepted)
  22053. noteStatistic(STATS_ACCEPTED, accepted, 1);
  22054. if (rejected)
  22055. noteStatistic(STATS_REJECTED, rejected, 1);
  22056. }
  22057. if (++fileNo < thisBase->numParts())
  22058. {
  22059. thisKey = thisBase->queryPart(fileNo);
  22060. tlk->setKey(thisKey);
  22061. tlk->setLayoutTranslator(translators->item(fileNo));
  22062. tlk->reset();
  22063. }
  22064. else
  22065. break;
  22066. }
  22067. tlk->releaseSegmentMonitors();
  22068. tlk->setKey(NULL);
  22069. }
  22070. catch (...)
  22071. {
  22072. tlk->releaseSegmentMonitors();
  22073. tlk->setKey(NULL);
  22074. throw;
  22075. }
  22076. }
  22077. }
  22078. noteEndReceived(jg, 0);
  22079. }
  22080. else
  22081. {
  22082. noteEndReceived(createJoinGroup(row), 0);
  22083. }
  22084. }
  22085. virtual void processEOG()
  22086. {
  22087. // called from front puller thread
  22088. if (preserveGroups)
  22089. endGroup();
  22090. }
  22091. void processGroup(const ConstPointerArray &)
  22092. {
  22093. throwUnexpected();
  22094. }
  22095. };
  22096. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  22097. {
  22098. Owned<const IResolvedFile> indexfile;
  22099. Owned<const IResolvedFile> datafile;
  22100. Owned<IKeyArray> keySet;
  22101. Owned<TranslatorArray> translatorArray;
  22102. Owned<IDefRecordMeta> activityMeta;
  22103. RemoteActivityId headId;
  22104. RemoteActivityId tailId;
  22105. IOutputMetaData *indexReadMeta;
  22106. Owned<IFilePartMap> map;
  22107. Owned<IFileIOArray> files;
  22108. unsigned joinFlags;
  22109. bool isHalfKeyed;
  22110. bool isLocal;
  22111. bool enableFieldTranslation;
  22112. bool variableFetchFileName;
  22113. bool variableIndexFileName;
  22114. bool isSimple;
  22115. public:
  22116. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_headId, const RemoteActivityId &_tailId, IPropertyTree &_graphNode)
  22117. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), headId(_headId), tailId(_tailId)
  22118. {
  22119. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  22120. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22121. isSimple = isLocal;
  22122. rtlDataAttr indexLayoutMeta;
  22123. size32_t indexLayoutSize;
  22124. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  22125. assertex(indexLayoutSize== 0);
  22126. MemoryBuffer m;
  22127. m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
  22128. activityMeta.setown(deserializeRecordMeta(m, true));
  22129. enableFieldTranslation = queryFactory.getEnableFieldTranslation();
  22130. translatorArray.setown(new TranslatorArray);
  22131. joinFlags = helper->getJoinFlags();
  22132. variableIndexFileName = allFilesDynamic || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename)) != 0);
  22133. variableFetchFileName = allFilesDynamic || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22134. if (!variableIndexFileName)
  22135. {
  22136. bool isOpt = (joinFlags & JFindexoptional) != 0;
  22137. OwnedRoxieString indexFileName(helper->getIndexFileName());
  22138. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit()));
  22139. if (indexfile)
  22140. keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
  22141. }
  22142. if (keySet && keySet->length()==1 && !isSimple)
  22143. {
  22144. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  22145. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.getDebugValueBool("disableLocalOptimizations", false))
  22146. isSimple = true;
  22147. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  22148. }
  22149. if (!simpleLocalKeyedJoins)
  22150. isSimple = false;
  22151. isHalfKeyed = !helper->diskAccessRequired();
  22152. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  22153. if (!isHalfKeyed && !variableFetchFileName)
  22154. {
  22155. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  22156. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode), isFetchOpt, true, true, _queryFactory.queryWorkUnit()));
  22157. if (datafile)
  22158. {
  22159. if (isLocal)
  22160. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  22161. else
  22162. map.setown(datafile->getFileMap());
  22163. }
  22164. }
  22165. }
  22166. virtual bool getEnableFieldTranslation() const
  22167. {
  22168. return enableFieldTranslation;
  22169. }
  22170. virtual IDefRecordMeta *queryActivityMeta() const
  22171. {
  22172. return activityMeta;
  22173. }
  22174. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22175. {
  22176. if (isHalfKeyed)
  22177. return new CRoxieServerHalfKeyedJoinActivity(this, _probeManager,
  22178. headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
  22179. else
  22180. return new CRoxieServerKeyedJoinActivity(this, _probeManager,
  22181. headId, keySet, translatorArray, indexReadMeta,
  22182. tailId, map, joinFlags, isLocal);
  22183. }
  22184. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22185. {
  22186. if (datafile)
  22187. addXrefFileInfo(reply, datafile);
  22188. if (indexfile)
  22189. addXrefFileInfo(reply, indexfile);
  22190. }
  22191. };
  22192. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2, IPropertyTree &_graphNode)
  22193. {
  22194. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _remoteId, _remoteId2, _graphNode);
  22195. }
  22196. //=================================================================================
  22197. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  22198. {
  22199. protected:
  22200. Owned<ISoapCallHelper> soaphelper;
  22201. IHThorSoapActionArg & helper;
  22202. StringBuffer authToken;
  22203. bool eof;
  22204. CriticalSection crit;
  22205. ClientCertificate *pClientCert;
  22206. public:
  22207. IMPLEMENT_IINTERFACE;
  22208. CRoxieServerSoapActivityBase(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22209. : CRoxieServerActivity(_factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  22210. {
  22211. eof = false;
  22212. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  22213. pClientCert = &clientCert;
  22214. else
  22215. pClientCert = NULL;
  22216. }
  22217. // ISoapCallRowProvider
  22218. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  22219. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  22220. virtual const void * getNextRow() { return NULL; };
  22221. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  22222. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22223. {
  22224. eof = false;
  22225. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22226. authToken.append(ctx->queryAuthToken());
  22227. }
  22228. virtual void reset()
  22229. {
  22230. // MORE - Shouldn't we make sure thread is stopped etc???
  22231. soaphelper.clear();
  22232. CRoxieServerActivity::reset();
  22233. }
  22234. // IRoxieAbortMonitor
  22235. virtual void checkForAbort() { checkAbort(); }
  22236. };
  22237. //---------------------------------------------------------------------------
  22238. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  22239. {
  22240. IHThorSoapCallArg & callHelper;
  22241. public:
  22242. CRoxieServerSoapRowCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22243. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22244. {
  22245. }
  22246. virtual IHThorSoapCallArg * queryCallHelper()
  22247. {
  22248. return &callHelper;
  22249. }
  22250. virtual bool needsAllocator() const { return true; }
  22251. virtual const void *nextInGroup()
  22252. {
  22253. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22254. if(eof) return NULL;
  22255. if (soaphelper == NULL)
  22256. {
  22257. if (factory->getKind()==TAKhttp_rowdataset)
  22258. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22259. else
  22260. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *ctx, this));
  22261. soaphelper->start();
  22262. }
  22263. OwnedConstRoxieRow ret = soaphelper->getRow();
  22264. if (!ret)
  22265. {
  22266. eof = true;
  22267. return NULL;
  22268. }
  22269. ++processed;
  22270. return ret.getClear();
  22271. }
  22272. };
  22273. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  22274. {
  22275. public:
  22276. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22277. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22278. {
  22279. }
  22280. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22281. {
  22282. return new CRoxieServerSoapRowCallActivity(this, _probeManager);
  22283. }
  22284. };
  22285. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22286. {
  22287. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22288. }
  22289. //---------------------------------------------------------------------------
  22290. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  22291. {
  22292. public:
  22293. CRoxieServerSoapRowActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22294. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22295. {}
  22296. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22297. {
  22298. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  22299. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *ctx, this));
  22300. soaphelper->start();
  22301. soaphelper->waitUntilDone();
  22302. IException *e = soaphelper->getError();
  22303. soaphelper.clear();
  22304. if (e)
  22305. throw e;
  22306. }
  22307. virtual IRoxieInput *queryOutput(unsigned idx)
  22308. {
  22309. return NULL;
  22310. }
  22311. virtual const void *nextInGroup()
  22312. {
  22313. throwUnexpected(); // I am nobody's input
  22314. }
  22315. };
  22316. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  22317. {
  22318. bool isRoot;
  22319. public:
  22320. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22321. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22322. {
  22323. }
  22324. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22325. {
  22326. return new CRoxieServerSoapRowActionActivity(this, _probeManager);
  22327. }
  22328. virtual bool isSink() const
  22329. {
  22330. return isRoot;
  22331. }
  22332. };
  22333. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22334. {
  22335. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22336. }
  22337. //---------------------------------------------------------------------------
  22338. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  22339. {
  22340. IHThorSoapCallArg & callHelper;
  22341. public:
  22342. CRoxieServerSoapDatasetCallActivity(const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22343. : CRoxieServerSoapActivityBase(_factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  22344. {
  22345. }
  22346. virtual IHThorSoapCallArg * queryCallHelper()
  22347. {
  22348. return &callHelper;
  22349. }
  22350. virtual const void *getNextRow()
  22351. {
  22352. CriticalBlock b(crit);
  22353. const void *nextrec = input->nextInGroup();
  22354. if (!nextrec)
  22355. {
  22356. nextrec = input->nextInGroup();
  22357. }
  22358. return nextrec;
  22359. }
  22360. virtual bool needsAllocator() const { return true; }
  22361. virtual const void *nextInGroup()
  22362. {
  22363. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  22364. if(eof) return NULL;
  22365. if (soaphelper == NULL)
  22366. {
  22367. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *ctx, this));
  22368. soaphelper->start();
  22369. }
  22370. OwnedConstRoxieRow ret = soaphelper->getRow();
  22371. if (!ret)
  22372. {
  22373. eof = true;
  22374. return NULL;
  22375. }
  22376. ++processed;
  22377. return ret.getClear();
  22378. }
  22379. };
  22380. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  22381. {
  22382. public:
  22383. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22384. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
  22385. {
  22386. }
  22387. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22388. {
  22389. return new CRoxieServerSoapDatasetCallActivity(this, _probeManager);
  22390. }
  22391. };
  22392. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind)
  22393. {
  22394. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind);
  22395. }
  22396. //---------------------------------------------------------------------------
  22397. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  22398. {
  22399. public:
  22400. CRoxieServerSoapDatasetActionActivity (const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  22401. : CRoxieServerSoapActivityBase(_factory, _probeManager)
  22402. {}
  22403. virtual const void *getNextRow()
  22404. {
  22405. CriticalBlock b(crit);
  22406. const void *nextrec = input->nextInGroup();
  22407. if (!nextrec)
  22408. {
  22409. nextrec = input->nextInGroup();
  22410. }
  22411. if (nextrec)
  22412. processed++;
  22413. return nextrec;
  22414. }
  22415. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  22416. {
  22417. try
  22418. {
  22419. start(parentExtractSize, parentExtract, false);
  22420. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *ctx, this));
  22421. soaphelper->start();
  22422. soaphelper->waitUntilDone();
  22423. IException *e = soaphelper->getError();
  22424. soaphelper.clear();
  22425. if (e)
  22426. throw e;
  22427. stop(false);
  22428. }
  22429. catch (IException *E)
  22430. {
  22431. ctx->notifyAbort(E);
  22432. stop(true);
  22433. throw;
  22434. }
  22435. catch(...)
  22436. {
  22437. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", __FILE__, __LINE__);
  22438. ctx->notifyAbort(E);
  22439. stop(true);
  22440. throw;
  22441. }
  22442. }
  22443. virtual IRoxieInput *queryOutput(unsigned idx)
  22444. {
  22445. return NULL;
  22446. }
  22447. virtual const void *nextInGroup()
  22448. {
  22449. throwUnexpected(); // I am nobody's input
  22450. }
  22451. };
  22452. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  22453. {
  22454. bool isRoot;
  22455. public:
  22456. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22457. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind), isRoot(_isRoot)
  22458. {
  22459. }
  22460. virtual IRoxieServerActivity *createActivity(IProbeManager *_probeManager) const
  22461. {
  22462. return new CRoxieServerSoapDatasetActionActivity(this, _probeManager);
  22463. }
  22464. virtual bool isSink() const
  22465. {
  22466. return isRoot;
  22467. }
  22468. };
  22469. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, bool _isRoot)
  22470. {
  22471. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _isRoot);
  22472. }
  22473. //=====================================================================================================
  22474. class CGraphResults : public CInterface, implements IRoxieGraphResults
  22475. {
  22476. IArrayOf<IGraphResult> results;
  22477. CriticalSection cs;
  22478. IGraphResult & select(unsigned idx)
  22479. {
  22480. CriticalBlock procedure(cs);
  22481. if (idx >= results.ordinality())
  22482. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  22483. return results.item(idx);
  22484. }
  22485. public:
  22486. IMPLEMENT_IINTERFACE
  22487. void clear()
  22488. {
  22489. CriticalBlock procedure(cs);
  22490. results.kill();
  22491. }
  22492. IRoxieInput * createIterator(unsigned id)
  22493. {
  22494. return select(id).createIterator();
  22495. }
  22496. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22497. {
  22498. select(id).getLinkedResult(count, ret);
  22499. }
  22500. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22501. {
  22502. select(id).getLinkedResult(count, ret);
  22503. }
  22504. void setResult(unsigned id, IGraphResult * result)
  22505. {
  22506. CriticalBlock procedure(cs);
  22507. if (results.ordinality() <= id)
  22508. {
  22509. while (results.ordinality() < id)
  22510. results.append(*new CGraphResult);
  22511. results.append(*LINK(result));
  22512. }
  22513. else
  22514. results.replace(*LINK(result), id);
  22515. }
  22516. void appendResult(IGraphResult * result)
  22517. {
  22518. CriticalBlock procedure(cs);
  22519. results.append(*LINK(result));
  22520. }
  22521. };
  22522. //===================================================================================================================
  22523. class CPseudoArg : public CInterface, implements IHThorArg
  22524. {
  22525. public:
  22526. IMPLEMENT_IINTERFACE
  22527. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  22528. };
  22529. class CPseudoActivity : public CRoxieServerActivity
  22530. {
  22531. public:
  22532. CPseudoActivity(IHThorArg & _helper) : CRoxieServerActivity(_helper) {}
  22533. virtual const void *nextInGroup()
  22534. {
  22535. throwUnexpected(); // I am nobody's input
  22536. }
  22537. };
  22538. class CActivityGraph : public CInterface, implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph
  22539. {
  22540. protected:
  22541. IArrayOf<IRoxieServerActivity> activities;
  22542. IArrayOf<IRoxieInput> probes;
  22543. IRoxieServerActivityCopyArray sinks;
  22544. StringAttr graphName;
  22545. Owned<CGraphResults> results;
  22546. CGraphResults graphLoopResults;
  22547. ActivityArray & graphDefinition;
  22548. CriticalSection evaluateCrit;
  22549. IProbeManager *probeManager;
  22550. unsigned id;
  22551. unsigned loopCounter;
  22552. class ActivityGraphSlaveContext : public IndirectSlaveContext
  22553. {
  22554. SpinLock abortLock;
  22555. bool aborted;
  22556. Owned<IException> exception;
  22557. public:
  22558. ActivityGraphSlaveContext(const IRoxieContextLogger &_logctx) : logctx(_logctx), loopCounter(0), codeContext(NULL)
  22559. {
  22560. aborted = false;
  22561. }
  22562. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  22563. virtual void notifyAbort(IException *E)
  22564. {
  22565. SpinBlock b(abortLock);
  22566. if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  22567. {
  22568. aborted = true;
  22569. exception.set(E);
  22570. }
  22571. }
  22572. virtual void checkAbort()
  22573. {
  22574. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  22575. {
  22576. SpinBlock b(abortLock);
  22577. if (!exception)
  22578. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  22579. throw exception.getLink();
  22580. }
  22581. IndirectSlaveContext::checkAbort();
  22582. }
  22583. virtual ICodeContext *queryCodeContext()
  22584. {
  22585. return codeContext;
  22586. }
  22587. void setCodeContext(ICodeContext * _codeContext)
  22588. {
  22589. codeContext = _codeContext;
  22590. }
  22591. void setLoopCounter(unsigned _loopCounter)
  22592. {
  22593. loopCounter = _loopCounter;
  22594. }
  22595. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  22596. {
  22597. childGraphs.setValue(id, childGraph);
  22598. }
  22599. virtual IActivityGraph * queryChildGraph(unsigned id)
  22600. {
  22601. if (queryTraceLevel() > 10)
  22602. CTXLOG("resolveChildGraph %d", id);
  22603. IActivityGraph *childGraph = childGraphs.getValue(id);
  22604. assertex(childGraph);
  22605. return childGraph;
  22606. }
  22607. // MORE should really redirect the other log context ones too (though mostly doesn't matter). Really should refactor to have a queryLogContext() method in IRoxieSlaveContext I think
  22608. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  22609. {
  22610. logctx.getLogPrefix(ret);
  22611. if (loopCounter)
  22612. ret.appendf("{%u}", loopCounter);
  22613. return ret;
  22614. }
  22615. protected:
  22616. const IRoxieContextLogger &logctx;
  22617. unsigned loopCounter;
  22618. ICodeContext * codeContext;
  22619. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  22620. } graphSlaveContext;
  22621. class ActivityGraphCodeContext : public IndirectCodeContext
  22622. {
  22623. public:
  22624. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  22625. {
  22626. if ((unsigned) activityId == container->queryId())
  22627. return container;
  22628. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22629. if (match)
  22630. return match->queryLocalGraph();
  22631. return IndirectCodeContext::resolveLocalQuery(activityId);
  22632. }
  22633. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  22634. {
  22635. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  22636. return LINK(match->queryChildGraph());
  22637. }
  22638. virtual unsigned getGraphLoopCounter() const
  22639. {
  22640. return container->queryLoopCounter(); // only called if value is valid
  22641. }
  22642. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  22643. {
  22644. slaveContext = _slaveContext;
  22645. container = _container;
  22646. }
  22647. protected:
  22648. IRoxieSlaveContext * slaveContext;
  22649. CActivityGraph * container;
  22650. } graphCodeContext;
  22651. public:
  22652. IMPLEMENT_IINTERFACE;
  22653. CActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  22654. : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_logctx)
  22655. {
  22656. id = x.getLibraryGraphId();
  22657. if (!id)
  22658. id = _id;
  22659. loopCounter = 0;
  22660. graphSlaveContext.setCodeContext(&graphCodeContext);
  22661. graphCodeContext.setContainer(&graphSlaveContext, this);
  22662. }
  22663. ~CActivityGraph()
  22664. {
  22665. if (probeManager)
  22666. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  22667. }
  22668. virtual const char *queryName() const
  22669. {
  22670. return graphName.get();
  22671. }
  22672. void createGraph()
  22673. {
  22674. ForEachItemIn(idx, graphDefinition)
  22675. {
  22676. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  22677. IRoxieServerActivity &activity = *donor.createActivity(probeManager);
  22678. activities.append(activity);
  22679. if (donor.isSink())
  22680. {
  22681. sinks.append(activity);
  22682. if (probeManager)
  22683. probeManager->noteSink(&activity);
  22684. }
  22685. }
  22686. ForEachItemIn(idx1, graphDefinition)
  22687. {
  22688. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  22689. IRoxieServerActivity &activity = activities.item(idx1);
  22690. unsigned inputidx = 0;
  22691. loop
  22692. {
  22693. unsigned outputidx;
  22694. unsigned source = donor.getInput(inputidx, outputidx);
  22695. if (source==(unsigned) -1)
  22696. break;
  22697. connectInput(idx1, inputidx, source, outputidx, 0);
  22698. inputidx++;
  22699. }
  22700. IntArray &dependencies = donor.queryDependencies();
  22701. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  22702. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  22703. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  22704. ForEachItemIn(idx2, dependencies)
  22705. {
  22706. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  22707. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  22708. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  22709. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  22710. if (probeManager)
  22711. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  22712. }
  22713. }
  22714. }
  22715. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  22716. {
  22717. IRoxieServerActivity &targetActivity = activities.item(target);
  22718. IRoxieServerActivity &sourceActivity = activities.item(source);
  22719. IRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  22720. if (probeManager)
  22721. {
  22722. IInputBase * inputBase = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  22723. output = static_cast<IRoxieInput*>(inputBase);
  22724. probes.append(*LINK(output));
  22725. }
  22726. targetActivity.setInput(targetIdx, output);
  22727. }
  22728. virtual void onCreate(IRoxieSlaveContext *ctx, IHThorArg *_colocalParent)
  22729. {
  22730. graphSlaveContext.set(ctx);
  22731. if (graphDefinition.isMultiInstance())
  22732. {
  22733. graphCodeContext.set(ctx->queryCodeContext());
  22734. ctx = &graphSlaveContext;
  22735. }
  22736. ForEachItemIn(idx, activities)
  22737. {
  22738. IRoxieServerActivity *activity = &activities.item(idx);
  22739. if (activity)
  22740. activity->onCreate(ctx, _colocalParent);
  22741. }
  22742. }
  22743. virtual void abort()
  22744. {
  22745. ForEachItemIn(idx, sinks)
  22746. {
  22747. IRoxieServerActivity &sink = sinks.item(idx);
  22748. sink.stop(true);
  22749. }
  22750. }
  22751. virtual void reset()
  22752. {
  22753. ForEachItemIn(idx, sinks)
  22754. {
  22755. IRoxieServerActivity &sink = sinks.item(idx);
  22756. sink.reset();
  22757. }
  22758. }
  22759. Linked<IException> exception;
  22760. CriticalSection eCrit;
  22761. virtual void noteException(IException *E)
  22762. {
  22763. CriticalBlock b(eCrit);
  22764. if (!exception)
  22765. {
  22766. if (graphSlaveContext.queryDebugContext())
  22767. {
  22768. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  22769. }
  22770. exception.set(E);
  22771. }
  22772. }
  22773. virtual void checkAbort()
  22774. {
  22775. CriticalBlock b(eCrit);
  22776. if (exception)
  22777. throw exception.getLink();
  22778. }
  22779. virtual void execute()
  22780. {
  22781. doExecute(0, NULL);
  22782. }
  22783. //New child query code...
  22784. virtual IThorChildGraph * queryChildGraph()
  22785. {
  22786. return this;
  22787. }
  22788. virtual IEclGraphResults * queryLocalGraph()
  22789. {
  22790. return this;
  22791. }
  22792. virtual IRoxieServerChildGraph * queryLoopGraph()
  22793. {
  22794. return this;
  22795. }
  22796. inline unsigned queryId() const
  22797. {
  22798. return id;
  22799. }
  22800. inline unsigned queryLoopCounter() const
  22801. {
  22802. return loopCounter;
  22803. }
  22804. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  22805. {
  22806. if (sinks.ordinality()==1)
  22807. sinks.item(0).execute(parentExtractSize, parentExtract);
  22808. #ifdef PARALLEL_EXECUTE
  22809. else if (!probeManager && !graphDefinition.isSequential())
  22810. {
  22811. class casyncfor: public CAsyncFor
  22812. {
  22813. public:
  22814. IActivityGraph &parent;
  22815. unsigned parentExtractSize;
  22816. const byte * parentExtract;
  22817. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  22818. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  22819. void Do(unsigned i)
  22820. {
  22821. try
  22822. {
  22823. sinks.item(i).execute(parentExtractSize, parentExtract);
  22824. }
  22825. catch (IException *E)
  22826. {
  22827. parent.noteException(E);
  22828. throw;
  22829. }
  22830. }
  22831. private:
  22832. IRoxieServerActivityCopyArray &sinks;
  22833. } afor(sinks, *this, parentExtractSize, parentExtract);
  22834. afor.For(sinks.ordinality(), sinks.ordinality());
  22835. }
  22836. #endif
  22837. else
  22838. {
  22839. ForEachItemIn(idx, sinks)
  22840. {
  22841. IRoxieServerActivity &sink = sinks.item(idx);
  22842. sink.execute(parentExtractSize, parentExtract);
  22843. }
  22844. }
  22845. }
  22846. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  22847. {
  22848. CriticalBlock block(evaluateCrit);
  22849. results.setown(new CGraphResults);
  22850. try
  22851. {
  22852. doExecute(parentExtractSize, parentExtract);
  22853. }
  22854. catch (...)
  22855. {
  22856. DBGLOG("Exception thrown in child query - cleaning up");
  22857. reset();
  22858. throw;
  22859. }
  22860. reset();
  22861. return results.getClear();
  22862. }
  22863. //interface IRoxieServerChildGraph
  22864. virtual void beforeExecute()
  22865. {
  22866. results.setown(new CGraphResults);
  22867. }
  22868. virtual IRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22869. {
  22870. IRoxieInput * ret = selectOutput(id);
  22871. ret->start(parentExtractSize, parentExtract, paused);
  22872. return ret;
  22873. }
  22874. virtual IRoxieInput * selectOutput(unsigned id)
  22875. {
  22876. ForEachItemIn(i, sinks)
  22877. {
  22878. IRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  22879. if (ret)
  22880. return ret;
  22881. }
  22882. throwUnexpected();
  22883. return NULL;
  22884. }
  22885. virtual void setInputResult(unsigned id, IGraphResult * result)
  22886. {
  22887. results->setResult(id, result);
  22888. }
  22889. virtual bool querySetInputResult(unsigned id, IRoxieInput * input)
  22890. {
  22891. ForEachItemIn(i, activities)
  22892. {
  22893. if (activities.item(i).querySetStreamInput(id, input))
  22894. return true;
  22895. }
  22896. return false;
  22897. }
  22898. virtual void stopUnusedOutputs()
  22899. {
  22900. //Hmm not sure how to do this...
  22901. }
  22902. virtual void afterExecute()
  22903. {
  22904. ForEachItemIn(i, sinks)
  22905. {
  22906. sinks.item(i).stop(false);
  22907. }
  22908. if (graphSlaveContext.queryDebugContext())
  22909. {
  22910. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  22911. }
  22912. reset();
  22913. }
  22914. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  22915. {
  22916. doExecute(parentExtractSize, parentExtract);
  22917. return LINK(results);
  22918. }
  22919. virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
  22920. {
  22921. results->getLinkedResult(count, ret, id);
  22922. }
  22923. virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
  22924. {
  22925. results->getLinkedResult(count, ret, id);
  22926. }
  22927. virtual void setResult(unsigned id, IGraphResult * result)
  22928. {
  22929. results->setResult(id, result);
  22930. }
  22931. virtual IRoxieInput * createResultIterator(unsigned id)
  22932. {
  22933. return results->createIterator(id);
  22934. }
  22935. virtual void setGraphLoopResult(IGraphResult * result)
  22936. {
  22937. graphLoopResults.appendResult(result);
  22938. }
  22939. virtual IRoxieInput * createGraphLoopResultIterator(unsigned id)
  22940. {
  22941. try
  22942. {
  22943. return graphLoopResults.createIterator(id);
  22944. }
  22945. catch (IException * e)
  22946. {
  22947. e->Release();
  22948. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  22949. }
  22950. }
  22951. virtual void clearGraphLoopResults()
  22952. {
  22953. graphLoopResults.clear();
  22954. }
  22955. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  22956. {
  22957. doExecute(parentExtractSize, parentExtract);
  22958. }
  22959. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  22960. {
  22961. graphLoopResults.setResult(id, result);
  22962. }
  22963. virtual IRoxieInput * getGraphLoopResult(unsigned id)
  22964. {
  22965. return graphLoopResults.createIterator(id);
  22966. }
  22967. virtual void getProbeResponse(IPropertyTree *query)
  22968. {
  22969. if (probeManager)
  22970. probeManager->getProbeResponse(query);
  22971. }
  22972. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  22973. {
  22974. throwUnexpected();
  22975. }
  22976. virtual CGraphIterationInfo *selectGraphLoopOutput()
  22977. {
  22978. return NULL;
  22979. }
  22980. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  22981. {
  22982. throwUnexpected();
  22983. }
  22984. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  22985. {
  22986. throwUnexpected();
  22987. }
  22988. };
  22989. class CIterationActivityGraph : public CActivityGraph
  22990. {
  22991. IHThorArg * colocalParent;
  22992. unsigned fixedParentExtractSize;
  22993. const byte * fixedParentExtract;
  22994. unsigned graphOutputActivityIndex;
  22995. public:
  22996. CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
  22997. unsigned _loopCounter, IRoxieSlaveContext *ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  22998. : CActivityGraph(_graphName, _id, x, _probeManager, _logctx)
  22999. {
  23000. graphOutputActivityIndex = 0;
  23001. loopCounter = _loopCounter;
  23002. colocalParent = _colocalParent;
  23003. graphSlaveContext.set(ctx);
  23004. graphSlaveContext.setLoopCounter(loopCounter);
  23005. graphCodeContext.set(ctx->queryCodeContext());
  23006. fixedParentExtractSize = parentExtractSize;
  23007. fixedParentExtract = parentExtract;
  23008. }
  23009. void createIterationGraph()
  23010. {
  23011. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(*new CPseudoArg);
  23012. ForEachItemIn(idx1, graphDefinition)
  23013. activities.append(*LINK(pseudoActivity));
  23014. graphOutputActivityIndex = queryGraphOutputIndex();
  23015. recursiveCreateGraph(graphOutputActivityIndex);
  23016. }
  23017. unsigned queryGraphOutputIndex() const
  23018. {
  23019. ForEachItemIn(i, graphDefinition)
  23020. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  23021. return i;
  23022. throwUnexpected();
  23023. }
  23024. void recursiveCreateGraph(unsigned whichActivity)
  23025. {
  23026. //Check to see if already created
  23027. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  23028. if (prevActivity.queryId() != 0)
  23029. {
  23030. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  23031. return;
  23032. }
  23033. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  23034. IRoxieServerActivity * activity = NULL;
  23035. if (donor.isGraphInvariant())
  23036. {
  23037. ThorActivityKind kind = donor.getKind();
  23038. switch (kind)
  23039. {
  23040. case TAKif:
  23041. case TAKchildif:
  23042. case TAKcase:
  23043. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  23044. {
  23045. Owned<IHThorArg> helper = &donor.getHelper();
  23046. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  23047. helper->onStart(fixedParentExtract, NULL);
  23048. unsigned branch;
  23049. switch (kind)
  23050. {
  23051. case TAKif: case TAKchildif:
  23052. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  23053. break;
  23054. case TAKcase: case TAKchildcase:
  23055. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  23056. if (branch >= donor.numInputs())
  23057. branch = donor.numInputs() - 1;
  23058. break;
  23059. default:
  23060. throwUnexpected();
  23061. }
  23062. helper.clear();
  23063. unsigned outputidx;
  23064. unsigned source = donor.getInput(branch, outputidx);
  23065. if (source ==(unsigned) -1)
  23066. activity = createRoxieServerNullActivity(&donor, probeManager);
  23067. else
  23068. activity = createRoxieServerPassThroughActivity(&donor, probeManager);
  23069. activities.replace(*activity, whichActivity);
  23070. activity->onCreate(&graphSlaveContext, colocalParent);
  23071. if (source ==(unsigned) -1)
  23072. return;
  23073. recursiveCreateGraph(source);
  23074. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  23075. break;
  23076. }
  23077. }
  23078. }
  23079. if (!activity)
  23080. {
  23081. activity = donor.createActivity(probeManager);
  23082. activities.replace(*activity, whichActivity);
  23083. activity->onCreate(&graphSlaveContext, colocalParent);
  23084. activity->resetOutputsUsed();
  23085. unsigned inputidx = 0;
  23086. loop
  23087. {
  23088. unsigned outputidx;
  23089. unsigned source = donor.getInput(inputidx, outputidx);
  23090. if (source==(unsigned) -1)
  23091. break;
  23092. recursiveCreateGraph(source);
  23093. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  23094. inputidx++;
  23095. }
  23096. }
  23097. IntArray &dependencies = donor.queryDependencies();
  23098. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  23099. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  23100. ForEachItemIn(idx2, dependencies)
  23101. {
  23102. unsigned input = dependencies.item(idx2);
  23103. recursiveCreateGraph(input);
  23104. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  23105. }
  23106. }
  23107. virtual CGraphIterationInfo *selectGraphLoopOutput()
  23108. {
  23109. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  23110. return new CGraphIterationInfo(&sourceActivity, sourceActivity.queryOutput(0), 0, loopCounter);
  23111. }
  23112. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  23113. {
  23114. ForEachItemIn(i, activities)
  23115. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  23116. }
  23117. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  23118. {
  23119. ForEachItemIn(i, activities)
  23120. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  23121. }
  23122. };
  23123. class CDelayedActivityGraph : public CInterface, implements IActivityGraph
  23124. {
  23125. StringAttr graphName;
  23126. ActivityArray & graphDefinition;
  23127. IProbeManager *probeManager;
  23128. unsigned id;
  23129. IRoxieSlaveContext * ctx;
  23130. IHThorArg * colocalParent;
  23131. public:
  23132. IMPLEMENT_IINTERFACE;
  23133. CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
  23134. : probeManager(_probeManager), graphDefinition(x)
  23135. {
  23136. graphName.set(_graphName);
  23137. id = _id;
  23138. ctx = NULL;
  23139. colocalParent = NULL;
  23140. }
  23141. virtual const char *queryName() const { return graphName.get(); }
  23142. virtual void abort() { throwUnexpected(); }
  23143. virtual void reset() { }
  23144. virtual void execute() { throwUnexpected(); }
  23145. virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
  23146. virtual void noteException(IException *E) { throwUnexpected(); }
  23147. virtual void checkAbort() { throwUnexpected(); }
  23148. virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
  23149. virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
  23150. virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
  23151. virtual void onCreate(IRoxieSlaveContext *_ctx, IHThorArg *_colocalParent)
  23152. {
  23153. ctx = _ctx;
  23154. colocalParent = _colocalParent;
  23155. }
  23156. virtual IRoxieServerChildGraph * createGraphLoopInstance(unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  23157. {
  23158. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  23159. ret->createIterationGraph();
  23160. return ret.getClear();
  23161. }
  23162. };
  23163. IActivityGraph *createActivityGraph(const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  23164. {
  23165. if (childFactories.isDelayed())
  23166. {
  23167. return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
  23168. }
  23169. else
  23170. {
  23171. Owned<IProbeManager> childProbe;
  23172. if (_probeManager)
  23173. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  23174. Owned<CActivityGraph> ret = new CActivityGraph(_graphName, id, childFactories, childProbe, _logctx);
  23175. ret->createGraph();
  23176. if (_probeManager)
  23177. _probeManager->endChildGraph(childProbe, parentActivity);
  23178. return ret.getClear();
  23179. }
  23180. }
  23181. //================================================================================================================
  23182. #ifdef _USE_CPPUNIT
  23183. #include "unittests.hpp"
  23184. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  23185. #if _MSC_VER==1200
  23186. #undef protected
  23187. #endif
  23188. static const char *sortAlgorithm;
  23189. class TestMetaData : public CInterface, implements IOutputMetaData
  23190. {
  23191. public:
  23192. IMPLEMENT_IINTERFACE;
  23193. virtual size32_t getRecordSize(const void *) { return 10; }
  23194. virtual size32_t getMinRecordSize() const { return 10; }
  23195. virtual size32_t getFixedSize() const { return 10; }
  23196. virtual void toXML(const byte * self, IXmlWriter & out) {}
  23197. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  23198. virtual unsigned getMetaFlags() { return 0; }
  23199. virtual void destruct(byte * self) {}
  23200. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23201. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23202. virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23203. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  23204. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23205. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  23206. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  23207. } testMeta;
  23208. class TestInput : public CInterface, implements IRoxieInput
  23209. {
  23210. char const * const *input;
  23211. IRoxieSlaveContext *ctx;
  23212. unsigned endSeen;
  23213. bool eof;
  23214. unsigned count;
  23215. unsigned __int64 totalCycles;
  23216. size32_t recordSize;
  23217. unsigned activityId;
  23218. public:
  23219. enum { STATEreset, STATEstarted, STATEstopped } state;
  23220. bool allRead;
  23221. IMPLEMENT_IINTERFACE;
  23222. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  23223. {
  23224. ctx = _ctx;
  23225. input = _input;
  23226. count = 0;
  23227. eof = false;
  23228. allRead = false;
  23229. endSeen = 0;
  23230. recordSize = testMeta.getFixedSize();
  23231. state = STATEreset;
  23232. totalCycles = 0;
  23233. activityId = 1;
  23234. }
  23235. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  23236. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  23237. {
  23238. ASSERT(state == STATEreset);
  23239. }
  23240. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23241. {
  23242. ASSERT(state == STATEreset);
  23243. state = STATEstarted;
  23244. }
  23245. virtual IRoxieServerActivity *queryActivity()
  23246. {
  23247. throwUnexpected();
  23248. }
  23249. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  23250. {
  23251. throwUnexpected();
  23252. }
  23253. virtual void stop(bool aborting)
  23254. {
  23255. state = STATEstopped;
  23256. }
  23257. virtual void reset()
  23258. {
  23259. ASSERT(state == STATEstopped);
  23260. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset; totalCycles = 0;
  23261. }
  23262. virtual void resetEOF()
  23263. {
  23264. throwUnexpected();
  23265. }
  23266. virtual void checkAbort() {}
  23267. virtual unsigned queryId() const { return activityId; };
  23268. virtual const void *nextInGroup()
  23269. {
  23270. ActivityTimer t(totalCycles, timeActivities, ctx->queryDebugContext());
  23271. ASSERT(state == STATEstarted);
  23272. ASSERT(allRead || !eof);
  23273. if (eof)
  23274. return NULL;
  23275. const char *nextSource = input[count++];
  23276. if (nextSource)
  23277. {
  23278. endSeen = 0;
  23279. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  23280. memset(ret, 0, recordSize);
  23281. strncpy((char *) ret, nextSource, recordSize);
  23282. return ret;
  23283. }
  23284. else
  23285. {
  23286. endSeen++;
  23287. if (endSeen==2)
  23288. eof = true;
  23289. return NULL;
  23290. }
  23291. }
  23292. virtual bool nextGroup(ConstPointerArray & group)
  23293. {
  23294. const void * next;
  23295. while ((next = nextInGroup()) != NULL)
  23296. group.append(next);
  23297. if (group.ordinality())
  23298. return true;
  23299. return false;
  23300. }
  23301. virtual unsigned __int64 queryTotalCycles() const { return totalCycles; }
  23302. virtual unsigned __int64 queryLocalCycles() const { return totalCycles; }
  23303. virtual IRoxieInput *queryInput(unsigned idx) const
  23304. {
  23305. return NULL;
  23306. }
  23307. };
  23308. struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
  23309. public:
  23310. struct CompareClass : public ICompare {
  23311. virtual int docompare(const void * _left, const void * _right) const {
  23312. return memcmp(_left, _right, 5);
  23313. }
  23314. } compare;
  23315. virtual ICompare * queryCompare() { return &compare; }
  23316. virtual IOutputMetaData * queryOutputMeta()
  23317. {
  23318. return &testMeta;
  23319. }
  23320. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  23321. virtual const char * getAlgorithm() { return sortAlgorithm; }
  23322. };
  23323. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  23324. struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
  23325. static bool isDedup;
  23326. public:
  23327. struct CompareClass : public ICompare {
  23328. virtual int docompare(const void * _left, const void * _right) const {
  23329. return memcmp(_left, _right, 5);
  23330. }
  23331. } compare;
  23332. virtual ICompare * queryCompare() { return &compare; }
  23333. virtual IOutputMetaData * queryOutputMeta()
  23334. {
  23335. return &testMeta;
  23336. }
  23337. virtual bool dedup() { return isDedup; }
  23338. };
  23339. bool MergeActivityTest::isDedup = false;
  23340. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  23341. class CcdServerTest : public CppUnit::TestFixture
  23342. {
  23343. CPPUNIT_TEST_SUITE(CcdServerTest);
  23344. CPPUNIT_TEST(testSetup);
  23345. CPPUNIT_TEST(testHeapSort);
  23346. CPPUNIT_TEST(testInsertionSort);
  23347. CPPUNIT_TEST(testQuickSort);
  23348. CPPUNIT_TEST(testMerge);
  23349. CPPUNIT_TEST(testMergeDedup);
  23350. CPPUNIT_TEST(testMiscellaneous);
  23351. CPPUNIT_TEST(testCleanup);
  23352. CPPUNIT_TEST_SUITE_END();
  23353. protected:
  23354. SlaveContextLogger logctx;
  23355. Owned<const IQueryDll> queryDll;
  23356. Owned<IRoxiePackage> package;
  23357. Owned<IRoxieSlaveContext> ctx;
  23358. Owned<IQueryFactory> queryFactory;
  23359. void testSetup()
  23360. {
  23361. roxiemem::setTotalMemoryLimit(false, 100 * 1024 * 1024, 0, NULL);
  23362. }
  23363. void testCleanup()
  23364. {
  23365. roxiemem::releaseRoxieHeap();
  23366. }
  23367. void init()
  23368. {
  23369. package.setown(createRoxiePackage(NULL, NULL));
  23370. ctx.setown(createSlaveContext(NULL, logctx, 0, 50*1024*1024, NULL));
  23371. queryDll.setown(createExeQueryDll("roxie"));
  23372. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, NULL));
  23373. timer->reset();
  23374. }
  23375. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  23376. {
  23377. testActivity(activity, input, NULL, output);
  23378. }
  23379. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output)
  23380. {
  23381. TestInput in(ctx, input);
  23382. TestInput in2(ctx, input2);
  23383. IRoxieInput *out = activity->queryOutput(0);
  23384. IOutputMetaData *meta = out->queryOutputMeta();
  23385. activity->setInput(0, &in);
  23386. if (input2)
  23387. activity->setInput(1, &in2);
  23388. void *buf = alloca(meta->getFixedSize());
  23389. for (unsigned iteration = 0; iteration < 8; iteration++)
  23390. {
  23391. // All activities should be able to be restarted multiple times in the same context (for child queries) or in a new context (for graph pooling, if we ever wanted it)
  23392. // This should be true whether we read all, some, or none of the data.
  23393. // Should not matter if an activity is not started
  23394. if (iteration % 4 == 0)
  23395. activity->onCreate(ctx, NULL);
  23396. unsigned count = 0;
  23397. if (iteration % 4 != 3)
  23398. {
  23399. activity->start(0, NULL, false);
  23400. ASSERT(in.state == TestInput::STATEstarted);
  23401. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  23402. loop
  23403. {
  23404. const void *next = out->nextInGroup();
  23405. if (!next)
  23406. {
  23407. ASSERT(output[count++] == NULL);
  23408. next = out->nextInGroup();
  23409. if (!next)
  23410. {
  23411. ASSERT(output[count++] == NULL);
  23412. break;
  23413. }
  23414. }
  23415. ASSERT(output[count] != NULL);
  23416. unsigned outsize = meta->getRecordSize(next);
  23417. memset(buf, 0, outsize);
  23418. strncpy((char *) buf, output[count++], outsize);
  23419. ASSERT(memcmp(next, buf, outsize) == 0);
  23420. ReleaseRoxieRow(next);
  23421. if (iteration % 4 == 2)
  23422. break;
  23423. }
  23424. if (iteration % 4 != 2)
  23425. {
  23426. // Check that reading after end is harmless
  23427. in.allRead = true;
  23428. const void *next = out->nextInGroup();
  23429. ASSERT(next == NULL);
  23430. }
  23431. }
  23432. activity->stop(false);
  23433. ASSERT(in.state == TestInput::STATEstopped);
  23434. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  23435. activity->reset();
  23436. ASSERT(in.state == TestInput::STATEreset);
  23437. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  23438. ctx->queryRowManager().reportLeaks();
  23439. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  23440. }
  23441. }
  23442. static int compareFunc(const void *l, const void *r)
  23443. {
  23444. return strcmp(*(char **) l, *(char **) r);
  23445. }
  23446. void testSort(unsigned type)
  23447. {
  23448. init();
  23449. sortAlgorithm = NULL;
  23450. if (type==2)
  23451. sortAlgorithm = "heapSort";
  23452. else if (type == 1)
  23453. sortAlgorithm = "insertionSort";
  23454. else
  23455. sortAlgorithm = "quickSort";
  23456. DBGLOG("Testing %s activity", sortAlgorithm);
  23457. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort);
  23458. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23459. const char * test[] = { NULL, NULL };
  23460. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23461. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  23462. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23463. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23464. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23465. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  23466. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23467. testActivity(activity, test, test);
  23468. testActivity(activity, test12345, test12345);
  23469. testActivity(activity, test54321, test12345);
  23470. testActivity(activity, test11111, test11111);
  23471. testActivity(activity, test11111_12345, test11111_12345);
  23472. testActivity(activity, test11111_54321, test11111_12345);
  23473. testActivity(activity, test54321_54321, test12345_12345);
  23474. // A few larger tests
  23475. char *input[2002];
  23476. char *output[2002];
  23477. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  23478. unsigned i;
  23479. // identical
  23480. for (i=0; i<2000; i++)
  23481. {
  23482. input[i] = new char[11];
  23483. output[i] = new char[11];
  23484. sprintf(input[i], "1");
  23485. sprintf(output[i], "1");
  23486. }
  23487. testActivity(activity, input, output);
  23488. // Ascending
  23489. for (i=0; i<2000; i++)
  23490. {
  23491. sprintf(input[i], "%04d", i);
  23492. sprintf(output[i], "%04d", i);
  23493. }
  23494. testActivity(activity, input, output);
  23495. // Almost sorted
  23496. for (i=0; i<20; i++)
  23497. {
  23498. unsigned h = i*100;
  23499. sprintf(input[h], "%04d", 1900-h);
  23500. }
  23501. testActivity(activity, input, output);
  23502. // Descending
  23503. for (i=0; i<2000; i++)
  23504. {
  23505. sprintf(input[i], "%04d", 1999-i);
  23506. sprintf(output[i], "%04d", i);
  23507. }
  23508. testActivity(activity, input, output);
  23509. // Random
  23510. for (i=0; i<2000; i++)
  23511. {
  23512. unsigned r = rand() % 1500;
  23513. sprintf(input[i], "%04d", r);
  23514. sprintf(output[i], "%04d", r);
  23515. }
  23516. qsort(output, 2000, sizeof(output[0]), compareFunc);
  23517. testActivity(activity, input, output);
  23518. #if 0
  23519. // Random
  23520. #define BIGSORTSIZE 1000000
  23521. char **linput = new char*[BIGSORTSIZE +2];
  23522. char **loutput = new char *[BIGSORTSIZE+2];
  23523. linput[BIGSORTSIZE] = linput[BIGSORTSIZE+1] = loutput[BIGSORTSIZE] = loutput[BIGSORTSIZE+1] = NULL;
  23524. for (i=0; i<BIGSORTSIZE; i++)
  23525. {
  23526. unsigned r = rand() % 15000;
  23527. linput[i] = loutput[i] = new char[11];
  23528. sprintf(linput[i], "%04d", r);
  23529. }
  23530. qsort(loutput, BIGSORTSIZE, 4, compareFunc);
  23531. testActivity(activity, linput, loutput);
  23532. for (i=0; i<BIGSORTSIZE; i++)
  23533. {
  23534. delete [] linput[i];
  23535. }
  23536. delete [] linput;
  23537. delete [] loutput;
  23538. #endif
  23539. unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
  23540. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  23541. factory->resetNodeProgressInfo();
  23542. if (type)
  23543. {
  23544. // Other than quicksort, it's supposed to be stable. Let's check that it is
  23545. // All sort identical
  23546. for (i=0; i<2000; i++)
  23547. {
  23548. sprintf(input[i], "1 %d", i);
  23549. sprintf(output[i], "1 %d", i);
  23550. }
  23551. testActivity(activity, input, output);
  23552. // Already sorted
  23553. for (i=0; i<2000; i++)
  23554. {
  23555. sprintf(input[i], "%04d %d", i / 10, i);
  23556. sprintf(output[i], "%04d %d", i / 10, i);
  23557. }
  23558. testActivity(activity, input, output);
  23559. // Reverse order
  23560. for (i=0; i<2000; i++)
  23561. {
  23562. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  23563. sprintf(output[i], "%04d %d", i / 10, i%10);
  23564. }
  23565. testActivity(activity, input, output);
  23566. }
  23567. for (i=0; i<2000; i++)
  23568. {
  23569. delete [] input[i];
  23570. delete [] output[i];
  23571. }
  23572. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  23573. }
  23574. void testQuickSort()
  23575. {
  23576. testSort(0);
  23577. }
  23578. void testInsertionSort()
  23579. {
  23580. testSort(1);
  23581. }
  23582. void testHeapSort()
  23583. {
  23584. testSort(2);
  23585. }
  23586. void testMerge()
  23587. {
  23588. DBGLOG("testMerge");
  23589. init();
  23590. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23591. factory->setInput(0,0,0);
  23592. factory->setInput(1,0,0);
  23593. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23594. const char * test[] = { NULL, NULL };
  23595. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23596. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  23597. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23598. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  23599. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23600. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23601. const char * test11111111111122334455[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  23602. testActivity(activity, test, test, test);
  23603. testActivity(activity, test12345, test, test12345);
  23604. testActivity(activity, test, test12345, test12345);
  23605. testActivity(activity, test12345, test12345, test1122334455);
  23606. testActivity(activity, test11111, test, test11111);
  23607. testActivity(activity, test, test11111, test11111);
  23608. testActivity(activity, test11111, test11111, test1111111111);
  23609. testActivity(activity, test11111_12345, test, test1111112345);
  23610. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  23611. // Should really test WHICH side gets kept...
  23612. // Should test with more than 2 inputs...
  23613. DBGLOG("testMerge done");
  23614. }
  23615. void testMergeDedup()
  23616. {
  23617. DBGLOG("testMergeDedup");
  23618. init();
  23619. MergeActivityTest::isDedup = true;
  23620. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge);
  23621. factory->setInput(0,0,0);
  23622. factory->setInput(1,0,0);
  23623. Owned <IRoxieServerActivity> activity = factory->createActivity(NULL);
  23624. const char * test[] = { NULL, NULL };
  23625. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  23626. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  23627. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  23628. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  23629. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  23630. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  23631. testActivity(activity, test, test11111, test11111);
  23632. testActivity(activity, test, test, test);
  23633. testActivity(activity, test12345, test, test12345);
  23634. testActivity(activity, test, test12345, test12345);
  23635. testActivity(activity, test12345, test12345, test12345);
  23636. testActivity(activity, test11111_12345, test, test1111112345);
  23637. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  23638. // Should really test WHICH side gets kept...
  23639. // Should test with more than 2 inputs...
  23640. DBGLOG("testMergeDedup done");
  23641. }
  23642. void testMiscellaneous()
  23643. {
  23644. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  23645. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  23646. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  23647. ASSERT(sizeof(CJoinGroup) <= 120);
  23648. }
  23649. };
  23650. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  23651. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  23652. #endif